blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
360d67b539061fa8273a1ce84256021fd9b608f6
|
61a9856c1c2aca1679400433761bf433c76bb9d5
|
/Wumpus/Wumpus.cpp
|
53d0e2dfc78c983105dcf299a94f56c980667821
|
[] |
no_license
|
lazycoding/Wumpus
|
f26372bd5a8f936cc22e2534ec5b0b3b7451374b
|
7ce229771a0329e1e533021f72b13b553a01076d
|
refs/heads/master
| 2021-01-24T06:40:52.362719
| 2015-07-22T05:45:16
| 2015-07-22T05:45:16
| 39,487,966
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 311
|
cpp
|
Wumpus.cpp
|
#include "Wumpus.h"
Wumpus::Wumpus(void):room_id(0), alive(true)
{
}
Wumpus::~Wumpus(void)
{
}
bool Wumpus::Alive() const
{
return alive;
}
void Wumpus::Move()
{
}
void Wumpus::Initialize( int roomId )
{
room_id = roomId;
alive = true;
}
std::string Wumpus::Warnning()
{
return "Wumpus wumpus!";
}
|
c6925e6db18dddbd3accc2f27433399d48a37065
|
437cd794cd8fce369efc09fe605bfdf4f0fdd897
|
/WzmPokerClient/PokerFace.cpp
|
8a253c0f7eca3c89a381a20f9f1f251a9d9d0e3e
|
[] |
no_license
|
wangzhimin/WzmPoker
|
fb28d2c94c4dcdbf52f0fbb562d973428b6ceeb6
|
ac4b2bf870b113559f800712fdc40d13e0b09994
|
refs/heads/master
| 2020-06-04T03:25:05.182785
| 2013-04-11T14:49:48
| 2013-04-11T14:49:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 152
|
cpp
|
PokerFace.cpp
|
#include "PokerFace.h"
PokerFace::PokerFace(int value, ID2D1Bitmap* bitmap)
:Color(value/100),
Number(value%100),
pBitmap(bitmap)
{
}
|
001bd3b6694f50691ff623791a7743a0ae2e26a6
|
7e029eac0f5b05117ccc61a13a2c4ea3de512c30
|
/D05/ex00/Bureaucrat.cpp
|
15e3ba1804e75fcfcf637a20aca3480e7a71809f
|
[] |
no_license
|
gvannest/piscineCPP
|
dafa72a021e3a79a7a02b032d9d87b935af93ae4
|
16cba4fd88d407ea5aa4abf215ee6544579edfb7
|
refs/heads/master
| 2021-04-05T16:05:13.012905
| 2020-04-30T07:53:27
| 2020-04-30T07:53:27
| 248,575,429
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,302
|
cpp
|
Bureaucrat.cpp
|
#include "Bureaucrat.hpp"
#include <iostream>
Bureaucrat::Bureaucrat(void) {}
Bureaucrat::Bureaucrat(std::string const & name, int grade) : _name(name){
if (grade < 1)
throw Bureaucrat::GradeTooHighException();
if (grade > 150)
throw Bureaucrat::GradeTooLowException();
this->_grade = grade;
std::cout << "Constructor called successfuly" << std::endl;
}
Bureaucrat::Bureaucrat(Bureaucrat const & src) : _name(src.getName()) {
*this = src;
}
Bureaucrat::~Bureaucrat(void) {
std::cout << "Destructor called successfuly" << std::endl;
}
Bureaucrat & Bureaucrat::operator=(Bureaucrat const & rhs){
this->_grade = rhs.getGrade();
return *this;
}
std::string const Bureaucrat::getName(void) const{
return this->_name;
}
int Bureaucrat::getGrade(void) const{
return this->_grade;
}
void Bureaucrat::decGrade(void){
if (this->_grade == 150)
throw Bureaucrat::GradeTooLowException();
this->_grade++;
}
void Bureaucrat::incGrade(void){
if (this->_grade == 1)
throw Bureaucrat::GradeTooHighException();
this->_grade--;
}
std::ostream & operator<<(std::ostream & o, Bureaucrat const & rhs){
o << rhs.getName() << ", bureaucrat grade " << rhs.getGrade();
return o;
}
|
c4ae98d98464d7e9ca14b656c8768eae4bf32bf7
|
56a8cd4d6e18f26c4c0c4b00bcad3cbf265a8a91
|
/level_1.h
|
9ef6106af0980f41ee9c2a0a4712b9f73f530f0e
|
[] |
no_license
|
G-H-Li/BallWorld
|
3c334e1990173f4d6a1f9ef5738f06dea9a3482b
|
fbd5afb39f79d40353ee30939a6e70c3921b06c8
|
refs/heads/master
| 2020-06-16T16:56:24.055890
| 2019-07-07T12:05:11
| 2019-07-07T12:05:11
| 195,642,504
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,297
|
h
|
level_1.h
|
#pragma once
#include "cocos2d.h"
#include "ui/UILoadingBar.h"
#include "ui/UIText.h"
class level_1 :public cocos2d::Layer
{
public:
level_1() {}
static cocos2d::Scene* createScene();
virtual bool init();
CREATE_FUNC(level_1);
//按钮的回调函数
void stopButtonTouch(Ref* sender);
//键盘事件回调函数
virtual void onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event);
virtual void onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event);
//鼠标事件回调函数
virtual void onMouseDown(cocos2d::Event* event);
//改变人物位置以及图片方向
void changeCharacterPosition(cocos2d::Sprite* sprite);
void changeDirection(cocos2d::Sprite* sprite);
void moveRight();//控制人物右移
void moveLeft();//控制人物左移
//控制子弹的发射
void bulletOut(cocos2d::Sprite* sprite);
//处理碰撞函数
bool onContactSeparate(cocos2d::PhysicsContact& contact);
//游戏刷新函数
virtual void update(float dt);//各种帧刷新处理
void timerAndScore(float dt); //处理计时
void changePosition(float dt); //改变幽灵位置(debug
void attack(float dt); //幽灵的全屏攻击
void fileWrite(int score, int time); //将时间和分数写入
static int time; //游戏时间(单位:秒
static int score; //所得分数
private:
//精灵声明
cocos2d::Node* csb;
cocos2d::Sprite* actor;
cocos2d::Sprite* monster;
cocos2d::Sprite* ball;
cocos2d::Sprite* levelBg1;
cocos2d::Sprite* levelBg2;
cocos2d::Sprite* gunSprite;
cocos2d::Sprite* ghost;
//精灵帧声明
cocos2d::SpriteFrame* bulletFrame;
cocos2d::SpriteFrame* ghostFrame;
//ui控件获取
cocos2d::ui::LoadingBar* actorLife;
cocos2d::ui::LoadingBar* ghostLife;
cocos2d::ui::Text* timeNum;
cocos2d::ui::Text* scoreNum;
//人物属性
bool accLeft = false; //加速度方向开关
bool accRight = false;
int lifeNum = 100; //生命值
int leftSpeed = 0; //速度
int rightSpeed = 0;
const int initSpeed = 5; //初始速度
const int acceleration = 3; //初始加速度
bool isKeyPressedA, isKeyPressedD; //键盘按下
//游戏画面属性
int brickNum = 30; //砖块数量
int monsterNum = 1; //小怪数量
int gunNum = 1; //枪的序号
int ghostLifeNum = 100; //幽灵生命值
};
|
7bfdca1e9fe406c300b5e36ad0d028cfa7474279
|
7ee4de3c6fdebdb2d62b3d6226cfe7b9815f609a
|
/Domain/Player/Shop.hpp
|
2e1240de553320b56381539c6567501bebce56c5
|
[] |
no_license
|
nathrichCSUF/DungeonDoers
|
2feb66b997aebda52fe354ef5f5245e8574bc34f
|
cbbcefcda0b8df69d9f1f8ed68807d3633231d1a
|
refs/heads/master
| 2020-08-29T19:49:44.624453
| 2019-12-04T14:37:09
| 2019-12-04T14:37:09
| 218,153,975
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 720
|
hpp
|
Shop.hpp
|
#pragma once
#include <memory>
#include <vector>
#include <string>
#include "Weapon.hpp"
#include "SwordWeapon.hpp"
#include "KnifeWeapon.hpp"
namespace Domain::Player
{
struct Shop
{
Shop()
{
weapons = {"Sword","Knife"};
}
std::unique_ptr<Weapon> PurchaseWeapon(std::string name)
{
if (name == "Sword")
{
return std::make_unique<Domain::Player::SwordWeapon>();
}
if (name == "Knife") //new derived class
{
return std::make_unique<Domain::Player::KnifeWeapon>();
}
}
std::vector<std::string> weapons;
};
}
|
048bf41e723032a40fb865ac1cbb958fe0139a22
|
ce64c59e1e2b6ae779f125c982e94f6de93d62f8
|
/tests/ksystemtraytest.cpp
|
0a59faf27a6f1ea4458b4b54a74c2ce72ba9853f
|
[] |
no_license
|
The-Oracle/kdeui
|
f3e2d7cc7335bdffce9d6a02de38ab196e5cf02d
|
87414d061d2f7156901212a19ea01bdf85d6e53d
|
refs/heads/master
| 2021-01-20T00:51:25.654205
| 2017-04-24T05:14:13
| 2017-04-24T05:14:13
| 89,200,851
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 481
|
cpp
|
ksystemtraytest.cpp
|
#include <ksystemtrayicon.h>
#include <kapplication.h>
#include <QtGui/QLabel>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
int main(int argc, char **argv)
{
KAboutData aboutData( "ksystemtraytest", 0 , ki18n("ksystemtraytest"), "1.0" );
KCmdLineArgs::init(argc, argv, &aboutData);
KApplication app;
QLabel *l = new QLabel("System Tray Main Window", 0L);
KSystemTrayIcon *tray = new KSystemTrayIcon( "test", l );
l->show();
tray->show();
return app.exec();
}
|
c4c6a2fd7e2a5ced38b451df5eab7f26a8450a24
|
747092ff693de7466341f314bcdae46e222b0ffb
|
/MappingCoreLib/Scenario.cpp
|
e464fe8b4e7c478b88e6eab371155427b21d0350
|
[
"MIT"
] |
permissive
|
tobeinged/Chkdraft
|
55028425464991e8be772c5dae0a1f7fdcf49705
|
c07df6675f42a24c8b32f86ab8a53abb0fcd158b
|
refs/heads/master
| 2023-03-18T01:16:42.045200
| 2021-03-09T15:09:30
| 2021-03-09T15:09:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 196,869
|
cpp
|
Scenario.cpp
|
#include "Scenario.h"
#include "sha256.h"
#include "Math.h"
#include "../CommanderLib/Logger.h"
#include "Sections.h"
#include <algorithm>
#include <cstdio>
#include <exception>
#include <functional>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <chrono>
extern Logger logger;
template <typename SectionType>
std::shared_ptr<SectionType> GetSection(std::unordered_map<SectionName, Section> & sections, const SectionName & sectionName)
{
auto found = sections.find(sectionName);
if ( found != sections.end() )
return std::dynamic_pointer_cast<SectionType>(found->second);
else
return nullptr;
}
Scenario::Scenario() :
versions(), strings(), players(), layers(), properties(), triggers(),
tailData({}), tailLength(0), mapIsProtected(false), jumpCompress(false)
{
versions.layers = &layers;
strings.versions = &versions;
strings.players = &players;
strings.layers = &layers;
strings.properties = &properties;
strings.triggers = &triggers;
players.strings = &strings;
layers.strings = &strings;
layers.triggers = &triggers;
properties.versions = &versions;
properties.strings = &strings;
triggers.strings = &strings;
triggers.layers = &layers;
}
Scenario::Scenario(Sc::Terrain::Tileset tileset, u16 width, u16 height) :
versions(true), strings(true), players(true), layers(tileset, width, height), properties(true), triggers(true),
tailData({}), tailLength(0), mapIsProtected(false), jumpCompress(false)
{
versions.layers = &layers;
strings.versions = &versions;
strings.players = &players;
strings.layers = &layers;
strings.properties = &properties;
strings.triggers = &triggers;
players.strings = &strings;
layers.strings = &strings;
layers.triggers = &triggers;
properties.versions = &versions;
properties.strings = &strings;
triggers.strings = &strings;
triggers.layers = &layers;
if ( versions.isHybridOrAbove() )
allSections.push_back(versions.type);
allSections.push_back(versions.ver);
if ( !versions.isHybridOrAbove() )
allSections.push_back(versions.iver);
allSections.push_back(versions.ive2);
allSections.push_back(versions.vcod);
allSections.push_back(players.iown);
allSections.push_back(players.ownr);
allSections.push_back(layers.era);
allSections.push_back(layers.dim);
allSections.push_back(players.side);
allSections.push_back(layers.mtxm);
allSections.push_back(properties.puni);
allSections.push_back(properties.upgr);
allSections.push_back(properties.ptec);
allSections.push_back(layers.unit);
allSections.push_back(layers.isom);
allSections.push_back(layers.tile);
allSections.push_back(layers.dd2);
allSections.push_back(layers.thg2);
allSections.push_back(layers.mask);
allSections.push_back(strings.str);
allSections.push_back(triggers.uprp);
allSections.push_back(triggers.upus);
allSections.push_back(layers.mrgn);
allSections.push_back(triggers.trig);
allSections.push_back(triggers.mbrf);
allSections.push_back(strings.sprp);
allSections.push_back(players.forc);
allSections.push_back(triggers.wav);
allSections.push_back(properties.unis);
allSections.push_back(properties.upgs);
allSections.push_back(properties.tecs);
allSections.push_back(triggers.swnm);
allSections.push_back(players.colr);
allSections.push_back(properties.pupx);
allSections.push_back(properties.ptex);
allSections.push_back(properties.unix);
allSections.push_back(properties.upgx);
allSections.push_back(properties.tecx);
}
Scenario::~Scenario()
{
}
void Scenario::clear()
{
strings.clear();
triggers.clear();
layers.clear();
properties.clear();
players.clear();
versions.clear();
allSections.clear();
for ( size_t i=0; i<tailData.size(); i++ )
tailData[i] = u8(0);
tailLength = 0;
jumpCompress = false;
mapIsProtected = false;
}
bool Scenario::empty() const
{
return allSections.empty() && tailLength == 0 && versions.empty() && strings.empty() && players.empty() && layers.empty() && properties.empty() && triggers.empty();
}
bool Scenario::isProtected() const
{
return mapIsProtected;
}
bool Scenario::hasPassword() const
{
return tailLength == 7;
}
bool Scenario::isPassword(const std::string & password) const
{
if ( hasPassword() )
{
SHA256 sha256;
std::string hashStr = sha256(password);
if ( hashStr.length() >= 7 )
{
u64 eightHashBytes = std::stoull(hashStr.substr(0, 8), nullptr, 16);
u8* hashBytes = (u8*)&eightHashBytes;
for ( u8 i = 0; i < tailLength; i++ )
{
if ( tailData[i] != hashBytes[i] )
return false;
}
return true;
}
else
return false;
}
else // No password
return false;
}
bool Scenario::setPassword(const std::string & oldPass, const std::string & newPass)
{
if ( isPassword(oldPass) )
{
if ( newPass == "" )
{
for ( u8 i = 0; i < tailLength; i++ )
tailData[i] = 0;
tailLength = 0;
return true;
}
else
{
SHA256 sha256;
std::string hashStr = sha256(newPass);
if ( hashStr.length() >= 7 )
{
u64 eightHashBytes = stoull(hashStr.substr(0, 8), nullptr, 16);
u8* hashBytes = (u8*)&eightHashBytes;
tailLength = 7;
for ( u8 i = 0; i < tailLength; i++ )
tailData[i] = hashBytes[i];
return true;
}
}
}
return false;
}
bool Scenario::login(const std::string & password) const
{
if ( isPassword(password) )
{
mapIsProtected = false;
return true;
}
return false;
}
bool Scenario::read(std::istream & is)
{
clear();
// First read contents of "is" to "chk", this will allow jumping backwards when reading chks with jump sections
std::stringstream chk(std::ios_base::binary|std::ios_base::in|std::ios_base::out);
chk << is.rdbuf();
if ( !is.good() && !is.eof() )
{
logger.error("Unexpected failure reading scenario contents!");
return false; // Read error on "is"
}
chk.seekg(std::ios_base::beg); // Move to start of chk
std::multimap<SectionName, Section> parsedSections;
do
{
Chk::SectionHeader sectionHeader = {};
chk.read((char*)§ionHeader, sizeof(Chk::SectionHeader));
std::streamsize headerBytesRead = chk.good() ? sizeof(Chk::SectionHeader) : chk.eof() ? chk.gcount() : 0;
if ( headerBytesRead == 0 && chk.eof() )
break;
else if ( headerBytesRead == 0 )
return parsingFailed("Unexpected failure reading chk section header!");
if ( headerBytesRead == sizeof(Chk::SectionHeader) ) // Valid section header
{
if ( sectionHeader.sizeInBytes >= 0 ) // Regular section
{
Chk::SectionSize sizeRead = 0;
Section section = nullptr;
try {
section = ChkSection::read(parsedSections, sectionHeader, chk, sizeRead);
} catch ( std::exception & e ) {
logger.error() << "Read of section " << ChkSection::getNameString(sectionHeader.name) << " failed with error: " << e.what() << std::endl;
section = nullptr;
}
if ( section != nullptr && (chk.good() || chk.eof()) )
{
parsedSections.insert(std::pair<SectionName, Section>(sectionHeader.name, section));
allSections.push_back(section);
if ( sizeRead != sectionHeader.sizeInBytes ) // Undersized section
mapIsProtected = true;
}
else
return parsingFailed("Unexpected error reading chk section contents!");
}
else // if ( sectionHeader.sizeInBytes < 0 ) // Jump section
{
chk.seekg(sectionHeader.sizeInBytes, std::ios_base::cur);
if ( !chk.good() )
return parsingFailed("Unexpected error processing chk jump section!");
jumpCompress = true;
}
}
else // if ( bytesRead < sizeof(Chk::SectionHeader) ) // Partial section header
{
for ( std::streamsize i=0; i<headerBytesRead; i++ )
tailData[i] = ((u8*)§ionHeader)[i];
for ( size_t i=headerBytesRead; i<tailData.size(); i++ )
tailData[i] = u8(0);
tailLength = (u8)headerBytesRead;
mapIsProtected = true;
}
}
while ( chk.good() );
// For all sections that are actually used by scenario, get the instance of the section that will be used
std::unordered_map<SectionName, Section> finalSections;
const std::vector<SectionName> & sectionNames = ChkSection::getNames();
for ( const SectionName & sectionName : sectionNames )
{
LoadBehavior loadBehavior = ChkSection::getLoadBehavior(sectionName);
auto sectionInstances = parsedSections.equal_range(sectionName);
auto it = sectionInstances.first;
if ( it != parsedSections.end() )
{
if ( loadBehavior == LoadBehavior::Standard ) // Last instance of a section is used
{
Section section = nullptr;
for ( ; it != sectionInstances.second; ++it )
section = it->second;
if ( section != nullptr )
finalSections.insert(std::pair<SectionName, Section>(sectionName, section));
}
else if ( loadBehavior == LoadBehavior::Append || loadBehavior == LoadBehavior::Override ) // First instance of a section is used
finalSections.insert(std::pair<SectionName, Section>(sectionName, sectionInstances.first->second));
}
}
versions.set(finalSections);
strings.set(finalSections);
players.set(finalSections);
layers.set(finalSections);
properties.set(finalSections);
triggers.set(finalSections);
if ( versions.ver == nullptr )
return parsingFailed("Map was missing the VER section!");
Chk::Version version = versions.ver->getVersion();
triggers.fixTriggerExtensions();
upgradeKstrToCurrent();
// TODO: More validation
return true;
}
StrSynchronizerPtr Scenario::getStrSynchronizer()
{
return StrSynchronizerPtr(&strings, [](StrSynchronizer*){});
}
void Scenario::addSection(Section section)
{
if ( section != nullptr )
{
for ( auto & existing : allSections )
{
if ( section == existing )
return;
}
allSections.push_back(section);
}
}
void Scenario::removeSection(const SectionName & sectionName)
{
bool foundSection = false;
do
{
foundSection = false;
for ( auto it = allSections.begin(); it != allSections.end(); ++it )
{
if ( (*it)->getName() == sectionName )
{
allSections.erase(it);
foundSection = true;
break;
}
}
}
while ( foundSection );
}
bool Scenario::parsingFailed(const std::string & error)
{
logger.error(error);
clear();
return false;
}
void Scenario::write(std::ostream & os)
{
try
{
for ( auto & section : allSections )
section->writeWithHeader(os, *this);
}
catch ( std::exception & e )
{
os.setstate(std::ios_base::failbit);
logger.error("Error writing scenario file ", e);
}
}
std::vector<u8> Scenario::serialize()
{
Chk::Size size = 0;
std::stringstream chk(std::ios_base::in|std::ios_base::out|std::ios_base::binary);
chk.write((const char*)&Chk::CHK, sizeof(Chk::CHK)); // Header
chk.write((const char*)&size, sizeof(size)); // Size
write(chk);
chk.unsetf(std::ios_base::skipws);
auto start = std::istream_iterator<u8>(chk);
std::vector<u8> chkBytes(start, std::istream_iterator<u8>());
(Chk::Size &)chkBytes[sizeof(Chk::CHK)] = Chk::Size(chkBytes.size() - sizeof(Chk::CHK) - sizeof(size));
return chkBytes;
}
bool Scenario::deserialize(Chk::SerializedChk* data)
{
if ( data->header.name == Chk::CHK )
{
Chk::Size size = data->header.sizeInBytes;
std::stringstream chk(std::ios_base::in|std::ios_base::out|std::ios_base::binary);
std::copy(&data->data[0], &data->data[size], std::ostream_iterator<u8>(chk));
}
return false;
}
void Scenario::updateSaveSections()
{
if ( strings.hasExtendedStrings() )
{
addSection(strings.ostr);
addSection(strings.kstr);
}
if ( triggers.ktrg != nullptr && !triggers.ktrg->empty() )
addSection(triggers.ktrg);
if ( triggers.ktgp != nullptr && !triggers.ktgp->empty() )
addSection(triggers.ktgp);
}
bool Scenario::changeVersionTo(Chk::Version version, bool lockAnywhere, bool autoDefragmentLocations)
{
if ( versions.changeTo(version, lockAnywhere, autoDefragmentLocations) )
{
strings.deleteUnusedStrings(Chk::Scope::Both);
if ( version < Chk::Version::StarCraft_BroodWar ) // Original or Hybrid: No COLR, include all original properties
{
if ( version < Chk::Version::StarCraft_Hybrid ) // Original: No TYPE, IVE2, or expansion properties
{
removeSection(SectionName::TYPE);
removeSection(SectionName::PUPx);
removeSection(SectionName::PTEx);
removeSection(SectionName::UNIx);
removeSection(SectionName::TECx);
}
removeSection(SectionName::COLR);
addSection(versions.iver);
addSection(properties.upgr);
addSection(properties.ptec);
addSection(properties.unis);
addSection(properties.upgs);
addSection(properties.tecs);
}
else // if ( version >= Chk::Version::StarCraft_BroodWar ) // Broodwar: No IVER or original properties, include COLR
{
removeSection(SectionName::IVER);
removeSection(SectionName::UPGR);
removeSection(SectionName::PTEC);
removeSection(SectionName::UNIS);
removeSection(SectionName::UPGS);
removeSection(SectionName::TECS);
addSection(players.colr);
}
if ( version >= Chk::Version::StarCraft_Hybrid ) // Hybrid or BroodWar: Include type, ive2, and all expansion properties
{
addSection(versions.type);
addSection(properties.pupx);
addSection(properties.ptex);
addSection(properties.unix);
addSection(properties.upgx);
addSection(properties.tecx);
}
return true;
}
return false;
}
void Scenario::setTileset(Sc::Terrain::Tileset tileset)
{
layers.setTileset(tileset);
}
void Scenario::upgradeKstrToCurrent()
{
if ( 0 == strings.kstr->getVersion() || 2 == strings.kstr->getVersion() )
{
size_t strCapacity = strings.getCapacity(Chk::Scope::Game);
for ( auto & section : allSections )
{
switch ( section->getName() )
{
case Chk::SectionName::TRIG:
{
auto trigSection = std::dynamic_pointer_cast<TrigSection>(section);
size_t numTriggers = trigSection->numTriggers();
for ( size_t triggerIndex=0; triggerIndex<numTriggers; triggerIndex++ )
{
auto trigger = trigSection->getTrigger(triggerIndex);
if ( trigger != nullptr )
{
size_t extendedCommentStringId = triggers.getExtendedCommentStringId(triggerIndex);
size_t extendedNotesStringId = triggers.getExtendedNotesStringId(triggerIndex);
for ( size_t actionIndex=0; actionIndex<Chk::Trigger::MaxActions; actionIndex++ )
{
Chk::Action & action = trigger->actions[actionIndex];
if ( action.actionType < Chk::Action::NumActionTypes )
{
if ( Chk::Action::actionUsesStringArg[action.actionType] &&
action.stringId > strCapacity &&
action.stringId != Chk::StringId::NoString &&
action.stringId < 65536 &&
strings.stringStored(65536 - action.stringId, Chk::Scope::Editor) )
{
if ( action.actionType == Chk::Action::Type::Comment &&
(extendedCommentStringId == Chk::StringId::NoString ||
extendedNotesStringId == Chk::StringId::NoString) )
{ // Move comment to extended comment or to notes
if ( extendedCommentStringId == Chk::StringId::NoString )
{
triggers.setExtendedCommentStringId(triggerIndex, 65536 - action.stringId);
extendedCommentStringId = triggers.getExtendedCommentStringId(triggerIndex);
action.stringId = 0;
}
else if ( extendedNotesStringId == Chk::StringId::NoString )
{
triggers.setExtendedNotesStringId(triggerIndex, 65536 - action.stringId);
extendedNotesStringId = triggers.getExtendedNotesStringId(triggerIndex);
action.stringId = 0;
}
}
else // Extended string is lost
{
auto actionString = strings.getString<ChkdString>(65536 - action.stringId);
logger.warn() << "Trigger #" << triggerIndex
<< " action #" << actionIndex
<< " lost extended string: \""
<< (actionString != nullptr ? *actionString : "")
<< "\"" << std::endl;
action.stringId = Chk::StringId::NoString;
}
}
if ( Chk::Action::actionUsesSoundArg[action.actionType] &&
action.soundStringId > strCapacity &&
action.soundStringId != Chk::StringId::NoString &&
action.soundStringId < 65536 &&
strings.stringStored(65536 - action.soundStringId, Chk::Scope::Editor) )
{
action.soundStringId = 65536 - action.soundStringId;
auto soundString = strings.getString<ChkdString>(65536 - action.soundStringId);
logger.warn() << "Trigger #" << triggerIndex
<< " action #" << actionIndex
<< " lost extended sound string: \""
<< (soundString != nullptr ? *soundString : "")
<< "\"" << std::endl;
action.soundStringId = Chk::StringId::NoString;
}
}
}
}
}
}
break;
case Chk::SectionName::MBRF:
{
auto mbrfSection = std::dynamic_pointer_cast<MbrfSection>(section);
size_t numBriefingTriggers = mbrfSection->numBriefingTriggers();
for ( size_t briefingTriggerIndex=0; briefingTriggerIndex<numBriefingTriggers; briefingTriggerIndex++ )
{
auto briefingTrigger = mbrfSection->getBriefingTrigger(briefingTriggerIndex);
if ( briefingTrigger != nullptr )
{
for ( size_t actionIndex=0; actionIndex<Chk::Trigger::MaxActions; actionIndex++ )
{
Chk::Action & briefingAction = briefingTrigger->actions[actionIndex];
if ( briefingAction.actionType < Chk::Action::NumBriefingActionTypes )
{
if ( Chk::Action::briefingActionUsesStringArg[briefingAction.actionType] &&
briefingAction.stringId > strCapacity &&
briefingAction.stringId != Chk::StringId::NoString &&
briefingAction.stringId < 65536 &&
strings.stringStored(65536 - briefingAction.stringId, Chk::Scope::Editor) )
{
auto briefingString = strings.getString<ChkdString>(65536 - briefingAction.stringId);
logger.warn() << "Briefing trigger #" << briefingTriggerIndex
<< " action #" << actionIndex
<< " lost extended string: \""
<< (briefingString != nullptr ? *briefingString : "")
<< "\"" << std::endl;
briefingAction.stringId = Chk::StringId::NoString;
}
if ( Chk::Action::briefingActionUsesSoundArg[briefingAction.actionType] &&
briefingAction.soundStringId > strCapacity &&
briefingAction.soundStringId != Chk::StringId::NoString &&
briefingAction.soundStringId < 65536 &&
strings.stringStored(65536 - briefingAction.stringId, Chk::Scope::Editor) )
{
auto briefingSoundString = strings.getString<ChkdString>(65536 - briefingAction.soundStringId);
logger.warn() << "Briefing trigger #" << briefingTriggerIndex
<< " action #" << actionIndex
<< " lost extended sound string: \""
<< (briefingSoundString != nullptr ? *briefingSoundString : "")
<< "\"" << std::endl;
briefingAction.soundStringId = Chk::StringId::NoString;
}
}
}
}
}
}
break;
case Chk::SectionName::MRGN:
{
auto mrgnSection = std::dynamic_pointer_cast<MrgnSection>(section);
size_t numLocations = mrgnSection->numLocations();
for ( size_t i=0; i<numLocations; i++ )
{
auto location = mrgnSection->getLocation(i);
if ( location != nullptr &&
location->stringId > strCapacity &&
location->stringId != Chk::StringId::NoString &&
location->stringId < 65536 &&
strings.stringStored(65536 - location->stringId, Chk::Scope::Editor) )
{
strings.setLocationNameStringId(i, 65536 - location->stringId, Chk::Scope::Editor);
location->stringId = Chk::StringId::NoString;
}
}
}
break;
case Chk::SectionName::SPRP:
{
auto sprpSection = std::dynamic_pointer_cast<SprpSection>(section);
u16 scenarioNameStringId = (u16)sprpSection->getScenarioNameStringId();
if ( scenarioNameStringId > strCapacity &&
scenarioNameStringId != Chk::StringId::NoString &&
scenarioNameStringId < 65536 &&
strings.stringStored(65536 - scenarioNameStringId, Chk::Scope::Editor) )
{
strings.setScenarioNameStringId(65536 - scenarioNameStringId, Chk::Scope::Editor);
sprpSection->setScenarioNameStringId(Chk::StringId::NoString);
}
u16 scenarioDescriptionStringId = (u16)sprpSection->getScenarioDescriptionStringId();
if ( scenarioDescriptionStringId > strCapacity &&
scenarioDescriptionStringId != Chk::StringId::NoString &&
scenarioDescriptionStringId < 65536 &&
strings.stringStored(65536 - scenarioDescriptionStringId, Chk::Scope::Editor) )
{
strings.setScenarioDescriptionStringId(65536 - scenarioDescriptionStringId, Chk::Scope::Editor);
sprpSection->setScenarioDescriptionStringId(Chk::StringId::NoString);
}
}
break;
case Chk::SectionName::FORC:
{
auto forcSection = std::dynamic_pointer_cast<ForcSection>(section);
for ( Chk::Force i=Chk::Force::Force1; i<=Chk::Force::Force4; ((u8 &)i)++ )
{
u16 forcStringId = (u16)forcSection->getForceStringId((Chk::Force)i);
if ( forcStringId > strCapacity &&
forcStringId != Chk::StringId::NoString &&
forcStringId < 65536 &&
strings.stringStored(65536 - forcStringId, Chk::Scope::Editor) )
{
strings.setForceNameStringId(i, 65536 - forcStringId, Chk::Scope::Editor);
forcSection->setForceStringId(i, Chk::StringId::NoString);
}
}
}
break;
case Chk::SectionName::WAV:
{
auto wavSection = std::dynamic_pointer_cast<WavSection>(section);
for ( size_t i=0; i<Chk::TotalSounds; i++ )
{
u32 soundStringId = (u32)wavSection->getSoundStringId(i);
if ( soundStringId > strCapacity &&
soundStringId != Chk::StringId::NoString &&
soundStringId < 65536 &&
strings.stringStored(65536 - soundStringId, Chk::Scope::Editor) )
{
strings.setSoundPathStringId(i, 65536 - soundStringId, Chk::Scope::Editor);
wavSection->setSoundStringId(i, Chk::StringId::NoString);
}
}
}
break;
case Chk::SectionName::SWNM:
{
auto swnmSection = std::dynamic_pointer_cast<SwnmSection>(section);
for ( size_t i=0; i<Chk::TotalSwitches; i++ )
{
u32 switchStringId = (u32)swnmSection->getSwitchNameStringId(i);
if ( switchStringId > strCapacity &&
switchStringId != Chk::StringId::NoString &&
switchStringId < 65536 &&
strings.stringStored(65536 - switchStringId, Chk::Scope::Editor) )
{
strings.setSwitchNameStringId(i, 65536 - switchStringId, Chk::Scope::Editor);
swnmSection->setSwitchNameStringId(i, Chk::StringId::NoString);
}
}
}
break;
case Chk::SectionName::UNIS:
{
auto unisSection = std::dynamic_pointer_cast<UnisSection>(section);
for ( Sc::Unit::Type i=Sc::Unit::Type::TerranMarine; i<Sc::Unit::TotalTypes; ((u16 &)i)++ )
{
u16 unitNameStringId = (u16)unisSection->getUnitNameStringId(i);
if ( unitNameStringId > strCapacity &&
unitNameStringId != Chk::StringId::NoString &&
unitNameStringId < 65536 &&
strings.stringStored(65536 - unitNameStringId, Chk::Scope::Editor) )
{
strings.setUnitNameStringId(i, 65536 - unitNameStringId, Chk::UseExpSection::No, Chk::Scope::Editor);
unisSection->setUnitNameStringId(i, Chk::StringId::NoString);
}
}
}
break;
case Chk::SectionName::UNIx:
{
auto unixSection = std::dynamic_pointer_cast<UnixSection>(section);
for ( Sc::Unit::Type i=Sc::Unit::Type::TerranMarine; i<Sc::Unit::TotalTypes; ((u16 &)i)++ )
{
u16 unitNameStringId = (u16)unixSection->getUnitNameStringId(i);
if ( unitNameStringId > strCapacity &&
unitNameStringId != Chk::StringId::NoString &&
unitNameStringId < 65536 &&
strings.stringStored(65536 - unitNameStringId, Chk::Scope::Editor) )
{
strings.setUnitNameStringId(i, 65536 - unitNameStringId, Chk::UseExpSection::Yes, Chk::Scope::Editor);
unixSection->setUnitNameStringId(i, Chk::StringId::NoString);
}
}
}
break;
}
}
strings.kstr->setVersion(Chk::KSTR::CurrentVersion);
strings.deleteUnusedStrings(Chk::Scope::Both);
}
else if ( 1 == strings.kstr->getVersion() )
{
*strings.kstr = *KstrSection::GetDefault();
}
}
Versions::Versions(bool useDefault) : layers(nullptr)
{
if ( useDefault )
{
ver = VerSection::GetDefault(); // StarCraft version information
type = TypeSection::GetDefault(ver->getVersion()); // Redundant versioning
iver = IverSection::GetDefault(); // Redundant versioning
ive2 = Ive2Section::GetDefault(); // Redundant versioning
vcod = VcodSection::GetDefault(); // Validation
if ( vcod == nullptr || ive2 == nullptr || iver == nullptr || type == nullptr || ver == nullptr )
{
throw ScenarioAllocationFailure(
(vcod == nullptr ? ChkSection::getNameString(SectionName::VCOD) :
(ive2 == nullptr ? ChkSection::getNameString(SectionName::IVE2) :
(iver == nullptr ? ChkSection::getNameString(SectionName::IVER) :
(type == nullptr ? ChkSection::getNameString(SectionName::TYPE) :
ChkSection::getNameString(SectionName::VER))))));
}
}
}
bool Versions::empty() const
{
return ver == nullptr && type == nullptr && iver == nullptr && ive2 == nullptr && vcod == nullptr;
}
Chk::Version Versions::getVersion() const
{
return ver->getVersion();
}
bool Versions::is(Chk::Version version) const
{
return ver->getVersion() == version;
}
bool Versions::isOriginal() const
{
return ver->isOriginal();
}
bool Versions::isHybrid() const
{
return ver->isHybrid();
}
bool Versions::isExpansion() const
{
return ver->isExpansion();
}
bool Versions::isHybridOrAbove() const
{
return ver->isHybridOrAbove();
}
bool Versions::changeTo(Chk::Version version, bool lockAnywhere, bool autoDefragmentLocations)
{
Chk::Version oldVersion = ver->getVersion();
ver->setVersion(version);
if ( version < Chk::Version::StarCraft_Hybrid )
{
if ( layers->trimLocationsToOriginal(lockAnywhere, autoDefragmentLocations) )
{
type->setType(Chk::Type::RAWS);
iver->setVersion(Chk::IVersion::Current);
}
else
{
logger.error("Cannot save as original with over 64 locations in use!");
return false;
}
}
else if ( version < Chk::Version::StarCraft_BroodWar )
{
type->setType(Chk::Type::RAWS);
iver->setVersion(Chk::IVersion::Current);
ive2->setVersion(Chk::I2Version::StarCraft_1_04);
layers->expandToScHybridOrExpansion();
}
else // version >= Chk::Version::StarCraft_Broodwar
{
type->setType(Chk::Type::RAWB);
iver->setVersion(Chk::IVersion::Current);
ive2->setVersion(Chk::I2Version::StarCraft_1_04);
layers->expandToScHybridOrExpansion();
}
return true;
}
bool Versions::hasDefaultValidation() const
{
return vcod->isDefault();
}
void Versions::setToDefaultValidation()
{
vcod->setToDefault();
}
void Versions::set(std::unordered_map<SectionName, Section> & sections)
{
ver = GetSection<VerSection>(sections, SectionName::VER);
type = GetSection<TypeSection>(sections, SectionName::TYPE);
iver = GetSection<IverSection>(sections, SectionName::IVER);
ive2 = GetSection<Ive2Section>(sections, SectionName::IVE2);
vcod = GetSection<VcodSection>(sections, SectionName::VCOD);
if ( ver != nullptr )
{
if ( type == nullptr )
type = TypeSection::GetDefault(ver->getVersion());
if ( iver == nullptr )
iver = IverSection::GetDefault();
if ( ive2 == nullptr )
ive2 = Ive2Section::GetDefault();
}
}
void Versions::clear()
{
ver = nullptr;
type = nullptr;
iver = nullptr;
ive2 = nullptr;
vcod = nullptr;
}
Strings::Strings(bool useDefault) : versions(nullptr), players(nullptr), layers(nullptr), properties(nullptr), triggers(nullptr),
StrSynchronizer(StrCompressFlag::DuplicateStringRecycling, StrCompressFlag::AllNonInterlacing)
{
if ( useDefault )
{
sprp = SprpSection::GetDefault(); // Scenario name and description
str = StrSection::GetDefault(); // StarCraft string data
ostr = OstrSection::GetDefault(); // Overrides for all but trigger and briefing strings
kstr = KstrSection::GetDefault(); // Editor only string data
if ( str == nullptr || sprp == nullptr )
{
throw ScenarioAllocationFailure(
str == nullptr ? ChkSection::getNameString(SectionName::STR) :
ChkSection::getNameString(SectionName::SPRP));
}
}
}
bool Strings::empty() const
{
return sprp == nullptr && str == nullptr && ostr == nullptr && kstr == nullptr;
}
bool Strings::hasExtendedStrings() const
{
return ostr != nullptr && kstr != nullptr && !kstr->empty();
}
size_t Strings::getCapacity(Chk::Scope storageScope) const
{
if ( storageScope == Chk::Scope::Game )
return str->getCapacity();
else if ( storageScope == Chk::Scope::Editor )
return kstr->getCapacity();
else
return 0;
}
size_t Strings::getBytesUsed(Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Game )
return str->getBytesUsed(std::shared_ptr<StrSynchronizer>(this, [](StrSynchronizer*){}));
else if ( storageScope == Chk::Scope::Editor )
return kstr->getBytesUsed(std::shared_ptr<StrSynchronizer>(this, [](StrSynchronizer*){}));
else
return 0;
}
bool Strings::stringStored(size_t stringId, Chk::Scope storageScope) const
{
return (storageScope & Chk::Scope::Game) == Chk::Scope::Game && str->stringStored(stringId) ||
(storageScope & Chk::Scope::Editor) == Chk::Scope::Editor && kstr->stringStored(stringId);
}
void Strings::appendUsage(size_t stringId, std::vector<Chk::StringUser> & stringUsers, Chk::Scope storageScope, u32 userMask) const
{
if ( storageScope == Chk::Scope::Game )
{
if ( stringId < Chk::MaxStrings ) // 16 or 32-bit stringId
{
if ( (userMask & Chk::StringUserFlag::ScenarioProperties) != Chk::StringUserFlag::None )
sprp->appendUsage(stringId, stringUsers, userMask);
if ( (userMask & Chk::StringUserFlag::Force) != Chk::StringUserFlag::None )
players->appendUsage(stringId, stringUsers, userMask);
if ( (userMask & Chk::StringUserFlag::BothUnitSettings) != Chk::StringUserFlag::None )
properties->appendUsage(stringId, stringUsers, userMask);
if ( (userMask & Chk::StringUserFlag::Location) != Chk::StringUserFlag::None )
layers->appendUsage(stringId, stringUsers, userMask);
if ( (userMask & Chk::StringUserFlag::AnyTrigger) != Chk::StringUserFlag::None )
triggers->appendUsage(stringId, stringUsers, storageScope, userMask);
}
else if ( (userMask & Chk::StringUserFlag::AnyTrigger) != Chk::StringUserFlag::None ) // stringId >= Chk::MaxStrings // 32-bit stringId
triggers->appendUsage(stringId, stringUsers, storageScope, userMask);
}
else if ( storageScope == Chk::Scope::Editor )
ostr->appendUsage(stringId, stringUsers, userMask);
}
bool Strings::stringUsed(size_t stringId, Chk::Scope usageScope, Chk::Scope storageScope, u32 userMask, bool ensureStored) const
{
if ( storageScope == Chk::Scope::Game && (str->stringStored(stringId) || !ensureStored) )
{
if ( stringId < Chk::MaxStrings ) // 16 or 32-bit stringId
{
if ( usageScope == Chk::Scope::Editor )
return layers->stringUsed(stringId, storageScope, userMask) || triggers->editorStringUsed(stringId, storageScope, userMask);
else if ( usageScope == Chk::Scope::Game )
{
return sprp->stringUsed(stringId, userMask) || players->stringUsed(stringId, userMask) ||
properties->stringUsed(stringId, userMask) || triggers->gameStringUsed(stringId, userMask);
}
else // if ( usageScope == Chk::Scope::Either )
{
return sprp->stringUsed(stringId, userMask) || players->stringUsed(stringId, userMask) ||
properties->stringUsed(stringId, userMask) || layers->stringUsed(stringId, storageScope, userMask) ||
triggers->stringUsed(stringId, storageScope, userMask);
}
}
else // stringId >= Chk::MaxStrings // 32-bit stringId
{
return usageScope == Chk::Scope::Either && triggers->stringUsed(stringId, storageScope, userMask) ||
usageScope == Chk::Scope::Game && triggers->gameStringUsed(stringId, userMask) ||
usageScope == Chk::Scope::Editor && triggers->editorStringUsed(stringId, storageScope, userMask);
}
}
else if ( storageScope == Chk::Scope::Editor && (kstr->stringStored(stringId) || !ensureStored) )
return ostr->stringUsed(stringId, userMask);
return false;
}
void Strings::markUsedStrings(std::bitset<Chk::MaxStrings> & stringIdUsed, Chk::Scope usageScope, Chk::Scope storageScope, u32 userMask) const
{
if ( storageScope == Chk::Scope::Game )
{
bool markGameStrings = (usageScope & Chk::Scope::Game) == Chk::Scope::Game;
bool markEditorStrings = (usageScope & Chk::Scope::Editor) == Chk::Scope::Editor;
if ( markGameStrings )
{
sprp->markUsedStrings(stringIdUsed, userMask); // {SPRP, Game, u16}: Scenario Name and Scenario Description
players->markUsedStrings(stringIdUsed, userMask); // {FORC, Game, u16}: Force Names
properties->markUsedStrings(stringIdUsed, userMask); // {UNIS, Game, u16}: Unit Names (original); {UNIx, Game, u16}: Unit names (expansion)
if ( markEditorStrings ) // {WAV, Editor, u32}: Sound Names; {SWNM, Editor, u32}: Switch Names; {TRIG, Game&Editor, u32}: text message, mission objectives, leaderboard text, ...
triggers->markUsedStrings(stringIdUsed, storageScope, userMask); // ... transmission text, next scenario, sound path, comment; {MBRF, Game, u32}: mission objectives, sound, text message
else
triggers->markUsedGameStrings(stringIdUsed, userMask); // {TRIG, Game&Editor, u32}: text message, mission objectives, leaderboard text, transmission text, next scenario, sound path
}
if ( markEditorStrings )
{
layers->markUsedStrings(stringIdUsed, userMask); // {MRGN, Editor, u16}: location name
if ( !markGameStrings )
triggers->markUsedEditorStrings(stringIdUsed, storageScope, userMask); // {WAV, Editor, u32}: Sound Names; {SWNM, Editor, u32}: Switch Names; {TRIG, Game&Editor, u32}: comment
}
}
else if ( storageScope == Chk::Scope::Editor )
{
ostr->markUsedStrings(stringIdUsed, userMask);
triggers->markUsedStrings(stringIdUsed, storageScope, userMask);
}
}
void Strings::markValidUsedStrings(std::bitset<Chk::MaxStrings> & stringIdUsed, Chk::Scope usageScope, Chk::Scope storageScope, u32 userMask) const
{
markUsedStrings(stringIdUsed, usageScope, storageScope, userMask);
switch ( storageScope )
{
case Chk::Scope::Game:
str->unmarkUnstoredStrings(stringIdUsed);
break;
case Chk::Scope::Editor:
kstr->unmarkUnstoredStrings(stringIdUsed);
break;
case Chk::Scope::Either:
{
size_t limit = std::min(std::min((size_t)Chk::MaxStrings, str->getCapacity()), kstr->getCapacity());
size_t stringId = 1;
for ( ; stringId < limit; stringId++ )
{
if ( stringIdUsed[stringId] && !str->stringStored(stringId) && !kstr->stringStored(stringId) )
stringIdUsed[stringId] = false;
}
if ( str->getCapacity() > kstr->getCapacity() )
{
for ( ; stringId < str->getCapacity(); stringId++ )
{
if ( stringIdUsed[stringId] && !str->stringStored(stringId) )
stringIdUsed[stringId] = false;
}
}
else if ( kstr->getCapacity() > str->getCapacity() )
{
for ( ; stringId < kstr->getCapacity(); stringId++ )
{
if ( stringIdUsed[stringId] && !kstr->stringStored(stringId) )
stringIdUsed[stringId] = false;
}
}
for ( ; stringId < Chk::MaxStrings; stringId++ )
{
if ( stringIdUsed[stringId] )
stringIdUsed[stringId] = false;
}
}
break;
}
}
StrProp Strings::getProperties(size_t editorStringId) const
{
return kstr != nullptr ? kstr->getProperties(editorStringId) : StrProp();
}
void Strings::setProperties(size_t editorStringId, const StrProp & strProp)
{
if ( kstr != nullptr )
kstr->setProperties(editorStringId, strProp);
}
template <typename StringType>
std::shared_ptr<StringType> Strings::getString(size_t stringId, Chk::Scope storageScope) const
{
switch ( storageScope )
{
case Chk::Scope::Either:
case Chk::Scope::EditorOverGame:
{
std::shared_ptr<StringType> editorResult = kstr->getString<StringType>(stringId);
return editorResult != nullptr ? editorResult : str->getString<StringType>(stringId) ;
}
case Chk::Scope::Game: return str->getString<StringType>(stringId);
case Chk::Scope::Editor: return kstr->getString<StringType>(stringId);
case Chk::Scope::GameOverEditor:
{
std::shared_ptr<StringType> gameResult = str->getString<StringType>(stringId);
return gameResult != nullptr ? gameResult : kstr->getString<StringType>(stringId) ;
}
default: return nullptr;
}
}
template std::shared_ptr<RawString> Strings::getString<RawString>(size_t stringId, Chk::Scope storageScope) const;
template std::shared_ptr<EscString> Strings::getString<EscString>(size_t stringId, Chk::Scope storageScope) const;
template std::shared_ptr<ChkdString> Strings::getString<ChkdString>(size_t stringId, Chk::Scope storageScope) const;
template std::shared_ptr<SingleLineChkdString> Strings::getString<SingleLineChkdString>(size_t stringId, Chk::Scope storageScope) const;
template <typename StringType>
size_t Strings::findString(const StringType & str, Chk::Scope storageScope) const
{
switch ( storageScope )
{
case Chk::Scope::Game: return this->str->findString<StringType>(str);
case Chk::Scope::Editor: return kstr->findString<StringType>(str);
case Chk::Scope::GameOverEditor:
case Chk::Scope::Either:
{
size_t gameResult = this->str->findString<StringType>(str);
return gameResult != Chk::StringId::NoString ? gameResult : kstr->findString<StringType>(str);
}
case Chk::Scope::EditorOverGame:
{
size_t editorResult = kstr->findString<StringType>(str);
return editorResult != Chk::StringId::NoString ? editorResult : this->str->findString<StringType>(str);
}
}
return (size_t)Chk::StringId::NoString;
}
template size_t Strings::findString<RawString>(const RawString & str, Chk::Scope storageScope) const;
template size_t Strings::findString<EscString>(const EscString & str, Chk::Scope storageScope) const;
template size_t Strings::findString<ChkdString>(const ChkdString & str, Chk::Scope storageScope) const;
template size_t Strings::findString<SingleLineChkdString>(const SingleLineChkdString & str, Chk::Scope storageScope) const;
void Strings::setCapacity(size_t stringCapacity, Chk::Scope storageScope, bool autoDefragment)
{
if ( storageScope == Chk::Scope::Game )
str->setCapacity(stringCapacity, *this, autoDefragment);
else if ( storageScope == Chk::Scope::Editor )
kstr->setCapacity(stringCapacity, *this, autoDefragment);
}
template <typename StringType>
size_t Strings::addString(const StringType & str, Chk::Scope storageScope, bool autoDefragment)
{
if ( storageScope == Chk::Scope::Game )
return this->str->addString<StringType>(str, *this, autoDefragment);
else if ( storageScope == Chk::Scope::Editor )
return kstr->addString<StringType>(str, *this, autoDefragment);
return (size_t)Chk::StringId::NoString;
}
template size_t Strings::addString<RawString>(const RawString & str, Chk::Scope storageScope, bool autoDefragment);
template size_t Strings::addString<EscString>(const EscString & str, Chk::Scope storageScope, bool autoDefragment);
template size_t Strings::addString<ChkdString>(const ChkdString & str, Chk::Scope storageScope, bool autoDefragment);
template size_t Strings::addString<SingleLineChkdString>(const SingleLineChkdString & str, Chk::Scope storageScope, bool autoDefragment);
template <typename StringType>
void Strings::replaceString(size_t stringId, const StringType & str, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Game )
this->str->replaceString<StringType>(stringId, str);
else if ( storageScope == Chk::Scope::Editor )
kstr->replaceString<StringType>(stringId, str);
}
template void Strings::replaceString<RawString>(size_t stringId, const RawString & str, Chk::Scope storageScope);
template void Strings::replaceString<EscString>(size_t stringId, const EscString & str, Chk::Scope storageScope);
template void Strings::replaceString<ChkdString>(size_t stringId, const ChkdString & str, Chk::Scope storageScope);
template void Strings::replaceString<SingleLineChkdString>(size_t stringId, const SingleLineChkdString & str, Chk::Scope storageScope);
void Strings::deleteUnusedStrings(Chk::Scope storageScope)
{
switch ( storageScope )
{
case Chk::Scope::Game: str->deleteUnusedStrings(*this); break;
case Chk::Scope::Editor: kstr->deleteUnusedStrings(*this); break;
case Chk::Scope::Both: str->deleteUnusedStrings(*this); kstr->deleteUnusedStrings(*this); break;
}
}
void Strings::deleteString(size_t stringId, Chk::Scope storageScope, bool deleteOnlyIfUnused)
{
if ( (storageScope & Chk::Scope::Game) == Chk::Scope::Game )
{
if ( !deleteOnlyIfUnused || !stringUsed(stringId, Chk::Scope::Game) )
{
str->deleteString(stringId, deleteOnlyIfUnused, std::shared_ptr<StrSynchronizer>(this, [](StrSynchronizer*){}));
sprp->deleteString(stringId);
players->deleteString(stringId);
properties->deleteString(stringId);
layers->deleteString(stringId);
triggers->deleteString(stringId, Chk::Scope::Game);
}
}
if ( (storageScope & Chk::Scope::Editor) == Chk::Scope::Editor )
{
if ( !deleteOnlyIfUnused || !stringUsed(stringId, Chk::Scope::Either, Chk::Scope::Editor, Chk::StringUserFlag::All, true) )
{
kstr->deleteString(stringId, deleteOnlyIfUnused, std::shared_ptr<StrSynchronizer>(this, [](StrSynchronizer*){}));
ostr->deleteString(stringId);
triggers->deleteString(stringId, Chk::Scope::Editor);
}
}
}
void Strings::moveString(size_t stringIdFrom, size_t stringIdTo, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Game )
str->moveString(stringIdFrom, stringIdTo, *this);
else if ( storageScope == Chk::Scope::Editor )
kstr->moveString(stringIdFrom, stringIdTo, *this);
}
size_t Strings::rescopeString(size_t stringId, Chk::Scope changeStorageScopeTo, bool autoDefragment)
{
if ( changeStorageScopeTo == Chk::Scope::Editor && stringUsed(stringId, Chk::Scope::Either, Chk::Scope::Game, Chk::StringUserFlag::All, true) )
{
RawStringPtr toRescope = getString<RawString>(stringId, Chk::Scope::Game);
size_t newStringId = addString<RawString>(*toRescope, Chk::Scope::Editor, autoDefragment);
if ( newStringId != 0 )
{
std::set<u32> stringIdsReplaced;
if ( stringId == sprp->getScenarioNameStringId() )
{
stringIdsReplaced.insert(ostr->getScenarioNameStringId());
ostr->setScenarioNameStringId((u32)newStringId);
}
if ( stringId == sprp->getScenarioDescriptionStringId() )
{
stringIdsReplaced.insert(ostr->getScenarioDescriptionStringId());
ostr->setScenarioDescriptionStringId((u32)newStringId);
}
for ( size_t i=0; i<Chk::TotalForces; i++ )
{
if ( stringId == players->getForceStringId((Chk::Force)i) )
{
stringIdsReplaced.insert(ostr->getForceNameStringId((Chk::Force)i));
ostr->setForceNameStringId((Chk::Force)i, (u32)newStringId);
}
}
for ( size_t i=0; i<Sc::Unit::TotalTypes; i++ )
{
if ( stringId == properties->getUnitNameStringId((Sc::Unit::Type)i, Chk::UseExpSection::No) )
{
stringIdsReplaced.insert(ostr->getUnitNameStringId((Sc::Unit::Type)i));
ostr->setUnitNameStringId((Sc::Unit::Type)i, (u32)newStringId);
}
}
for ( size_t i=0; i<Sc::Unit::TotalTypes; i++ )
{
if ( stringId == properties->getUnitNameStringId((Sc::Unit::Type)i, Chk::UseExpSection::Yes) )
{
stringIdsReplaced.insert(ostr->getExpUnitNameStringId((Sc::Unit::Type)i));
ostr->setExpUnitNameStringId((Sc::Unit::Type)i, (u32)newStringId);
}
}
for ( size_t i=0; i<Chk::TotalSounds; i++ )
{
if ( stringId == triggers->getSoundStringId(i) )
{
stringIdsReplaced.insert(ostr->getSoundPathStringId(i));
ostr->setSoundPathStringId(i, (u32)newStringId);
}
}
for ( size_t i=0; i<Chk::TotalSwitches; i++ )
{
if ( stringId == triggers->getSwitchNameStringId(i) )
{
stringIdsReplaced.insert(ostr->getSwitchNameStringId(i));
ostr->setSwitchNameStringId(i, (u32)newStringId);
}
}
size_t numLocations = layers->numLocations();
for ( size_t i=1; i<=numLocations; i++ )
{
if ( stringId == layers->getLocation(i)->stringId )
{
stringIdsReplaced.insert(ostr->getLocationNameStringId(i));
ostr->setLocationNameStringId(i, (u32)newStringId);
}
}
deleteString(stringId, Chk::Scope::Game, false);
for ( auto stringIdReplaced : stringIdsReplaced )
deleteString(stringIdReplaced, Chk::Scope::Editor, true);
}
}
else if ( changeStorageScopeTo == Chk::Scope::Game && stringUsed(stringId, Chk::Scope::Either, Chk::Scope::Editor, Chk::StringUserFlag::All, true) )
{
RawStringPtr toRescope = getString<RawString>(stringId, Chk::Scope::Editor);
size_t newStringId = addString<RawString>(*toRescope, Chk::Scope::Game, autoDefragment);
if ( newStringId != 0 )
{
std::set<u32> stringIdsReplaced;
if ( stringId == ostr->getScenarioNameStringId() )
{
stringIdsReplaced.insert((u32)sprp->getScenarioNameStringId());
sprp->setScenarioNameStringId((u16)newStringId);
}
if ( stringId == ostr->getScenarioDescriptionStringId() )
{
stringIdsReplaced.insert((u32)sprp->getScenarioDescriptionStringId());
sprp->setScenarioDescriptionStringId((u16)newStringId);
}
for ( size_t i=0; i<Chk::TotalForces; i++ )
{
if ( stringId == ostr->getForceNameStringId((Chk::Force)i) )
{
stringIdsReplaced.insert((u32)players->getForceStringId((Chk::Force)i));
players->setForceStringId((Chk::Force)i, (u16)newStringId);
}
}
for ( size_t i=0; i<Sc::Unit::TotalTypes; i++ )
{
if ( stringId == ostr->getUnitNameStringId((Sc::Unit::Type)i) )
{
stringIdsReplaced.insert((u32)properties->getUnitNameStringId((Sc::Unit::Type)i, Chk::UseExpSection::No));
properties->setUnitNameStringId((Sc::Unit::Type)i, newStringId, Chk::UseExpSection::No);
}
}
for ( size_t i=0; i<Sc::Unit::TotalTypes; i++ )
{
if ( stringId == ostr->getExpUnitNameStringId((Sc::Unit::Type)i) )
{
stringIdsReplaced.insert((u32)properties->getUnitNameStringId((Sc::Unit::Type)i, Chk::UseExpSection::Yes));
properties->setUnitNameStringId((Sc::Unit::Type)i, newStringId, Chk::UseExpSection::Yes);
}
}
for ( size_t i=0; i<Chk::TotalSounds; i++ )
{
if ( stringId == ostr->getSoundPathStringId(i) )
{
stringIdsReplaced.insert((u32)triggers->getSoundStringId(i));
triggers->setSoundStringId(i, newStringId);
}
}
for ( size_t i=0; i<Chk::TotalSwitches; i++ )
{
if ( stringId == ostr->getSwitchNameStringId(i) )
{
stringIdsReplaced.insert((u32)triggers->getSwitchNameStringId(i));
triggers->setSwitchNameStringId(i, newStringId);
}
}
size_t numLocations = layers->numLocations();
for ( size_t i=1; i<=numLocations; i++ )
{
if ( stringId == ostr->getLocationNameStringId(i) )
{
Chk::LocationPtr location = layers->getLocation(i);
stringIdsReplaced.insert(location->stringId);
location->stringId = (u16)newStringId;
}
}
deleteString(stringId, Chk::Scope::Editor, false);
for ( auto stringIdReplaced : stringIdsReplaced )
deleteString(stringIdReplaced, Chk::Scope::Game, true);
}
}
return 0;
}
std::vector<u8> & Strings::getTailData() const
{
return str->getTailData();
}
size_t Strings::getTailDataOffset()
{
return str->getTailDataOffset(*this);
}
size_t Strings::getInitialTailDataOffset() const
{
return str->getInitialTailDataOffset();
}
size_t Strings::getBytePaddedTo() const
{
return str->getBytePaddedTo();
}
void Strings::setBytePaddedTo(size_t bytePaddedTo) const
{
str->setBytePaddedTo(bytePaddedTo);
}
size_t Strings::getScenarioNameStringId(Chk::Scope storageScope) const
{
return storageScope == Chk::Scope::Editor ? ostr->getScenarioNameStringId() : sprp->getScenarioNameStringId();
}
size_t Strings::getScenarioDescriptionStringId(Chk::Scope storageScope) const
{
return storageScope == Chk::Scope::Editor ? ostr->getScenarioDescriptionStringId() : sprp->getScenarioDescriptionStringId();
}
size_t Strings::getForceNameStringId(Chk::Force force, Chk::Scope storageScope) const
{
return storageScope == Chk::Scope::Editor ? ostr->getForceNameStringId(force) : players->getForceStringId(force);
}
size_t Strings::getUnitNameStringId(Sc::Unit::Type unitType, Chk::UseExpSection useExp, Chk::Scope storageScope) const
{
if ( storageScope == Chk::Scope::Game )
return properties->getUnitNameStringId(unitType, useExp);
else if ( storageScope == Chk::Scope::Editor )
{
switch ( useExp )
{
case Chk::UseExpSection::Auto: return versions->isHybridOrAbove() ? ostr->getExpUnitNameStringId(unitType) : ostr->getUnitNameStringId(unitType);
case Chk::UseExpSection::Yes: return ostr->getExpUnitNameStringId(unitType);
case Chk::UseExpSection::No: return ostr->getUnitNameStringId(unitType);
case Chk::UseExpSection::YesIfAvailable: return ostr->getExpUnitNameStringId(unitType) != 0 ? ostr->getExpUnitNameStringId(unitType) : ostr->getUnitNameStringId(unitType);
case Chk::UseExpSection::NoIfOrigAvailable: return ostr->getUnitNameStringId(unitType) != 0 ? ostr->getUnitNameStringId(unitType) : ostr->getExpUnitNameStringId(unitType);
}
}
return 0;
}
size_t Strings::getSoundPathStringId(size_t soundIndex, Chk::Scope storageScope) const
{
return storageScope == Chk::Scope::Editor ? ostr->getSoundPathStringId(soundIndex) : triggers->getSoundStringId(soundIndex);
}
size_t Strings::getSwitchNameStringId(size_t switchIndex, Chk::Scope storageScope) const
{
return storageScope == Chk::Scope::Editor ? ostr->getSwitchNameStringId(switchIndex) : triggers->getSwitchNameStringId(switchIndex);
}
size_t Strings::getLocationNameStringId(size_t locationId, Chk::Scope storageScope) const
{
if ( storageScope == Chk::Scope::Editor )
return ostr->getLocationNameStringId(locationId);
else
{
Chk::LocationPtr location = layers->getLocation(locationId);
return location != nullptr ? location->stringId : 0;
}
}
void Strings::setScenarioNameStringId(size_t scenarioNameStringId, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Editor )
ostr->setScenarioNameStringId((u32)scenarioNameStringId);
else
sprp->setScenarioNameStringId((u16)scenarioNameStringId);
}
void Strings::setScenarioDescriptionStringId(size_t scenarioDescriptionStringId, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Editor )
ostr->setScenarioDescriptionStringId((u32)scenarioDescriptionStringId);
else
sprp->setScenarioDescriptionStringId((u16)scenarioDescriptionStringId);
}
void Strings::setForceNameStringId(Chk::Force force, size_t forceNameStringId, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Editor )
ostr->setForceNameStringId(force, (u32)forceNameStringId);
else
players->setForceStringId(force, (u16)forceNameStringId);
}
void Strings::setUnitNameStringId(Sc::Unit::Type unitType, size_t unitNameStringId, Chk::UseExpSection useExp, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Game )
properties->setUnitNameStringId(unitType, unitNameStringId, useExp);
else
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both: ostr->setUnitNameStringId(unitType, (u32)unitNameStringId); ostr->setExpUnitNameStringId(unitType, (u32)unitNameStringId); break;
case Chk::UseExpSection::YesIfAvailable:
case Chk::UseExpSection::Yes: ostr->setExpUnitNameStringId(unitType, (u32)unitNameStringId); break;
case Chk::UseExpSection::NoIfOrigAvailable:
case Chk::UseExpSection::No: ostr->setUnitNameStringId(unitType, (u32)unitNameStringId); break;
}
}
}
void Strings::setSoundPathStringId(size_t soundIndex, size_t soundPathStringId, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Editor )
ostr->setSoundPathStringId(soundIndex, (u32)soundPathStringId);
else
triggers->setSoundStringId(soundIndex, (u32)soundPathStringId);
}
void Strings::setSwitchNameStringId(size_t switchIndex, size_t switchNameStringId, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Editor )
ostr->setSwitchNameStringId(switchIndex, (u32)switchNameStringId);
else
triggers->setSwitchNameStringId(switchIndex, (u32)switchNameStringId);
}
void Strings::setLocationNameStringId(size_t locationId, size_t locationNameStringId, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Editor )
ostr->setLocationNameStringId(locationId, (u32)locationNameStringId);
else
{
auto location = layers->getLocation(locationId);
if ( location != nullptr )
location->stringId = (u16)locationNameStringId;
}
}
template <typename StringType> // Strings may be RawString (no escaping), EscString (C++ style \r\r escape characters) or ChkString (Editor <01>Style)
std::shared_ptr<StringType> Strings::getString(size_t gameStringId, size_t editorStringId, Chk::Scope storageScope) const
{
switch ( storageScope )
{
case Chk::Scope::Game: return getString<StringType>(gameStringId, Chk::Scope::Game);
case Chk::Scope::Editor: return getString<StringType>(editorStringId, Chk::Scope::Editor);
case Chk::Scope::GameOverEditor: return gameStringId != 0 ? getString<StringType>(gameStringId, Chk::Scope::Game) : getString<StringType>(editorStringId, Chk::Scope::Editor);
case Chk::Scope::Either:
case Chk::Scope::EditorOverGame: return editorStringId != 0 ? getString<StringType>(editorStringId, Chk::Scope::Editor) : getString<StringType>(gameStringId, Chk::Scope::Game);
}
return nullptr;
}
template std::shared_ptr<RawString> Strings::getString<RawString>(size_t gameStringId, size_t editorStringId, Chk::Scope storageScope) const;
template std::shared_ptr<EscString> Strings::getString<EscString>(size_t gameStringId, size_t editorStringId, Chk::Scope storageScope) const;
template std::shared_ptr<ChkdString> Strings::getString<ChkdString>(size_t gameStringId, size_t editorStringId, Chk::Scope storageScope) const;
template std::shared_ptr<SingleLineChkdString> Strings::getString<SingleLineChkdString>(size_t gameStringId, size_t editorStringId, Chk::Scope storageScope) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getScenarioName(Chk::Scope storageScope) const
{
return getString<StringType>(sprp->getScenarioNameStringId(), ostr->getScenarioNameStringId(), storageScope);
}
template std::shared_ptr<RawString> Strings::getScenarioName<RawString>(Chk::Scope storageScope) const;
template std::shared_ptr<EscString> Strings::getScenarioName<EscString>(Chk::Scope storageScope) const;
template std::shared_ptr<ChkdString> Strings::getScenarioName<ChkdString>(Chk::Scope storageScope) const;
template std::shared_ptr<SingleLineChkdString> Strings::getScenarioName<SingleLineChkdString>(Chk::Scope storageScope) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getScenarioDescription(Chk::Scope storageScope) const
{
return getString<StringType>(sprp->getScenarioDescriptionStringId(), ostr->getScenarioDescriptionStringId(), storageScope);
}
template std::shared_ptr<RawString> Strings::getScenarioDescription<RawString>(Chk::Scope storageScope) const;
template std::shared_ptr<EscString> Strings::getScenarioDescription<EscString>(Chk::Scope storageScope) const;
template std::shared_ptr<ChkdString> Strings::getScenarioDescription<ChkdString>(Chk::Scope storageScope) const;
template std::shared_ptr<SingleLineChkdString> Strings::getScenarioDescription<SingleLineChkdString>(Chk::Scope storageScope) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getForceName(Chk::Force force, Chk::Scope storageScope) const
{
return getString<StringType>(players->getForceStringId(force), ostr->getForceNameStringId(force), storageScope);
}
template std::shared_ptr<RawString> Strings::getForceName<RawString>(Chk::Force force, Chk::Scope storageScope) const;
template std::shared_ptr<EscString> Strings::getForceName<EscString>(Chk::Force force, Chk::Scope storageScope) const;
template std::shared_ptr<ChkdString> Strings::getForceName<ChkdString>(Chk::Force force, Chk::Scope storageScope) const;
template std::shared_ptr<SingleLineChkdString> Strings::getForceName<SingleLineChkdString>(Chk::Force force, Chk::Scope storageScope) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getUnitName(Sc::Unit::Type unitType, bool defaultIfNull, Chk::UseExpSection useExp, Chk::Scope storageScope) const
{
std::shared_ptr<StringType> mapUnitName = unitType < Sc::Unit::TotalTypes ? getString<StringType>(
properties->getUnitNameStringId(unitType, useExp),
properties->useExpansionUnitSettings(useExp) ? ostr->getExpUnitNameStringId(unitType) : ostr->getUnitNameStringId(unitType),
storageScope) : nullptr;
if ( mapUnitName != nullptr )
return mapUnitName;
else if ( unitType < Sc::Unit::TotalTypes )
return std::shared_ptr<StringType>(new StringType(Sc::Unit::defaultDisplayNames[unitType]));
else
return std::shared_ptr<StringType>(new StringType("ID:" + std::to_string(unitType)));
}
template std::shared_ptr<RawString> Strings::getUnitName<RawString>(Sc::Unit::Type unitType, bool defaultIfNull, Chk::UseExpSection useExp, Chk::Scope storageScope) const;
template std::shared_ptr<EscString> Strings::getUnitName<EscString>(Sc::Unit::Type unitType, bool defaultIfNull, Chk::UseExpSection useExp, Chk::Scope storageScope) const;
template std::shared_ptr<ChkdString> Strings::getUnitName<ChkdString>(Sc::Unit::Type unitType, bool defaultIfNull, Chk::UseExpSection useExp, Chk::Scope storageScope) const;
template std::shared_ptr<SingleLineChkdString> Strings::getUnitName<SingleLineChkdString>(Sc::Unit::Type unitType, bool defaultIfNull, Chk::UseExpSection useExp, Chk::Scope storageScope) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getSoundPath(size_t soundIndex, Chk::Scope storageScope) const
{
return getString<StringType>(triggers->getSoundStringId(soundIndex), ostr->getSoundPathStringId(soundIndex), storageScope);
}
template std::shared_ptr<RawString> Strings::getSoundPath<RawString>(size_t soundIndex, Chk::Scope storageScope) const;
template std::shared_ptr<EscString> Strings::getSoundPath<EscString>(size_t soundIndex, Chk::Scope storageScope) const;
template std::shared_ptr<ChkdString> Strings::getSoundPath<ChkdString>(size_t soundIndex, Chk::Scope storageScope) const;
template std::shared_ptr<SingleLineChkdString> Strings::getSoundPath<SingleLineChkdString>(size_t soundIndex, Chk::Scope storageScope) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getSwitchName(size_t switchIndex, Chk::Scope storageScope) const
{
return getString<StringType>(triggers->getSwitchNameStringId(switchIndex), ostr->getSwitchNameStringId(switchIndex), storageScope);
}
template std::shared_ptr<RawString> Strings::getSwitchName<RawString>(size_t switchIndex, Chk::Scope storageScope) const;
template std::shared_ptr<EscString> Strings::getSwitchName<EscString>(size_t switchIndex, Chk::Scope storageScope) const;
template std::shared_ptr<ChkdString> Strings::getSwitchName<ChkdString>(size_t switchIndex, Chk::Scope storageScope) const;
template std::shared_ptr<SingleLineChkdString> Strings::getSwitchName<SingleLineChkdString>(size_t switchIndex, Chk::Scope storageScope) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getLocationName(size_t locationId, Chk::Scope storageScope) const
{
return getString<StringType>((locationId > 0 && locationId <= layers->numLocations() ? layers->getLocation(locationId)->stringId : 0), ostr->getLocationNameStringId(locationId), storageScope);
}
template std::shared_ptr<RawString> Strings::getLocationName<RawString>(size_t locationId, Chk::Scope storageScope) const;
template std::shared_ptr<EscString> Strings::getLocationName<EscString>(size_t locationId, Chk::Scope storageScope) const;
template std::shared_ptr<ChkdString> Strings::getLocationName<ChkdString>(size_t locationId, Chk::Scope storageScope) const;
template std::shared_ptr<SingleLineChkdString> Strings::getLocationName<SingleLineChkdString>(size_t locationId, Chk::Scope storageScope) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getComment(size_t triggerIndex) const
{
return getString<StringType>(triggers->getCommentStringId(triggerIndex), Chk::Scope::Game);
}
template std::shared_ptr<RawString> Strings::getComment<RawString>(size_t triggerIndex) const;
template std::shared_ptr<EscString> Strings::getComment<EscString>(size_t triggerIndex) const;
template std::shared_ptr<ChkdString> Strings::getComment<ChkdString>(size_t triggerIndex) const;
template std::shared_ptr<SingleLineChkdString> Strings::getComment<SingleLineChkdString>(size_t triggerIndex) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getExtendedComment(size_t triggerIndex) const
{
return getString<StringType>(triggers->getExtendedCommentStringId(triggerIndex), Chk::Scope::Editor);
}
template std::shared_ptr<RawString> Strings::getExtendedComment<RawString>(size_t triggerIndex) const;
template std::shared_ptr<EscString> Strings::getExtendedComment<EscString>(size_t triggerIndex) const;
template std::shared_ptr<ChkdString> Strings::getExtendedComment<ChkdString>(size_t triggerIndex) const;
template std::shared_ptr<SingleLineChkdString> Strings::getExtendedComment<SingleLineChkdString>(size_t triggerIndex) const;
template <typename StringType>
std::shared_ptr<StringType> Strings::getExtendedNotes(size_t triggerIndex) const
{
return getString<StringType>(triggers->getExtendedNotesStringId(triggerIndex), Chk::Scope::Editor);
}
template std::shared_ptr<RawString> Strings::getExtendedNotes<RawString>(size_t triggerIndex) const;
template std::shared_ptr<EscString> Strings::getExtendedNotes<EscString>(size_t triggerIndex) const;
template std::shared_ptr<ChkdString> Strings::getExtendedNotes<ChkdString>(size_t triggerIndex) const;
template std::shared_ptr<SingleLineChkdString> Strings::getExtendedNotes<SingleLineChkdString>(size_t triggerIndex) const;
template <typename StringType>
void Strings::setScenarioName(const StringType & scenarioNameString, Chk::Scope storageScope, bool autoDefragment)
{
if ( storageScope == Chk::Scope::Game || storageScope == Chk::Scope::Editor )
{
size_t newStringId = addString<StringType>(scenarioNameString, storageScope, autoDefragment);
if ( newStringId != (size_t)Chk::StringId::NoString )
{
if ( storageScope == Chk::Scope::Game )
sprp->setScenarioNameStringId((u16)newStringId);
else if ( storageScope == Chk::Scope::Editor )
ostr->setScenarioNameStringId((u32)newStringId);
}
}
}
template void Strings::setScenarioName<RawString>(const RawString & scenarioNameString, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setScenarioName<EscString>(const EscString & scenarioNameString, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setScenarioName<ChkdString>(const ChkdString & scenarioNameString, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setScenarioName<SingleLineChkdString>(const SingleLineChkdString & scenarioNameString, Chk::Scope storageScope, bool autoDefragment);
template <typename StringType>
void Strings::setScenarioDescription(const StringType & scenarioDescription, Chk::Scope storageScope, bool autoDefragment)
{
if ( storageScope == Chk::Scope::Game || storageScope == Chk::Scope::Editor )
{
size_t newStringId = addString<StringType>(scenarioDescription, storageScope, autoDefragment);
if ( newStringId != (size_t)Chk::StringId::NoString )
{
if ( storageScope == Chk::Scope::Game )
sprp->setScenarioDescriptionStringId((u16)newStringId);
else if ( storageScope == Chk::Scope::Editor )
ostr->setScenarioDescriptionStringId((u32)newStringId);
}
}
}
template void Strings::setScenarioDescription<RawString>(const RawString & scenarioNameString, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setScenarioDescription<EscString>(const EscString & scenarioNameString, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setScenarioDescription<ChkdString>(const ChkdString & scenarioNameString, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setScenarioDescription<SingleLineChkdString>(const SingleLineChkdString & scenarioNameString, Chk::Scope storageScope, bool autoDefragment);
template <typename StringType>
void Strings::setForceName(Chk::Force force, const StringType & forceName, Chk::Scope storageScope, bool autoDefragment)
{
if ( (storageScope == Chk::Scope::Game || storageScope == Chk::Scope::Editor) && (u32)force < Chk::TotalForces )
{
size_t newStringId = addString<StringType>(forceName, storageScope, autoDefragment);
if ( newStringId != (size_t)Chk::StringId::NoString )
{
if ( storageScope == Chk::Scope::Game )
players->setForceStringId(force, (u16)newStringId);
else if ( storageScope == Chk::Scope::Editor )
ostr->setForceNameStringId(force, (u32)newStringId);
}
}
}
template void Strings::setForceName<RawString>(Chk::Force force, const RawString & forceName, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setForceName<EscString>(Chk::Force force, const EscString & forceName, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setForceName<ChkdString>(Chk::Force force, const ChkdString & forceName, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setForceName<SingleLineChkdString>(Chk::Force force, const SingleLineChkdString & forceName, Chk::Scope storageScope, bool autoDefragment);
template <typename StringType>
void Strings::setUnitName(Sc::Unit::Type unitType, const StringType & unitName, Chk::UseExpSection useExp, Chk::Scope storageScope, bool autoDefragment)
{
if ( (storageScope == Chk::Scope::Game || storageScope == Chk::Scope::Editor) && unitType < Sc::Unit::TotalTypes )
{
size_t newStringId = addString<StringType>(unitName, storageScope, autoDefragment);
if ( newStringId != (size_t)Chk::StringId::NoString )
{
if ( storageScope == Chk::Scope::Game )
properties->setUnitNameStringId(unitType, newStringId, useExp);
else if ( storageScope == Chk::Scope::Editor )
{
switch ( useExp )
{
case Chk::UseExpSection::Auto: versions->isHybridOrAbove() ? ostr->setExpUnitNameStringId(unitType, (u32)newStringId) : ostr->setUnitNameStringId(unitType, (u32)newStringId); break;
case Chk::UseExpSection::Yes: ostr->setExpUnitNameStringId(unitType, (u32)newStringId); break;
case Chk::UseExpSection::No: ostr->setUnitNameStringId(unitType, (u32)newStringId); break;
default: ostr->setUnitNameStringId(unitType, (u32)newStringId); ostr->setExpUnitNameStringId(unitType, (u32)newStringId); break;
}
}
}
}
}
template void Strings::setUnitName<RawString>(Sc::Unit::Type unitType, const RawString & unitName, Chk::UseExpSection useExp, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setUnitName<EscString>(Sc::Unit::Type unitType, const EscString & unitName, Chk::UseExpSection useExp, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setUnitName<ChkdString>(Sc::Unit::Type unitType, const ChkdString & unitName, Chk::UseExpSection useExp, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setUnitName<SingleLineChkdString>(Sc::Unit::Type unitType, const SingleLineChkdString & unitName, Chk::UseExpSection useExp, Chk::Scope storageScope, bool autoDefragment);
template <typename StringType>
void Strings::setSoundPath(size_t soundIndex, const StringType & soundPath, Chk::Scope storageScope, bool autoDefragment)
{
if ( storageScope == Chk::Scope::Game || storageScope == Chk::Scope::Editor && soundIndex < Chk::TotalSounds )
{
size_t newStringId = addString<StringType>(soundPath, storageScope, autoDefragment);
if ( newStringId != (size_t)Chk::StringId::NoString )
{
if ( storageScope == Chk::Scope::Game )
triggers->setSoundStringId(soundIndex, newStringId);
else if ( storageScope == Chk::Scope::Editor )
ostr->setSoundPathStringId(soundIndex, (u32)newStringId);
}
}
}
template void Strings::setSoundPath<RawString>(size_t soundIndex, const RawString & soundPath, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setSoundPath<EscString>(size_t soundIndex, const EscString & soundPath, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setSoundPath<ChkdString>(size_t soundIndex, const ChkdString & soundPath, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setSoundPath<SingleLineChkdString>(size_t soundIndex, const SingleLineChkdString & soundPath, Chk::Scope storageScope, bool autoDefragment);
template <typename StringType>
void Strings::setSwitchName(size_t switchIndex, const StringType & switchName, Chk::Scope storageScope, bool autoDefragment)
{
if ( storageScope == Chk::Scope::Game || storageScope == Chk::Scope::Editor && switchIndex < Chk::TotalSwitches )
{
size_t newStringId = addString<StringType>(switchName, storageScope, autoDefragment);
if ( newStringId != (size_t)Chk::StringId::NoString )
{
if ( storageScope == Chk::Scope::Game )
triggers->setSwitchNameStringId(switchIndex, newStringId);
else if ( storageScope == Chk::Scope::Editor )
ostr->setSwitchNameStringId(switchIndex, (u32)newStringId);
}
}
}
template void Strings::setSwitchName<RawString>(size_t switchIndex, const RawString & switchName, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setSwitchName<EscString>(size_t switchIndex, const EscString & switchName, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setSwitchName<ChkdString>(size_t switchIndex, const ChkdString & switchName, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setSwitchName<SingleLineChkdString>(size_t switchIndex, const SingleLineChkdString & switchName, Chk::Scope storageScope, bool autoDefragment);
template <typename StringType>
void Strings::setLocationName(size_t locationId, const StringType & locationName, Chk::Scope storageScope, bool autoDefragment)
{
if ( storageScope == Chk::Scope::Game || storageScope == Chk::Scope::Editor && locationId > 0 && locationId <= layers->numLocations() )
{
size_t newStringId = addString<StringType>(locationName, storageScope, autoDefragment);
if ( newStringId != (size_t)Chk::StringId::NoString )
{
if ( storageScope == Chk::Scope::Game )
layers->getLocation(locationId)->stringId = (u16)newStringId;
else if ( storageScope == Chk::Scope::Editor )
ostr->setLocationNameStringId(locationId, (u32)newStringId);
}
}
}
template void Strings::setLocationName<RawString>(size_t locationId, const RawString & locationName, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setLocationName<EscString>(size_t locationId, const EscString & locationName, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setLocationName<ChkdString>(size_t locationId, const ChkdString & locationName, Chk::Scope storageScope, bool autoDefragment);
template void Strings::setLocationName<SingleLineChkdString>(size_t locationId, const SingleLineChkdString & locationName, Chk::Scope storageScope, bool autoDefragment);
template <typename StringType>
void Strings::setExtendedComment(size_t triggerIndex, const StringType & comment, bool autoDefragment)
{
Chk::ExtendedTrigDataPtr extension = triggers->getTriggerExtension(triggerIndex, true);
if ( extension != nullptr )
{
size_t newStringId = addString<StringType>(comment, Chk::Scope::Editor, autoDefragment);
if ( newStringId != (size_t)Chk::StringId::NoString )
extension->commentStringId = (u32)newStringId;
}
}
template void Strings::setExtendedComment<RawString>(size_t triggerIndex, const RawString & comment, bool autoDefragment);
template void Strings::setExtendedComment<EscString>(size_t triggerIndex, const EscString & comment, bool autoDefragment);
template void Strings::setExtendedComment<ChkdString>(size_t triggerIndex, const ChkdString & comment, bool autoDefragment);
template void Strings::setExtendedComment<SingleLineChkdString>(size_t triggerIndex, const SingleLineChkdString & comment, bool autoDefragment);
template <typename StringType>
void Strings::setExtendedNotes(size_t triggerIndex, const StringType & notes, bool autoDefragment)
{
Chk::ExtendedTrigDataPtr extension = triggers->getTriggerExtension(triggerIndex, true);
if ( extension != nullptr )
{
size_t newStringId = addString<StringType>(notes, Chk::Scope::Editor, autoDefragment);
if ( newStringId != (size_t)Chk::StringId::NoString )
extension->notesStringId = (u32)newStringId;
}
}
template void Strings::setExtendedNotes<RawString>(size_t triggerIndex, const RawString & notes, bool autoDefragment);
template void Strings::setExtendedNotes<EscString>(size_t triggerIndex, const EscString & notes, bool autoDefragment);
template void Strings::setExtendedNotes<ChkdString>(size_t triggerIndex, const ChkdString & notes, bool autoDefragment);
template void Strings::setExtendedNotes<SingleLineChkdString>(size_t triggerIndex, const SingleLineChkdString & notes, bool autoDefragment);
void Strings::syncStringsToBytes(std::deque<ScStrPtr> & strings, std::vector<u8> & stringBytes,
StrCompressionElevatorPtr compressionElevator, u32 requestedCompressionFlags, u32 allowedCompressionFlags)
{
/**
Uses the basic, staredit standard, STR section format, and not allowing section sizes over 65536
u16 numStrings;
u16 stringOffsets[numStrings]; // Offset of the start of the string within the section
void[] stringData; // Character data, first comes initial NUL character... then all strings, in order, each NUL terminated
*/
constexpr size_t maxStrings = (size_t(u16_max) - sizeof(u16))/sizeof(u16);
size_t numStrings = strings.size() > 0 ? strings.size()-1 : 0; // Exclude string at index 0
if ( numStrings > maxStrings )
throw MaximumStringsExceeded(ChkSection::getNameString(SectionName::STR), numStrings, maxStrings);
size_t sizeAndOffsetSpaceAndNulSpace = sizeof(u16) + sizeof(u16)*numStrings + 1;
size_t sectionSize = sizeAndOffsetSpaceAndNulSpace;
for ( size_t i=1; i<=numStrings; i++ )
{
if ( strings[i] != nullptr )
sectionSize += strings[i]->length();
}
constexpr size_t maxStandardSize = u16_max;
if ( sectionSize > maxStandardSize )
throw MaximumCharactersExceeded(ChkSection::getNameString(SectionName::STR), sectionSize-sizeAndOffsetSpaceAndNulSpace, maxStandardSize);
stringBytes.assign(sizeof(u16)+sizeof(u16)*numStrings, u8(0));
(u16 &)stringBytes[0] = (u16)numStrings;
u16 initialNulOffset = u16(stringBytes.size());
stringBytes.push_back(u8('\0')); // Add initial NUL character
for ( size_t i=1; i<=numStrings; i++ )
{
if ( strings[i] == nullptr )
(u16 &)stringBytes[sizeof(u16)*i] = initialNulOffset;
else
{
(u16 &)stringBytes[sizeof(u16)*i] = u16(stringBytes.size());
stringBytes.insert(stringBytes.end(), strings[i]->str, strings[i]->str+(strings[i]->length()+1));
}
}
}
void Strings::syncKstringsToBytes(std::deque<ScStrPtr> & strings, std::vector<u8> & stringBytes,
StrCompressionElevatorPtr compressionElevator, u32 requestedCompressionFlags, u32 allowedCompressionFlags)
{
/**
Uses the standard KSTR format
u32 version; // Current version: 2
u32 numStrings; // Number of strings in the section
u32 stringOffsets[0]; // u32 stringOffsets[numStrings]; // Offsets to each string within the string section (not within stringData, but within the whole section)
StringProperties[numStrings] stringProperties; // String properties
void[] stringData; // List of strings, each null terminated
*/
constexpr size_t maxStrings = (size_t(s32_max) - 2*sizeof(u32))/sizeof(u32);
size_t numStrings = strings.size() > 0 ? strings.size()-1 : 0; // Exclude string at index 0
if ( numStrings > maxStrings )
throw MaximumStringsExceeded(ChkSection::getNameString(SectionName::KSTR), numStrings, maxStrings);
size_t stringPropertiesStart = 2*sizeof(u32)+2*numStrings;
size_t versionAndSizeAndOffsetAndStringPropertiesAndNulSpace = 2*sizeof(u32) + 2*sizeof(u32)*numStrings + 1;
size_t sectionSize = versionAndSizeAndOffsetAndStringPropertiesAndNulSpace;
for ( size_t i=1; i<=numStrings; i++ )
{
if ( strings[i] != nullptr )
sectionSize += strings[i]->length();
}
constexpr size_t maxStandardSize = s32_max;
if ( sectionSize > maxStandardSize )
throw MaximumCharactersExceeded(ChkSection::getNameString(SectionName::KSTR), sectionSize-versionAndSizeAndOffsetAndStringPropertiesAndNulSpace, maxStandardSize);
stringBytes.assign(2*sizeof(u32)+2*sizeof(u32)*numStrings, u8(0));
(u32 &)stringBytes[0] = Chk::KSTR::CurrentVersion;
(u32 &)stringBytes[sizeof(u32)] = (u32)numStrings;
u32 initialNulOffset = u32(stringBytes.size());
stringBytes.push_back(u8('\0')); // Add initial NUL character
for ( size_t i=1; i<=numStrings; i++ )
{
if ( strings[i] == nullptr )
(u32 &)stringBytes[sizeof(u32)+sizeof(u32)*i] = initialNulOffset;
else
{
auto prop = strings[i]->properties();
(u32 &)stringBytes[stringPropertiesStart+sizeof(u32)*i] = (u32 &)Chk::StringProperties(prop.red, prop.green, prop.blue, prop.isUsed, prop.hasPriority, prop.isBold, prop.isUnderlined, prop.isItalics, prop.size);
(u32 &)stringBytes[sizeof(u32)+sizeof(u32)*i] = u32(stringBytes.size());
stringBytes.insert(stringBytes.end(), strings[i]->str, strings[i]->str+strings[i]->length()+1);
}
}
}
const std::vector<u32> Strings::compressionFlagsProgression = {
StrCompressFlag::None,
StrCompressFlag::DuplicateStringRecycling,
StrCompressFlag::LastStringTrick,
StrCompressFlag::LastStringTrick | StrCompressFlag::DuplicateStringRecycling,
StrCompressFlag::ReverseStacking,
StrCompressFlag::ReverseStacking | StrCompressFlag::DuplicateStringRecycling,
StrCompressFlag::ReverseStacking | StrCompressFlag::LastStringTrick,
StrCompressFlag::ReverseStacking | StrCompressFlag::LastStringTrick | StrCompressFlag::DuplicateStringRecycling,
StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking,
StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking | StrCompressFlag::DuplicateStringRecycling,
StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking | StrCompressFlag::LastStringTrick,
StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking | StrCompressFlag::LastStringTrick | StrCompressFlag::DuplicateStringRecycling,
StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking,
StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking | StrCompressFlag::DuplicateStringRecycling,
StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking | StrCompressFlag::LastStringTrick,
StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking | StrCompressFlag::LastStringTrick | StrCompressFlag::DuplicateStringRecycling,
StrCompressFlag::SubStringRecycling,
StrCompressFlag::SubStringRecycling | StrCompressFlag::LastStringTrick,
StrCompressFlag::SubStringRecycling | StrCompressFlag::ReverseStacking,
StrCompressFlag::SubStringRecycling | StrCompressFlag::ReverseStacking | StrCompressFlag::LastStringTrick,
StrCompressFlag::SubStringRecycling | StrCompressFlag::SizeBytesRecycling,
StrCompressFlag::SubStringRecycling | StrCompressFlag::SizeBytesRecycling | StrCompressFlag::LastStringTrick,
StrCompressFlag::SubStringRecycling | StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking,
StrCompressFlag::SubStringRecycling | StrCompressFlag::SizeBytesRecycling | StrCompressFlag::ReverseStacking | StrCompressFlag::LastStringTrick,
StrCompressFlag::OffsetInterlacing,
StrCompressFlag::OffsetInterlacing | StrCompressFlag::LastStringTrick,
StrCompressFlag::OffsetInterlacing | StrCompressFlag::SizeBytesRecycling,
StrCompressFlag::OffsetInterlacing | StrCompressFlag::SizeBytesRecycling | StrCompressFlag::LastStringTrick,
StrCompressFlag::OrderShuffledInterlacing,
StrCompressFlag::OrderShuffledInterlacing | StrCompressFlag::SizeBytesRecycling,
StrCompressFlag::SpareShuffledInterlacing,
StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::LastStringTrick,
StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::SizeBytesRecycling,
StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::SizeBytesRecycling | StrCompressFlag::LastStringTrick,
StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::OrderShuffledInterlacing,
StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::OrderShuffledInterlacing | StrCompressFlag::SizeBytesRecycling,
StrCompressFlag::SubShuffledInterlacing,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::LastStringTrick,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::SizeBytesRecycling,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::SizeBytesRecycling | StrCompressFlag::LastStringTrick,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::OrderShuffledInterlacing,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::OrderShuffledInterlacing | StrCompressFlag::SizeBytesRecycling,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::SpareShuffledInterlacing,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::LastStringTrick,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::SizeBytesRecycling,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::SizeBytesRecycling | StrCompressFlag::LastStringTrick,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::OrderShuffledInterlacing,
StrCompressFlag::SubShuffledInterlacing | StrCompressFlag::SpareShuffledInterlacing | StrCompressFlag::OrderShuffledInterlacing
| StrCompressFlag::SizeBytesRecycling
};
Strings::StringBackup Strings::backup() const
{
return { (str == nullptr ? nullptr : str->backup()) };
}
void Strings::restore(StringBackup & backup)
{
if ( str != nullptr )
str->restore(backup.strBackup);
}
void Strings::remapStringIds(const std::map<u32, u32> & stringIdRemappings, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Game )
{
sprp->remapStringIds(stringIdRemappings);
players->remapStringIds(stringIdRemappings);
properties->remapStringIds(stringIdRemappings);
layers->remapStringIds(stringIdRemappings);
triggers->remapStringIds(stringIdRemappings, storageScope);
}
else if ( storageScope == Chk::Scope::Editor )
{
ostr->remapStringIds(stringIdRemappings);
triggers->remapStringIds(stringIdRemappings, storageScope);
}
}
void Strings::set(std::unordered_map<SectionName, Section> & sections)
{
sprp = GetSection<SprpSection>(sections, SectionName::SPRP);
str = GetSection<StrSection>(sections, SectionName::STR);
ostr = GetSection<OstrSection>(sections, SectionName::OSTR);
kstr = GetSection<KstrSection>(sections, SectionName::KSTR);
if ( str == nullptr )
str = StrSection::GetDefault(true);
if ( ostr == nullptr )
ostr = OstrSection::GetDefault();
if ( kstr == nullptr )
kstr = KstrSection::GetDefault();
}
void Strings::clear()
{
sprp = nullptr;
str = nullptr;
ostr = nullptr;
kstr = nullptr;
}
Players::Players(bool useDefault) : strings(nullptr)
{
if ( useDefault )
{
side = SideSection::GetDefault(); // Races
colr = ColrSection::GetDefault(); // Player colors
forc = ForcSection::GetDefault(); // Forces
ownr = OwnrSection::GetDefault(); // Slot owners
iown = IownSection::GetDefault(); // Redundant slot owners
if ( iown == nullptr || ownr == nullptr || forc == nullptr || colr == nullptr || side == nullptr )
{
throw ScenarioAllocationFailure(
iown == nullptr ? ChkSection::getNameString(SectionName::IOWN) :
(ownr == nullptr ? ChkSection::getNameString(SectionName::OWNR) :
(forc == nullptr ? ChkSection::getNameString(SectionName::FORC) :
(colr == nullptr ? ChkSection::getNameString(SectionName::COLR) :
ChkSection::getNameString(SectionName::SIDE)))));
}
}
}
bool Players::empty() const
{
return side == nullptr && colr == nullptr && forc == nullptr && ownr == nullptr && iown == nullptr;
}
Sc::Player::SlotType Players::getSlotType(size_t slotIndex, Chk::Scope scope) const
{
switch ( scope )
{
case Chk::Scope::Game: return ownr->getSlotType(slotIndex);
case Chk::Scope::Editor: return iown->getSlotType(slotIndex);
case Chk::Scope::EditorOverGame: return iown != nullptr ? iown->getSlotType(slotIndex) : ownr->getSlotType(slotIndex);
default: return ownr != nullptr ? ownr->getSlotType(slotIndex) : iown->getSlotType(slotIndex);
}
return Sc::Player::SlotType::Inactive;
}
void Players::setSlotType(size_t slotIndex, Sc::Player::SlotType slotType, Chk::Scope scope)
{
switch ( scope )
{
case Chk::Scope::Game: ownr->setSlotType(slotIndex, slotType); break;
case Chk::Scope::Editor: iown->setSlotType(slotIndex, slotType); break;
default: ownr->setSlotType(slotIndex, slotType); iown->setSlotType(slotIndex, slotType); break;
}
}
Chk::Race Players::getPlayerRace(size_t playerIndex) const
{
return side->getPlayerRace(playerIndex);
}
void Players::setPlayerRace(size_t playerIndex, Chk::Race race)
{
side->setPlayerRace(playerIndex, race);
}
Chk::PlayerColor Players::getPlayerColor(size_t slotIndex) const
{
return colr->getPlayerColor(slotIndex);
}
void Players::setPlayerColor(size_t slotIndex, Chk::PlayerColor color)
{
colr->setPlayerColor(slotIndex, color);
}
Chk::Force Players::getPlayerForce(size_t slotIndex) const
{
return forc->getPlayerForce(slotIndex);
}
size_t Players::getForceStringId(Chk::Force force) const
{
return forc->getForceStringId(force);
}
u8 Players::getForceFlags(Chk::Force force) const
{
return forc->getForceFlags(force);
}
void Players::setPlayerForce(size_t slotIndex, Chk::Force force)
{
forc->setPlayerForce(slotIndex, force);
}
void Players::setForceStringId(Chk::Force force, u16 forceStringId)
{
forc->setForceStringId(force, forceStringId);
}
void Players::setForceFlags(Chk::Force force, u8 forceFlags)
{
forc->setForceFlags(force, forceFlags);
}
void Players::appendUsage(size_t stringId, std::vector<Chk::StringUser> & stringUsers, u32 userMask) const
{
if ( (userMask & Chk::StringUserFlag::Force) == Chk::StringUserFlag::Force )
forc->appendUsage(stringId, stringUsers);
}
bool Players::stringUsed(size_t stringId, u32 userMask) const
{
return (userMask & Chk::StringUserFlag::Force) == Chk::StringUserFlag::Force && forc->stringUsed(stringId);
}
void Players::markUsedStrings(std::bitset<Chk::MaxStrings> & stringIdUsed, u32 userMask) const
{
if ( (userMask & Chk::StringUserFlag::Force) == Chk::StringUserFlag::Force )
forc->markUsedStrings(stringIdUsed);
}
void Players::remapStringIds(const std::map<u32, u32> & stringIdRemappings)
{
forc->remapStringIds(stringIdRemappings);
}
void Players::deleteString(size_t stringId)
{
forc->deleteString(stringId);
}
void Players::set(std::unordered_map<SectionName, Section> & sections)
{
side = GetSection<SideSection>(sections, SectionName::SIDE);
colr = GetSection<ColrSection>(sections, SectionName::COLR);
forc = GetSection<ForcSection>(sections, SectionName::FORC);
ownr = GetSection<OwnrSection>(sections, SectionName::OWNR);
iown = GetSection<IownSection>(sections, SectionName::IOWN);
if ( colr == nullptr )
colr = ColrSection::GetDefault();
if ( iown == nullptr )
iown = IownSection::GetDefault();
}
void Players::clear()
{
side = nullptr;
colr = nullptr;
forc = nullptr;
ownr = nullptr;
iown = nullptr;
}
Terrain::Terrain()
{
}
Terrain::Terrain(Sc::Terrain::Tileset tileset, u16 width, u16 height)
{
era = EraSection::GetDefault(tileset); // Tileset
dim = DimSection::GetDefault(width, height); // Dimensions
mtxm = MtxmSection::GetDefault(width, height); // Real terrain data
tile = TileSection::GetDefault(width, height); // Intermediate terrain data
isom = IsomSection::GetDefault(width, height); // Isometric terrain data
if ( isom == nullptr || tile == nullptr || mtxm == nullptr || dim == nullptr || era == nullptr )
{
throw ScenarioAllocationFailure(
isom == nullptr ? ChkSection::getNameString(SectionName::ISOM) :
(tile == nullptr ? ChkSection::getNameString(SectionName::TILE) :
(mtxm == nullptr ? ChkSection::getNameString(SectionName::MTXM) :
(dim == nullptr ? ChkSection::getNameString(SectionName::DIM) :
ChkSection::getNameString(SectionName::ERA)))));
}
}
bool Terrain::empty() const
{
return era == nullptr && dim == nullptr && mtxm == nullptr && tile == nullptr && isom == nullptr;
}
Sc::Terrain::Tileset Terrain::getTileset() const
{
return era->getTileset();
}
void Terrain::setTileset(Sc::Terrain::Tileset tileset)
{
era->setTileset(tileset);
}
size_t Terrain::getTileWidth() const
{
return dim->getTileWidth();
}
size_t Terrain::getTileHeight() const
{
return dim->getTileHeight();
}
size_t Terrain::getPixelWidth() const
{
return dim->getPixelWidth();
}
size_t Terrain::getPixelHeight() const
{
return dim->getPixelHeight();
}
void Terrain::setTileWidth(u16 newTileWidth, s32 leftEdge)
{
u16 tileWidth = (u16)dim->getTileWidth();
u16 tileHeight = (u16)dim->getTileHeight();
isom->setDimensions(newTileWidth, tileHeight, tileWidth, tileHeight, leftEdge, 0);
tile->setDimensions(newTileWidth, tileHeight, tileWidth, tileHeight, leftEdge, 0);
mtxm->setDimensions(newTileWidth, tileHeight, tileWidth, tileHeight, leftEdge, 0);
dim->setTileWidth(tileWidth);
}
void Terrain::setTileHeight(u16 newTileHeight, s32 topEdge)
{
u16 tileWidth = (u16)dim->getTileWidth();
u16 tileHeight = (u16)dim->getTileHeight();
isom->setDimensions(tileWidth, newTileHeight, tileWidth, tileHeight, 0, topEdge);
tile->setDimensions(tileWidth, newTileHeight, tileWidth, tileHeight, 0, topEdge);
mtxm->setDimensions(tileWidth, newTileHeight, tileWidth, tileHeight, 0, topEdge);
dim->setTileHeight(tileHeight);
}
void Terrain::setDimensions(u16 newTileWidth, u16 newTileHeight, s32 leftEdge, s32 topEdge)
{
u16 tileWidth = (u16)dim->getTileWidth();
u16 tileHeight = (u16)dim->getTileHeight();
isom->setDimensions(newTileWidth, newTileHeight, tileWidth, tileHeight, leftEdge, topEdge);
tile->setDimensions(newTileWidth, newTileHeight, tileWidth, tileHeight, leftEdge, topEdge);
mtxm->setDimensions(newTileWidth, newTileHeight, tileWidth, tileHeight, leftEdge, topEdge);
dim->setDimensions(newTileWidth, newTileHeight);
}
u16 Terrain::getTile(size_t tileXc, size_t tileYc, Chk::Scope scope) const
{
size_t tileWidth = dim->getTileWidth();
size_t tileIndex = tileYc*tileWidth + tileXc;
switch ( scope )
{
case Chk::Scope::Game: return mtxm->getTile(tileIndex);
case Chk::Scope::Editor: return tile->getTile(tileIndex);
case Chk::Scope::EditorOverGame: return tile != nullptr ? tile->getTile(tileIndex) : mtxm->getTile(tileIndex);
default: return mtxm != nullptr ? mtxm->getTile(tileIndex) : tile->getTile(tileIndex);
}
return 0;
}
inline u16 Terrain::getTilePx(size_t pixelXc, size_t pixelYc, Chk::Scope scope) const
{
return getTile(pixelXc / Sc::Terrain::PixelsPerTile, pixelYc / Sc::Terrain::PixelsPerTile, scope);
}
void Terrain::setTile(size_t tileXc, size_t tileYc, u16 tileValue, Chk::Scope scope)
{
size_t tileWidth = dim->getTileWidth();
size_t tileIndex = tileYc*tileWidth + tileXc;
switch ( scope )
{
case Chk::Scope::Game: mtxm->setTile(tileIndex, tileValue); break;
case Chk::Scope::Editor: tile->setTile(tileIndex, tileValue); break;
default: mtxm->setTile(tileIndex, tileValue); tile->setTile(tileIndex, tileValue); break;
}
}
inline void Terrain::setTilePx(size_t pixelXc, size_t pixelYc, u16 tileValue, Chk::Scope scope)
{
setTile(pixelXc / Sc::Terrain::PixelsPerTile, pixelYc / Sc::Terrain::PixelsPerTile, tileValue, scope);
}
Chk::IsomEntry & Terrain::getIsomEntry(size_t isomIndex)
{
return isom->getIsomEntry(isomIndex);
}
const Chk::IsomEntry & Terrain::getIsomEntry(size_t isomIndex) const
{
return isom->getIsomEntry(isomIndex);
}
void Terrain::set(std::unordered_map<SectionName, Section> & sections)
{
era = GetSection<EraSection>(sections, SectionName::ERA);
dim = GetSection<DimSection>(sections, SectionName::DIM);
mtxm = GetSection<MtxmSection>(sections, SectionName::MTXM);
tile = GetSection<TileSection>(sections, SectionName::TILE);
isom = GetSection<IsomSection>(sections, SectionName::ISOM);
if ( dim != nullptr )
{
if ( tile == nullptr )
tile = TileSection::GetDefault((u16)dim->getTileWidth(), (u16)dim->getTileHeight());
if ( isom == nullptr )
isom = IsomSection::GetDefault((u16)dim->getTileWidth(), (u16)dim->getTileHeight());
}
}
void Terrain::clear()
{
era = nullptr;
dim = nullptr;
mtxm = nullptr;
tile = nullptr;
isom = nullptr;
}
Layers::Layers() : Terrain(), strings(nullptr), triggers(nullptr)
{
}
Layers::Layers(Sc::Terrain::Tileset tileset, u16 width, u16 height) : Terrain(tileset, width, height), strings(nullptr)
{
mask = MaskSection::GetDefault(width, height); // Fog of war
thg2 = Thg2Section::GetDefault(); // Sprites
dd2 = Dd2Section::GetDefault(); // Doodads
unit = UnitSection::GetDefault(); // Units
mrgn = MrgnSection::GetDefault(width, height); // Locations
if ( mrgn == nullptr || unit == nullptr || dd2 == nullptr || thg2 == nullptr || mask == nullptr )
{
throw ScenarioAllocationFailure(
mrgn == nullptr ? ChkSection::getNameString(SectionName::MRGN) :
(unit == nullptr ? ChkSection::getNameString(SectionName::UNIT) :
(dd2 == nullptr ? ChkSection::getNameString(SectionName::DD2) :
(thg2 == nullptr ? ChkSection::getNameString(SectionName::THG2) :
ChkSection::getNameString(SectionName::MASK)))));
}
}
bool Layers::empty() const
{
return Terrain::empty() && mask == nullptr && thg2 == nullptr && dd2 == nullptr && unit == nullptr & mrgn == nullptr;
}
void Layers::setTileWidth(u16 tileWidth, u16 sizeValidationFlags, s32 leftEdge)
{
Terrain::setTileWidth(tileWidth, leftEdge);
validateSizes(sizeValidationFlags);
}
void Layers::setTileHeight(u16 tileHeight, u16 sizeValidationFlags, s32 topEdge)
{
Terrain::setTileHeight(tileHeight, topEdge);
validateSizes(sizeValidationFlags);
}
void Layers::setDimensions(u16 tileWidth, u16 tileHeight, u16 sizeValidationFlags, s32 leftEdge, s32 topEdge)
{
Terrain::setDimensions(tileWidth, tileHeight, leftEdge, topEdge);
validateSizes(sizeValidationFlags);
}
void Layers::validateSizes(u16 sizeValidationFlags)
{
bool updateAnywhereIfAlreadyStandard = (sizeValidationFlags & SizeValidationFlag::UpdateAnywhereIfAlreadyStandard) == SizeValidationFlag::UpdateAnywhereIfAlreadyStandard;
bool updateAnywhere = (sizeValidationFlags & SizeValidationFlag::UpdateAnywhere) == SizeValidationFlag::UpdateAnywhere;
if ( (!updateAnywhereIfAlreadyStandard && updateAnywhere) || (updateAnywhereIfAlreadyStandard && anywhereIsStandardDimensions()) )
matchAnywhereToDimensions();
if ( (sizeValidationFlags & SizeValidationFlag::UpdateOutOfBoundsLocations) == SizeValidationFlag::UpdateOutOfBoundsLocations )
downsizeOutOfBoundsLocations();
if ( (sizeValidationFlags & SizeValidationFlag::RemoveOutOfBoundsDoodads) == SizeValidationFlag::RemoveOutOfBoundsDoodads )
removeOutOfBoundsDoodads();
if ( (sizeValidationFlags & SizeValidationFlag::UpdateOutOfBoundsUnits) == SizeValidationFlag::UpdateOutOfBoundsUnits )
updateOutOfBoundsUnits();
else if ( (sizeValidationFlags & SizeValidationFlag::RemoveOutOfBoundsUnits) == SizeValidationFlag::RemoveOutOfBoundsUnits )
removeOutOfBoundsUnits();
if ( (sizeValidationFlags & SizeValidationFlag::UpdateOutOfBoundsSprites) == SizeValidationFlag::UpdateOutOfBoundsSprites )
updateOutOfBoundsSprites();
else if ( (sizeValidationFlags & SizeValidationFlag::RemoveOutOfBoundsSprites) == SizeValidationFlag::RemoveOutOfBoundsSprites )
removeOutOfBoundsSprites();
}
u8 Layers::getFog(size_t tileXc, size_t tileYc) const
{
size_t tileWidth = dim->getTileWidth();
size_t tileIndex = tileWidth*tileYc + tileXc;
return mask->getFog(tileIndex);
}
u8 Layers::getFogPx(size_t pixelXc, size_t pixelYc) const
{
return getFog(pixelXc / Sc::Terrain::PixelsPerTile, pixelYc / Sc::Terrain::PixelsPerTile);
}
void Layers::setFog(size_t tileXc, size_t tileYc, u8 fogOfWarPlayers)
{
size_t tileWidth = dim->getTileWidth();
size_t tileIndex = tileWidth*tileYc + tileXc;
mask->setFog(tileIndex, fogOfWarPlayers);
}
void Layers::setFogPx(size_t pixelXc, size_t pixelYc, u8 fogOfWarPlayers)
{
setFog(pixelXc / Sc::Terrain::PixelsPerTile, pixelYc / Sc::Terrain::PixelsPerTile, fogOfWarPlayers);
}
size_t Layers::numSprites() const
{
return thg2->numSprites();
}
std::shared_ptr<Chk::Sprite> Layers::getSprite(size_t spriteIndex)
{
return thg2->getSprite(spriteIndex);
}
const std::shared_ptr<Chk::Sprite> Layers::getSprite(size_t spriteIndex) const
{
return thg2->getSprite(spriteIndex);
}
size_t Layers::addSprite(std::shared_ptr<Chk::Sprite> sprite)
{
return thg2->addSprite(sprite);
}
void Layers::insertSprite(size_t spriteIndex, std::shared_ptr<Chk::Sprite> sprite)
{
thg2->insertSprite(spriteIndex, sprite);
}
void Layers::deleteSprite(size_t spriteIndex)
{
thg2->deleteSprite(spriteIndex);
}
void Layers::moveSprite(size_t spriteIndexFrom, size_t spriteIndexTo)
{
thg2->moveSprite(spriteIndexFrom, spriteIndexTo);
}
void Layers::updateOutOfBoundsSprites()
{
size_t pixelWidth = dim->getPixelWidth();
size_t pixelHeight = dim->getPixelHeight();
size_t numSprites = thg2->numSprites();
for ( size_t i=0; i<numSprites; i++ )
{
std::shared_ptr<Chk::Sprite> sprite = thg2->getSprite(i);
if ( sprite->xc >= pixelWidth )
sprite->xc = u16(pixelWidth-1);
if ( sprite->yc >= pixelHeight )
sprite->yc = u16(pixelHeight-1);
}
}
void Layers::removeOutOfBoundsSprites()
{
size_t pixelWidth = dim->getPixelWidth();
size_t pixelHeight = dim->getPixelHeight();
size_t numSprites = thg2->numSprites();
for ( size_t i = numSprites-1; i < numSprites; i-- )
{
std::shared_ptr<Chk::Sprite> sprite = thg2->getSprite(i);
if ( sprite->xc >= pixelWidth || sprite->yc >= pixelHeight )
thg2->deleteSprite(i);
}
}
size_t Layers::numDoodads() const
{
return dd2->numDoodads();
}
std::shared_ptr<Chk::Doodad> Layers::getDoodad(size_t doodadIndex)
{
return dd2->getDoodad(doodadIndex);
}
const std::shared_ptr<Chk::Doodad> Layers::getDoodad(size_t doodadIndex) const
{
return dd2->getDoodad(doodadIndex);
}
size_t Layers::addDoodad(std::shared_ptr<Chk::Doodad> doodad)
{
return dd2->addDoodad(doodad);
}
void Layers::insertDoodad(size_t doodadIndex, std::shared_ptr<Chk::Doodad> doodad)
{
return dd2->insertDoodad(doodadIndex, doodad);
}
void Layers::deleteDoodad(size_t doodadIndex)
{
return dd2->deleteDoodad(doodadIndex);
}
void Layers::moveDoodad(size_t doodadIndexFrom, size_t doodadIndexTo)
{
return dd2->moveDoodad(doodadIndexFrom, doodadIndexTo);
}
void Layers::removeOutOfBoundsDoodads()
{
size_t pixelWidth = dim->getPixelWidth();
size_t pixelHeight = dim->getPixelHeight();
size_t numDoodads = dd2->numDoodads();
for ( size_t i = numDoodads-1; i < numDoodads; i-- )
{
std::shared_ptr<Chk::Doodad> doodad = dd2->getDoodad(i);
if ( doodad->xc >= pixelWidth || doodad->yc >= pixelHeight )
dd2->deleteDoodad(i);
}
}
size_t Layers::numUnits() const
{
return unit->numUnits();
}
std::shared_ptr<Chk::Unit> Layers::getUnit(size_t unitIndex)
{
return unit->getUnit(unitIndex);
}
const std::shared_ptr<Chk::Unit> Layers::getUnit(size_t unitIndex) const
{
return unit->getUnit(unitIndex);
}
size_t Layers::addUnit(std::shared_ptr<Chk::Unit> unit)
{
return this->unit->addUnit(unit);
}
void Layers::insertUnit(size_t unitIndex, std::shared_ptr<Chk::Unit> unit)
{
return this->unit->insertUnit(unitIndex, unit);
}
void Layers::deleteUnit(size_t unitIndex)
{
return unit->deleteUnit(unitIndex);
}
void Layers::moveUnit(size_t unitIndexFrom, size_t unitIndexTo)
{
return unit->moveUnit(unitIndexFrom, unitIndexTo);
}
void Layers::updateOutOfBoundsUnits()
{
size_t pixelWidth = dim->getPixelWidth();
size_t pixelHeight = dim->getPixelHeight();
size_t numUnits = unit->numUnits();
for ( size_t i=0; i<numUnits; i++ )
{
std::shared_ptr<Chk::Unit> currUnit = unit->getUnit(i);
if ( currUnit->xc >= pixelWidth )
currUnit->xc = u16(pixelWidth-1);
if ( currUnit->yc >= pixelHeight )
currUnit->yc = u16(pixelHeight-1);
}
}
void Layers::removeOutOfBoundsUnits()
{
size_t pixelWidth = dim->getPixelWidth();
size_t pixelHeight = dim->getPixelHeight();
size_t numUnits = unit->numUnits();
for ( size_t i = numUnits-1; i < numUnits; i-- )
{
std::shared_ptr<Chk::Unit> currUnit = unit->getUnit(i);
if ( currUnit->xc >= pixelWidth || currUnit->yc >= pixelHeight )
unit->deleteUnit(i);
}
}
size_t Layers::numLocations() const
{
return mrgn->numLocations();
}
std::shared_ptr<Chk::Location> Layers::getLocation(size_t locationId)
{
return mrgn->getLocation(locationId);
}
const std::shared_ptr<Chk::Location> Layers::getLocation(size_t locationId) const
{
return mrgn->getLocation(locationId);
}
size_t Layers::addLocation(std::shared_ptr<Chk::Location> location)
{
return mrgn->addLocation(location);
}
void Layers::replaceLocation(size_t locationId, std::shared_ptr<Chk::Location> location)
{
mrgn->replaceLocation(locationId, location);
}
void Layers::deleteLocation(size_t locationId, bool deleteOnlyIfUnused)
{
if ( !deleteOnlyIfUnused || !triggers->locationUsed(locationId) )
mrgn->deleteLocation(locationId);
}
bool Layers::moveLocation(size_t locationIdFrom, size_t locationIdTo, bool lockAnywhere)
{
return mrgn->moveLocation(locationIdFrom, locationIdTo, lockAnywhere);
}
bool Layers::isBlank(size_t locationId) const
{
return mrgn->isBlank(locationId);
}
void Layers::downsizeOutOfBoundsLocations()
{
size_t pixelWidth = dim->getPixelWidth();
size_t pixelHeight = dim->getPixelHeight();
size_t numLocations = mrgn->numLocations();
for ( size_t i=1; i<=numLocations; i++ )
{
std::shared_ptr<Chk::Location> location = mrgn->getLocation(i);
if ( location->left >= pixelWidth )
location->left = u32(pixelWidth-1);
if ( location->right >= pixelWidth )
location->right = u32(pixelWidth-1);
if ( location->top >= pixelHeight )
location->top = u32(pixelHeight-1);
if ( location->bottom >= pixelHeight )
location->bottom = u32(pixelHeight-1);
}
}
bool Layers::locationsFitOriginal(bool lockAnywhere, bool autoDefragment)
{
return mrgn->locationsFitOriginal(*triggers, lockAnywhere, autoDefragment);
}
bool Layers::trimLocationsToOriginal(bool lockAnywhere, bool autoDefragment)
{
return mrgn->trimToOriginal(*triggers, lockAnywhere, autoDefragment);
}
void Layers::expandToScHybridOrExpansion()
{
mrgn->expandToScHybridOrExpansion();
}
bool Layers::anywhereIsStandardDimensions() const
{
std::shared_ptr<Chk::Location> anywhere = mrgn->getLocation(Chk::LocationId::Anywhere);
return anywhere != nullptr && anywhere->left == 0 && anywhere->top == 0 && anywhere->right == dim->getPixelWidth() && anywhere->bottom == dim->getPixelHeight();
}
void Layers::matchAnywhereToDimensions()
{
std::shared_ptr<Chk::Location> anywhere = mrgn->getLocation(Chk::LocationId::Anywhere);
if ( anywhere != nullptr )
{
anywhere->left = 0;
anywhere->top = 0;
anywhere->right = (u32)dim->getPixelWidth();
anywhere->bottom = (u32)dim->getPixelHeight();
}
}
void Layers::appendUsage(size_t stringId, std::vector<Chk::StringUser> & stringUsers, u32 userMask) const
{
if ( (userMask & Chk::StringUserFlag::Location) == Chk::StringUserFlag::Location )
mrgn->appendUsage(stringId, stringUsers);
}
bool Layers::stringUsed(size_t stringId, Chk::Scope storageScope, u32 userMask) const
{
if ( (userMask & Chk::StringUserFlag::Location) == Chk::StringUserFlag::Location )
{
switch ( storageScope )
{
case Chk::Scope::Either:
case Chk::Scope::EditorOverGame:
case Chk::Scope::GameOverEditor: return mrgn->stringUsed(stringId) || strings->ostr->stringUsed(stringId, Chk::StringUserFlag::Location);
case Chk::Scope::Game: return mrgn->stringUsed(stringId);
case Chk::Scope::Editor: return strings->ostr->stringUsed(stringId, Chk::StringUserFlag::Location);
default: return false;
}
}
return false;
}
void Layers::markUsedStrings(std::bitset<Chk::MaxStrings> & stringIdUsed, u32 userMask) const
{
if ( (userMask & Chk::StringUserFlag::Location) == Chk::StringUserFlag::Location )
mrgn->markUsedStrings(stringIdUsed);
}
void Layers::remapStringIds(const std::map<u32, u32> & stringIdRemappings)
{
mrgn->remapStringIds(stringIdRemappings);
}
void Layers::deleteString(size_t stringId)
{
mrgn->deleteString(stringId);
}
void Layers::set(std::unordered_map<SectionName, Section> & sections)
{
Terrain::set(sections);
mask = GetSection<MaskSection>(sections, SectionName::MASK);
thg2 = GetSection<Thg2Section>(sections, SectionName::THG2);
dd2 = GetSection<Dd2Section>(sections, SectionName::DD2);
unit = GetSection<UnitSection>(sections, SectionName::UNIT);
mrgn = GetSection<MrgnSection>(sections, SectionName::MRGN);
if ( Terrain::dim != nullptr )
{
if ( mask == nullptr )
mask = MaskSection::GetDefault((u16)dim->getTileWidth(), (u16)dim->getTileHeight());
if ( mrgn == nullptr )
mrgn = MrgnSection::GetDefault((u16)dim->getTileWidth(), (u16)dim->getTileHeight());
}
if ( dd2 == nullptr )
dd2 = Dd2Section::GetDefault();
}
void Layers::clear()
{
Terrain::clear();
mask = nullptr;
thg2 = nullptr;
dd2 = nullptr;
unit = nullptr;
mrgn = nullptr;
}
Properties::Properties(bool useDefault) : versions(nullptr), strings(nullptr)
{
if ( useDefault )
{
unis = UnisSection::GetDefault(); // Unit settings
unix = UnixSection::GetDefault(); // Expansion Unit Settings
puni = PuniSection::GetDefault(); // Unit availability
upgs = UpgsSection::GetDefault(); // Upgrade costs
upgx = UpgxSection::GetDefault(); // Expansion upgrade costs
upgr = UpgrSection::GetDefault(); // Upgrade leveling
pupx = PupxSection::GetDefault(); // Expansion upgrade leveling
tecs = TecsSection::GetDefault(); // Technology costs
tecx = TecxSection::GetDefault(); // Expansion technology costs
ptec = PtecSection::GetDefault(); // Technology availability
ptex = PtexSection::GetDefault(); // Expansion technology availability
if ( unis == nullptr || unix == nullptr || puni == nullptr || upgs == nullptr || upgx == nullptr || upgr == nullptr || pupx == nullptr ||
tecs == nullptr || tecx == nullptr || ptec == nullptr || ptex == nullptr )
{
throw ScenarioAllocationFailure(
unis == nullptr ? ChkSection::getNameString(SectionName::UNIS) :
(unix == nullptr ? ChkSection::getNameString(SectionName::UNIx) :
(puni == nullptr ? ChkSection::getNameString(SectionName::PUNI) :
(upgs == nullptr ? ChkSection::getNameString(SectionName::UPGS) :
(upgx == nullptr ? ChkSection::getNameString(SectionName::UPGx) :
(upgr == nullptr ? ChkSection::getNameString(SectionName::UPGR) :
(pupx == nullptr ? ChkSection::getNameString(SectionName::PUPx) :
(tecs == nullptr ? ChkSection::getNameString(SectionName::TECS) :
(tecx == nullptr ? ChkSection::getNameString(SectionName::TECx) :
(ptec == nullptr ? ChkSection::getNameString(SectionName::PTEC) :
ChkSection::getNameString(SectionName::PTEx)))))))))));
}
}
}
bool Properties::empty() const
{
return unis == nullptr && unix == nullptr && puni == nullptr && upgs == nullptr && upgx == nullptr &&
upgr == nullptr && pupx == nullptr && tecs == nullptr && tecx == nullptr & ptec == nullptr && ptex == nullptr;
}
bool Properties::useExpansionUnitSettings(Chk::UseExpSection useExp) const
{
switch ( useExp )
{
case Chk::UseExpSection::Auto: return versions->isHybridOrAbove() ? true : false;
case Chk::UseExpSection::Yes: true;
case Chk::UseExpSection::No: false;
case Chk::UseExpSection::NoIfOrigAvailable: return unis != nullptr ? false : true;
case Chk::UseExpSection::YesIfAvailable:
default: return unix != nullptr ? true : false;
}
return true;
}
bool Properties::unitUsesDefaultSettings(Sc::Unit::Type unitType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->unitUsesDefaultSettings(unitType) : unis->unitUsesDefaultSettings(unitType);
}
u32 Properties::getUnitHitpoints(Sc::Unit::Type unitType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->getUnitHitpoints(unitType) : unis->getUnitHitpoints(unitType);
}
u16 Properties::getUnitShieldPoints(Sc::Unit::Type unitType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->getUnitShieldPoints(unitType) : unis->getUnitShieldPoints(unitType);
}
u8 Properties::getUnitArmorLevel(Sc::Unit::Type unitType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->getUnitArmorLevel(unitType) : unis->getUnitArmorLevel(unitType);
}
u16 Properties::getUnitBuildTime(Sc::Unit::Type unitType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->getUnitBuildTime(unitType) : unis->getUnitBuildTime(unitType);
}
u16 Properties::getUnitMineralCost(Sc::Unit::Type unitType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->getUnitMineralCost(unitType) : unis->getUnitMineralCost(unitType);
}
u16 Properties::getUnitGasCost(Sc::Unit::Type unitType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->getUnitGasCost(unitType) : unis->getUnitGasCost(unitType);
}
size_t Properties::getUnitNameStringId(Sc::Unit::Type unitType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->getUnitNameStringId(unitType) : unis->getUnitNameStringId(unitType);
}
u16 Properties::getWeaponBaseDamage(Sc::Weapon::Type weaponType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->getWeaponBaseDamage(weaponType) : unis->getWeaponBaseDamage(weaponType);
}
u16 Properties::getWeaponUpgradeDamage(Sc::Weapon::Type weaponType, Chk::UseExpSection useExp) const
{
return useExpansionUnitSettings(useExp) ? unix->getWeaponUpgradeDamage(weaponType) : unis->getWeaponUpgradeDamage(weaponType);
}
void Properties::setUnitUsesDefaultSettings(Sc::Unit::Type unitType, bool useDefault, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both: unis->setUnitUsesDefaultSettings(unitType, useDefault); unix->setUnitUsesDefaultSettings(unitType, useDefault); break;
case Chk::UseExpSection::Yes: unix->setUnitUsesDefaultSettings(unitType, useDefault); break;
case Chk::UseExpSection::No: unis->setUnitUsesDefaultSettings(unitType, useDefault); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setUnitUsesDefaultSettings(unitType, useDefault) : unis->setUnitUsesDefaultSettings(unitType, useDefault); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setUnitUsesDefaultSettings(unitType, useDefault) : unix->setUnitUsesDefaultSettings(unitType, useDefault); break;
}
}
void Properties::setUnitHitpoints(Sc::Unit::Type unitType, u32 hitpoints, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both: unis->setUnitHitpoints(unitType, hitpoints); unix->setUnitHitpoints(unitType, hitpoints); break;
case Chk::UseExpSection::Yes: unix->setUnitHitpoints(unitType, hitpoints); break;
case Chk::UseExpSection::No: unis->setUnitHitpoints(unitType, hitpoints); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setUnitHitpoints(unitType, hitpoints) : unis->setUnitHitpoints(unitType, hitpoints); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setUnitHitpoints(unitType, hitpoints) : unix->setUnitHitpoints(unitType, hitpoints); break;
}
}
void Properties::setUnitShieldPoints(Sc::Unit::Type unitType, u16 shieldPoints, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both: unis->setUnitShieldPoints(unitType, shieldPoints); unix->setUnitShieldPoints(unitType, shieldPoints); break;
case Chk::UseExpSection::Yes: unix->setUnitShieldPoints(unitType, shieldPoints); break;
case Chk::UseExpSection::No: unis->setUnitShieldPoints(unitType, shieldPoints); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setUnitShieldPoints(unitType, shieldPoints) : unis->setUnitShieldPoints(unitType, shieldPoints); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setUnitShieldPoints(unitType, shieldPoints) : unix->setUnitShieldPoints(unitType, shieldPoints); break;
}
}
void Properties::setUnitArmorLevel(Sc::Unit::Type unitType, u8 armorLevel, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both: unis->setUnitArmorLevel(unitType, armorLevel); unix->setUnitArmorLevel(unitType, armorLevel); break;
case Chk::UseExpSection::Yes: unix->setUnitArmorLevel(unitType, armorLevel); break;
case Chk::UseExpSection::No: unis->setUnitArmorLevel(unitType, armorLevel); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setUnitArmorLevel(unitType, armorLevel) : unis->setUnitArmorLevel(unitType, armorLevel); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setUnitArmorLevel(unitType, armorLevel) : unix->setUnitArmorLevel(unitType, armorLevel); break;
}
}
void Properties::setUnitBuildTime(Sc::Unit::Type unitType, u16 buildTime, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both: unis->setUnitBuildTime(unitType, buildTime); unix->setUnitBuildTime(unitType, buildTime); break;
case Chk::UseExpSection::Yes: unix->setUnitBuildTime(unitType, buildTime); break;
case Chk::UseExpSection::No: unis->setUnitBuildTime(unitType, buildTime); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setUnitBuildTime(unitType, buildTime) : unis->setUnitBuildTime(unitType, buildTime); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setUnitBuildTime(unitType, buildTime) : unix->setUnitBuildTime(unitType, buildTime); break;
}
}
void Properties::setUnitMineralCost(Sc::Unit::Type unitType, u16 mineralCost, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both: unis->setUnitMineralCost(unitType, mineralCost); unix->setUnitMineralCost(unitType, mineralCost); break;
case Chk::UseExpSection::Yes: unix->setUnitMineralCost(unitType, mineralCost); break;
case Chk::UseExpSection::No: unis->setUnitMineralCost(unitType, mineralCost); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setUnitMineralCost(unitType, mineralCost) : unis->setUnitMineralCost(unitType, mineralCost); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setUnitMineralCost(unitType, mineralCost) : unix->setUnitMineralCost(unitType, mineralCost); break;
}
}
void Properties::setUnitGasCost(Sc::Unit::Type unitType, u16 gasCost, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both: unis->setUnitGasCost(unitType, gasCost); unix->setUnitGasCost(unitType, gasCost); break;
case Chk::UseExpSection::Yes: unix->setUnitGasCost(unitType, gasCost); break;
case Chk::UseExpSection::No: unis->setUnitGasCost(unitType, gasCost); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setUnitGasCost(unitType, gasCost) : unis->setUnitGasCost(unitType, gasCost); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setUnitGasCost(unitType, gasCost) : unix->setUnitGasCost(unitType, gasCost); break;
}
}
void Properties::setUnitNameStringId(Sc::Unit::Type unitType, size_t nameStringId, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both: unis->setUnitNameStringId(unitType, (u16)nameStringId); unix->setUnitNameStringId(unitType, (u16)nameStringId); break;
case Chk::UseExpSection::Yes: unix->setUnitNameStringId(unitType, (u16)nameStringId); break;
case Chk::UseExpSection::No: unis->setUnitNameStringId(unitType, (u16)nameStringId); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setUnitNameStringId(unitType, (u16)nameStringId) : unis->setUnitNameStringId(unitType, (u16)nameStringId); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setUnitNameStringId(unitType, (u16)nameStringId) : unix->setUnitNameStringId(unitType, (u16)nameStringId); break;
}
}
void Properties::setWeaponBaseDamage(Sc::Weapon::Type weaponType, u16 baseDamage, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( weaponType < Sc::Weapon::TotalOriginal && unis != nullptr )
unis->setWeaponBaseDamage(weaponType, baseDamage);
if ( unix != nullptr )
unix->setWeaponBaseDamage(weaponType, baseDamage);
break;
case Chk::UseExpSection::Both: unis->setWeaponBaseDamage(weaponType, baseDamage); unix->setWeaponBaseDamage(weaponType, baseDamage); break;
case Chk::UseExpSection::Yes: unix->setWeaponBaseDamage(weaponType, baseDamage); break;
case Chk::UseExpSection::No: unis->setWeaponBaseDamage(weaponType, baseDamage); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setWeaponBaseDamage(weaponType, baseDamage) : unis->setWeaponBaseDamage(weaponType, baseDamage); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setWeaponBaseDamage(weaponType, baseDamage) : unix->setWeaponBaseDamage(weaponType, baseDamage); break;
}
}
void Properties::setWeaponUpgradeDamage(Sc::Weapon::Type weaponType, u16 upgradeDamage, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( weaponType < Sc::Weapon::TotalOriginal && unis != nullptr )
unis->setWeaponUpgradeDamage(weaponType, upgradeDamage);
if ( unix != nullptr )
unix->setWeaponUpgradeDamage(weaponType, upgradeDamage);
break;
case Chk::UseExpSection::Both: unis->setWeaponUpgradeDamage(weaponType, upgradeDamage); unix->setWeaponUpgradeDamage(weaponType, upgradeDamage); break;
case Chk::UseExpSection::Yes: unix->setWeaponUpgradeDamage(weaponType, upgradeDamage); break;
case Chk::UseExpSection::No: unis->setWeaponUpgradeDamage(weaponType, upgradeDamage); break;
case Chk::UseExpSection::YesIfAvailable: unix != nullptr ? unix->setWeaponUpgradeDamage(weaponType, upgradeDamage) : unis->setWeaponUpgradeDamage(weaponType, upgradeDamage); break;
case Chk::UseExpSection::NoIfOrigAvailable: unis != nullptr ? unis->setWeaponUpgradeDamage(weaponType, upgradeDamage) : unix->setWeaponUpgradeDamage(weaponType, upgradeDamage); break;
}
}
bool Properties::isUnitBuildable(Sc::Unit::Type unitType, size_t playerIndex) const
{
return puni->isUnitBuildable(unitType, playerIndex);
}
bool Properties::isUnitDefaultBuildable(Sc::Unit::Type unitType) const
{
return puni->isUnitDefaultBuildable(unitType);
}
bool Properties::playerUsesDefaultUnitBuildability(Sc::Unit::Type unitType, size_t playerIndex) const
{
return puni->playerUsesDefault(unitType, playerIndex);
}
void Properties::setUnitBuildable(Sc::Unit::Type unitType, size_t playerIndex, bool buildable)
{
puni->setUnitBuildable(unitType, playerIndex, buildable);
}
void Properties::setUnitDefaultBuildable(Sc::Unit::Type unitType, bool buildable)
{
puni->setUnitDefaultBuildable(unitType, buildable);
}
void Properties::setPlayerUsesDefaultUnitBuildability(Sc::Unit::Type unitType, size_t playerIndex, bool useDefault)
{
puni->setPlayerUsesDefault(unitType, playerIndex, useDefault);
}
void Properties::setUnitsToDefault(Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both:
*unis = *UnisSection::GetDefault();
*unix = *UnixSection::GetDefault();
*puni = *PuniSection::GetDefault();
break;
case Chk::UseExpSection::Yes:
*unix = *UnixSection::GetDefault();
*puni = *PuniSection::GetDefault();
break;
case Chk::UseExpSection::No:
*unis = *UnisSection::GetDefault();
*puni = *PuniSection::GetDefault();
break;
case Chk::UseExpSection::YesIfAvailable:
if ( unix != nullptr )
*unix = *UnixSection::GetDefault();
else
*unis = *UnisSection::GetDefault();
*puni = *PuniSection::GetDefault();
break;
case Chk::UseExpSection::NoIfOrigAvailable:
if ( unis != nullptr )
*unis = *UnisSection::GetDefault();
else
*unix = *UnixSection::GetDefault();
*puni = *PuniSection::GetDefault();
break;
}
}
bool Properties::useExpansionUpgradeCosts(Chk::UseExpSection useExp) const
{
switch ( useExp )
{
case Chk::UseExpSection::Auto: return versions->isHybridOrAbove() ? true : false;
case Chk::UseExpSection::Yes: true;
case Chk::UseExpSection::No: false;
case Chk::UseExpSection::NoIfOrigAvailable: return upgs != nullptr ? false : true;
case Chk::UseExpSection::YesIfAvailable:
default: return upgx != nullptr ? true : false;
}
}
bool Properties::upgradeUsesDefaultCosts(Sc::Upgrade::Type upgradeType, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeCosts(useExp) ? upgx->upgradeUsesDefaultCosts(upgradeType) : upgs->upgradeUsesDefaultCosts(upgradeType);
}
u16 Properties::getUpgradeBaseMineralCost(Sc::Upgrade::Type upgradeType, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeCosts(useExp) ? upgx->getBaseMineralCost(upgradeType) : upgs->getBaseMineralCost(upgradeType);
}
u16 Properties::getUpgradeMineralCostFactor(Sc::Upgrade::Type upgradeType, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeCosts(useExp) ? upgx->getMineralCostFactor(upgradeType) : upgs->getMineralCostFactor(upgradeType);
}
u16 Properties::getUpgradeBaseGasCost(Sc::Upgrade::Type upgradeType, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeCosts(useExp) ? upgx->getBaseGasCost(upgradeType) : upgs->getBaseGasCost(upgradeType);
}
u16 Properties::getUpgradeGasCostFactor(Sc::Upgrade::Type upgradeType, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeCosts(useExp) ? upgx->getGasCostFactor(upgradeType) : upgs->getGasCostFactor(upgradeType);
}
u16 Properties::getUpgradeBaseResearchTime(Sc::Upgrade::Type upgradeType, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeCosts(useExp) ? upgx->getBaseResearchTime(upgradeType) : upgs->getBaseResearchTime(upgradeType);
}
u16 Properties::getUpgradeResearchTimeFactor(Sc::Upgrade::Type upgradeType, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeCosts(useExp) ? upgx->getResearchTimeFactor(upgradeType) : upgs->getResearchTimeFactor(upgradeType);
}
void Properties::setUpgradeUsesDefaultCosts(Sc::Upgrade::Type upgradeType, bool useDefault, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgs != nullptr )
upgs->setUpgradeUsesDefaultCosts(upgradeType, useDefault);
if ( upgx != nullptr )
upgx->setUpgradeUsesDefaultCosts(upgradeType, useDefault);
break;
case Chk::UseExpSection::Both: upgs->setUpgradeUsesDefaultCosts(upgradeType, useDefault); upgx->setUpgradeUsesDefaultCosts(upgradeType, useDefault); break;
case Chk::UseExpSection::Yes: upgx->setUpgradeUsesDefaultCosts(upgradeType, useDefault); break;
case Chk::UseExpSection::No: upgs->setUpgradeUsesDefaultCosts(upgradeType, useDefault); break;
case Chk::UseExpSection::YesIfAvailable: upgx != nullptr ? upgx->setUpgradeUsesDefaultCosts(upgradeType, useDefault) : upgs->setUpgradeUsesDefaultCosts(upgradeType, useDefault); break;
case Chk::UseExpSection::NoIfOrigAvailable: upgs != nullptr ? upgs->setUpgradeUsesDefaultCosts(upgradeType, useDefault) : upgx->setUpgradeUsesDefaultCosts(upgradeType, useDefault); break;
}
}
void Properties::setUpgradeBaseMineralCost(Sc::Upgrade::Type upgradeType, u16 baseMineralCost, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgs != nullptr )
upgs->setBaseMineralCost(upgradeType, baseMineralCost);
if ( upgx != nullptr )
upgx->setBaseMineralCost(upgradeType, baseMineralCost);
break;
case Chk::UseExpSection::Both: upgs->setBaseMineralCost(upgradeType, baseMineralCost); upgx->setBaseMineralCost(upgradeType, baseMineralCost); break;
case Chk::UseExpSection::Yes: upgx->setBaseMineralCost(upgradeType, baseMineralCost); break;
case Chk::UseExpSection::No: upgs->setBaseMineralCost(upgradeType, baseMineralCost); break;
case Chk::UseExpSection::YesIfAvailable: upgx != nullptr ? upgx->setBaseMineralCost(upgradeType, baseMineralCost) : upgs->setBaseMineralCost(upgradeType, baseMineralCost); break;
case Chk::UseExpSection::NoIfOrigAvailable: upgs != nullptr ? upgs->setBaseMineralCost(upgradeType, baseMineralCost) : upgx->setBaseMineralCost(upgradeType, baseMineralCost); break;
}
}
void Properties::setUpgradeMineralCostFactor(Sc::Upgrade::Type upgradeType, u16 mineralCostFactor, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgs != nullptr )
upgs->setMineralCostFactor(upgradeType, mineralCostFactor);
if ( upgx != nullptr )
upgx->setMineralCostFactor(upgradeType, mineralCostFactor);
break;
case Chk::UseExpSection::Both: upgs->setMineralCostFactor(upgradeType, mineralCostFactor); upgx->setMineralCostFactor(upgradeType, mineralCostFactor); break;
case Chk::UseExpSection::Yes: upgx->setMineralCostFactor(upgradeType, mineralCostFactor); break;
case Chk::UseExpSection::No: upgs->setMineralCostFactor(upgradeType, mineralCostFactor); break;
case Chk::UseExpSection::YesIfAvailable: upgx != nullptr ? upgx->setMineralCostFactor(upgradeType, mineralCostFactor) : upgs->setMineralCostFactor(upgradeType, mineralCostFactor); break;
case Chk::UseExpSection::NoIfOrigAvailable: upgs != nullptr ? upgs->setMineralCostFactor(upgradeType, mineralCostFactor) : upgx->setMineralCostFactor(upgradeType, mineralCostFactor); break;
}
}
void Properties::setUpgradeBaseGasCost(Sc::Upgrade::Type upgradeType, u16 baseGasCost, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgs != nullptr )
upgs->setBaseGasCost(upgradeType, baseGasCost);
if ( upgx != nullptr )
upgx->setBaseGasCost(upgradeType, baseGasCost);
break;
case Chk::UseExpSection::Both: upgs->setBaseGasCost(upgradeType, baseGasCost); upgx->setBaseGasCost(upgradeType, baseGasCost); break;
case Chk::UseExpSection::Yes: upgx->setBaseGasCost(upgradeType, baseGasCost); break;
case Chk::UseExpSection::No: upgs->setBaseGasCost(upgradeType, baseGasCost); break;
case Chk::UseExpSection::YesIfAvailable: upgx != nullptr ? upgx->setBaseGasCost(upgradeType, baseGasCost) : upgs->setBaseGasCost(upgradeType, baseGasCost); break;
case Chk::UseExpSection::NoIfOrigAvailable: upgs != nullptr ? upgs->setBaseGasCost(upgradeType, baseGasCost) : upgx->setBaseGasCost(upgradeType, baseGasCost); break;
}
}
void Properties::setUpgradeGasCostFactor(Sc::Upgrade::Type upgradeType, u16 gasCostFactor, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgs != nullptr )
upgs->setGasCostFactor(upgradeType, gasCostFactor);
if ( upgx != nullptr )
upgx->setGasCostFactor(upgradeType, gasCostFactor);
break;
case Chk::UseExpSection::Both: upgs->setGasCostFactor(upgradeType, gasCostFactor); upgx->setGasCostFactor(upgradeType, gasCostFactor); break;
case Chk::UseExpSection::Yes: upgx->setGasCostFactor(upgradeType, gasCostFactor); break;
case Chk::UseExpSection::No: upgs->setGasCostFactor(upgradeType, gasCostFactor); break;
case Chk::UseExpSection::YesIfAvailable: upgx != nullptr ? upgx->setGasCostFactor(upgradeType, gasCostFactor) : upgs->setGasCostFactor(upgradeType, gasCostFactor); break;
case Chk::UseExpSection::NoIfOrigAvailable: upgs != nullptr ? upgs->setGasCostFactor(upgradeType, gasCostFactor) : upgx->setGasCostFactor(upgradeType, gasCostFactor); break;
}
}
void Properties::setUpgradeBaseResearchTime(Sc::Upgrade::Type upgradeType, u16 baseResearchTime, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgs != nullptr )
upgs->setBaseResearchTime(upgradeType, baseResearchTime);
if ( upgx != nullptr )
upgx->setBaseResearchTime(upgradeType, baseResearchTime);
break;
case Chk::UseExpSection::Both: upgs->setBaseResearchTime(upgradeType, baseResearchTime); upgx->setBaseResearchTime(upgradeType, baseResearchTime); break;
case Chk::UseExpSection::Yes: upgx->setBaseResearchTime(upgradeType, baseResearchTime); break;
case Chk::UseExpSection::No: upgs->setBaseResearchTime(upgradeType, baseResearchTime); break;
case Chk::UseExpSection::YesIfAvailable: upgx != nullptr ? upgx->setBaseResearchTime(upgradeType, baseResearchTime) : upgs->setBaseResearchTime(upgradeType, baseResearchTime); break;
case Chk::UseExpSection::NoIfOrigAvailable: upgs != nullptr ? upgs->setBaseResearchTime(upgradeType, baseResearchTime) : upgx->setBaseResearchTime(upgradeType, baseResearchTime); break;
}
}
void Properties::setUpgradeResearchTimeFactor(Sc::Upgrade::Type upgradeType, u16 researchTimeFactor, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgs != nullptr )
upgs->setResearchTimeFactor(upgradeType, researchTimeFactor);
if ( upgx != nullptr )
upgx->setResearchTimeFactor(upgradeType, researchTimeFactor);
break;
case Chk::UseExpSection::Both: upgs->setResearchTimeFactor(upgradeType, researchTimeFactor); upgx->setResearchTimeFactor(upgradeType, researchTimeFactor); break;
case Chk::UseExpSection::Yes: upgx->setResearchTimeFactor(upgradeType, researchTimeFactor); break;
case Chk::UseExpSection::No: upgs->setResearchTimeFactor(upgradeType, researchTimeFactor); break;
case Chk::UseExpSection::YesIfAvailable: upgx != nullptr ? upgx->setResearchTimeFactor(upgradeType, researchTimeFactor) : upgs->setResearchTimeFactor(upgradeType, researchTimeFactor); break;
case Chk::UseExpSection::NoIfOrigAvailable: upgs != nullptr ? upgs->setResearchTimeFactor(upgradeType, researchTimeFactor) : upgx->setResearchTimeFactor(upgradeType, researchTimeFactor); break;
}
}
bool Properties::useExpansionUpgradeLeveling(Chk::UseExpSection useExp) const
{
switch ( useExp )
{
case Chk::UseExpSection::Auto: return versions->isHybridOrAbove() ? true : false;
case Chk::UseExpSection::Yes: true;
case Chk::UseExpSection::No: false;
case Chk::UseExpSection::NoIfOrigAvailable: return upgr != nullptr ? false : true;
case Chk::UseExpSection::YesIfAvailable:
default: return pupx != nullptr ? true : false;
}
}
size_t Properties::getMaxUpgradeLevel(Sc::Upgrade::Type upgradeType, size_t playerIndex, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeLeveling(useExp) ? pupx->getMaxUpgradeLevel(upgradeType, playerIndex) : upgr->getMaxUpgradeLevel(upgradeType, playerIndex);
}
size_t Properties::getStartUpgradeLevel(Sc::Upgrade::Type upgradeType, size_t playerIndex, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeLeveling(useExp) ? pupx->getStartUpgradeLevel(upgradeType, playerIndex) : upgr->getStartUpgradeLevel(upgradeType, playerIndex);
}
size_t Properties::getDefaultMaxUpgradeLevel(Sc::Upgrade::Type upgradeType, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeLeveling(useExp) ? pupx->getDefaultMaxUpgradeLevel(upgradeType) : upgr->getDefaultMaxUpgradeLevel(upgradeType);
}
size_t Properties::getDefaultStartUpgradeLevel(Sc::Upgrade::Type upgradeType, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeLeveling(useExp) ? pupx->getDefaultStartUpgradeLevel(upgradeType) : upgr->getDefaultStartUpgradeLevel(upgradeType);
}
bool Properties::playerUsesDefaultUpgradeLeveling(Sc::Upgrade::Type upgradeType, size_t playerIndex, Chk::UseExpSection useExp) const
{
return useExpansionUpgradeLeveling(useExp) ? pupx->playerUsesDefault(upgradeType, playerIndex) : upgr->playerUsesDefault(upgradeType, playerIndex);
}
void Properties::setMaxUpgradeLevel(Sc::Upgrade::Type upgradeType, size_t playerIndex, size_t maxUpgradeLevel, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgr != nullptr )
upgr->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel);
if ( pupx != nullptr )
pupx->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel);
break;
case Chk::UseExpSection::Both: upgr->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel); pupx->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel); break;
case Chk::UseExpSection::Yes: pupx->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel); break;
case Chk::UseExpSection::No: upgr->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel); break;
case Chk::UseExpSection::YesIfAvailable:
pupx != nullptr ? pupx->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel) : upgr->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel); break;
case Chk::UseExpSection::NoIfOrigAvailable:
upgr != nullptr ? upgr->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel) : pupx->setMaxUpgradeLevel(upgradeType, playerIndex, maxUpgradeLevel); break;
}
}
void Properties::setStartUpgradeLevel(Sc::Upgrade::Type upgradeType, size_t playerIndex, size_t startUpgradeLevel, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgr != nullptr )
upgr->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel);
if ( pupx != nullptr )
pupx->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel);
break;
case Chk::UseExpSection::Both: upgr->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel); pupx->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel); break;
case Chk::UseExpSection::Yes: pupx->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel); break;
case Chk::UseExpSection::No: upgr->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel); break;
case Chk::UseExpSection::YesIfAvailable:
pupx != nullptr ? pupx->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel) : upgr->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel); break;
case Chk::UseExpSection::NoIfOrigAvailable:
upgr != nullptr ? upgr->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel) : pupx->setStartUpgradeLevel(upgradeType, playerIndex, startUpgradeLevel); break;
}
}
void Properties::setDefaultMaxUpgradeLevel(Sc::Upgrade::Type upgradeType, size_t maxUpgradeLevel, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgr != nullptr )
upgr->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel);
if ( pupx != nullptr )
pupx->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel);
break;
case Chk::UseExpSection::Both: upgr->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel); pupx->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel); break;
case Chk::UseExpSection::Yes: pupx->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel); break;
case Chk::UseExpSection::No: upgr->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel); break;
case Chk::UseExpSection::YesIfAvailable: pupx != nullptr ? pupx->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel) : upgr->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel); break;
case Chk::UseExpSection::NoIfOrigAvailable: upgr != nullptr ? upgr->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel) : pupx->setDefaultMaxUpgradeLevel(upgradeType, maxUpgradeLevel); break;
}
}
void Properties::setDefaultStartUpgradeLevel(Sc::Upgrade::Type upgradeType, size_t startUpgradeLevel, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgr != nullptr )
upgr->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel);
if ( pupx != nullptr )
pupx->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel);
break;
case Chk::UseExpSection::Both: upgr->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel); pupx->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel); break;
case Chk::UseExpSection::Yes: pupx->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel); break;
case Chk::UseExpSection::No: upgr->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel); break;
case Chk::UseExpSection::YesIfAvailable:
pupx != nullptr ? pupx->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel) : upgr->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel); break;
case Chk::UseExpSection::NoIfOrigAvailable:
upgr != nullptr ? upgr->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel) : pupx->setDefaultStartUpgradeLevel(upgradeType, startUpgradeLevel); break;
}
}
void Properties::setPlayerUsesDefaultUpgradeLeveling(Sc::Upgrade::Type upgradeType, size_t playerIndex, bool useDefault, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( upgradeType < Sc::Upgrade::TotalOriginalTypes && upgr != nullptr )
upgr->setPlayerUsesDefault(upgradeType, playerIndex, useDefault);
if ( pupx != nullptr )
pupx->setPlayerUsesDefault(upgradeType, playerIndex, useDefault);
break;
case Chk::UseExpSection::Both: upgr->setPlayerUsesDefault(upgradeType, playerIndex, useDefault); pupx->setPlayerUsesDefault(upgradeType, playerIndex, useDefault); break;
case Chk::UseExpSection::Yes: pupx->setPlayerUsesDefault(upgradeType, playerIndex, useDefault); break;
case Chk::UseExpSection::No: upgr->setPlayerUsesDefault(upgradeType, playerIndex, useDefault); break;
case Chk::UseExpSection::YesIfAvailable: pupx != nullptr ? pupx->setPlayerUsesDefault(upgradeType, playerIndex, useDefault) : upgr->setPlayerUsesDefault(upgradeType, playerIndex, useDefault); break;
case Chk::UseExpSection::NoIfOrigAvailable: upgr != nullptr ? upgr->setPlayerUsesDefault(upgradeType, playerIndex, useDefault) : pupx->setPlayerUsesDefault(upgradeType, playerIndex, useDefault); break;
}
}
void Properties::setUpgradesToDefault(Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both:
*upgs = *UpgsSection::GetDefault();
*upgx = *UpgxSection::GetDefault();
*upgr = *UpgrSection::GetDefault();
*pupx = *PupxSection::GetDefault();
break;
case Chk::UseExpSection::Yes:
*upgx = *UpgxSection::GetDefault();
*pupx = *PupxSection::GetDefault();
break;
case Chk::UseExpSection::No:
*upgs = *UpgsSection::GetDefault();
*upgr = *UpgrSection::GetDefault();
break;
case Chk::UseExpSection::YesIfAvailable:
if ( upgx != nullptr )
*upgx = *UpgxSection::GetDefault();
else
*upgs = *UpgsSection::GetDefault();
if ( pupx != nullptr )
*pupx = *PupxSection::GetDefault();
else
*upgr = *UpgrSection::GetDefault();
break;
case Chk::UseExpSection::NoIfOrigAvailable:
if ( upgs != nullptr )
*upgs = *UpgsSection::GetDefault();
else
*upgx = *UpgxSection::GetDefault();
if ( upgr != nullptr )
*upgr = *UpgrSection::GetDefault();
else
*pupx = *PupxSection::GetDefault();
break;
}
}
bool Properties::useExpansionTechCosts(Chk::UseExpSection useExp) const
{
switch ( useExp )
{
case Chk::UseExpSection::Auto: return versions->isHybridOrAbove() ? true : false;
case Chk::UseExpSection::Yes: true;
case Chk::UseExpSection::No: false;
case Chk::UseExpSection::NoIfOrigAvailable: return tecs != nullptr ? false : true;
case Chk::UseExpSection::YesIfAvailable:
default: return tecx != nullptr ? true : false;
}
}
bool Properties::techUsesDefaultSettings(Sc::Tech::Type techType, Chk::UseExpSection useExp) const
{
return useExpansionTechCosts(useExp) ? tecx->techUsesDefaultSettings(techType) : tecs->techUsesDefaultSettings(techType);
}
u16 Properties::getTechMineralCost(Sc::Tech::Type techType, Chk::UseExpSection useExp) const
{
return useExpansionTechCosts(useExp) ? tecx->getTechMineralCost(techType) : tecs->getTechMineralCost(techType);
}
u16 Properties::getTechGasCost(Sc::Tech::Type techType, Chk::UseExpSection useExp) const
{
return useExpansionTechCosts(useExp) ? tecx->getTechGasCost(techType) : tecs->getTechGasCost(techType);
}
u16 Properties::getTechResearchTime(Sc::Tech::Type techType, Chk::UseExpSection useExp) const
{
return useExpansionTechCosts(useExp) ? tecx->getTechResearchTime(techType) : tecs->getTechResearchTime(techType);
}
u16 Properties::getTechEnergyCost(Sc::Tech::Type techType, Chk::UseExpSection useExp) const
{
return useExpansionTechCosts(useExp) ? tecx->getTechEnergyCost(techType) : tecs->getTechEnergyCost(techType);
}
void Properties::setTechUsesDefaultSettings(Sc::Tech::Type techType, bool useDefault, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && tecs != nullptr )
tecs->setTechUsesDefaultSettings(techType, useDefault);
if ( tecx != nullptr )
tecx->setTechUsesDefaultSettings(techType, useDefault);
break;
case Chk::UseExpSection::Both: tecs->setTechUsesDefaultSettings(techType, useDefault); tecx->setTechUsesDefaultSettings(techType, useDefault); break;
case Chk::UseExpSection::Yes: tecx->setTechUsesDefaultSettings(techType, useDefault); break;
case Chk::UseExpSection::No: tecs->setTechUsesDefaultSettings(techType, useDefault); break;
case Chk::UseExpSection::YesIfAvailable: tecx != nullptr ? tecx->setTechUsesDefaultSettings(techType, useDefault) : tecs->setTechUsesDefaultSettings(techType, useDefault); break;
case Chk::UseExpSection::NoIfOrigAvailable: tecs != nullptr ? tecs->setTechUsesDefaultSettings(techType, useDefault) : tecx->setTechUsesDefaultSettings(techType, useDefault); break;
}
}
void Properties::setTechMineralCost(Sc::Tech::Type techType, u16 mineralCost, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && tecs != nullptr )
tecs->setTechMineralCost(techType, mineralCost);
if ( tecx != nullptr )
tecx->setTechMineralCost(techType, mineralCost);
break;
case Chk::UseExpSection::Both: tecs->setTechMineralCost(techType, mineralCost); tecx->setTechMineralCost(techType, mineralCost); break;
case Chk::UseExpSection::Yes: tecx->setTechMineralCost(techType, mineralCost); break;
case Chk::UseExpSection::No: tecs->setTechMineralCost(techType, mineralCost); break;
case Chk::UseExpSection::YesIfAvailable: tecx != nullptr ? tecx->setTechMineralCost(techType, mineralCost) : tecs->setTechMineralCost(techType, mineralCost); break;
case Chk::UseExpSection::NoIfOrigAvailable: tecs != nullptr ? tecs->setTechMineralCost(techType, mineralCost) : tecx->setTechMineralCost(techType, mineralCost); break;
}
}
void Properties::setTechGasCost(Sc::Tech::Type techType, u16 gasCost, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && tecs != nullptr )
tecs->setTechGasCost(techType, gasCost);
if ( tecx != nullptr )
tecx->setTechGasCost(techType, gasCost);
break;
case Chk::UseExpSection::Both: tecs->setTechGasCost(techType, gasCost); tecx->setTechGasCost(techType, gasCost); break;
case Chk::UseExpSection::Yes: tecx->setTechGasCost(techType, gasCost); break;
case Chk::UseExpSection::No: tecs->setTechGasCost(techType, gasCost); break;
case Chk::UseExpSection::YesIfAvailable: tecx != nullptr ? tecx->setTechGasCost(techType, gasCost) : tecs->setTechGasCost(techType, gasCost); break;
case Chk::UseExpSection::NoIfOrigAvailable: tecs != nullptr ? tecs->setTechGasCost(techType, gasCost) : tecx->setTechGasCost(techType, gasCost); break;
}
}
void Properties::setTechResearchTime(Sc::Tech::Type techType, u16 researchTime, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && tecs != nullptr )
tecs->setTechResearchTime(techType, researchTime);
if ( tecx != nullptr )
tecx->setTechResearchTime(techType, researchTime);
break;
case Chk::UseExpSection::Both: tecs->setTechResearchTime(techType, researchTime); tecx->setTechResearchTime(techType, researchTime); break;
case Chk::UseExpSection::Yes: tecx->setTechResearchTime(techType, researchTime); break;
case Chk::UseExpSection::No: tecs->setTechResearchTime(techType, researchTime); break;
case Chk::UseExpSection::YesIfAvailable: tecx != nullptr ? tecx->setTechResearchTime(techType, researchTime) : tecs->setTechResearchTime(techType, researchTime); break;
case Chk::UseExpSection::NoIfOrigAvailable: tecs != nullptr ? tecs->setTechResearchTime(techType, researchTime) : tecx->setTechResearchTime(techType, researchTime); break;
}
}
void Properties::setTechEnergyCost(Sc::Tech::Type techType, u16 energyCost, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && tecs != nullptr )
tecs->setTechEnergyCost(techType, energyCost);
if ( tecx != nullptr )
tecx->setTechEnergyCost(techType, energyCost);
break;
case Chk::UseExpSection::Both: tecs->setTechEnergyCost(techType, energyCost); tecx->setTechEnergyCost(techType, energyCost); break;
case Chk::UseExpSection::Yes: tecx->setTechEnergyCost(techType, energyCost); break;
case Chk::UseExpSection::No: tecs->setTechEnergyCost(techType, energyCost); break;
case Chk::UseExpSection::YesIfAvailable: tecx != nullptr ? tecx->setTechEnergyCost(techType, energyCost) : tecs->setTechEnergyCost(techType, energyCost); break;
case Chk::UseExpSection::NoIfOrigAvailable: tecs != nullptr ? tecs->setTechEnergyCost(techType, energyCost) : tecx->setTechEnergyCost(techType, energyCost); break;
}
}
bool Properties::useExpansionTechAvailability(Chk::UseExpSection useExp) const
{
switch ( useExp )
{
case Chk::UseExpSection::Auto: return versions->isHybridOrAbove() ? true : false;
case Chk::UseExpSection::Yes: true;
case Chk::UseExpSection::No: false;
case Chk::UseExpSection::NoIfOrigAvailable: return ptec != nullptr ? false : true;
case Chk::UseExpSection::YesIfAvailable:
default: return ptex != nullptr ? true : false;
}
}
bool Properties::techAvailable(Sc::Tech::Type techType, size_t playerIndex, Chk::UseExpSection useExp) const
{
return useExpansionTechAvailability(useExp) ? ptex->techAvailable(techType, playerIndex) : ptec->techAvailable(techType, playerIndex);
}
bool Properties::techResearched(Sc::Tech::Type techType, size_t playerIndex, Chk::UseExpSection useExp) const
{
return useExpansionTechAvailability(useExp) ? ptex->techResearched(techType, playerIndex) : ptec->techResearched(techType, playerIndex);
}
bool Properties::techDefaultAvailable(Sc::Tech::Type techType, Chk::UseExpSection useExp) const
{
return useExpansionTechAvailability(useExp) ? ptex->techDefaultAvailable(techType) : ptec->techDefaultAvailable(techType);
}
bool Properties::techDefaultResearched(Sc::Tech::Type techType, Chk::UseExpSection useExp) const
{
return useExpansionTechAvailability(useExp) ? ptex->techDefaultResearched(techType) : ptec->techDefaultResearched(techType);
}
bool Properties::playerUsesDefaultTechSettings(Sc::Tech::Type techType, size_t playerIndex, Chk::UseExpSection useExp) const
{
return useExpansionTechAvailability(useExp) ? ptex->playerUsesDefault(techType, playerIndex) : ptec->playerUsesDefault(techType, playerIndex);
}
void Properties::setTechAvailable(Sc::Tech::Type techType, size_t playerIndex, bool available, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && ptec != nullptr )
ptec->setTechAvailable(techType, playerIndex, available);
if ( ptex != nullptr )
ptex->setTechAvailable(techType, playerIndex, available);
break;
case Chk::UseExpSection::Both: ptec->setTechAvailable(techType, playerIndex, available); ptex->setTechAvailable(techType, playerIndex, available); break;
case Chk::UseExpSection::Yes: ptex->setTechAvailable(techType, playerIndex, available); break;
case Chk::UseExpSection::No: ptec->setTechAvailable(techType, playerIndex, available); break;
case Chk::UseExpSection::YesIfAvailable: ptex != nullptr ? ptex->setTechAvailable(techType, playerIndex, available) : ptec->setTechAvailable(techType, playerIndex, available); break;
case Chk::UseExpSection::NoIfOrigAvailable: ptec != nullptr ? ptec->setTechAvailable(techType, playerIndex, available) : ptex->setTechAvailable(techType, playerIndex, available); break;
}
}
void Properties::setTechResearched(Sc::Tech::Type techType, size_t playerIndex, bool researched, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && ptec != nullptr )
ptec->setTechResearched(techType, playerIndex, researched);
if ( ptex != nullptr )
ptex->setTechResearched(techType, playerIndex, researched);
break;
case Chk::UseExpSection::Both: ptec->setTechResearched(techType, playerIndex, researched); ptex->setTechResearched(techType, playerIndex, researched); break;
case Chk::UseExpSection::Yes: ptex->setTechResearched(techType, playerIndex, researched); break;
case Chk::UseExpSection::No: ptec->setTechResearched(techType, playerIndex, researched); break;
case Chk::UseExpSection::YesIfAvailable: ptex != nullptr ? ptex->setTechResearched(techType, playerIndex, researched) : ptec->setTechResearched(techType, playerIndex, researched); break;
case Chk::UseExpSection::NoIfOrigAvailable: ptec != nullptr ? ptec->setTechResearched(techType, playerIndex, researched) : ptex->setTechResearched(techType, playerIndex, researched); break;
}
}
void Properties::setDefaultTechAvailable(Sc::Tech::Type techType, bool available, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && ptec != nullptr )
ptec->setDefaultTechAvailable(techType, available);
if ( ptex != nullptr )
ptex->setDefaultTechAvailable(techType, available);
break;
case Chk::UseExpSection::Both: ptec->setDefaultTechAvailable(techType, available); ptex->setDefaultTechAvailable(techType, available); break;
case Chk::UseExpSection::Yes: ptex->setDefaultTechAvailable(techType, available); break;
case Chk::UseExpSection::No: ptec->setDefaultTechAvailable(techType, available); break;
case Chk::UseExpSection::YesIfAvailable: ptex != nullptr ? ptex->setDefaultTechAvailable(techType, available) : ptec->setDefaultTechAvailable(techType, available); break;
case Chk::UseExpSection::NoIfOrigAvailable: ptec != nullptr ? ptec->setDefaultTechAvailable(techType, available) : ptex->setDefaultTechAvailable(techType, available); break;
}
}
void Properties::setDefaultTechResearched(Sc::Tech::Type techType, bool researched, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && ptec != nullptr )
ptec->setDefaultTechResearched(techType, researched);
if ( ptex != nullptr )
ptex->setDefaultTechResearched(techType, researched);
break;
case Chk::UseExpSection::Both: ptec->setDefaultTechResearched(techType, researched); ptex->setDefaultTechResearched(techType, researched); break;
case Chk::UseExpSection::Yes: ptex->setDefaultTechResearched(techType, researched); break;
case Chk::UseExpSection::No: ptec->setDefaultTechResearched(techType, researched); break;
case Chk::UseExpSection::YesIfAvailable: ptex != nullptr ? ptex->setDefaultTechResearched(techType, researched) : ptec->setDefaultTechResearched(techType, researched); break;
case Chk::UseExpSection::NoIfOrigAvailable: ptec != nullptr ? ptec->setDefaultTechResearched(techType, researched) : ptex->setDefaultTechResearched(techType, researched); break;
}
}
void Properties::setPlayerUsesDefaultTechSettings(Sc::Tech::Type techType, size_t playerIndex, bool useDefault, Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
if ( techType < Sc::Tech::TotalOriginalTypes && ptec != nullptr )
ptec->setPlayerUsesDefault(techType, playerIndex, useDefault);
if ( ptex != nullptr )
ptex->setPlayerUsesDefault(techType, playerIndex, useDefault);
break;
case Chk::UseExpSection::Both: ptec->setPlayerUsesDefault(techType, playerIndex, useDefault); ptex->setPlayerUsesDefault(techType, playerIndex, useDefault); break;
case Chk::UseExpSection::Yes: ptex->setPlayerUsesDefault(techType, playerIndex, useDefault); break;
case Chk::UseExpSection::No: ptec->setPlayerUsesDefault(techType, playerIndex, useDefault); break;
case Chk::UseExpSection::YesIfAvailable: ptex != nullptr ? ptex->setPlayerUsesDefault(techType, playerIndex, useDefault) : ptec->setPlayerUsesDefault(techType, playerIndex, useDefault); break;
case Chk::UseExpSection::NoIfOrigAvailable: ptec != nullptr ? ptec->setPlayerUsesDefault(techType, playerIndex, useDefault) : ptex->setPlayerUsesDefault(techType, playerIndex, useDefault); break;
}
}
void Properties::setTechsToDefault(Chk::UseExpSection useExp)
{
switch ( useExp )
{
case Chk::UseExpSection::Auto:
case Chk::UseExpSection::Both:
*tecs = *TecsSection::GetDefault();
*tecx = *TecxSection::GetDefault();
*ptec = *PtecSection::GetDefault();
*ptex = *PtexSection::GetDefault();
break;
case Chk::UseExpSection::Yes:
*tecx = *TecxSection::GetDefault();
*ptex = *PtexSection::GetDefault();
break;
case Chk::UseExpSection::No:
*tecs = *TecsSection::GetDefault();
*ptec = *PtecSection::GetDefault();
break;
case Chk::UseExpSection::YesIfAvailable:
if ( tecx != nullptr )
*tecx = *TecxSection::GetDefault();
else
*tecs = *TecsSection::GetDefault();
if ( ptex != nullptr )
*ptex = *PtexSection::GetDefault();
else
*ptec = *PtecSection::GetDefault();
break;
case Chk::UseExpSection::NoIfOrigAvailable:
if ( tecs != nullptr )
*tecs = *TecsSection::GetDefault();
else
*tecx = *TecxSection::GetDefault();
if ( ptec != nullptr )
*ptec = *PtecSection::GetDefault();
else
*ptex = *PtexSection::GetDefault();
break;
}
}
void Properties::appendUsage(size_t stringId, std::vector<Chk::StringUser> & stringUsers, u32 userMask) const
{
if ( (userMask & Chk::StringUserFlag::OriginalUnitSettings) == Chk::StringUserFlag::OriginalUnitSettings )
unis->appendUsage(stringId, stringUsers);
if ( (userMask & Chk::StringUserFlag::ExpansionUnitSettings) == Chk::StringUserFlag::ExpansionUnitSettings )
unix->appendUsage(stringId, stringUsers);
}
bool Properties::stringUsed(size_t stringId, u32 userMask) const
{
return ((userMask & Chk::StringUserFlag::OriginalUnitSettings) == Chk::StringUserFlag::OriginalUnitSettings && unis->stringUsed(stringId)) ||
((userMask & Chk::StringUserFlag::ExpansionUnitSettings) == Chk::StringUserFlag::ExpansionUnitSettings && unix->stringUsed(stringId));
}
void Properties::markUsedStrings(std::bitset<Chk::MaxStrings> & stringIdUsed, u32 userMask) const
{
if ( (userMask & Chk::StringUserFlag::OriginalUnitSettings) == Chk::StringUserFlag::OriginalUnitSettings )
unis->markUsedStrings(stringIdUsed);
if ( (userMask & Chk::StringUserFlag::ExpansionUnitSettings) == Chk::StringUserFlag::ExpansionUnitSettings )
unix->markUsedStrings(stringIdUsed);
}
void Properties::remapStringIds(const std::map<u32, u32> & stringIdRemappings)
{
unis->remapStringIds(stringIdRemappings);
unix->remapStringIds(stringIdRemappings);
}
void Properties::deleteString(size_t stringId)
{
unis->deleteString(stringId);
unix->deleteString(stringId);
}
void Properties::set(std::unordered_map<SectionName, Section> & sections)
{
unis = GetSection<UnisSection>(sections, SectionName::UNIS);
unix = GetSection<UnixSection>(sections, SectionName::UNIx);
puni = GetSection<PuniSection>(sections, SectionName::PUNI);
upgs = GetSection<UpgsSection>(sections, SectionName::UPGS);
upgx = GetSection<UpgxSection>(sections, SectionName::UPGx);
upgr = GetSection<UpgrSection>(sections, SectionName::UPGR);
pupx = GetSection<PupxSection>(sections, SectionName::PUPx);
tecs = GetSection<TecsSection>(sections, SectionName::TECS);
tecx = GetSection<TecxSection>(sections, SectionName::TECx);
ptec = GetSection<PtecSection>(sections, SectionName::PTEC);
ptex = GetSection<PtexSection>(sections, SectionName::PTEx);
if ( unis == nullptr )
unis = UnisSection::GetDefault();
if ( unix == nullptr )
unix = UnixSection::GetDefault();
if ( puni == nullptr )
puni = PuniSection::GetDefault();
if ( upgs == nullptr )
upgs = UpgsSection::GetDefault();
if ( upgx == nullptr )
upgx = UpgxSection::GetDefault();
if ( upgr == nullptr )
upgr = UpgrSection::GetDefault();
if ( pupx == nullptr )
pupx = PupxSection::GetDefault();
if ( tecs == nullptr )
tecs = TecsSection::GetDefault();
if ( tecx == nullptr )
tecx = TecxSection::GetDefault();
if ( ptec == nullptr )
ptec = PtecSection::GetDefault();
if ( ptex == nullptr )
ptex = PtexSection::GetDefault();
}
void Properties::clear()
{
unis = nullptr;
unix = nullptr;
puni = nullptr;
upgs = nullptr;
upgx = nullptr;
upgr = nullptr;
pupx = nullptr;
tecs = nullptr;
tecx = nullptr;
ptec = nullptr;
ptex = nullptr;
}
Triggers::Triggers(bool useDefault) : LocationSynchronizer(), strings(nullptr), layers(nullptr)
{
if ( useDefault )
{
uprp = UprpSection::GetDefault(); // CUWP - Create unit with properties properties
upus = UpusSection::GetDefault(); // CUWP usage
trig = TrigSection::GetDefault(); // Triggers
mbrf = MbrfSection::GetDefault(); // Mission briefing triggers
swnm = SwnmSection::GetDefault(); // Switch names
wav = WavSection::GetDefault(); // Sound names
ktrg = KtrgSection::GetDefault(); // Trigger extensions
ktgp = KtgpSection::GetDefault(); // Trigger groups
if ( wav == nullptr || swnm == nullptr || mbrf == nullptr || trig == nullptr || upus == nullptr || uprp == nullptr || ktrg == nullptr || ktgp == nullptr )
{
throw ScenarioAllocationFailure(
wav == nullptr ? ChkSection::getNameString(SectionName::WAV) :
(swnm == nullptr ? ChkSection::getNameString(SectionName::SWNM) :
(mbrf == nullptr ? ChkSection::getNameString(SectionName::MBRF) :
(trig == nullptr ? ChkSection::getNameString(SectionName::TRIG) :
(upus == nullptr ? ChkSection::getNameString(SectionName::UPUS) :
(uprp == nullptr ? ChkSection::getNameString(SectionName::UPRP) :
(ktrg == nullptr ? ChkSection::getNameString(SectionName::KTRG) :
ChkSection::getNameString(SectionName::KTGP))))))));
}
}
}
bool Triggers::empty() const
{
return uprp == nullptr && upus == nullptr && trig == nullptr && mbrf == nullptr && swnm == nullptr && wav == nullptr && ktrg == nullptr && ktgp == nullptr;
}
Chk::Cuwp Triggers::getCuwp(size_t cuwpIndex) const
{
return uprp->getCuwp(cuwpIndex);
}
void Triggers::setCuwp(size_t cuwpIndex, const Chk::Cuwp & cuwp)
{
return uprp->setCuwp(cuwpIndex, cuwp);
}
size_t Triggers::addCuwp(const Chk::Cuwp & cuwp, bool fixUsageBeforeAdding, size_t excludedTriggerIndex, size_t excludedTriggerActionIndex)
{
size_t found = uprp->findCuwp(cuwp);
if ( found < Sc::Unit::MaxCuwps )
return found;
else
{
if ( fixUsageBeforeAdding )
fixCuwpUsage(excludedTriggerIndex, excludedTriggerActionIndex);
size_t nextUnused = upus->getNextUnusedCuwpIndex();
if ( nextUnused < Sc::Unit::MaxCuwps )
uprp->setCuwp(nextUnused, cuwp);
return nextUnused;
}
}
void Triggers::fixCuwpUsage(size_t excludedTriggerIndex, size_t excludedTriggerActionIndex)
{
for ( size_t i=0; i<Sc::Unit::MaxCuwps; i++ )
upus->setCuwpUsed(i, false);
size_t numTriggers = trig->numTriggers();
for ( size_t triggerIndex=0; triggerIndex<numTriggers; triggerIndex++ )
{
Chk::TriggerPtr trigger = trig->getTrigger(triggerIndex);
for ( size_t actionIndex=0; actionIndex < Chk::Trigger::MaxActions; actionIndex++ )
{
Chk::Action & action = trigger->action(actionIndex);
if ( action.actionType == Chk::Action::Type::CreateUnitWithProperties && action.number < Sc::Unit::MaxCuwps && !(triggerIndex == excludedTriggerIndex && actionIndex == excludedTriggerActionIndex) )
upus->setCuwpUsed(action.number, true);
}
}
}
bool Triggers::cuwpUsed(size_t cuwpIndex) const
{
return upus->cuwpUsed(cuwpIndex);
}
void Triggers::setCuwpUsed(size_t cuwpIndex, bool cuwpUsed)
{
upus->setCuwpUsed(cuwpIndex, cuwpUsed);
}
size_t Triggers::numTriggers() const
{
return trig->numTriggers();
}
std::shared_ptr<Chk::Trigger> Triggers::getTrigger(size_t triggerIndex)
{
return trig->getTrigger(triggerIndex);
}
const std::shared_ptr<Chk::Trigger> Triggers::getTrigger(size_t triggerIndex) const
{
return trig->getTrigger(triggerIndex);
}
size_t Triggers::addTrigger(std::shared_ptr<Chk::Trigger> trigger)
{
return trig->addTrigger(trigger);
}
void Triggers::insertTrigger(size_t triggerIndex, std::shared_ptr<Chk::Trigger> trigger)
{
trig->insertTrigger(triggerIndex, trigger);
fixTriggerExtensions();
}
void Triggers::deleteTrigger(size_t triggerIndex)
{
trig->deleteTrigger(triggerIndex);
fixTriggerExtensions();
}
void Triggers::moveTrigger(size_t triggerIndexFrom, size_t triggerIndexTo)
{
trig->moveTrigger(triggerIndexFrom, triggerIndexTo);
fixTriggerExtensions();
}
std::deque<Chk::TriggerPtr> Triggers::replaceRange(size_t beginIndex, size_t endIndex, std::deque<Chk::TriggerPtr> & triggers)
{
return trig->replaceRange(beginIndex, endIndex, triggers);
fixTriggerExtensions();
}
Chk::ExtendedTrigDataPtr Triggers::getTriggerExtension(size_t triggerIndex, bool addIfNotFound)
{
auto trigger = trig->getTrigger(triggerIndex);
if ( trigger != nullptr )
{
size_t extendedTrigDataIndex = trigger->getExtendedDataIndex();
auto extendedTrigger = ktrg->getExtendedTrigger(extendedTrigDataIndex);
if ( extendedTrigger != nullptr )
return extendedTrigger;
else if ( addIfNotFound )
{
auto newExtendedTrigData = Chk::ExtendedTrigDataPtr(new Chk::ExtendedTrigData());
size_t newExtendedTrigDataIndex = ktrg->addExtendedTrigger(newExtendedTrigData);
if ( newExtendedTrigDataIndex != 0 )
{
trigger->setExtendedDataIndex(newExtendedTrigDataIndex);
return newExtendedTrigData;
}
}
}
return nullptr;
}
const Chk::ExtendedTrigDataPtr Triggers::getTriggerExtension(size_t triggerIndex) const
{
auto trigger = trig->getTrigger(triggerIndex);
if ( trigger != nullptr )
{
size_t extendedTrigDataIndex = trigger->getExtendedDataIndex();
auto extendedTrigger = ktrg->getExtendedTrigger(extendedTrigDataIndex);
if ( extendedTrigger != nullptr )
return extendedTrigger;
}
return nullptr;
}
void Triggers::deleteTriggerExtension(size_t triggerIndex)
{
auto trigger = trig->getTrigger(triggerIndex);
if ( trigger != nullptr )
{
size_t extendedTrigDataIndex = trigger->getExtendedDataIndex();
if ( extendedTrigDataIndex != 0 )
{
trigger->clearExtendedDataIndex();
ktrg->deleteExtendedTrigger(extendedTrigDataIndex);
}
}
}
void Triggers::fixTriggerExtensions()
{
std::set<size_t> usedExtendedTrigDataIndexes;
size_t numTriggers = trig->numTriggers();
for ( size_t i=0; i<numTriggers; i++ )
{
Chk::TriggerPtr trigger = trig->getTrigger(i);
if ( trigger != nullptr )
{
size_t extendedDataIndex = trigger->getExtendedDataIndex();
if ( extendedDataIndex != Chk::ExtendedTrigDataIndex::None )
{
Chk::ExtendedTrigDataPtr extension = ktrg->getExtendedTrigger(extendedDataIndex);
if ( extension == nullptr ) // Invalid extendedDataIndex
trigger->clearExtendedDataIndex();
else if ( usedExtendedTrigDataIndexes.find(extendedDataIndex) == usedExtendedTrigDataIndexes.end() ) // Valid extension
{
extension->trigNum = (u32)i; // Ensure the trigNum is correct
usedExtendedTrigDataIndexes.insert(extendedDataIndex);
}
else // Same extension used by multiple triggers
trigger->clearExtendedDataIndex();
}
}
}
size_t numTriggerExtensions = ktrg->numExtendedTriggers();
for ( size_t i=0; i<numTriggerExtensions; i++ )
{
Chk::ExtendedTrigDataPtr extension = ktrg->getExtendedTrigger(i);
if ( extension != nullptr && usedExtendedTrigDataIndexes.find(i) == usedExtendedTrigDataIndexes.end() ) // Extension exists, but no trigger uses it
{
if ( extension->trigNum != Chk::ExtendedTrigData::TrigNum::None ) // Refers to a trigger
{
Chk::TriggerPtr trigger = trig->getTrigger(extension->trigNum);
if ( trigger != nullptr && trigger->getExtendedDataIndex() == Chk::ExtendedTrigDataIndex::None ) // This trigger exists without an extension
trigger->setExtendedDataIndex(i); // Link up extension to the trigger
else if ( trigger == nullptr ) // Trigger does not exist
ktrg->deleteExtendedTrigger(i); // Delete the extension
}
else if ( extension->trigNum == Chk::ExtendedTrigData::TrigNum::None ) // Does not refer to a trigger
ktrg->deleteExtendedTrigger(i); // Delete the extension
}
}
}
size_t Triggers::getCommentStringId(size_t triggerIndex) const
{
auto trigger = trig->getTrigger(triggerIndex);
if ( trigger != nullptr )
return trigger->getComment();
else
return Chk::StringId::NoString;
}
size_t Triggers::getExtendedCommentStringId(size_t triggerIndex) const
{
const Chk::ExtendedTrigDataPtr extension = getTriggerExtension(triggerIndex);
if ( extension != nullptr )
return extension->commentStringId;
return Chk::StringId::NoString;
}
void Triggers::setExtendedCommentStringId(size_t triggerIndex, size_t stringId)
{
Chk::ExtendedTrigDataPtr extension = getTriggerExtension(triggerIndex, stringId != Chk::StringId::NoString);
if ( extension != nullptr )
{
extension->commentStringId = (u32)stringId;
if ( stringId == Chk::StringId::NoString && extension->isBlank() )
deleteTriggerExtension(triggerIndex);
}
}
size_t Triggers::getExtendedNotesStringId(size_t triggerIndex) const
{
const Chk::ExtendedTrigDataPtr extension = getTriggerExtension(triggerIndex);
if ( extension != nullptr )
return extension->notesStringId;
return Chk::StringId::NoString;
}
void Triggers::setExtendedNotesStringId(size_t triggerIndex, size_t stringId)
{
Chk::ExtendedTrigDataPtr extension = getTriggerExtension(triggerIndex, stringId != Chk::StringId::NoString);
if ( extension != nullptr )
{
extension->notesStringId = (u32)stringId;
if ( stringId == Chk::StringId::NoString && extension->isBlank() )
deleteTriggerExtension(triggerIndex);
}
}
size_t Triggers::numBriefingTriggers() const
{
return mbrf->numBriefingTriggers();
}
std::shared_ptr<Chk::Trigger> Triggers::getBriefingTrigger(size_t briefingTriggerIndex)
{
return mbrf->getBriefingTrigger(briefingTriggerIndex);
}
const std::shared_ptr<Chk::Trigger> Triggers::getBriefingTrigger(size_t briefingTriggerIndex) const
{
return mbrf->getBriefingTrigger(briefingTriggerIndex);
}
size_t Triggers::addBriefingTrigger(std::shared_ptr<Chk::Trigger> briefingTrigger)
{
return mbrf->addBriefingTrigger(briefingTrigger);
}
void Triggers::insertBriefingTrigger(size_t briefingTriggerIndex, std::shared_ptr<Chk::Trigger> briefingTrigger)
{
mbrf->insertBriefingTrigger(briefingTriggerIndex, briefingTrigger);
}
void Triggers::deleteBriefingTrigger(size_t briefingTriggerIndex)
{
mbrf->deleteBriefingTrigger(briefingTriggerIndex);
}
void Triggers::moveBriefingTrigger(size_t briefingTriggerIndexFrom, size_t briefingTriggerIndexTo)
{
mbrf->moveBriefingTrigger(briefingTriggerIndexFrom, briefingTriggerIndexTo);
}
size_t Triggers::getSwitchNameStringId(size_t switchIndex) const
{
return swnm->getSwitchNameStringId(switchIndex);
}
void Triggers::setSwitchNameStringId(size_t switchIndex, size_t stringId)
{
swnm->setSwitchNameStringId(switchIndex, stringId);
}
size_t Triggers::addSound(size_t stringId)
{
return wav->addSound(stringId);
}
bool Triggers::stringIsSound(size_t stringId) const
{
return wav->stringIsSound(stringId);
}
size_t Triggers::getSoundStringId(size_t soundIndex) const
{
return wav->getSoundStringId(soundIndex);
}
void Triggers::setSoundStringId(size_t soundIndex, size_t soundStringId)
{
wav->setSoundStringId(soundIndex, soundStringId);
}
bool Triggers::locationUsed(size_t locationId) const
{
return trig->locationUsed(locationId);
}
void Triggers::appendUsage(size_t stringId, std::vector<Chk::StringUser> & stringUsers, Chk::Scope storageScope, u32 userMask) const
{
if ( (storageScope & Chk::Scope::Game) == Chk::Scope::Game )
{
if ( (userMask & Chk::StringUserFlag::Sound) != Chk::StringUserFlag::None )
wav->appendUsage(stringId, stringUsers);
if ( (userMask & Chk::StringUserFlag::Switch) != Chk::StringUserFlag::None )
swnm->appendUsage(stringId, stringUsers);
if ( (userMask & Chk::StringUserFlag::AnyTrigger) != Chk::StringUserFlag::None )
trig->appendUsage(stringId, stringUsers, userMask);
if ( (userMask & Chk::StringUserFlag::AnyBriefingTrigger) != Chk::StringUserFlag::None )
mbrf->appendUsage(stringId, stringUsers, userMask);
}
if ( (storageScope & Chk::Scope::Editor) == Chk::Scope::Editor && (userMask & Chk::StringUserFlag::AnyTriggerExtension) != Chk::StringUserFlag::None )
ktrg->appendUsage(stringId, stringUsers, userMask);
}
bool Triggers::stringUsed(size_t stringId, Chk::Scope storageScope, u32 userMask) const
{
if ( storageScope == Chk::Scope::Game )
{
return (userMask & Chk::StringUserFlag::Sound) == Chk::StringUserFlag::Sound && wav->stringUsed(stringId) ||
(userMask & Chk::StringUserFlag::Switch) == Chk::StringUserFlag::Switch && swnm->stringUsed(stringId) ||
(userMask & Chk::StringUserFlag::AnyTrigger) > 0 && trig->stringUsed(stringId, userMask) ||
(userMask & Chk::StringUserFlag::AnyBriefingTrigger) > 0 && mbrf->stringUsed(stringId, userMask);
}
else
return storageScope == Chk::Scope::Editor && (userMask & Chk::StringUserFlag::AnyTriggerExtension) > 0 && ktrg->editorStringUsed(stringId, userMask);
}
bool Triggers::gameStringUsed(size_t stringId, u32 userMask) const
{
return (userMask & Chk::StringUserFlag::AnyTrigger) > 0 && trig->gameStringUsed(stringId, userMask) ||
(userMask & Chk::StringUserFlag::AnyBriefingTrigger) > 0 && mbrf->stringUsed(stringId);
}
bool Triggers::editorStringUsed(size_t stringId, Chk::Scope storageScope, u32 userMask) const
{
if ( storageScope == Chk::Scope::Game )
{
return (userMask & Chk::StringUserFlag::Sound) == Chk::StringUserFlag::Sound && wav->stringUsed(stringId) ||
(userMask & Chk::StringUserFlag::Switch) == Chk::StringUserFlag::Switch && swnm->stringUsed(stringId) ||
(userMask & Chk::StringUserFlag::TriggerAction) == Chk::StringUserFlag::TriggerAction && trig->commentStringUsed(stringId) ||
(userMask & Chk::StringUserFlag::AnyTriggerExtension) > 0 && ktrg->editorStringUsed(stringId, userMask);
}
else
return storageScope == Chk::Scope::Editor && (userMask & Chk::StringUserFlag::AnyTriggerExtension) > 0 && ktrg->editorStringUsed(stringId, userMask);
}
void Triggers::markUsedLocations(std::bitset<Chk::TotalLocations+1> & locationIdUsed) const
{
trig->markUsedLocations(locationIdUsed);
}
void Triggers::markUsedStrings(std::bitset<Chk::MaxStrings> & stringIdUsed, Chk::Scope storageScope, u32 userMask) const
{
if ( storageScope == Chk::Scope::Game )
{
if ( (userMask & Chk::StringUserFlag::Sound) == Chk::StringUserFlag::Sound )
wav->markUsedStrings(stringIdUsed);
if ( (userMask & Chk::StringUserFlag::Switch) == Chk::StringUserFlag::Switch )
swnm->markUsedStrings(stringIdUsed);
if ( (userMask & Chk::StringUserFlag::AnyTrigger) > 0 )
trig->markUsedStrings(stringIdUsed, userMask);
if ( (userMask & Chk::StringUserFlag::AnyBriefingTrigger) > 0 )
mbrf->markUsedStrings(stringIdUsed, userMask);
}
else if ( storageScope == Chk::Scope::Editor && (userMask & Chk::StringUserFlag::AnyTriggerExtension) > 0 )
ktrg->markUsedEditorStrings(stringIdUsed, userMask);
}
void Triggers::markUsedGameStrings(std::bitset<Chk::MaxStrings> & stringIdUsed, u32 userMask) const
{
if ( (userMask & Chk::StringUserFlag::AnyTrigger) > 0 )
trig->markUsedGameStrings(stringIdUsed);
if ( (userMask & Chk::StringUserFlag::AnyBriefingTrigger) > 0 )
mbrf->markUsedStrings(stringIdUsed);
}
void Triggers::markUsedEditorStrings(std::bitset<Chk::MaxStrings> & stringIdUsed, Chk::Scope storageScope, u32 userMask) const
{
if ( storageScope == Chk::Scope::Game )
{
if ( (userMask & Chk::StringUserFlag::Sound) == Chk::StringUserFlag::Sound )
wav->markUsedStrings(stringIdUsed);
if ( (userMask & Chk::StringUserFlag::Switch) == Chk::StringUserFlag::Switch )
swnm->markUsedStrings(stringIdUsed);
if ( (userMask & Chk::StringUserFlag::TriggerAction) == Chk::StringUserFlag::TriggerAction )
trig->markUsedCommentStrings(stringIdUsed);
}
else if ( storageScope == Chk::Scope::Editor && (userMask & Chk::StringUserFlag::AnyTriggerExtension) > 0 )
ktrg->markUsedEditorStrings(stringIdUsed, userMask);
}
void Triggers::remapLocationIds(const std::map<u32, u32> & locationIdRemappings)
{
trig->remapLocationIds(locationIdRemappings);
}
void Triggers::remapStringIds(const std::map<u32, u32> & stringIdRemappings, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Game )
{
wav->remapStringIds(stringIdRemappings);
swnm->remapStringIds(stringIdRemappings);
trig->remapStringIds(stringIdRemappings);
mbrf->remapStringIds(stringIdRemappings);
}
else if ( storageScope == Chk::Scope::Editor )
ktrg->remapEditorStringIds(stringIdRemappings);
}
void Triggers::deleteLocation(size_t locationId)
{
trig->deleteLocation(locationId);
}
void Triggers::deleteString(size_t stringId, Chk::Scope storageScope)
{
if ( storageScope == Chk::Scope::Game )
{
wav->deleteString(stringId);
swnm->deleteString(stringId);
trig->deleteString(stringId);
mbrf->deleteString(stringId);
}
else if ( storageScope == Chk::Scope::Editor )
ktrg->deleteEditorString(stringId);
}
void Triggers::set(std::unordered_map<SectionName, Section> & sections)
{
uprp = GetSection<UprpSection>(sections, SectionName::UPRP);
upus = GetSection<UpusSection>(sections, SectionName::UPUS);
trig = GetSection<TrigSection>(sections, SectionName::TRIG);
mbrf = GetSection<MbrfSection>(sections, SectionName::MBRF);
swnm = GetSection<SwnmSection>(sections, SectionName::SWNM);
wav = GetSection<WavSection>(sections, SectionName::WAV);
ktrg = GetSection<KtrgSection>(sections, SectionName::KTRG);
ktgp = GetSection<KtgpSection>(sections, SectionName::KTGP);
if ( uprp == nullptr )
uprp = UprpSection::GetDefault();
if ( upus == nullptr )
upus = UpusSection::GetDefault();
if ( trig == nullptr )
trig = TrigSection::GetDefault();
if ( mbrf == nullptr )
mbrf = MbrfSection::GetDefault();
if ( swnm == nullptr )
swnm = SwnmSection::GetDefault();
if ( wav == nullptr )
wav = WavSection::GetDefault();
if ( ktrg == nullptr )
ktrg = KtrgSection::GetDefault();
if ( ktgp == nullptr )
ktgp = KtgpSection::GetDefault();
}
void Triggers::clear()
{
uprp = nullptr;
upus = nullptr;
trig = nullptr;
mbrf = nullptr;
swnm = nullptr;
wav = nullptr;
ktrg = nullptr;
ktgp = nullptr;
}
|
d9950b42615c5d069f962994ad4d7e4c3911336c
|
cd9313c4dfe06d831016919233e2d2886ddca8a7
|
/boj2573.cpp
|
2085572ec0d13e834ec15432529792e2b1fab259
|
[] |
no_license
|
HJPyo/C
|
b198efa19f7484cc5b13e3e83798cdac99b6cd20
|
47d49f3aea1bc928fec5bcb344197c3dfecf5dd1
|
refs/heads/main
| 2023-04-12T15:04:44.844842
| 2021-05-11T09:13:07
| 2021-05-11T09:13:07
| 328,389,106
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 873
|
cpp
|
boj2573.cpp
|
#include<stdio.h>
#include<string.h>
int n, m, ar[303][303], vis[303][303];
int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};
void dfs(int x, int y)
{
vis[x][y] = 1;
for(int i = 0; i < 4; i++){
int nx = x+dx[i];
int ny = y+dy[i];
if(ar[nx][ny]){
dfs(nx,ny);
}
}
}
int main()
{
memset(ar, -1, sizeof(ar));
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
scanf("%d", &ar[i][j]);
}
}
int ans = 0;
while(1)
{
memset(vis, 0, sizeof(vis));
int cnt = 0;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(ar[i][j]){
cnt++;
dfs(i,j);
}
}
}
if(cnt == 0){
ans = 0;
break;
}
else if(cnt == 1){
break;
}
else{
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(ar[i][j]) ar[i][j]--;
}
}
ans++;
}
}
printf("%d", ans);
}
|
ffc0ca120b47c8126d5079af2f58aa172e6d5e2d
|
dd71e72950b532226396ad012e051e1f1d8975f8
|
/codes/subarraySumEqualsK.cpp
|
cf7eca59572f43bc9dafdc66c1a7e5c8a2e7491f
|
[] |
no_license
|
ashishbisoi236/CF
|
0ca3626ec8138265fea2718f028b13a56dcbcb35
|
aade9143c96503896666511114f56969f0ad0872
|
refs/heads/master
| 2023-02-21T03:53:10.383657
| 2021-01-24T12:06:44
| 2021-01-24T12:06:44
| 296,493,451
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,116
|
cpp
|
subarraySumEqualsK.cpp
|
// count no of subarrays
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> um;
int count = 0;
int sum = 0;
int n = nums.size();
for(int i = 0; i < n; i++) {
sum += nums[i];
if(sum == k)
count++;
if(um.find(sum - k) != um.end())
count += um[sum - k];
um[sum]++;
}
return count;
}
};
// position of first subarray
#include <iostream>
using namespace std;
int main() {
//code
int t;
cin >> t;
while(t--) {
int n, s;
cin >> n >> s;
int a[n];
for(int i = 0; i < n; i++)
cin >> a[i];
int sum = 0, pivot = 0, flag = 0;
for(int i = 0; i < n; i++) {
sum += a[i];
while(sum > s) {
sum -= a[pivot];
pivot++;
}
if(sum == s) {
cout << pivot + 1 << " " << i + 1 << "\n";
flag = 1;
break;
}
}
if(flag == 0)
cout << -1 << "\n";
}
return 0;
}
|
e02e8026fe0b1050e71a2a87743b4d631290df0a
|
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
|
/out/release/gen/content/common/page_state.mojom.cc
|
cbeb1533c0b8fb2c65f4795871ca6a5cbb469e5c
|
[
"BSD-3-Clause"
] |
permissive
|
xueqiya/chromium_src
|
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
|
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
|
refs/heads/main
| 2022-07-30T03:15:14.818330
| 2021-01-16T16:47:22
| 2021-01-16T16:47:22
| 330,115,551
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 19,199
|
cc
|
page_state.mojom.cc
|
// content/common/page_state.mojom.cc is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-private-field"
#elif defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4056)
#pragma warning(disable:4065)
#pragma warning(disable:4756)
#endif
#include "content/common/page_state.mojom.h"
#include <math.h>
#include <stdint.h>
#include <utility>
#include "base/hash/md5_constexpr.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "base/task/common/task_annotator.h"
#include "mojo/public/cpp/bindings/lib/generated_code_util.h"
#include "mojo/public/cpp/bindings/lib/message_internal.h"
#include "mojo/public/cpp/bindings/lib/serialization_util.h"
#include "mojo/public/cpp/bindings/lib/unserialized_message_context.h"
#include "mojo/public/cpp/bindings/lib/validate_params.h"
#include "mojo/public/cpp/bindings/lib/validation_context.h"
#include "mojo/public/cpp/bindings/lib/validation_errors.h"
#include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h"
#include "content/common/page_state.mojom-params-data.h"
#include "content/common/page_state.mojom-shared-message-ids.h"
#include "content/common/page_state.mojom-import-headers.h"
#ifndef CONTENT_COMMON_PAGE_STATE_MOJOM_JUMBO_H_
#define CONTENT_COMMON_PAGE_STATE_MOJOM_JUMBO_H_
#include "mojo/public/cpp/base/string16_mojom_traits.h"
#include "mojo/public/cpp/base/time_mojom_traits.h"
#include "ui/gfx/geometry/mojom/geometry_mojom_traits.h"
#include "url/mojom/url_gurl_mojom_traits.h"
#endif
namespace content {
namespace history {
namespace mojom {
DEPRECATED_FileSystemFile::DEPRECATED_FileSystemFile()
: filesystem_url(),
offset(),
length(),
modification_time() {}
DEPRECATED_FileSystemFile::DEPRECATED_FileSystemFile(
const ::GURL& filesystem_url_in,
uint64_t offset_in,
uint64_t length_in,
::base::Time modification_time_in)
: filesystem_url(std::move(filesystem_url_in)),
offset(std::move(offset_in)),
length(std::move(length_in)),
modification_time(std::move(modification_time_in)) {}
DEPRECATED_FileSystemFile::~DEPRECATED_FileSystemFile() = default;
bool DEPRECATED_FileSystemFile::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
return Data_::Validate(data, validation_context);
}
File::File()
: path(),
offset(),
length(),
modification_time() {}
File::File(
const ::base::string16& path_in,
uint64_t offset_in,
uint64_t length_in,
::base::Time modification_time_in)
: path(std::move(path_in)),
offset(std::move(offset_in)),
length(std::move(length_in)),
modification_time(std::move(modification_time_in)) {}
File::~File() = default;
bool File::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
return Data_::Validate(data, validation_context);
}
RequestBody::RequestBody()
: elements(),
identifier(),
contains_sensitive_info() {}
RequestBody::RequestBody(
std::vector<ElementPtr> elements_in,
int64_t identifier_in,
bool contains_sensitive_info_in)
: elements(std::move(elements_in)),
identifier(std::move(identifier_in)),
contains_sensitive_info(std::move(contains_sensitive_info_in)) {}
RequestBody::~RequestBody() = default;
bool RequestBody::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
return Data_::Validate(data, validation_context);
}
HttpBody::HttpBody()
: http_content_type(),
request_body(),
contains_passwords(false) {}
HttpBody::HttpBody(
const base::Optional<::base::string16>& http_content_type_in,
RequestBodyPtr request_body_in,
bool contains_passwords_in)
: http_content_type(std::move(http_content_type_in)),
request_body(std::move(request_body_in)),
contains_passwords(std::move(contains_passwords_in)) {}
HttpBody::~HttpBody() = default;
bool HttpBody::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
return Data_::Validate(data, validation_context);
}
ViewState::ViewState()
: visual_viewport_scroll_offset(),
scroll_offset(),
page_scale_factor(),
scroll_anchor_selector(),
scroll_anchor_offset(),
scroll_anchor_simhash(0ULL) {}
ViewState::ViewState(
const ::gfx::PointF& visual_viewport_scroll_offset_in,
const ::gfx::Point& scroll_offset_in,
double page_scale_factor_in)
: visual_viewport_scroll_offset(std::move(visual_viewport_scroll_offset_in)),
scroll_offset(std::move(scroll_offset_in)),
page_scale_factor(std::move(page_scale_factor_in)),
scroll_anchor_selector(),
scroll_anchor_offset(),
scroll_anchor_simhash(0ULL) {}
ViewState::ViewState(
const ::gfx::PointF& visual_viewport_scroll_offset_in,
const ::gfx::Point& scroll_offset_in,
double page_scale_factor_in,
const base::Optional<::base::string16>& scroll_anchor_selector_in,
const base::Optional<::gfx::PointF>& scroll_anchor_offset_in,
uint64_t scroll_anchor_simhash_in)
: visual_viewport_scroll_offset(std::move(visual_viewport_scroll_offset_in)),
scroll_offset(std::move(scroll_offset_in)),
page_scale_factor(std::move(page_scale_factor_in)),
scroll_anchor_selector(std::move(scroll_anchor_selector_in)),
scroll_anchor_offset(std::move(scroll_anchor_offset_in)),
scroll_anchor_simhash(std::move(scroll_anchor_simhash_in)) {}
ViewState::~ViewState() = default;
bool ViewState::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
return Data_::Validate(data, validation_context);
}
FrameState::FrameState()
: url_string(),
referrer(),
target(),
state_object(),
document_state(),
scroll_restoration_type(),
view_state(),
item_sequence_number(),
document_sequence_number(),
referrer_policy(),
http_body(),
children(),
initiator_origin() {}
FrameState::FrameState(
const base::Optional<::base::string16>& url_string_in,
const base::Optional<::base::string16>& referrer_in,
const base::Optional<::base::string16>& target_in,
const base::Optional<::base::string16>& state_object_in,
std::vector<base::Optional<::base::string16>> document_state_in,
ScrollRestorationType scroll_restoration_type_in,
ViewStatePtr view_state_in,
int64_t item_sequence_number_in,
int64_t document_sequence_number_in,
::network::mojom::ReferrerPolicy referrer_policy_in,
HttpBodyPtr http_body_in,
std::vector<FrameStatePtr> children_in)
: url_string(std::move(url_string_in)),
referrer(std::move(referrer_in)),
target(std::move(target_in)),
state_object(std::move(state_object_in)),
document_state(std::move(document_state_in)),
scroll_restoration_type(std::move(scroll_restoration_type_in)),
view_state(std::move(view_state_in)),
item_sequence_number(std::move(item_sequence_number_in)),
document_sequence_number(std::move(document_sequence_number_in)),
referrer_policy(std::move(referrer_policy_in)),
http_body(std::move(http_body_in)),
children(std::move(children_in)),
initiator_origin() {}
FrameState::FrameState(
const base::Optional<::base::string16>& url_string_in,
const base::Optional<::base::string16>& referrer_in,
const base::Optional<::base::string16>& target_in,
const base::Optional<::base::string16>& state_object_in,
std::vector<base::Optional<::base::string16>> document_state_in,
ScrollRestorationType scroll_restoration_type_in,
ViewStatePtr view_state_in,
int64_t item_sequence_number_in,
int64_t document_sequence_number_in,
::network::mojom::ReferrerPolicy referrer_policy_in,
HttpBodyPtr http_body_in,
std::vector<FrameStatePtr> children_in,
const base::Optional<std::string>& initiator_origin_in)
: url_string(std::move(url_string_in)),
referrer(std::move(referrer_in)),
target(std::move(target_in)),
state_object(std::move(state_object_in)),
document_state(std::move(document_state_in)),
scroll_restoration_type(std::move(scroll_restoration_type_in)),
view_state(std::move(view_state_in)),
item_sequence_number(std::move(item_sequence_number_in)),
document_sequence_number(std::move(document_sequence_number_in)),
referrer_policy(std::move(referrer_policy_in)),
http_body(std::move(http_body_in)),
children(std::move(children_in)),
initiator_origin(std::move(initiator_origin_in)) {}
FrameState::~FrameState() = default;
bool FrameState::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
return Data_::Validate(data, validation_context);
}
PageState::PageState()
: referenced_files(),
top() {}
PageState::PageState(
std::vector<base::Optional<::base::string16>> referenced_files_in,
FrameStatePtr top_in)
: referenced_files(std::move(referenced_files_in)),
top(std::move(top_in)) {}
PageState::~PageState() = default;
bool PageState::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
return Data_::Validate(data, validation_context);
}
Element::Element() : tag_(Tag::BLOB_UUID) {
data_.blob_uuid = new std::string;
}
Element::~Element() {
DestroyActive();
}
void Element::set_blob_uuid(
const std::string& blob_uuid) {
if (tag_ == Tag::BLOB_UUID) {
*(data_.blob_uuid) = std::move(blob_uuid);
} else {
DestroyActive();
tag_ = Tag::BLOB_UUID;
data_.blob_uuid = new std::string(
std::move(blob_uuid));
}
}
void Element::set_bytes(
std::vector<uint8_t> bytes) {
if (tag_ == Tag::BYTES) {
*(data_.bytes) = std::move(bytes);
} else {
DestroyActive();
tag_ = Tag::BYTES;
data_.bytes = new std::vector<uint8_t>(
std::move(bytes));
}
}
void Element::set_file(
FilePtr file) {
if (tag_ == Tag::FILE) {
*(data_.file) = std::move(file);
} else {
DestroyActive();
tag_ = Tag::FILE;
data_.file = new FilePtr(
std::move(file));
}
}
void Element::set_DEPRECATED_file_system_file(
DEPRECATED_FileSystemFilePtr DEPRECATED_file_system_file) {
if (tag_ == Tag::DEPRECATED_FILE_SYSTEM_FILE) {
*(data_.DEPRECATED_file_system_file) = std::move(DEPRECATED_file_system_file);
} else {
DestroyActive();
tag_ = Tag::DEPRECATED_FILE_SYSTEM_FILE;
data_.DEPRECATED_file_system_file = new DEPRECATED_FileSystemFilePtr(
std::move(DEPRECATED_file_system_file));
}
}
void Element::DestroyActive() {
switch (tag_) {
case Tag::BLOB_UUID:
delete data_.blob_uuid;
break;
case Tag::BYTES:
delete data_.bytes;
break;
case Tag::FILE:
delete data_.file;
break;
case Tag::DEPRECATED_FILE_SYSTEM_FILE:
delete data_.DEPRECATED_file_system_file;
break;
}
}
bool Element::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
return Data_::Validate(data, validation_context, false);
}
} // namespace mojom
} // namespace history
} // namespace content
namespace mojo {
// static
bool StructTraits<::content::history::mojom::DEPRECATED_FileSystemFile::DataView, ::content::history::mojom::DEPRECATED_FileSystemFilePtr>::Read(
::content::history::mojom::DEPRECATED_FileSystemFile::DataView input,
::content::history::mojom::DEPRECATED_FileSystemFilePtr* output) {
bool success = true;
::content::history::mojom::DEPRECATED_FileSystemFilePtr result(::content::history::mojom::DEPRECATED_FileSystemFile::New());
if (success && !input.ReadFilesystemUrl(&result->filesystem_url))
success = false;
if (success)
result->offset = input.offset();
if (success)
result->length = input.length();
if (success && !input.ReadModificationTime(&result->modification_time))
success = false;
*output = std::move(result);
return success;
}
// static
bool StructTraits<::content::history::mojom::File::DataView, ::content::history::mojom::FilePtr>::Read(
::content::history::mojom::File::DataView input,
::content::history::mojom::FilePtr* output) {
bool success = true;
::content::history::mojom::FilePtr result(::content::history::mojom::File::New());
if (success && !input.ReadPath(&result->path))
success = false;
if (success)
result->offset = input.offset();
if (success)
result->length = input.length();
if (success && !input.ReadModificationTime(&result->modification_time))
success = false;
*output = std::move(result);
return success;
}
// static
bool StructTraits<::content::history::mojom::RequestBody::DataView, ::content::history::mojom::RequestBodyPtr>::Read(
::content::history::mojom::RequestBody::DataView input,
::content::history::mojom::RequestBodyPtr* output) {
bool success = true;
::content::history::mojom::RequestBodyPtr result(::content::history::mojom::RequestBody::New());
if (success && !input.ReadElements(&result->elements))
success = false;
if (success)
result->identifier = input.identifier();
if (success)
result->contains_sensitive_info = input.contains_sensitive_info();
*output = std::move(result);
return success;
}
// static
bool StructTraits<::content::history::mojom::HttpBody::DataView, ::content::history::mojom::HttpBodyPtr>::Read(
::content::history::mojom::HttpBody::DataView input,
::content::history::mojom::HttpBodyPtr* output) {
bool success = true;
::content::history::mojom::HttpBodyPtr result(::content::history::mojom::HttpBody::New());
if (success && !input.ReadHttpContentType(&result->http_content_type))
success = false;
if (success && !input.ReadRequestBody(&result->request_body))
success = false;
if (success)
result->contains_passwords = input.contains_passwords();
*output = std::move(result);
return success;
}
// static
bool StructTraits<::content::history::mojom::ViewState::DataView, ::content::history::mojom::ViewStatePtr>::Read(
::content::history::mojom::ViewState::DataView input,
::content::history::mojom::ViewStatePtr* output) {
bool success = true;
::content::history::mojom::ViewStatePtr result(::content::history::mojom::ViewState::New());
if (success && !input.ReadVisualViewportScrollOffset(&result->visual_viewport_scroll_offset))
success = false;
if (success && !input.ReadScrollOffset(&result->scroll_offset))
success = false;
if (success)
result->page_scale_factor = input.page_scale_factor();
if (success && !input.ReadScrollAnchorSelector(&result->scroll_anchor_selector))
success = false;
if (success && !input.ReadScrollAnchorOffset(&result->scroll_anchor_offset))
success = false;
if (success)
result->scroll_anchor_simhash = input.scroll_anchor_simhash();
*output = std::move(result);
return success;
}
// static
bool StructTraits<::content::history::mojom::FrameState::DataView, ::content::history::mojom::FrameStatePtr>::Read(
::content::history::mojom::FrameState::DataView input,
::content::history::mojom::FrameStatePtr* output) {
bool success = true;
::content::history::mojom::FrameStatePtr result(::content::history::mojom::FrameState::New());
if (success && !input.ReadUrlString(&result->url_string))
success = false;
if (success && !input.ReadReferrer(&result->referrer))
success = false;
if (success && !input.ReadTarget(&result->target))
success = false;
if (success && !input.ReadStateObject(&result->state_object))
success = false;
if (success && !input.ReadDocumentState(&result->document_state))
success = false;
if (success && !input.ReadScrollRestorationType(&result->scroll_restoration_type))
success = false;
if (success && !input.ReadViewState(&result->view_state))
success = false;
if (success)
result->item_sequence_number = input.item_sequence_number();
if (success)
result->document_sequence_number = input.document_sequence_number();
if (success && !input.ReadReferrerPolicy(&result->referrer_policy))
success = false;
if (success && !input.ReadHttpBody(&result->http_body))
success = false;
if (success && !input.ReadChildren(&result->children))
success = false;
if (success && !input.ReadInitiatorOrigin(&result->initiator_origin))
success = false;
*output = std::move(result);
return success;
}
// static
bool StructTraits<::content::history::mojom::PageState::DataView, ::content::history::mojom::PageStatePtr>::Read(
::content::history::mojom::PageState::DataView input,
::content::history::mojom::PageStatePtr* output) {
bool success = true;
::content::history::mojom::PageStatePtr result(::content::history::mojom::PageState::New());
if (success && !input.ReadReferencedFiles(&result->referenced_files))
success = false;
if (success && !input.ReadTop(&result->top))
success = false;
*output = std::move(result);
return success;
}
// static
bool UnionTraits<::content::history::mojom::Element::DataView, ::content::history::mojom::ElementPtr>::Read(
::content::history::mojom::Element::DataView input,
::content::history::mojom::ElementPtr* output) {
using UnionType = ::content::history::mojom::Element;
using Tag = UnionType::Tag;
switch (input.tag()) {
case Tag::BLOB_UUID: {
std::string result_blob_uuid;
if (!input.ReadBlobUuid(&result_blob_uuid))
return false;
*output = UnionType::NewBlobUuid(
std::move(result_blob_uuid));
break;
}
case Tag::BYTES: {
std::vector<uint8_t> result_bytes;
if (!input.ReadBytes(&result_bytes))
return false;
*output = UnionType::NewBytes(
std::move(result_bytes));
break;
}
case Tag::FILE: {
::content::history::mojom::FilePtr result_file;
if (!input.ReadFile(&result_file))
return false;
*output = UnionType::NewFile(
std::move(result_file));
break;
}
case Tag::DEPRECATED_FILE_SYSTEM_FILE: {
::content::history::mojom::DEPRECATED_FileSystemFilePtr result_DEPRECATED_file_system_file;
if (!input.ReadDEPRECATEDFileSystemFile(&result_DEPRECATED_file_system_file))
return false;
*output = UnionType::NewDEPRECATEDFileSystemFile(
std::move(result_DEPRECATED_file_system_file));
break;
}
default:
return false;
}
return true;
}
} // namespace mojo
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(_MSC_VER)
#pragma warning(pop)
#endif
|
e3314d5aced7387057cb139b24c5a7cce32803a2
|
349b0dbeaccc8b9113434c7bce7b9166f4ad51de
|
/src/lcs/LCEI/EXT.CPP
|
88a80bdb710525ed46aecbf2f7f3b020e743789a
|
[] |
no_license
|
jbailhache/log
|
94a89342bb2ac64018e5aa0cf84c19ef40aa84b4
|
2780adfe3df18f9e40653296aae9c56a31369d47
|
refs/heads/master
| 2021-01-10T08:55:43.044934
| 2020-01-09T02:57:38
| 2020-01-09T02:57:38
| 54,238,064
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,265
|
cpp
|
EXT.CPP
|
#include "lctm.h"
DEM transym_redu (DEM ab, DEM cd)
{
DEM ae, cf, fc, eb, fd, bd;
if (ab == cd)
return right (ab);
if (left(ab) == left(cd))
{
bd = transym (ab, cd);
}
else
{
ae = redu (left(ab));
eb = transym (ae, ab);
cf = redu (left(cd));
fd = transym (cf, cd);
bd = transym (eb, fd);
}
return bd;
}
DEM ext (DEM x, DEM t)
{
DEM ext_I, ext_K, ext_S, te, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10;
trace_dem ("ext", x);
trace_dem ("ext", t);
ext_I = Ext1;
ext_K = Ext2;
ext_S = Ext3;
if (t == x)
{
trace_dem ("return", I);
return I;
}
if (!in (x, left(t)) && !in (x, right(t)))
{
te = ap (K, t);
trace_dem ("", te);
return te;
}
if (node(t) == _ap && subdem(1,t) == x &&
!in (x, left(subdem(0,t))) && !in (x, right(subdem(0,t))))
return subdem(0,t);
switch (node(t))
{
case _transym:
trace_dem ("transym", t);
t1 = ext (x, subdem(0,t)); trace_dem ("", t1);
t2 = ext (x, subdem(1,t)); trace_dem ("", t2);
trace_dem ("", t1);
trace_dem ("transym", t);
te = transym_redu (t1, t2); trace_dem ("", te);
return te;
case _ap:
trace_dem ("ap", t);
t1 = ext (x, subdem(0,t)); trace_dem ("", t1);
t2 = ext (x, subdem(1,t)); trace_dem ("", t2);
te = app (S, t1, t2); trace_dem ("", te);
return te;
case _defI:
trace_dem ("defI", t);
t1 = ext (x, subdem(0,t)); trace_dem ("", t1);
te = trans (ap (ext_I, t1), defI (right(t1)));
trace_dem ("", te);
return te;
case _defK:
trace_dem ("defK", t);
t1 = ext (x, subdem(0,t)); trace_dem ("", t1);
t2 = ext (x, subdem(1,t)); trace_dem ("", t2);
t3 = app (ext_K, t1, t2); trace_dem ("", t3);
t4 = defK (right(t1), right(t2)); trace_dem ("", t4);
t5 = trans (t3, t4); trace_dem ("", t5);
t6 = red (left(t5)); trace_dem ("", t6);
t7 = transym1 (t6, t5); trace_dem ("", t7);
return t7;
case _defS:
trace_dem ("defS", t);
t1 = ext (x, subdem(0,t)); trace_dem ("", t1);
t2 = ext (x, subdem(1,t)); trace_dem ("", t2);
t3 = ext (x, subdem(2,t)); trace_dem ("", t3);
t4 = appp (ext_S, t1, t2, t3); trace_dem ("", t4);
t5 = red (left(t4)); trace_dem ("", t5);
t7 = transym1 (t5, t4); trace_dem ("", t7);
t8 = red (right(t7)); trace_dem ("", t8);
t9 = trans (t7, t8); trace_dem ("", t9);
return t9;
default:
trace_dem ("return", I);
return I;
}
}
DEM exten (DEM v, DEM t)
{
DEM ax1, ax2, ext_I, ext_K, ext_S, x, y, t1, t2, t3, t4, t5, t6;
ax1 = Ext4;
ax2 = Ext5;
ext_I = Ext1;
ext_K = Ext2;
ext_S = Ext3;
t1 = ext (v, t);
trace_dem ("", t1);
x = left(t1);
trace_dem ("", x);
y = right(t1);
trace_dem ("", y);
t2 = redu (x);
trace_dem ("", t2);
t3 = redu (y);
trace_dem ("", t3);
t5 = transym1 (t2, t1);
trace_dem ("", t5);
t6 = trans (t5, t3);
trace_dem ("", t6);
return t6;
}
|
bb598005919e2794b58033b418c0d674c94811f6
|
fa6559f36ed84f5fbc6bcacd68f41ae45d1e2535
|
/src/tagger/SGDTrainer.cc
|
fc27657dc3edb75789b7c3029d7c63198196abc2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Traubert/FinnPos
|
7d6739426ba631b068580a2099cdb59fffab09cd
|
8a5184237a854e60e422bf3e5ef1de7b04bf962e
|
refs/heads/master
| 2020-05-19T17:16:17.409529
| 2020-05-15T07:00:37
| 2020-05-15T07:00:37
| 185,130,598
| 0
| 0
|
Apache-2.0
| 2019-05-06T05:41:42
| 2019-05-06T05:41:42
| null |
UTF-8
|
C++
| false
| false
| 10,229
|
cc
|
SGDTrainer.cc
|
/**
* @file SGDTrainer.cc
* @Author Miikka Silfverberg
* @brief An instance of Trainer that performs SGD.
*/
///////////////////////////////////////////////////////////////////////////////
// //
// (C) Copyright 2014, University of Helsinki //
// 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 "SGDTrainer.hh"
#ifndef TEST_SGDTrainer_cc
#define STRUCT_SL 1
#define USTRUCT_SL 1
SGDTrainer::SGDTrainer(unsigned int max_passes,
unsigned int max_useless_passes,
ParamTable &pt,
const LabelExtractor &label_extractor,
const LemmaExtractor &lemma_extractor,
std::ostream &msg_out,
const TaggerOptions &options):
Trainer(max_passes, max_useless_passes, pt, label_extractor, lemma_extractor, msg_out, options),
iter(0),
sublabel_order(options.sublabel_order),
model_order(options.model_order),
options(options),
delta(options.delta),
sigma(options.sigma),
bw(label_extractor.get_boundary_label())
{
std::cerr << delta << std::endl;
pt.set_param_filter(options);
pos_params = pt;
pos_params.set_label_extractor(label_extractor);
}
void SGDTrainer::train(const Data &train_data,
const Data &dev_data,
unsigned int beam,
float beam_mass)
{
Data train_data_copy(train_data);
Data dev_data_copy(dev_data);
dev_data_copy.unset_label();
TrellisVector train_trellises;
std::cerr << "SL: " << sublabel_order << std::endl;
for (unsigned int i = 0; i < train_data.size(); ++i)
{
train_trellises.push_back(new Trellis(train_data_copy.at(i), boundary_label,
sublabel_order, model_order, beam));
if (beam != static_cast<unsigned int>(-1))
{ train_trellises.back()->set_beam(beam); }
if (beam_mass != -1)
{ train_trellises.back()->set_beam_mass(beam_mass); }
}
TrellisVector dev_trellises;
for (unsigned int i = 0; i < dev_data.size(); ++i)
{
dev_trellises.push_back(new Trellis(dev_data_copy.at(i), boundary_label, sublabel_order, model_order, beam));
if (beam != static_cast<float>(-1))
{ dev_trellises.back()->set_beam(beam); }
if (beam_mass != -1)
{ dev_trellises.back()->set_beam_mass(beam_mass); }
}
float best_dev_acc = -1;
ParamTable best_params;
best_params.set_param_filter(options);
best_params.set_label_extractor(label_extractor);
unsigned int useless_passes = 0;
for (unsigned int i = 0; i < max_passes; ++i)
{
if (useless_passes >= max_useless_passes)
{ break; }
msg_out << " Train pass " << i + 1 << std::endl;
// Train pass.
for (unsigned int j = 0; j < train_trellises.size(); ++j)
{
// train_trellises[j]->set_maximum_a_posteriori_assignment
// (pos_params);
train_trellises[j]->set_marginals(pos_params);
update(train_data_copy.at(j), train_data.at(j), *train_trellises[j]);
std::cerr << j << " of " << train_trellises.size() - 1 << "\r";
}
std::cerr << std::endl;
// Tag dev data.
for (unsigned int j = 0; j < dev_trellises.size(); ++j)
{
dev_trellises[j]->set_maximum_a_posteriori_assignment(pos_params);
}
float acc = dev_data.get_acc(dev_data_copy, lemma_extractor).label_acc;
msg_out << " Dev acc: " << acc * 100.00 << "%" << std::endl;
if (acc > best_dev_acc)
{
useless_passes = 0;
best_dev_acc = acc;
best_params = pos_params;
}
else
{
++useless_passes;
}
}
msg_out << " Final dev acc: " << best_dev_acc * 100.00 << "%" << std::endl;
pt = best_params;
pt.set_label_extractor(label_extractor);
pt.set_trained();
pt.set_train_iters(iter);
for (TrellisVector::const_iterator it = train_trellises.begin();
it != train_trellises.end();
++it)
{ delete *it; }
for (TrellisVector::const_iterator it = dev_trellises.begin();
it != dev_trellises.end();
++it)
{ delete *it; }
}
void SGDTrainer::update(const Sentence &gold_s,
const Sentence &sys_s,
const Trellis &trellis)
{
++iter;
for (unsigned int i = 0; i < sys_s.size() ; ++i)
{
unsigned int gold_label = gold_s.at(i).get_label();
unsigned int pgold_label = (i < 1 ? boundary_label : gold_s.at(i - 1).get_label());
unsigned int ppgold_label = (i < 2 ? boundary_label : gold_s.at(i - 2).get_label());
pos_params.update_all_unstruct(gold_s.at(i), gold_label, delta, sublabel_order);
pos_params.update_all_struct_fw(ppgold_label, pgold_label, gold_label, delta, sublabel_order, model_order);
const Word * word = &(sys_s.at(i));
const Word * pword = &(i < 1 ? bw : sys_s.at(i - 1));
const Word * ppword = &(i < 2 ? bw : sys_s.at(i - 2));
for (unsigned int j = 0; j < word->get_label_count(); ++j)
{
unsigned int j_label = word->get_label(j);
float ug_marginal = trellis.get_marginal(i, j);
pos_params.update_all_unstruct(sys_s.at(i), j_label, -ug_marginal*delta, sublabel_order);
pos_params.update_struct1(j_label, -ug_marginal*delta, sublabel_order);
pos_params.regularize_all_unstruct(sys_s.at(i), j_label, sigma, sublabel_order);
pos_params.regularize_struct1(j_label, sigma, sublabel_order);
for (unsigned int k = 0; k < pword->get_label_count(); ++k)
{
unsigned int k_label = pword->get_label(k);
float bg_marginal = 0;
if (i < 1)
{ bg_marginal = ug_marginal; }
else
{ bg_marginal = trellis.get_marginal(i, k, j); }
// std::cerr << bg_marginal << std::endl;
pos_params.update_struct2(k_label, j_label, -bg_marginal*delta, sublabel_order);
pos_params.regularize_struct2(k_label, j_label, sigma, sublabel_order);
for (unsigned int l = 0; l < ppword->get_label_count(); ++l)
{
unsigned int l_label = ppword->get_label(l);
float tg_marginal = 0;
if (i < 2)
{ tg_marginal = bg_marginal; }
else
{
tg_marginal = trellis.get_marginal(i, l, k, j);
}
//std::cerr << tg_marginal << std::endl;
pos_params.update_struct3(l_label, k_label, j_label, -tg_marginal*delta, sublabel_order);
pos_params.regularize_struct3(l_label, k_label, j_label, sigma, sublabel_order);
}
}
}
}
}
#else // TEST_SGDTrainer_cc
class SillyLabelExtractor : public LabelExtractor
{
public:
SillyLabelExtractor(void):
LabelExtractor(1)
{}
void set_label_candidates(const std::string &word_form,
bool use_label_dict,
float mass,
LabelVector &target,
int candidate_count) const
{
static_cast<void>(use_label_dict);
static_cast<void>(mass);
if (word_form == BOUNDARY_WF)
{
target.push_back(get_boundary_label());
}
else
{
target.clear();
for (unsigned int i = 0; i < static_cast<unsigned int>(candidate_count); ++i)
{
target.push_back(i);
}
}
}
};
class SillyLemmaExtractor : public LemmaExtractor
{
public:
std::string get_lemma_candidate(const std::string &word_form,
const std::string &label)
{
static_cast<void>(word_form);
static_cast<void>(label);
return "FOO";
}
bool is_known_wf(const std::string &word_form) const
{
static_cast<void>(word_form);
return 1;
}
};
#include <cassert>
int main(void)
{
TaggerOptions options;
options.delta = 0.1;
options.sigma = 0.01;
std::string contents("\n"
"The\tWORD=The\tthe\tDT\t_\n"
"dog\tWORD=dog\tdog\tNN\t_\n"
".\tWORD=.\t.\t.\t_\n"
"\n"
"\n"
"The\tWORD=The\tthe\tDT\t_\n"
"dog\tWORD=dog\tdog\tNN\t_\n"
"sleeps\tWORD=sleeps\tsleep\tVB\t_\n"
"but\tWORD=but\tbut\tCC\t_\n"
"they\tWORD=they\tthey\tPNP\t_\n"
"dog\tWORD=dog\tdog\tVB\t_\n"
"me\tWORD=me\tme\tPNP\t_\n"
".\tWORD=.\t.\t.\t_\n");
std::istringstream in(contents);
SillyLabelExtractor label_extractor;
ParamTable pt;
Data train_data(in, 1, label_extractor, pt, 2);
train_data.set_label_guesses(label_extractor,
0,
0,
label_extractor.label_count());
Data dev_data(train_data);
Data dev_data_copy(dev_data);
dev_data.set_label_guesses(label_extractor,
0,
0,
label_extractor.label_count());
dev_data_copy.unset_label();
dev_data_copy.set_label_guesses(label_extractor,
0,
0,
label_extractor.label_count());
std::ostringstream null_out;
SillyLemmaExtractor sle;
SGDTrainer trainer(5,3,pt, label_extractor, sle, null_out, options);
std::cerr << "Initial label acc: " << dev_data.get_acc(dev_data_copy, SillyLemmaExtractor()).label_acc << std::endl;
trainer.train(train_data, dev_data);
for (unsigned int i = 0; i < dev_data_copy.size(); ++i)
{
Trellis trellis(dev_data_copy.at(i), label_extractor.get_boundary_label(), NODEG, SECOND);
trellis.set_maximum_a_posteriori_assignment(pt);
}
std::cerr << "Final label acc: " << dev_data.get_acc(dev_data_copy, SillyLemmaExtractor()).label_acc << std::endl;
std::cerr << pt << std::endl;
assert(dev_data.get_acc(dev_data_copy, SillyLemmaExtractor()).label_acc == 1);
}
#endif // TEST_SGDTrainer_cc
|
11211ce1a6c9cdd14a361458109d31ded226c1a9
|
2c78de0b151238b1c0c26e6a4d1a36c7fa09268c
|
/garant6x/implementation/Garant/GblAdapterLib/impl/UserJournal_i/JournalNode.cpp
|
eb4585a309fff7913f87126f8053a2a53a703d14
|
[] |
no_license
|
bravesoftdz/realwork
|
05a3b308cef59bed8a9efda4212849c391b4b267
|
19b446ce8ad2adf82ab8ce7988bc003221accad2
|
refs/heads/master
| 2021-06-07T23:57:22.429896
| 2016-11-01T18:30:21
| 2016-11-01T18:30:21
| null | 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 4,131
|
cpp
|
JournalNode.cpp
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Модуль: "w:/garant6x/implementation/Garant/GblAdapterLib/impl/UserJournal_i/JournalNode.cpp"
// генератор файлов реализации C++ (.cpp)
// Generated from UML model, root element: <<Servant::Class>> garant6x::GblAdapterLib::UserJournal_i::JournalNode
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "shared/CoreSrv/sys/std_inc.h"
#include "garant6x/implementation/Garant/GblAdapterLib/LibHome.h"
#include "garant6x/implementation/Garant/GblAdapterLib/impl/UserJournal_i/JournalNode.h"
// by <<uses>> dependencies
#include "garant6x/implementation/Garant/GblAdapterLib/impl/UserJournal_i/JournalObjectTypeTranslator.h"
namespace GblAdapterLib {
//////////////////////////////////////////////////////////////////////////////////////////
// constructors and destructor
JournalNode::JournalNode ()
//#UC START# *45EEB95901C5_45F6694A01B5_4A92B65B024B_BASE_INIT*
//#UC END# *45EEB95901C5_45F6694A01B5_4A92B65B024B_BASE_INIT*
{
//#UC START# *45EEB95901C5_45F6694A01B5_4A92B65B024B_BODY*
//#UC END# *45EEB95901C5_45F6694A01B5_4A92B65B024B_BODY*
}
JournalNode::JournalNode (FakeFacetForFactory* owner_tree, const GTree::Node& snode)
//#UC START# *45EEB95901C5_45FFF849002E_4A92B65B024B_BASE_INIT*
: RealNodeBase (dynamic_cast <TreeBase*> (owner_tree), snode)
, DefaultNodeBase (dynamic_cast <TreeBase*> (owner_tree))
, NodeBase_i (dynamic_cast <TreeBase*> (owner_tree), snode)
//#UC END# *45EEB95901C5_45FFF849002E_4A92B65B024B_BASE_INIT*
{
//#UC START# *45EEB95901C5_45FFF849002E_4A92B65B024B_BODY*
GblUserJournalDef::JournalValue* jv = GblUserJournalDef::JournalValue::_downcast(snode.value.in ());
m_type = translate (jv->type ());
//#UC END# *45EEB95901C5_45FFF849002E_4A92B65B024B_BODY*
}
JournalNode::~JournalNode () {
//#UC START# *4A92B65B024B_DESTR_BODY*
//#UC END# *4A92B65B024B_DESTR_BODY*
}
//////////////////////////////////////////////////////////////////////////////////////////
// overloaded base methods
// overloaded method from NodeBase
const EntityBase* JournalNode::get_entity () const
/*throw (NoEntity)*/
{
//#UC START# *45F65BEA00DA_4A92B65B024B_GET*
try {
GTree::NodeEntity_var server_entity = this->entity ();
GblUserJournal::JournalBookmark* server_journal_bookmark;
if (*server_entity >>= server_journal_bookmark) {
return JournalBookmarkFactory::make (server_journal_bookmark);
}
GblUserJournal::JournalQuery* server_journal_query;
if (*server_entity >>= server_journal_query) {
QueryCreator_var creator (QueryCreatorFactory::make ());
return creator->make_query (server_journal_query);
}
} catch (GTree::InvalidPointer&) {
} catch (GCD::CanNotFindData&) {
}
throw NoEntity ();
//#UC END# *45F65BEA00DA_4A92B65B024B_GET*
}
EntityBase* JournalNode::get_entity ()
/*throw (NoEntity)*/
{
return const_cast<EntityBase*>(((const JournalNode*)this)->get_entity ());
}
void JournalNode::set_entity (EntityBase* entity) {
//#UC START# *45F65BEA00DA_4A92B65B024B_SET*
GDS_ASSERT (false);
//#UC END# *45F65BEA00DA_4A92B65B024B_SET*
}
// overloaded method from NodeBase
// Пользовательский тип ноды. Может определять тип связанной сущности, или просто использоваться
// для диффиренцации отображения
NodeType JournalNode::get_type () const {
//#UC START# *45EEB9590224_4A92B65B024B_GET*
return m_type;
//#UC END# *45EEB9590224_4A92B65B024B_GET*
}
void JournalNode::set_type (NodeType type)
/*throw (ConstantModify)*/
{
//#UC START# *45EEB9590224_4A92B65B024B_SET*
GDS_ASSERT (false);
throw ConstantModify ();
//#UC END# *45EEB9590224_4A92B65B024B_SET*
}
} // namespace GblAdapterLib
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
264ad45ec03f1fc5642599cd67ef43f9f50a2e95
|
674c8230197442d3b17ac372a99bc41d4511de62
|
/Src/UI/DialogueWindow.cpp
|
e40cc9e9b31ae102a0f45752bb2b198cc770fe51
|
[] |
no_license
|
niello/dem-test
|
96bed2756456ee7ecb9d3513ea51d96777e9505d
|
38cfa045d8fd57d7309cc2ca1e2a094e81bb0faf
|
refs/heads/master
| 2021-01-23T18:07:53.598812
| 2016-12-17T17:06:45
| 2016-12-17T17:06:45
| 42,161,082
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,761
|
cpp
|
DialogueWindow.cpp
|
#include "DialogueWindow.h"
#include <Dlg/DialogueManager.h>
#include <Game/GameServer.h>
#include <Game/Entity.h>
#include <Events/EventServer.h>
#include <UI/UIServer.h>
#include <UI/CEGUI/FmtLbTextItem.h>
#include <Data/StringUtils.h>
#include <CEGUI/Event.h>
#include <CEGUI/widgets/Listbox.h>
#include <CEGUI/widgets/PushButton.h>
namespace UI
{
CDialogueWindow::~CDialogueWindow()
{
}
//---------------------------------------------------------------------
void CDialogueWindow::Init(CEGUI::Window* pWindow)
{
CUIWindow::Init(pWindow);
CString WndName(pWindow->getName().c_str());
pContinueBtn = (CEGUI::PushButton*)pWnd->getChild("MainButton");
pContinueBtn->subscribeEvent(CEGUI::PushButton::EventClicked,
CEGUI::Event::Subscriber(&CDialogueWindow::OnContinueBtnClicked, this));
pTextArea = (CEGUI::Listbox*)pWnd->getChild("TextArea");
pTextArea->setShowVertScrollbar(true);
pTextArea->setMultiselectEnabled(false);
//!!!not here - bug below!
ConnKeyUp = pWnd->subscribeEvent(CEGUI::Window::EventKeyUp,
CEGUI::Event::Subscriber(&CDialogueWindow::OnKeyUp, this));
ConnTextAreaMM = pTextArea->subscribeEvent(CEGUI::Listbox::EventMouseMove,
CEGUI::Event::Subscriber(&CDialogueWindow::OnTextAreaMouseMove, this));
ConnAnswerClicked = pTextArea->subscribeEvent(CEGUI::Listbox::EventMouseClick,
CEGUI::Event::Subscriber(&CDialogueWindow::OnAnswerClicked, this));
//!!!DBG! - works
//ConnKeyUp->disconnect();
SUBSCRIBE_PEVENT(OnDlgStart, CDialogueWindow, OnDlgStart);
SUBSCRIBE_PEVENT(OnDlgEnd, CDialogueWindow, OnDlgEnd);
SUBSCRIBE_PEVENT(OnForegroundDlgNodeEnter, CDialogueWindow, OnDlgNodeEnter);
}
//---------------------------------------------------------------------
bool CDialogueWindow::OnContinueBtnClicked(const CEGUI::EventArgs& e)
{
n_assert_dbg(DlgID.IsValid());
Story::CDlgContext* pCtx = DlgMgr->GetDialogue(DlgID);
n_assert(pCtx);
pCtx->State = Story::DlgState_InLink;
OK;
}
//---------------------------------------------------------------------
bool CDialogueWindow::OnAnswerClicked(const CEGUI::EventArgs& e)
{
n_assert_dbg(DlgID.IsValid());
const CEGUI::MouseEventArgs& Args = (const CEGUI::MouseEventArgs&)e;
CEGUI::ListboxTextItem* pItem = (CEGUI::ListboxTextItem*)pTextArea->getItemAtPoint(Args.position);
if (pItem)
{
Story::CDlgContext* pCtx = DlgMgr->GetDialogue(DlgID);
n_assert(pCtx);
//!!!subscribe CEGUI event only on answer (select) nodes instead!
if (pCtx->pCurrNode->LinkMode == Story::CDlgNode::Link_Select)
{
UPTR ValidLinkCount = pCtx->ValidLinkIndices.GetCount();
UPTR Idx = pTextArea->getItemIndex(pItem) + ValidLinkCount - pTextArea->getItemCount();
if (Idx < ValidLinkCount) SelectAnswer(*pCtx, Idx);
}
}
OK;
}
//---------------------------------------------------------------------
bool CDialogueWindow::OnTextAreaMouseMove(const CEGUI::EventArgs& e)
{
/*const CEGUI::MouseEventArgs& Args = (const CEGUI::MouseEventArgs&)e;
CEGUI::ListboxTextItem* pItem = (CEGUI::ListboxTextItem*)pTextArea->getItemAtPoint(Args.position);
if (pItem != pLastItemUnderCursor)
{
if (pLastItemUnderCursor) pLastItemUnderCursor->setTextColours(CEGUI::colour(0xffff0000));
if (pItem)
{
pItem->setTextColours(CEGUI::colour(0xffffffff));
pItem->setText("SELECTED");
}
pTextArea->handleUpdatedItemData();
pTextArea->invalidate();
pWnd->invalidate();
pLastItemUnderCursor = pItem;
}*/
OK;
}
//---------------------------------------------------------------------
bool CDialogueWindow::OnKeyUp(const CEGUI::EventArgs& e)
{
n_assert_dbg(DlgID.IsValid());
const CEGUI::KeyEventArgs& KeyArgs = (const CEGUI::KeyEventArgs&)e;
Story::CDlgContext* pCtx = DlgMgr->GetDialogue(DlgID);
n_assert(pCtx);
if (pCtx->pCurrNode->LinkMode == Story::CDlgNode::Link_Select &&
KeyArgs.scancode >= CEGUI::Key::One &&
KeyArgs.scancode < (CEGUI::Key::One + (IPTR)pCtx->ValidLinkIndices.GetCount()))
{
SelectAnswer(*pCtx, KeyArgs.scancode - CEGUI::Key::One);
OK;
}
else if (KeyArgs.scancode == CEGUI::Key::Return && pContinueBtn->isVisible())
{
OnContinueBtnClicked(e);
OK;
}
FAIL;
}
//---------------------------------------------------------------------
void CDialogueWindow::SelectAnswer(Story::CDlgContext& Ctx, UPTR Idx)
{
Ctx.SelectValidLink(Idx);
int ValidLinkCount = Ctx.ValidLinkIndices.GetCount();
while (ValidLinkCount-- > 0)
pTextArea->removeItem(pTextArea->getListboxItemFromIndex(pTextArea->getItemCount() - 1));
//!!!bug!
//ConnKeyUp->disconnect();
//ConnTextAreaMM->disconnect();
//ConnAnswerClicked->disconnect();
pLastItemUnderCursor = NULL;
}
//---------------------------------------------------------------------
bool CDialogueWindow::OnDlgStart(Events::CEventDispatcher* pDispatcher, const Events::CEventBase& Event)
{
Data::PParams P = ((const Events::CEvent&)Event).Params;
if (!P->Get<bool>(CStrID("IsForeground"))) FAIL;
n_assert_dbg(!DlgID.IsValid());
DlgID = P->Get<CStrID>(CStrID("Initiator"));
pContinueBtn->setVisible(false);
//Show(); - delayed to first actual phrase
OK;
}
//---------------------------------------------------------------------
bool CDialogueWindow::OnDlgEnd(Events::CEventDispatcher* pDispatcher, const Events::CEventBase& Event)
{
Data::PParams P = ((const Events::CEvent&)Event).Params;
if (!P->Get<bool>(CStrID("IsForeground"))) FAIL;
n_assert_dbg(DlgID.IsValid() && P->Get<CStrID>(CStrID("Initiator")) == DlgID);
DlgID = CStrID::Empty;
Hide();
pTextArea->resetList();
OK;
}
//---------------------------------------------------------------------
bool CDialogueWindow::OnDlgNodeEnter(Events::CEventDispatcher* pDispatcher, const Events::CEventBase& Event)
{
n_assert_dbg(DlgID.IsValid());
Story::CDlgContext* pCtx = DlgMgr->GetDialogue(DlgID);
n_assert(pCtx);
CStrID SpeakerEntity = pCtx->pCurrNode->SpeakerEntity;
if (!SpeakerEntity.IsValid() || !pCtx->pCurrNode->Phrase.IsValid()) OK;
if (SpeakerEntity == CStrID("$DlgOwner")) SpeakerEntity = pCtx->DlgOwner;
else if (SpeakerEntity == CStrID("$PlrSpeaker")) SpeakerEntity = pCtx->PlrSpeaker;
Game::PEntity Speaker = GameSrv->GetEntityMgr()->GetEntity(SpeakerEntity);
if (Speaker.IsNullPtr())
Sys::Error("CDialogueWindow::OnDlgNodeEnter -> speaker entity '%s' not found", SpeakerEntity.CStr());
CString Text;
if (!Speaker->GetAttr<CString>(Text, CStrID("Name")))
Text = Speaker->GetUID().CStr();
Text += ": ";
Text += pCtx->pCurrNode->Phrase.CStr();
CEGUI::FormattedListboxTextItem* NewItem =
n_new(CEGUI::FormattedListboxTextItem((CEGUI::utf8*)Text.CStr(), CEGUI::HTF_WORDWRAP_LEFT_ALIGNED));//!!!, 0, 0, true);
n_assert(NewItem);
NewItem->setTextColours(CEGUI::Colour(0xffb0b0b0));
pTextArea->addItem(NewItem);
pTextArea->ensureItemIsVisible(pTextArea->getItemCount() - 1);
Show();
pWnd->activate(); //???activate button when it is visible?
UPTR ValidLinkCount = pCtx->ValidLinkIndices.GetCount();
if (pCtx->pCurrNode->LinkMode == Story::CDlgNode::Link_Select && ValidLinkCount > 0)
{
pContinueBtn->setVisible(false);
//???remove cegui event conn here?
for (UPTR i = 0; i < ValidLinkCount; ++i)
{
Story::CDlgNode::CLink& Link = pCtx->pCurrNode->Links[pCtx->ValidLinkIndices[i]];
Text = StringUtils::FromInt(i + 1);
Text += ": ";
Text += Link.pTargetNode ? Link.pTargetNode->Phrase.CStr() : NULL;
//???pool instead of new?
CEGUI::FormattedListboxTextItem* pNewItem =
n_new(CEGUI::FormattedListboxTextItem((CEGUI::utf8*)Text.CStr(), CEGUI::HTF_WORDWRAP_LEFT_ALIGNED));
n_assert(pNewItem);
pNewItem->setTextColours(CEGUI::Colour(0xffff0000));
pTextArea->addItem(pNewItem);
pTextArea->ensureItemIsVisible(pTextArea->getItemCount());
}
//!!!bug!
//ConnKeyUp = pWnd->subscribeEvent(CEGUI::Window::EventKeyUp,
// CEGUI::Event::Subscriber(&CDialogueWindow::OnKeyUp, this));
//ConnTextAreaMM = pTextArea->subscribeEvent(CEGUI::Listbox::EventMouseMove,
// CEGUI::Event::Subscriber(&CDialogueWindow::OnTextAreaMouseMove, this));
//ConnAnswerClicked = pTextArea->subscribeEvent(CEGUI::Listbox::EventMouseClick,
// CEGUI::Event::Subscriber(&CDialogueWindow::OnAnswerClicked, this));
}
else if (pCtx->LinkIdx >= 0 && pCtx->LinkIdx < ValidLinkCount)
{
pContinueBtn->setText("Continue");
pContinueBtn->setVisible(true);
//???cegui event conn here?
}
else
{
pContinueBtn->setText("End dialogue");
pContinueBtn->setVisible(true);
//???cegui event conn here?
}
OK;
}
//---------------------------------------------------------------------
}
|
da71e5d71e7a5c8115f031021bc42ae198b9d5ed
|
32670501e4cba8212e52bbb3b1e3bf06f31e7397
|
/source/Weapon.h
|
301d50e7e823d5b2a75d60fa68db967e3153078c
|
[] |
no_license
|
LucasTjarnstrom/TDDC76
|
cfcb7ecc438869e435a2e81cf5933edc41d85b17
|
c5c1ad989dfa2ba8e8d0805744244778573b1097
|
refs/heads/master
| 2020-06-19T20:11:49.931832
| 2018-01-08T11:58:49
| 2018-01-08T11:58:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 481
|
h
|
Weapon.h
|
/*
* IDENTIFICATION
* File: Weapon.h
* Module: Environment
*
* DESCRIPTION
* This class acts as a weapon in the game loop,
* i.e. increases the player characters attack upon collision.
*/
#ifndef WEAPON_H
#define WEAPON_H
#include <string>
#include "Environment.h"
class Weapon : public Environment
{
public:
Weapon(double,double,double,double, std::string);
sf::Sprite draw_this() override;
void is_colliding(std::string) override;
};
#endif
|
e84a5d4e9e1fe9a3747284f27960aae37f45a509
|
4c4920a07abdea07db67a34e9eedfdb361140883
|
/Rozdzial10/zad08/list.h
|
612d81613575b175a3c1276b8874b0336558f73b
|
[] |
no_license
|
emttiew/StephenPrataCpp
|
6b34f68655047362a822f17689ca799d3a1f0e97
|
6a037e69b5d682b3202cd1ac8a724ae0fc9a50a5
|
refs/heads/master
| 2021-01-02T17:07:46.511784
| 2020-09-04T06:54:45
| 2020-09-04T06:54:45
| 239,715,216
| 0
| 1
| null | 2020-02-17T14:35:08
| 2020-02-11T08:45:52
|
C++
|
UTF-8
|
C++
| false
| false
| 399
|
h
|
list.h
|
#ifndef LIST_H_
#define LIST_H_
typedef unsigned long Item;
class List
{
enum { MAX = 10 };
Item items[MAX];
int top;
public:
List(); // tworzy pustą listę
bool isempty() const;
bool isfull() const;
void visit(void (*pf)(Item &), int); // odwiedza element listy i wykonuje na nim zadaną operację
bool add(const Item &);
void showList() const;
};
#endif
|
cb61fac7e97e3c9c6b14f024ee3b0586b88e0e77
|
7e8879867baee281c4e1680f9ad4a57cf8a7a0ac
|
/helloworld.cpp
|
94b191926f024a61cef551c72240255745cedb47
|
[] |
no_license
|
bholubangdoo/hello-world
|
683f7ade2c12b2e91735ef1483869e93c8e3881c
|
e95cfec31b2b760e6d4139004e5d2372b2a293bc
|
refs/heads/master
| 2020-03-19T17:49:49.601148
| 2018-06-17T05:28:08
| 2018-06-17T05:28:08
| 136,780,147
| 2
| 0
| null | 2018-06-17T05:28:09
| 2018-06-10T04:52:50
|
C++
|
UTF-8
|
C++
| false
| false
| 136
|
cpp
|
helloworld.cpp
|
#include<iostream>
void main(){
cout<<"hello world";
cout<<"did first changes";
cout<<"these changes are coming from a branch";
}
|
9c9b81d9fc944db9a44ec9baa1219d58b34a027d
|
396b3e583b21af6cdcea13eaba7e1095906f2e11
|
/mtcnn_c/align.h
|
dcd7491868672ef2e14de09797401c78bbe2fc3b
|
[] |
no_license
|
xizhan0513/MTCNN
|
c2a93c8636269661b0cff22890e80b64b5c1d8a5
|
eff7cba1587477664064b46862c36f20c9cf8e82
|
refs/heads/master
| 2020-09-23T22:42:41.478950
| 2018-12-27T01:19:18
| 2018-12-27T01:19:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 285
|
h
|
align.h
|
#ifndef ALIGN_H_
#define ALIGN_H_
#include "mtcnn.h"
int Align(cv::Mat& image, cv::Mat& image_crop, std::vector<cv::Point2d> source_pts);
cv::Mat findSimilarityTransform(std::vector<cv::Point2d> source_points, std::vector<cv::Point2d> target_points, cv::Mat& Tinv);
#endif
|
54d10dce0305f1b9cd6bbae3e1b353cfc77a5803
|
050850793055d1942878bd0918f4a64738595c89
|
/AQI_LIGHT_V1/AQI_LIGHT_V1.ino
|
4c94955caeb29c0836d2b4eda4421fbb61315fec
|
[] |
no_license
|
shark526/aqi_light
|
ab32cbf59034af3815d277ac824fd5d97d652cce
|
065f244fc8f968cd9b62a49cf198e8b6e2502523
|
refs/heads/main
| 2023-02-28T14:11:43.754698
| 2021-02-01T15:42:54
| 2021-02-01T15:42:54
| 330,127,614
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,910
|
ino
|
AQI_LIGHT_V1.ino
|
#include <SimpleTimer.h> //https://playground.arduino.cc/Code/SimpleTimer/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
// Assign output variables to GPIO pins
#define redPin D1
#define greenPin D2
#define bluePin D0
SimpleTimer timer;
String pm25="";
int aqi=0;
// request for your own token here https://aqicn.org/data-platform/token/cn/, replace following "demo"
const char* locationHereAPIUrl = "http://api.waqi.info/feed/here/?token=demo";
void setLight()
{
if(aqi<=50){
//setColor(int red, int green, int blue)
// green
setColor(0, 255, 0);
}
else if (aqi<=100){
// yellow
setColor(255, 222, 51);
}
else if (aqi<=150){
// orange
setColor(255, 153, 51);
}
else if (aqi<=200){
// red
setColor(255, 0, 0);
}
else if (aqi<=300){
// purple
setColor(102, 0, 153);
}
else
{
// brown
setColor(126, 0, 35);
}
}
void GetAQI(){
HTTPClient http;
http.begin(locationHereAPIUrl );
int httpCode = http.GET();
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
//Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
DynamicJsonDocument doc(6144);
DeserializationError err=deserializeJson(doc, payload);
if(err) {
Serial.print(F("deserializeJson() failed with code "));
Serial.println(err.c_str());
return;
}
//extract the pm2.5 values
aqi = doc["data"]["aqi"];
pm25=(String)(aqi);
Serial.println("pm2.5 is :" + pm25);
setLight();
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
void setColor(int red, int green, int blue)
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
void testlight()
{
setColor(255, 0, 0); // 红色
delay(1000);
setColor(0, 255, 0); // 绿色
delay(1000);
setColor(0, 0, 255); // 蓝色
delay(1000);
setColor(255, 255, 0); // 黄色
delay(1000);
setColor(80, 0, 80); // 紫色
delay(1000);
setColor(0, 255, 255); // 浅绿色
delay(1000);
}
void setup() {
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
// Set outputs to LOW
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, LOW);
// WiFiManager
// Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
// Uncomment and run it once, if you want to erase all the stored information
//wifiManager.resetSettings();
// set custom ip for portal
//wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
// fetches ssid and pass from eeprom and tries to connect
// if it does not connect it starts an access point with the specified name
// here "AutoConnectAP"
// and goes into a blocking loop awaiting configuration
wifiManager.autoConnect("AQI_LIGHT");
// or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();
// if you get here you have connected to the WiFi
Serial.println("Connected.");
testlight();
GetAQI();
//timer.setInterval(600000L,GetAQI);//10 minute
timer.setInterval(60000L,GetAQI);//1 minute
}
void loop(){
timer.run();
}
|
42d0e15ad3005eb0b2f129686bbfa6b708dde5b2
|
e2d3a3696f026f9620c48ddeec76b9ae878fcbcd
|
/firmware/firmware.ino
|
1189abe06733acd06f53b703a83467c31bcea80a
|
[] |
no_license
|
BernardoGiordano/Wattmetro
|
db1115a1091a7db65e284e7955953b5b29fc803a
|
7437bacdf7fd8b429dc64b545880fe7d0ab4852d
|
refs/heads/master
| 2021-03-27T12:47:08.695366
| 2017-06-20T09:39:17
| 2017-06-20T09:39:17
| 91,573,301
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,190
|
ino
|
firmware.ino
|
/**
* Laboratorio di Misure e Diagnostica Industriale, A.A. 2016/2017
* Modulo II: Progettazione e implementazione di un wattmetro numerico
*
* Firmware per Arduino Due
*
* Giordano Bernardo A13/854
* Loffredo Tommaso A13/910
* Egizio Ivan A13/916
* Di Spazio Fabio A13/974
*/
#include <DueTimer.h>
// A0 CORRENTE
// A1 TENSIONE
// numero di periodi controllabile
#define NP 50
// frequenza di campionamento a 2kHz
#define FC 2000
// supponiamo l'array di appoggio con una dimensione sufficiente
// per memorizzare i valori delle letture su almeno due periodi
#define DIMENSIONE_MAX 100
// valori di fondo scala di arduino
#define VFS 3.3
#define NMAX 4095
// valori delle costanti k1 e k2
#define K2_TENSIONE 0.49212
#define K1_TENSIONE 0.43894
#define K1_CORRENTE 0.22002
#define K2_CORRENTE 0.4884
// variabili globali
int memoria_tensione[DIMENSIONE_MAX];
int memoria_corrente[DIMENSIONE_MAX];
int primoIndice = 0;
int secondoIndice = 0;
int nEventiDiTrigger = 0;
bool HALF_BUFFER = false;
bool FULL_BUFFER = false;
bool primoElemento = true;
// definisco delle variabili di appoggio che mi serviranno per memorizzare
// in locale i valori e usarli in caso di evento di trigger rilevato
double appoggioPrecedenteTensione = 0;
double appoggioSuccessivoTensione = 0;
double appoggioPrecedenteCorrente = 0;
double appoggioSuccessivoCorrente = 0;
int contatorePeriodi = 0;
// definisco variabili di appoggio globali che mi serviranno al momento della media su NP periodi
double appoggioFrequenza = 0;
double appoggioPotenzaAttiva = 0;
double appoggioTensioneRMS = 0;
double appoggioCorrenteRMS = 0;
double appoggioPotenzaApparente = 0;
double appoggioFattorePotenza = 0;
/**
* @brief Funzione per convertire un valore numero in tensione
* @param valore numerico da convertire
* @return valore di tensione tra 0 e 3.3V
*/
double numerico2tensione(int num) {
return VFS*num/NMAX;
}
/**
* @brief Funzione per rilevare un evento di trigger
* @param campione precedente (x-1)
* @param valore successivo (x)
* @return booleano
*/
bool trigger(double precedente, double successivo) {
return precedente*successivo < 0 && precedente <= 0;
}
/**
* Handler associato al timer
*/
void getVI() {
// effettuo la lettura dei valori dagli ingressi analogici
int corrente = analogRead(A0);
int tensione = analogRead(A1);
if (primoElemento) {
// se sto rilevando il primissimo elemento dall'analogRead, metto direttamente il valore nell'appoggio successivo
appoggioSuccessivoTensione = tensione;
appoggioSuccessivoCorrente = corrente;
primoElemento = false;
} else {
// ho già un valore relativo alla precedente chiamata dell'handler
// porto i vecchi new negli old
appoggioPrecedenteTensione = appoggioSuccessivoTensione;
appoggioPrecedenteCorrente = appoggioSuccessivoCorrente;
// nei new metto i valori appena letti
appoggioSuccessivoTensione = tensione;
appoggioSuccessivoCorrente = corrente;
bool eventoDiTrigger = trigger(numerico2tensione(appoggioPrecedenteTensione) - VFS/2, numerico2tensione(appoggioSuccessivoTensione) - VFS/2);
// aumento il contatore degli eventi di trigger in caso di evento rilevato
if (eventoDiTrigger) {
nEventiDiTrigger++;
}
// se non si sono ancora verificati eventi di trigger non faccio nulla e ritorno
if (nEventiDiTrigger == 0)
return;
// Se il numero di eventi di trigger è pari (e diverso da zero, per la condizione precedente),
// significa che abbiamo completato il riempimento della prima metà del buffer.
// Se invece esso diventa dispari (ma non 1), abbiamo completato il
// riempimento della seconda metà del buffer.
if (eventoDiTrigger) {
if (nEventiDiTrigger % 2 == 0)
HALF_BUFFER = true;
else if (nEventiDiTrigger != 1)
FULL_BUFFER = true;
}
if (!HALF_BUFFER && nEventiDiTrigger % 2 == 1) {
memoria_tensione[primoIndice] = appoggioSuccessivoTensione;
memoria_corrente[primoIndice] = appoggioSuccessivoCorrente;
primoIndice++;
}
else if (!FULL_BUFFER && nEventiDiTrigger % 2 == 0) {
int offset = DIMENSIONE_MAX/2;
memoria_tensione[secondoIndice + offset] = appoggioSuccessivoTensione;
memoria_corrente[secondoIndice + offset] = appoggioSuccessivoCorrente;
secondoIndice++;
}
}
}
void setup() {
Serial.begin(115200);
analogReadResolution(12);
Timer3.attachInterrupt(getVI);
Timer3.start(500);
// pulisco i buffer di tensione e corrente in fase di inizializzazione
memset(memoria_tensione, 0, DIMENSIONE_MAX);
memset(memoria_corrente, 0, DIMENSIONE_MAX);
}
/**
* @brief Calcolo del valore efficace di tensione
* @param vero se il periodo del segnale è memorizzato nella prima metà del buffer, falso se nella seconda metà del buffer
* @param numero di campioni nel periodo
* @return valore efficace di tensione che comprende il prodotto per il fattore 100 introdotto dal trasduttore di tensione
*/
double v_rms(bool isPrimaMeta, int n) {
double tmp_rms = 0;
for (int offset = isPrimaMeta ? 0 : DIMENSIONE_MAX/2, i = offset; i < n + offset; i++) {
double valore = (numerico2tensione(memoria_tensione[i]) - K2_TENSIONE*VFS)/K1_TENSIONE;
tmp_rms += valore*valore;
}
tmp_rms = sqrt(tmp_rms/n);
// restituisco il valore rms che abbiamo all'ingresso del trasduttore di tensione
return tmp_rms * 100;
}
/**
* @brief Calcolo del valore efficace di corrente
* @param vero se il periodo del segnale è memorizzato nella prima metà del buffer, falso se nella seconda metà del buffer
* @param numero di campioni nel periodo
* @return valore efficace di corrente che comprende il prodotto per il fattore 2 introdotto dal trasduttore di corrente
*/
double i_rms(bool isPrimaMeta, int n) {
double tmp_rms = 0;
for (int offset = isPrimaMeta ? 0 : DIMENSIONE_MAX/2, i = offset; i < n + offset; i++) {
double valore = (numerico2tensione(memoria_corrente[i]) - K2_CORRENTE*VFS)/K1_CORRENTE;
tmp_rms += valore*valore;
}
tmp_rms = sqrt(tmp_rms/n);
// restituisco il valore rms che abbiamo all'ingresso del trasduttore di corrente
return tmp_rms * 2;
}
/**
* @brief Calcolo della potenza attiva
* @param vero se il periodo del segnale è memorizzato nella prima metà del buffer, falso se nella seconda metà del buffer
* @param numero di campioni nel periodo
* @return potenza attiva del segnale
*/
double potenza_attiva(bool isPrimaMeta, int n) {
double tmp_pot = 0;
for (int offset = isPrimaMeta ? 0 : DIMENSIONE_MAX/2, i = offset; i < n + offset; i++) {
double ik = (numerico2tensione(memoria_corrente[i]) - K2_CORRENTE*VFS)/K1_CORRENTE * 2;
double vk = (numerico2tensione(memoria_tensione[i]) - K2_TENSIONE*VFS)/K1_TENSIONE * 100;
tmp_pot += vk*ik;
}
return tmp_pot / n;
}
/**
* @brief stampa dei risultati su monitor seriale
*/
void stampa() {
if (contatorePeriodi == NP) {
Serial.print("\n\n\n\nTensione RMS: ");
Serial.print(appoggioTensioneRMS / NP);
Serial.println(" V");
Serial.print("Corrente RMS: ");
Serial.print(appoggioCorrenteRMS / NP);
Serial.println(" A");
Serial.print("Potenza apparente: ");
Serial.print(appoggioPotenzaApparente / NP);
Serial.println(" VA");
Serial.print("Potenza attiva: ");
Serial.print(appoggioPotenzaAttiva / NP);
Serial.println(" W");
Serial.print("Fattore di potenza: ");
Serial.print(appoggioFattorePotenza / NP);
Serial.print(" Gradi: ");
Serial.println(acos(appoggioFattorePotenza / NP)*180/PI);
Serial.print("Frequenza: ");
Serial.print((FC / appoggioFrequenza) * NP);
Serial.println(" Hz");
Serial.print("Numero di punti totali: ");
Serial.println(appoggioFrequenza);
appoggioPotenzaAttiva = 0;
appoggioPotenzaApparente = 0;
appoggioFattorePotenza = 0;
appoggioTensioneRMS = 0;
appoggioCorrenteRMS = 0;
appoggioFrequenza = 0;
contatorePeriodi = 0;
}
}
/**
* Ciclo della CPU. E' l'unico che ha la facoltà di settare a false le flag di HALF_BUFFER e FULL_BUFFER
*/
void loop() {
if (HALF_BUFFER) {
double veff = v_rms(true, primoIndice);
double ieff = i_rms(true, primoIndice);
double potapp = veff*ieff;
double potatt = potenza_attiva(true, primoIndice);
appoggioCorrenteRMS += ieff;
appoggioTensioneRMS += veff;
appoggioPotenzaAttiva += potatt;
appoggioPotenzaApparente += potapp;
appoggioFattorePotenza += potatt/potapp;
appoggioFrequenza += primoIndice;
contatorePeriodi++;
stampa();
primoIndice = 0;
HALF_BUFFER = false;
}
else if (FULL_BUFFER) {
double veff = v_rms(false, secondoIndice);
double ieff = i_rms(false, secondoIndice);
double potapp = veff*ieff;
double potatt = potenza_attiva(false, secondoIndice);
appoggioCorrenteRMS += ieff;
appoggioTensioneRMS += veff;
appoggioPotenzaAttiva += potatt;
appoggioPotenzaApparente += potapp;
appoggioFattorePotenza += potatt/potapp;
appoggioFrequenza += secondoIndice;
contatorePeriodi++;
stampa();
secondoIndice = 0;
FULL_BUFFER = false;
}
}
|
8cf470c737980098a51fb4df01706228695f5e09
|
f34e75ea5e0a1e8fb97dc9b8425d5c4b39ee593e
|
/analog_read/analog_read.ino
|
0d7943f17be75b683f4fe8e825bbd21be5af7633
|
[] |
no_license
|
cmsparks/arduino-demo-code
|
e6bf95f3648847d24a579e267422511bc4f0f71d
|
8f1b4e02c878ce07557ae7aa3a08f7487a9d2518
|
refs/heads/master
| 2021-05-18T21:23:10.122228
| 2020-03-30T21:12:53
| 2020-03-30T21:12:53
| 251,427,797
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 243
|
ino
|
analog_read.ino
|
void setup() {
// put your setup code here, to run once:
pinMode(A0, INPUT);
pinMode(5, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int read = analogRead(A0);
read = read / 4;
analogWrite(5, read);
}
|
0cb96ff1d1a4c662d941465edc1d71f16723435f
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/multimedia/danim/src/appel/utils/debug.cpp
|
88d78fb1bf3bc04482db599654de42cdf3842f06
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 4,878
|
cpp
|
debug.cpp
|
////////////////////////////////////////////////////////////////
//
// File: debug.cpp
//
// Support for internal debugging
//
// Microsoft Corporation Copyright (c) 1995-96
//
////////////////////////////////////////////////////////////////
// Define & register the trace tags.
#include "headers.h"
#if _DEBUG
#include "appelles/common.h"
#include <stdio.h>
#include <windows.h>
#define DEFINE_TAGS 1
#include "privinc/debug.h"
#include "backend/bvr.h"
typedef void (*PrintFunc)(char*);
static PrintFunc fp = NULL;
extern HINSTANCE hInst;
extern void
SetDebugPrintFunc(PrintFunc f)
{
fp = f;
}
// Use this function as you would use printf(char *format, ...).
// This results in the information being printed to the
// debugger.
void
DebugPrint(char *format, ...)
{
char tmp[1024];
va_list marker;
va_start(marker, format);
wvsprintf(tmp, format, marker);
// Win32 call to output the string to the "debugger" window.
if (fp)
(*fp)(tmp);
else
OutputDebugStr(tmp);
}
#if _USE_PRINT
/*
* Package debug output as C++ output stream.
* To do this we need to define a unbuffered stream buffer
* that dumps its characters to the debug console.
*
* cdebug is the externed global for the resulting ostream
*/
class DebugStreambuf : public streambuf
{
public:
DebugStreambuf();
virtual int overflow(int);
virtual int underflow();
};
DebugStreambuf::DebugStreambuf()
{
unbuffered(1);
}
int
DebugStreambuf::overflow(int c)
{
char buf[2] = {(CHAR)c, 0};
if (fp)
(*fp)(buf);
else
OutputDebugStr(buf);
return 0;
}
int
DebugStreambuf::underflow()
{
return EOF;
}
static DebugStreambuf debugstreambuf;
extern ostream cdebug(&debugstreambuf);
const int MAXSIZE = 32000;
const int LINESIZE = 80;
static char printObjBuf[MAXSIZE];
extern "C" void DumpDebugBuffer(int n)
{
// Debug output seems to have a line size limit, so chop them
// off into smaller lines.
int i = n, j = 0;
char linebuf[LINESIZE + 2];
linebuf[LINESIZE] = '\n';
linebuf[LINESIZE+1] = 0;
while (i > 0) {
if (i > LINESIZE)
strncpy(linebuf, &printObjBuf[j], LINESIZE);
else {
strncpy(linebuf, &printObjBuf[j], i);
linebuf[i] = '\n';
linebuf[i+1] = 0;
}
i -= LINESIZE;
j += LINESIZE;
OutputDebugStr(linebuf);
}
}
extern "C" void PrintObj(GCBase* b)
{
TCHAR szResultLine[MAX_PATH];
TCHAR szTmpPath[MAX_PATH];
TCHAR szTmpInFile[MAX_PATH], szTmpOutFile[MAX_PATH];
TCHAR szCmd[MAX_PATH];
TCHAR szModulePath[MAX_PATH];
ofstream outFile;
ostrstream ost(printObjBuf, MAXSIZE);
b->Print(ost);
ost << endl << ends;
int n = strlen(ost.str());
if (n < LINESIZE)
OutputDebugStr(ost.str());
else {
DumpDebugBuffer(n);
}
#ifdef UNTILWORKING
if ( GetTempPath( MAX_PATH, szTmpPath ) == 0 )
{
TraceTag(( tagError, _T("Could not create temporary file for pretty printing purposes")));
return;
}
strcpy( szTmpInFile, szTmpPath );
strcat( szTmpInFile, _T("EXPRESSION") );
strcpy( szTmpOutFile, szTmpPath );
strcat( szTmpOutFile, _T("EXPRESSION.OUT") );
// Send results to temporary file
outFile.open( szTmpInFile );
outFile << ost.str();
outFile.close();
GetModuleFileName( hInst, szModulePath, sizeof(szModulePath) );
// Put a terminating NULL at the first blackslash
TCHAR *psz = szModulePath+strlen(szModulePath)-1;
while ( psz != szModulePath )
{
if ( *psz == '\\' )
{
*psz = 0;
break;
}
--psz;
}
strcpy( szCmd, _T("PERL.EXE "));
strcat( szCmd, szModulePath );
strcat( szCmd, _T("\\..\\..\\tools\\x86\\utils\\ppfactor.pl "));
strcat( szCmd, szTmpInFile );
strcat( szCmd, _T(" > ") );
strcat( szCmd, szTmpOutFile );
// For now comment out since it brings up dialogs all over the place
// in Win98
// system( szCmd );
FILE *fp;
if ( (fp = fopen( szTmpOutFile, "r" )) == NULL )
{
TraceTag(( tagError, _T("Could not open pretty printing temporary result file")));
return;
}
while ( !feof( fp ) )
{
_fgetts( szResultLine, sizeof(szResultLine), fp );
OutputDebugStr( szResultLine );
}
fclose( fp );
#endif
}
#endif
// Strictly for debugging... don't count on the results
extern "C" int DumpRefCount(IUnknown *obj)
{
int refCountOnAdd = obj->AddRef();
int refCountOnRelease = obj->Release();
return refCountOnRelease;
}
#endif
|
1a31bbebadc64476abfafdbddf802f6739431b74
|
41cb484e223591c763d3b45db251f480b3af3ef8
|
/ICONOS_LISTO.cpp
|
35d50c6433e0ca66f4cfc9c33db85c52b43a5992
|
[] |
no_license
|
juantobiasdl7/FIGURES-IN-C-
|
bebb3a90f816091771f1cb464189c79e438a494a
|
77182001324ecbc535bad3efb92b2afbe6a113c0
|
refs/heads/master
| 2022-07-03T15:52:35.619989
| 2020-05-07T06:50:11
| 2020-05-07T06:50:11
| 261,972,149
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 24,877
|
cpp
|
ICONOS_LISTO.cpp
|
#include <winbgim.h>
#include<cmath>
#include <iostream>
using namespace std;
struct PASOS
{
int tipo;
};
struct linea
{
double px1,py1,px2,py2;
double px,py;
};
struct circulo
{
double cx,cy,r1;
};
struct linea2
{
double px,py;
};
struct arco
{
double ch,ck,r,B1,B2,ap1,gi1,ag,inca;
};
void waitForLeftMouseClick()
{
const int DELAY = 1;
int A, B;
while (!ismouseclick (WM_LBUTTONDOWN))
{delay(DELAY);}
getmouseclick(WM_LBUTTONDOWN, A, B);
}
int Fx(int gx)
{
int x3,x4,x5;
x3=gx/10;
x3=x3*10;
x4=x3+5;
x5=x3+10;
if(gx>=x3 && gx<x4)
{
gx=x3;
}
else
{
gx=x5;
}
return gx;
}
int Fy(int gy)
{
int y3,y4,y5;
y3=gy/10;
y3=y3*10;
y4=y3+5;
y5=y3+10;
if(gy>=y3 && gy<y4)
{
gy=y3;
}
else
{
gy=y5;
}
return gy;
}
int main()
{
linea lin[50];
PASOS pas[50];
circulo cir[50];
arco bir[50];
initwindow(5000,800);
settextstyle(0,0,2);
setcolor(14);
outtextxy(350,5,"PINTA UNA LINEA");
setcolor(15);
int px1=0,py1=0,gi,pt,px3,py3,pj,fw=0;//arcs
float xc=0,yc=0, r=0, s=0;
//VARIABLES JUAN
int x=0,y=0,xS=0,yS=0,i,t,j,w=0,w1=0,w2=0;
float px,py,x1,x2,y1,y2,y3,x3,rm,A,B,C,h,k,h1,h2,k1,k2,dis,ang,angi,ang1,ang2,m1,m2,app;
int op,giro,ejex,ejey,pasos,p=0,u=0,v=0;
long double pi=3.141592653589;
char l;
float r1=0;
//ICONOS
//LINEA DIAGONAL
rectangle(50,50,100,100);
moveto(60,60);
lineto(90,90);
//DOS RECTANGULOS
rectangle(50,110,100,160);
for(gi=55;gi<=70;gi+=5)
{
for(pj=115;pj<=155;pj+=5)
{
circle(gi,pj,1); }
}
moveto(75,110);
lineto(75,160);
//CIRCULO
rectangle(50,200,100,250);
moveto(75,275);
circle(75,225,20);
//ARCOS
rectangle(50,350,100,400);
arc (95,395,90,180,40);
//SALIR
rectangle(50,500,100,550);
arc(75,525,130,50,20);
line(75,525,75,505);
//FORZAR
rectangle(50,600,100,650);
moveto(75,600);
lineto(75,650);
moveto(60,600);
lineto(60,650);
moveto(65,600);
lineto(65,650);
moveto(50,600);
lineto(75,650);
moveto(75,600);
lineto(50,650);
//BORRAR
rectangle(50,700,100,750);
moveto(67,710);
lineto(52,720);
moveto(52,710);
lineto(67,720);
//AREA DE TRABAJO
rectangle(130,50,1500,750);
// rectangle(800,50,900,100);
// moveto(850,50);
// lineto(850,100);
// VERIFIAR ICONOS
I:
waitForLeftMouseClick();
px=mousex( );
py=mousey( );
setcolor(15);
if ( px>= 50 && px<= 75 && py>= 600 && py<= 650) goto FORZAR;
if ( px>= 75 && px<= 100 && py>= 600 && py<= 650) goto I;
if ( px>= 50 && px<= 100 && py>= 50 && py<= 100) {p=p+1; pas[p].tipo=1; goto LINEA;}
if ( px>= 50 && px<= 100 && py>= 200 && py<= 250){ p=p+1; pas[p].tipo=2; goto CIRCULO;}
if (px>=50 && px<=100 && py>=500 &&py<=550)goto CERRAR;
if(px>=50&&px<=100&&py>=700&&py<=750)goto BORRAR;
if(px>=50&&px<=100&&py>=350&&py<=400){p=p+1; pas[p].tipo=3;goto ARCOS;}
if(px>=50&&px<=75&&py>=110&&py<=160) goto PUNTOS;
if(px>=75&&px<=100&&py>=110&&py<=160)goto NEGRO;
goto I;
//LINEAS___________________________________________________________________________________________
LINEA:
while(1)
{
waitForLeftMouseClick();
px=mousex( );
py=mousey( );
waitForLeftMouseClick();
px1=mousex( );
py1=mousey( );
if ( px>= 130 && px<= 1500 && py>= 50 && py<= 750 && px1>= 130 && px1<= 1500 && py1>= 50 && py1<= 750)
{
line(px,py,px1,py1);
u=u+1;
lin[u].px1=px;
lin[u].py1=py;
lin[u].px2=px1;
lin[u].py2=py1;
}
break;
}
goto I;
//CIRCULOS__________________________________________________________________________________________________________
CIRCULO:
while(1)
{
waitForLeftMouseClick();
px=mousex( );
py=mousey( );
waitForLeftMouseClick();
px1=mousex( );
py1=mousey( );
//radio
xc = (px1-px);
xc = xc*xc;
yc = (py1-py);
yc = yc*yc;
r=sqrt((xc+yc));
circle(px,py,r);
v=v+1;
cir[v].cx=px;
cir[v].cy=py;
cir[v].r1=r;
break;
}
goto I;
//PINTA LOS PUNTOS______________________________________________________________________________________________________
PUNTOS:
fw=1;
while(1)
{
for(gi=140;gi<=1490;gi+=10)
{
for(pj=60;pj<=740;pj+=10)
{
circle(gi,pj,1); }
}
break;
}
goto I;
//_______________________________________________________________________________________________________________________
//BORRA LOS PUNTOS_______________________________________________________________________________________________________
NEGRO:
fw=2;
while(1)
{
setcolor(0);
for(gi=140;gi<=1490;gi+=10)
{
for(pj=60;pj<=740;pj+=10)
{
circle(gi,pj,1); }
}
break;
}
goto I;
//________________________________________________________________________________________________________________________
//ARCOS________________________________________________________________________________________________________________________
ARCOS:
while(1)
{
Posicion:
system("cls");
waitForLeftMouseClick();
cout<<endl<<"Movimiento en arco"<<endl<<endl<<"Introduzca posicion inicial x,y"<<endl;
x1=mousex();
y1=mousey();
waitForLeftMouseClick();
cout<<endl<<"Introduzca posicion final x,y"<<endl;
x2=mousex();
y2=mousey();
rm=(sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)))/2;
if(rm==0)
{
cout<<"No hay distancia entre los puntos"<<endl<<"Imposible trazar arco"<<endl;
system("pause");
goto Posicion;
}
Radio:
system("cls");
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<endl<<"Introduzca radio de giro"<<endl<<"Radio minimo = "<<rm<<endl;
cin>>r;
if(r<rm)
{
cout<<endl<<"Radio invalido"<<endl;
system("pause");
goto Radio;
}
Centros:
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<"Radio de "<<r<<endl;
y3=y2-y1;
x3=x2-x1;
if(x3==0&&y3!=0)
{
A=((x3*x3)/(y3*y3))+1;
B=(-1)*(x3+((x3*x3*x3)/(y3*y3)));
C=((x3*x3*x3*x3)/(4*y3*y3))+((y3*y3)/(4))+((x3*x3)/2)-(r*r);
dis=(B*B)-4*A*C;
dis=sqrt(dis);
h1=((-1*B)+dis)/(2*A);
h2=((-1*B)-dis)/(2*A);
k1=(y3/2)+y1;
k2=(y3/2)+y1;
h1=h1+x1;
h2=h2+x1;
}
else
{
A=((y3*y3)/(x3*x3))+1;
B=(-1)*(y3+((y3*y3*y3)/(x3*x3)));
C=((y3*y3*y3*y3)/(4*x3*x3))+((x3*x3)/(4))+((y3*y3)/2)-(r*r);
dis=(B*B)-4*A*C;
dis=sqrt(dis);
k1=((-1*B)+dis)/(2*A);
k2=((-1*B)-dis)/(2*A);
h1=((y3*y3)/(2*x3))+(x3/2)-(k1*y3/x3)+x1;
h2=((y3*y3)/(2*x3))+(x3/2)-(k2*y3/x3)+x1;
k1=k1+y1;
k2=k2+y1;
}
Escoger:
system("cls");
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<"Radio de "<<r<<endl<<endl;
if(h1==h2&&k1==k2)
{
cout<<"Centro unico en = ("<<h1<<","<<k1<<")"<<endl;
h=h1;
k=k1;
system("pause");
}
else
{
cout<<"Escoger centro:"<<endl<<"1. Centro 1 = ("<<h1<<","<<k1<<")"<<endl<<"2. Centro 2 = ("<<h2<<","<<k2<<")"<<endl;
cin>>op;
switch(op)
{
case 1:
h=h1;
k=k1;
break;
case 2:
h=h2;
k=k2;
break;
default:
goto Escoger;
}
}
Giro:
system("cls");
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<"Radio de "<<r<<endl<<"Centro en ("<<h<<","<<k<<")"<<endl;
cout<<endl<<"Escoger sentido del giro:"<<endl<<"1. Horario"<<endl<<"2. Antihorario"<<endl;
cin>>op;
switch(op)
{
case 1:
giro=-1;
break;
case 2:
giro=1;
break;
default:
goto Giro;
}
Datos:
system("cls");
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<"Radio de "<<r<<endl<<"Centro en ("<<h<<","<<k<<")"<<endl;
if(giro==1)
{
cout<<"Sentido antihorario"<<endl<<endl;
}
else if(giro==-1)
{
cout<<"Sentido horario"<<endl<<endl;
}
cout<<endl<<"1. Confirmar datos"<<endl<<"2. Introducir nuevos datos"<<endl;
cin>>op;
switch(op)
{
case 1:
break;
case 2:
goto Posicion;
break;
default:
goto Datos;
break;
}
Angulo:
if(r==rm)//180 grados
{
ang=180;
if(k-y1==0||h-x1==0&&k-y2==0||h-x2==0)
{
if(x2>x1)
{
angi=180;
}
else if(x1>x2)
{
angi=0;
}
else if(x2==x1)
{
if(y2>y1)
{
angi=270;
}
else if(y1>y2)
{
angi=90;
}
}
}
else
{
x3=x1-h;
y3=y1-k;
angi=(atan((y3)/(x3)))*(180/pi);
if(x3<0&&y3>0||x3<0&&y3<0)
{
angi=180+angi;
}
else
{
angi=360+angi;
}
}
}
else if (k-y1==0||h-x1==0&&k-y2==0||h-x2==0) //90 grados
{
if(h==x2&&k==y1)
{
if(h>x1)
{
angi=180;
if(k<y2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
else if(k>y2)
{
if(giro==1)
{
ang=90;
}
else if(giro==-1)
{
ang=270;
}
}
}
else if(h<x1)
{
angi=0;
if(k<y2)
{
if(giro==1)
{
ang=90;
}
else if(giro==-1)
{
ang=270;
}
}
else if(k>y2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
}
}
else if(h==x1&&k==y2)
{
if(k>y1)
{
angi=270;
if(h<x2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
else if(h>x2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
}
else if(k<y1)
{
angi=90;
if(h>x2)
{
if(giro==1)
{
ang=90;
}
else if(giro==-1)
{
ang=270;
}
}
else if(h<x2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
}
}
}
else //x grados
{
x3=x2-h;
y3=y2-k;
ang2=atan(y3/x3)*(180/pi);
if(x3<0&&y3>0||x3<0&&y3<0)
{
ang2=180+ang2;
}
else if(x3>0&&y3<0)
{
ang2=360+ang2;
}
x3=x1-h;
y3=y1-k;
ang1=atan(y3/x3)*(180/pi);
if(x3<0&&y3>0||x3<0&&y3<0)
{
ang1=180+ang1;
}
else if(x3>0&&y3<0)
{
ang1=360+ang1;
}
m1=(y1-k)/(x1-h);
m2=(y2-k)/(x2-h);
ang=ang2-ang1;
cout<<"ang ="<<ang<<endl;
if(ang>0)
{
ang2=ang;
ang1=360-ang;
}
else if(ang<0)
{
ang1=ang*-1;
ang=sqrt(ang*ang);
ang2=360-ang;
}
if(giro==1)
{
ang=ang2;
}
else if(giro==-1)
{
ang=ang1;
}
angi=atan(m1)*(180/pi);
if(x3<0&&y3>0||x3<0&&y3<0)
{
angi=angi+180;
}
else if(x3>0&&y3<0)
{
angi=angi+360;
}
}
pasos=ang;
app=ang/pasos;
px=x1;
py=y1;
for(int i=0;i<=pasos;i++)
{
moveto(px,py);
px=r*(cos((i*app*giro+angi)*(pi/180)))+h;
py=r*(sin((i*app*giro+angi)*(pi/180)))+k;
lineto(px,py);
}
w=w+1;
bir[w].ch=h;
bir[w].ck=k;
bir[w].r=r;
bir[w].B1=px;
bir[w].B2=py;
bir[w].ap1=app;
bir[w].gi1=giro;
bir[w].ag=angi;
bir[w].inca=i;
break;
system("cls");
break;
}
goto I;
//________________________________________________________________________________________________________________________
CERRAR:
closegraph();
//__________________________________________________________________________________________________________________
BORRAR:
while(1){
p=p;
if(pas[p].tipo==1){
u=u;
setcolor(0);
line(lin[u].px1,lin[u].py1,lin[u].px2,lin[u].py2);
u=u-1;
}
else if(pas[p].tipo==2){
v=v;
setcolor(0);
circle(cir[v].cx,cir[v].cy,cir[v].r1);
v=v-1;
}
else if(pas[p].tipo==3){
w=w;
setcolor(0);
pasos=ang;
app=ang/pasos;
bir[w].B1=x1;
bir[w].B2=y1;
for(int i=0;i<=pasos;i++)
{
setlinestyle(SOLID_LINE,0,5);
moveto(bir[w].B1,bir[w].B2);
bir[w].B1=bir[w].r*(cos((i*bir[w].ap1*bir[w].gi1+bir[w].ag)*(pi/180)))+bir[w].ch;
bir[w].B2=bir[w].r*(sin((i*bir[w].ap1*bir[w].gi1+bir[w].ag)*(pi/180)))+bir[w].ck;
lineto(bir[w].B1,bir[w].B2);
circle(bir[w].ch,bir[w].ck,bir[w].r);
setlinestyle(SOLID_LINE,0,1);
}
w=w-1;
system("cls");
}
setcolor(15);
if(fw==1)
{
while(1)
{
for(gi=140;gi<=1490;gi+=10)
{
for(pj=60;pj<=740;pj+=10)
{
circle(gi,pj,1); }
}
break;
}
}
p=p-1;
break;
}
setcolor(15);
goto I;
//FORZAR_______________________________________________FORZAR________________________________________________________FORZAR
//FORZAR_______________________________________________FORZAR________________________________________________________FORZAR
//FORZAR_______________________________________________FORZAR________________________________________________________FORZAR
FORZAR:
waitForLeftMouseClick();
px=mousex( );
py=mousey( );
setcolor(15);
if ( px>= 75 && px<= 100 && py>= 600 && py<= 650) goto I;
if ( px>= 50 && px<= 100 && py>= 50 && py<= 100) {p=p+1; pas[p].tipo=1; goto LINEA1;}
if ( px>= 50 && px<= 100 && py>= 200 && py<= 250){ p=p+1; pas[p].tipo=2; goto CIRCULO1;}
if (px>=50 && px<=100 && py>=500 &&py<=550)goto CERRAR;
if(px>=50&&px<=100&&py>=700&&py<=750)goto BORRAR1;
if(px>=50&&px<=100&&py>=350&&py<=400){p=p+1; pas[p].tipo=3;goto ARCOS1;}
if(px>=50&&px<=75&&py>=110&&py<=160) goto PUNTOS1;
if(px>=75&&px<=100&&py>=110&&py<=160)goto NEGRO1;
//LINEA1__________________________________________FORZAR______________________________________________________________________
LINEA1:
while(1)
{
waitForLeftMouseClick();
px=mousex( );
px=Fx(px);
py=mousey( );
py=Fy(py);
waitForLeftMouseClick();
px1=mousex( );
px1=Fx(px1);
py1=mousey( );
py1=Fy(py1);
if ( px>= 130 && px<= 1500 && py>= 50 && py<= 750 && px1>= 130 && px1<= 1500 && py1>= 50 && py1<= 750)
{
line(px,py,px1,py1);
u=u+1;
lin[u].px1=px;
lin[u].py1=py;
lin[u].px2=px1;
lin[u].py2=py1;
}
break;
}
goto FORZAR;
//CIRCULOS1__________________________________________________________________________________________________________
CIRCULO1:
while(1)
{
waitForLeftMouseClick();
px=mousex( );
px=Fx(px);
py=mousey( );
py=Fy(py);
waitForLeftMouseClick();
px1=mousex( );
px1=Fx(px1);
py1=mousey( );
py1=Fy(py1);
//radio
xc = (px1-px);
xc = xc*xc;
yc = (py1-py);
yc = yc*yc;
r=sqrt((xc+yc));
circle(px,py,r);
v=v+1;
cir[v].cx=px;
cir[v].cy=py;
cir[v].r1=r;
break;
}
goto FORZAR;
//PINTA LOS PUNTOS__________________________________________NOFORZAR____________________________________________________________
PUNTOS1:
fw=1;
while(1)
{
for(gi=140;gi<=1490;gi+=10)
{
for(pj=60;pj<=740;pj+=10)
{
circle(gi,pj,1); }
}
break;
}
goto FORZAR;
//_______________________________________________________________________________________________________________________
//BORRA LOS PUNTOS__________________________________________NOFORZAR_____________________________________________________________
NEGRO1:
fw=2;
while(1)
{
setcolor(0);
for(gi=140;gi<=1490;gi+=10)
{
for(pj=60;pj<=740;pj+=10)
{
circle(gi,pj,1); }
}
break;
}
goto FORZAR;
//ARCOS1________________________________________________________________________________________________________________________
ARCOS1:
while(1)
{
Posicion2:
system("cls");
cout<<endl<<"Movimiento en arco"<<endl<<endl<<"Introduzca posicion inicial x,y"<<endl;
waitForLeftMouseClick();
x1=mousex();
x1=Fx(x1);
y1=mousey();
y1=Fy(y1);
waitForLeftMouseClick();
cout<<endl<<"Introduzca posicion final x,y"<<endl;
x2=mousex();
x2=Fx(x2);
y2=mousey();
y2=Fy(y2);
rm=(sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)))/2;
if(rm==0)
{
cout<<"No hay distancia entre los puntos"<<endl<<"Imposible trazar arco"<<endl;
system("pause");
goto Posicion2;
}
Radio2:
system("cls");
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<endl<<"Introduzca radio de giro"<<endl<<"Radio minimo = "<<rm<<endl;
cin>>r;
if(r<rm)
{
cout<<endl<<"Radio invalido"<<endl;
system("pause");
goto Radio2;
}
Centros2:
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<"Radio de "<<r<<endl;
y3=y2-y1;
x3=x2-x1;
if(x3==0&&y3!=0)
{
A=((x3*x3)/(y3*y3))+1;
B=(-1)*(x3+((x3*x3*x3)/(y3*y3)));
C=((x3*x3*x3*x3)/(4*y3*y3))+((y3*y3)/(4))+((x3*x3)/2)-(r*r);
dis=(B*B)-4*A*C;
dis=sqrt(dis);
h1=((-1*B)+dis)/(2*A);
h2=((-1*B)-dis)/(2*A);
k1=(y3/2)+y1;
k2=(y3/2)+y1;
h1=h1+x1;
h2=h2+x1;
}
else
{
A=((y3*y3)/(x3*x3))+1;
B=(-1)*(y3+((y3*y3*y3)/(x3*x3)));
C=((y3*y3*y3*y3)/(4*x3*x3))+((x3*x3)/(4))+((y3*y3)/2)-(r*r);
dis=(B*B)-4*A*C;
dis=sqrt(dis);
k1=((-1*B)+dis)/(2*A);
k2=((-1*B)-dis)/(2*A);
h1=((y3*y3)/(2*x3))+(x3/2)-(k1*y3/x3)+x1;
h2=((y3*y3)/(2*x3))+(x3/2)-(k2*y3/x3)+x1;
k1=k1+y1;
k2=k2+y1;
}
Escoger2:
system("cls");
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<"Radio de "<<r<<endl<<endl;
if(h1==h2&&k1==k2)
{
cout<<"Centro unico en = ("<<h1<<","<<k1<<")"<<endl;
h=h1;
k=k1;
system("pause");
}
else
{
cout<<"Escoger centro:"<<endl<<"1. Centro 1 = ("<<h1<<","<<k1<<")"<<endl<<"2. Centro 2 = ("<<h2<<","<<k2<<")"<<endl;
cin>>op;
switch(op)
{
case 1:
h=h1;
k=k1;
break;
case 2:
h=h2;
k=k2;
break;
default:
goto Escoger2;
}
}
Giro2:
system("cls");
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<"Radio de "<<r<<endl<<"Centro en ("<<h<<","<<k<<")"<<endl;
cout<<endl<<"Escoger sentido del giro:"<<endl<<"1. Horario"<<endl<<"2. Antihorario"<<endl;
cin>>op;
switch(op)
{
case 1:
giro=-1;
break;
case 2:
giro=1;
break;
default:
goto Giro2;
}
Datos2:
system("cls");
cout<<"Datos= "<<endl<<"Posicion incial en ("<<x1<<","<<y1<<")"<<endl<<"Posicion final en ("<<x2<<","<<y2<<")"<<endl<<"Radio de "<<r<<endl<<"Centro en ("<<h<<","<<k<<")"<<endl;
if(giro==1)
{
cout<<"Sentido antihorario"<<endl<<endl;
}
else if(giro==-1)
{
cout<<"Sentido horario"<<endl<<endl;
}
cout<<endl<<"1. Confirmar datos"<<endl<<"2. Introducir nuevos datos"<<endl;
cin>>op;
switch(op)
{
case 1:
break;
case 2:
goto Posicion2;
break;
default:
goto Datos2;
break;
}
Angulo2:
if(r==rm)//180 grados
{
ang=180;
if(k-y1==0||h-x1==0&&k-y2==0||h-x2==0)
{
if(x2>x1)
{
angi=180;
}
else if(x1>x2)
{
angi=0;
}
else if(x2==x1)
{
if(y2>y1)
{
angi=270;
}
else if(y1>y2)
{
angi=90;
}
}
}
else
{
x3=x1-h;
y3=y1-k;
angi=(atan((y3)/(x3)))*(180/pi);
if(x3<0&&y3>0||x3<0&&y3<0)
{
angi=180+angi;
}
else
{
angi=360+angi;
}
}
}
else if (k-y1==0||h-x1==0&&k-y2==0||h-x2==0) //90 grados
{
if(h==x2&&k==y1)
{
if(h>x1)
{
angi=180;
if(k<y2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
else if(k>y2)
{
if(giro==1)
{
ang=90;
}
else if(giro==-1)
{
ang=270;
}
}
}
else if(h<x1)
{
angi=0;
if(k<y2)
{
if(giro==1)
{
ang=90;
}
else if(giro==-1)
{
ang=270;
}
}
else if(k>y2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
}
}
else if(h==x1&&k==y2)
{
if(k>y1)
{
angi=270;
if(h<x2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
else if(h>x2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
}
else if(k<y1)
{
angi=90;
if(h>x2)
{
if(giro==1)
{
ang=90;
}
else if(giro==-1)
{
ang=270;
}
}
else if(h<x2)
{
if(giro==1)
{
ang=270;
}
else if(giro==-1)
{
ang=90;
}
}
}
}
}
else //x grados
{
x3=x2-h;
y3=y2-k;
ang2=atan(y3/x3)*(180/pi);
if(x3<0&&y3>0||x3<0&&y3<0)
{
ang2=180+ang2;
}
else if(x3>0&&y3<0)
{
ang2=360+ang2;
}
x3=x1-h;
y3=y1-k;
ang1=atan(y3/x3)*(180/pi);
if(x3<0&&y3>0||x3<0&&y3<0)
{
ang1=180+ang1;
}
else if(x3>0&&y3<0)
{
ang1=360+ang1;
}
m1=(y1-k)/(x1-h);
m2=(y2-k)/(x2-h);
ang=ang2-ang1;
cout<<"ang ="<<ang<<endl;
if(ang>0)
{
ang2=ang;
ang1=360-ang;
}
else if(ang<0)
{
ang1=ang*-1;
ang=sqrt(ang*ang);
ang2=360-ang;
}
if(giro==1)
{
ang=ang2;
}
else if(giro==-1)
{
ang=ang1;
}
angi=atan(m1)*(180/pi);
if(x3<0&&y3>0||x3<0&&y3<0)
{
angi=angi+180;
}
else if(x3>0&&y3<0)
{
angi=angi+360;
}
}
pasos=ang;
app=ang/pasos;
px=x1;
py=y1;
for(int i=0;i<=pasos;i++)
{
moveto(px,py);
px=r*(cos((i*app*giro+angi)*(pi/180)))+h;
py=r*(sin((i*app*giro+angi)*(pi/180)))+k;
lineto(px,py);
}
w=w+1;
bir[w].ch=h;
bir[w].ck=k;
bir[w].r=r;
bir[w].B1=px;
bir[w].B2=py;
bir[w].ap1=app;
bir[w].gi1=giro;
bir[w].ag=angi;
bir[w].inca=i;
break;
system("cls");
break; }
goto FORZAR;
//__________________________________________________________________________________________________________________
BORRAR1:
while(1){
p=p;
if(pas[p].tipo==1){
u=u;
setcolor(0);
line(lin[u].px1,lin[u].py1,lin[u].px2,lin[u].py2);
u=u-1;
}
else if(pas[p].tipo==2){
v=v;
setcolor(0);
circle(cir[v].cx,cir[v].cy,cir[v].r1);
v=v-1;
}
else if(pas[p].tipo==3){
w=w;
setcolor(0);
pasos=ang;
app=ang/pasos;
bir[w].B1=x1;
bir[w].B2=y1;
for(int i=0;i<=pasos;i++)
{
setlinestyle(SOLID_LINE,0,5);
moveto(bir[w].B1,bir[w].B2);
bir[w].B1=bir[w].r*(cos((i*bir[w].ap1*bir[w].gi1+bir[w].ag)*(pi/180)))+bir[w].ch;
bir[w].B2=bir[w].r*(sin((i*bir[w].ap1*bir[w].gi1+bir[w].ag)*(pi/180)))+bir[w].ck;
lineto(bir[w].B1,bir[w].B2);
circle(bir[w].ch,bir[w].ck,bir[w].r);
setlinestyle(SOLID_LINE,0,1);
}
// setlinestyle(SOLID_LINE,0,1);
w=w-1;
system("cls");
}
setcolor(15);
if(fw==1)
{
while(1)
{
for(gi=140;gi<=1490;gi+=10)
{
for(pj=60;pj<=740;pj+=10)
{
circle(gi,pj,1); }
}
break;
}
}
p=p-1;
break;
}
setcolor(15);
goto FORZAR;
}
|
160d9daa656270d9257cf96a7f5c241daf1a42c7
|
aa4d34070ac27c893252f46193bd77ac6a6bbe8d
|
/2/2_12.cpp
|
b03948312d2759bffde23f356c5a1352da535097
|
[] |
no_license
|
MaiMeng1204/Pracetice-in-Cpp-Primer
|
78eef0e883add08c4ca189636776e0d6f2eea904
|
744ddac895952b5cc95cec52172217e930caabd1
|
refs/heads/main
| 2023-03-08T22:39:26.212748
| 2021-02-27T03:05:25
| 2021-02-27T03:05:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 167
|
cpp
|
2_12.cpp
|
#include <iostream>
int main()
{
// int _; // legal
// int 1_or_2 = 1; // error: expected unqualified-id before numeric constant
double Double = 3.14;
}
|
357a75ed6d628d4a8bcf02f2cf5bfed822711589
|
f55e5e4c4f6f4c42ccd3647b78cf81aa831b6a91
|
/obstacle_detection/include/lib/range_sensor.h
|
536d61d46308c4d4e2cbc2ce6395704162fceab2
|
[] |
no_license
|
cpswarm/sensing_actuation
|
bd691a71e40e9bf48b0c3ba647eb60045ebc654a
|
e3224cbc785ddf1e4e3832785899e37f85060d31
|
refs/heads/noetic-devel
| 2023-07-23T13:43:50.950497
| 2023-07-17T13:50:52
| 2023-07-17T13:50:52
| 218,629,850
| 0
| 1
| null | 2022-04-06T13:04:06
| 2019-10-30T21:27:01
|
C++
|
UTF-8
|
C++
| false
| false
| 3,229
|
h
|
range_sensor.h
|
#ifndef RANGE_SENSOR_H
#define RANGE_SENSOR_H
#include <ros/ros.h>
#include <sensor_msgs/Range.h>
using namespace std;
using namespace ros;
/**
* @brief A helper class to process range sensor readings.
*/
class range_sensor
{
public:
/**
* @brief Constructor that initializes the private member variables.
* @param topic Topic for receiving sensor readings.
* @param angle The angle at which the sensor is mounted in radians from the forward direction of the CPS.
*/
range_sensor (string topic, double angle);
/**
* @brief Check if the CPS is dangerously close to an obstacle.
* @return The distance that the CPS has to back off in order to reach a safe distance again. Returns 0.0 in case no obstacle is closer than the critical distance.
*/
double danger ();
/**
* @brief Get the angle at which the sensor is looking.
* @return The angle of the sensor.
*/
double get_angle () const;
/**
* @brief Get the field of view of the sensor as read from the sensor messages.
* @return The FOV of the sensor.
*/
double get_fov () const;
/**
* @brief Get the computed reliable sensor range.
* @return The sensor range.
*/
double get_range ();
/**
* @brief Check if obstacles are detected by the range sensor.
* @return True if there is an obstacle between min_dist and max_dist, false otherwise.
*/
bool obstacle ();
private:
/**
* @brief Process the msgs to compute a reliable range.
*/
void process ();
/**
* @brief Callback function for sensor readings.
* @param msg Sensor message received from the UAV.
*/
void callback (const sensor_msgs::Range::ConstPtr& msg);
/**
* @brief A node handle for the main ROS node.
*/
NodeHandle nh;
/**
* @brief Subscriber for sensor readings.
*/
Subscriber subscriber;
/**
* @brief The horizontal angle at which the sensor is looking.
*/
double angle;
/**
* @brief The field of view of the sensor as read from the sensor messages.
*/
double fov;
/**
* @brief The reliable range of the sensor computed by this class.
*/
double range;
/**
* @brief Multiple sensor messages which are used to compute a reliable range.
*/
vector<sensor_msgs::Range> msgs;
/**
* @brief The position of the latest sensor message in the msgs vector.
*/
unsigned int cur_msg;
/**
* @brief The minimum range at which obstacles are considered.
*/
double min_dist;
/**
* @brief The maximum range at which obstacles are considered.
*/
double max_dist;
/**
* @brief The distance in meters to an obstacle below which the CPS has to back off first before the standard avoidance procedure.
*/
double critical_dist;
/**
* @brief Percentage of sensor messages that must report an obstacle in order for the behavior to assume an obstacle.
*/
double threshold;
/**
* @brief True when the msgs have been updated but no reliable range has been computed, false otherwise.
*/
bool dirty;
};
#endif // RANGE_SENSOR_H
|
74997b5153e548f9b77a14dd04b850bc900314f2
|
3333edce8305b199431da4ed1e2bbe9bf5aef175
|
/BOJ/3000~/3986/src.cpp
|
4d77707fdfd9129eea08db871ce33f3ef916cbc1
|
[] |
no_license
|
suhyunch/shalstd
|
d208ba10ab16c3f904de9148e4fa11f243148c03
|
85ede530ebe01d1fffc3b5e2df5eee1fa88feaf0
|
refs/heads/master
| 2021-06-07T10:45:58.181997
| 2019-08-11T13:14:48
| 2019-08-11T13:14:48
| 110,432,069
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 512
|
cpp
|
src.cpp
|
//https://www.acmicpc.net/problem/3986
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
int n;
int cnt=0;
cin >> n;
for(int i=0; i<n; i++)
{
string s;
cin >> s;
int l=s.size();
stack<char> st;
for(int j=0; j<l; j++)
{
if(!st.empty() && st.top()==s[j]) st.pop();
else st.push(s[j]);
}
if(st.empty()) cnt++;
}
cout <<cnt;
}
|
5d29698091bac517292a1c63f8560b56d96b5669
|
eb2ce3ee3d77d2543a79eac8919fb056e0e43e17
|
/include/Mojo/TextureAtlas.hpp
|
607a25efd55dd1f6683b024c36e5c159069b3f41
|
[
"MIT"
] |
permissive
|
mtwilliams/mojo
|
b65a75a8f406113602124bb6fd6606a5d067ef33
|
e9d3c718617d9668049a17731844a4b35be9759d
|
refs/heads/master
| 2020-05-18T04:46:20.928021
| 2012-04-30T06:26:57
| 2012-04-30T06:26:57
| 4,081,721
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 560
|
hpp
|
TextureAtlas.hpp
|
#ifndef MOJO_TEXTURE_ATLAS_HPP
#define MOJO_TEXTURE_ATLAS_HPP
#include <Mojo/Core.hpp>
#include <Mojo/Graphics.hpp>
namespace Mojo
{
class MOJO_CLASS_EXPORT(TextureAtlas) : public Mojo::NonCopyable
{
public:
TextureAtlas( const uint32_t width, const uint32_t height, const uint32_t bpp );
~TextureAtlas();
Mojo::Texture Compile( const bool mipmap = true ) const;
public:
const uint32_t _width, _height, _bpp;
uint8_t* _pixels;
};
}
#endif /* MOJO_TEXTURE_ATLAS_HPP */
|
2403c132f44d935fe9cb3441c3ba979c3c24ae82
|
a33aac97878b2cb15677be26e308cbc46e2862d2
|
/program_data/PKU_raw/61/758.c
|
074f7664341d9bb0f22c792363a41ad0902f88be
|
[] |
no_license
|
GabeOchieng/ggnn.tensorflow
|
f5d7d0bca52258336fc12c9de6ae38223f28f786
|
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
|
refs/heads/master
| 2022-05-30T11:17:42.278048
| 2020-05-02T11:33:31
| 2020-05-02T11:33:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 306
|
c
|
758.c
|
int main()
{
int i,n,a[20],m;
int f[20]={1,1};
for(i=2;i<20;i++)
f[i]=f[i-2]+f[i-1];
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&m);
a[i]=f[m-1];
}
for(i=1;i<=n;i++)
printf("%d\n",a[i]);
getchar();
getchar();
return 0;
}
|
f4eb963f3cac0fd794b4b7ff440b6f3eec72daef
|
c842eebea4a90c0fef20ec3580d32f25c32d9d5c
|
/treinamento-c/2016/aula-01/turma-01/Treinamento_002_printf.cpp
|
2802689c4a5109a88cd089aa165aeac1a4300f30
|
[] |
no_license
|
ITAbits/documentacao
|
16a6fb7c157db4b38822b0d933141fd425a289ee
|
86c1ddef14c99dcfe221995ca59e6b6d754c5f33
|
refs/heads/master
| 2021-03-22T05:12:59.524668
| 2020-03-25T16:59:14
| 2020-03-25T16:59:14
| 120,128,133
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 925
|
cpp
|
Treinamento_002_printf.cpp
|
#include <stdio.h>
int main()
{
int a = 2;
float b = 2.5;
double c = 2.52;
char d = 'n';
///Como imprimir mensagens na tela? printf !!!
printf("Assim que vc escreve na tela ;-)");
///Para imprimir informacoes das variaveis?
///int:
printf("Valor de a = %d", a);
///float:
printf("Valor de b = %f", b);
///double:
printf("Valor de c = %lf", c);
///char:
printf("Caractere em d = %c",d);
///Compile esse programa (comente a parte de baixo e de F9), vc vera que as msgs estao juntas e fica ruim de entender assim
///bizu para isso: '\n', veja:
printf("\n\nCOM O \\n\nValor de a = %d\nValor de b = %f\nValor de c = %lf\nCaractere em d = %c\n\n\n",a,b,c,d);
///Manipulando a maneira que os numeros se apresentam, veja:
printf("Valor de b = %f\nValor de b = %.2f\nValor de b = %10.1f\n",b,b,b);
printf("Valor de a = %2d\n",a);
return 0;
}
|
78374cb11aa26e57fd2183aca4ed3642d84bce5a
|
2ddd6b8bdddc4ff98ba2ba60cf20ef82fec10e58
|
/Sources/etwprof/Profiler/IETWBasedProfiler.hpp
|
37640caf4367569ee2f5daeb54c11733525864dc
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
zhangshuangjun/etwprof
|
f91d606220c0a236e28a28db37d4ad433998a417
|
7d23283c9939e04e7faada52b28b17d391178101
|
refs/heads/master
| 2021-02-26T20:15:31.135562
| 2020-01-03T08:35:01
| 2020-01-03T08:35:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,159
|
hpp
|
IETWBasedProfiler.hpp
|
#ifndef ETWP_I_ETW_BASED_PROFILER_HPP
#define ETWP_I_ETW_BASED_PROFILER_HPP
#include <windows.h>
#include "IProfiler.hpp"
#include "Utility/Macros.hpp"
namespace ETWP {
// Interface for thread-safe ETW-based profiler objects
class IETWBasedProfiler : public IProfiler {
public:
ETWP_DISABLE_COPY_AND_MOVE (IETWBasedProfiler);
struct ProviderInfo {
GUID providerID;
bool stack;
UCHAR level;
ULONGLONG flags;
};
using Flags = uint8_t;
enum Options : Flags {
Default = 0b000,
RecordCSwitches = 0b001, // Record context switch information
Compress = 0b010, // Compress result ETL with ETW's built-in compression
Debug = 0b100 // Preserve intermediate ETL files (if any)
};
IETWBasedProfiler () = default;
virtual ~IETWBasedProfiler () = default;
virtual bool EnableProvider (const ProviderInfo& providerInfo) = 0;
};
bool operator== (const IETWBasedProfiler::ProviderInfo& lhs, const IETWBasedProfiler::ProviderInfo& rhs);
} // namespace ETWP
#endif // #ifndef ETWP_I_ETW_BASED_PROFILER_HPP
|
be8bb11bf5fefc6a7b16661a63bc314ccd0f864b
|
abb667cfc26ae9fcbb1970383fea256e12511860
|
/procc.cpp
|
36a171af4d3e68d475eed46e6a79e1892c22f29d
|
[] |
no_license
|
Siarhei-Hanchuk/kb2clone
|
91a01834162534e3f9321247e48a464e85b5c406
|
a20acbd7b5fd83fb73d22d002541aac3b48f8900
|
refs/heads/master
| 2022-07-26T06:20:10.710991
| 2011-12-10T21:15:33
| 2011-12-10T21:15:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,239
|
cpp
|
procc.cpp
|
#include "header.h"
#include "world.h"
#include "texts.h"
#include "gui.h"
void init_map()
{
gw_c1_main(world.country[0].map);
gw_c2_main(world.country[1].map);
gw_c3_main(world.country[2].map);
gw_c4_main(world.country[3].map);
gw_c5_main(world.country[4].map);
gw_c0_def();
pl.country=0;
pl.X=5;
pl.Y=5;
pl.wallkick=FALSE;
pl.money=20000;
pl.authority=50;
world.cut_cap=0;
//init_army();
for(gint i=0;i<10;i++)
pl.army[i].armid=0;
pl.workers.carpenter=4;
pl.workers.woodsman=6;
pl.workers.groundsman=0;
pl.workers.stonesman=3;
GV.tmpv_wrk=0;
}
gint8 cstep(int x, int y,gint ox=0,gint oy=0)
{
if(GV.gui_dialog_showed){
gui_dialog_hideall();
//gui_dlg_showed=FALSE;
return 0;
}
if(world.country[pl.country].map[x][y].obj==o_nave){
pl.Y=y;
pl.X=x;
pl.innave=TRUE;
return 1;
}
if((world.country[pl.country].map[x][y].land==l_water)&&(pl.innave==TRUE)){
gboolean s=FALSE;
if((x>1)&&(x<63)){pl.X=x;s=TRUE;}
if((y>1)&&(y<63)){pl.Y=y;s=TRUE;}
//pl.X=x;s=TRUE;
//pl.Y=y;s=TRUE;
if(s){world.country[pl.country].map[ox][oy].obj=0;
world.country[pl.country].map[pl.X][pl.Y].obj=o_nave;}
world.naveX=pl.X;
world.naveY=pl.Y;
world.naveC=pl.country;
return 1;
}
if((world.country[pl.country].map[x][y].land==l_plot)&&(world.country[pl.country].map[x][y].obj==0)){
pl.X=x;
pl.Y=y;
return 1;
}
if(((world.country[pl.country].map[x][y].land==l_land)||(world.country[pl.country].map[x][y].land==l_sand))&&(world.country[pl.country].map[x][y].obj==0)){
pl.X=x;
pl.Y=y;
if(pl.innave){pl.innave=FALSE;}
return 1;
}
if(world.country[pl.country].map[x][y].obj==o_guidepost){
gchar *s2=text_get_strid("sid_guidepost_name");
gchar *s1=text_get_strid_rand("sid_guidepost",12);
gui_dialog_show(s2,s1);
delete[] s1;
delete[] s2;
GV.gui_dialog_showed=TRUE;
return 0;
}
if(world.country[pl.country].map[x][y].obj==o_city){
GV.tmpv_cityX=x;
GV.tmpv_cityY=y;
Tmenu m=gui_menu_city_set(world.country[pl.country].map[x][y].addid);
GV.gui_keylock_event=o_city;
GV.tmpv_city=world.country[pl.country].map[x][y].addid;
gui_menu_show(m);
gui_menu_free(m);
}
if(world.country[pl.country].map[x][y].obj==o_army){
GV.gui_keylock_event=o_army;
gui_byarmy_show(world.country[pl.country].map[x][y].addid);
}
if(world.country[pl.country].map[x][y].obj==o_goldchest){
Tmenu m=gui_menu_set_gold();
GV.gui_keylock_event=o_goldchest;
gui_menu_show(m);
gui_menu_free(m);
world.country[pl.country].map[x][y].obj=0;
}
return -1;
}
id** gui_getA()
{
id **a=new id*[10];
for(int i=0;i<10;i++){a[i]=new id[10];}
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
a[i][j]=world.country[pl.country].map[pl.X-2+i][pl.Y-2+j].land;
if(world.country[pl.country].map[pl.X-2+i][pl.Y-2+j].obj!=0){a[i][j]=world.country[pl.country].map[pl.X-2+i][pl.Y-2+j].obj;}
}}
if(!pl.innave){
a[2][2]=o_player;
}else{
a[2][2]=o_nave;
}
if(pl.wallkick)
a[5][1]=s_wallkick_c;
else
a[5][1]=s_wallkick_b;
if(pl.contract)
a[5][0]=s_contract_c;
else
a[5][0]=s_contract_b;
a[5][2]=s_magic_0;
a[5][3]=s_money_0;
a[5][4]=s_ancientmap_0;
a[9][9]=world.country[pl.country].map[pl.X][pl.Y].land;
return a;
}
void gui_freeA(id **A)
{
for(int i=0;i<10;i++){delete A[i];}
delete A;
}
id** procw(id key)
{
gint8 r=0;
if(GV.gui_dialog_showed){gui_dialog_hideall();return gui_getA();}
if(key==key_down){
r=cstep(pl.X,pl.Y+1,pl.X,pl.Y);
}
if(key==key_up){
r=cstep(pl.X,pl.Y-1,pl.X,pl.Y);
}
if(key==key_right){
r=cstep(pl.X+1,pl.Y,pl.X,pl.Y);
}
if(key==key_left){
r=cstep(pl.X-1,pl.Y,pl.X,pl.Y);
}
if(r==1){
return gui_getA();
}else{return 0;}
}
|
f9d191488d694e0ab89fcb8c99ea9683f8e2ce12
|
a437f2892facb598e6e9ee27bce5f85bdc4ede10
|
/src/mpi/mpi_sorting.hpp
|
43c2c335a59427e715b2e8aeef603ad9732a6248
|
[] |
no_license
|
TheSonOfDeimos/Bioinformatic-gray-sort
|
7aa5cd1fbf7cc00f1eed5a0f78cdba8f049896b2
|
7d38ae02aec75b35f560cef8894a0ebbd018b97a
|
refs/heads/master
| 2020-09-07T01:24:13.732032
| 2019-12-23T21:27:50
| 2019-12-23T21:27:50
| 220,615,085
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,484
|
hpp
|
mpi_sorting.hpp
|
#ifndef MPI_SORTING_HPP
#define MPI_SORTING_HPP
#include <cmath>
#include "mpi.h"
#include "bioscience/bio.hh"
template < typename T >
void mpi_proc_send_pkg(const int proc_dest, T& dataStruct)
{
int num_procs;
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
if (proc_dest < 0) {
return;
}
MPI_Status stat;
MPI_Request req;
MPI_Isend(dataStruct.data(), sizeof(decltype(dataStruct.back())) * dataStruct.size(), MPI_BYTE, proc_dest, 0, MPI_COMM_WORLD, &req);
MPI_Request_free(&req);
MPI_Recv(dataStruct.data(), sizeof(decltype(dataStruct.back())) * dataStruct.size(), MPI_BYTE, proc_dest, 0, MPI_COMM_WORLD, &stat);
}
template < typename T >
void mpi_proc_recive_pkg(const int proc_sourse, T& dataStruct)
{
int num_procs;
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
if (proc_sourse > num_procs - 1) {
return;
}
MPI_Status stat;
MPI_Request req;
int datasize = 0;
MPI_Probe(proc_sourse, 0, MPI_COMM_WORLD, &stat);
MPI_Get_count(&stat, MPI_BYTE, &datasize);
assert(datasize >= 0);
unsigned int original_size = dataStruct.size();
dataStruct.resize(original_size + (datasize / sizeof(decltype(dataStruct.back()))));
MPI_Recv(&dataStruct[original_size], datasize, MPI_BYTE, proc_sourse, 0, MPI_COMM_WORLD, &stat);
std::stable_sort(dataStruct.begin(), dataStruct.end());
MPI_Isend(&dataStruct[original_size], datasize, MPI_BYTE, proc_sourse, 0, MPI_COMM_WORLD, &req);
MPI_Request_free(&req);
dataStruct.resize(original_size);
}
template < typename T >
void mpi_sort(T& data)
{
int proc_rank;
int num_procs;
MPI_Comm_rank(MPI_COMM_WORLD, &proc_rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
bool phase_indicator = 0;
for (uint i = 0; i < num_procs; i++)
{
if (proc_rank == 0) {
phase_indicator = !phase_indicator;
}
MPI_Bcast(&phase_indicator, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (phase_indicator == 0) {
if (proc_rank % 2 == 0) {
mpi_proc_send_pkg(proc_rank - 1, data);
}
else {
mpi_proc_recive_pkg(proc_rank + 1, data);
}
}
else if (phase_indicator == 1) {
if (proc_rank % 2 == 1) {
mpi_proc_send_pkg(proc_rank - 1, data);
}
else {
mpi_proc_recive_pkg(proc_rank + 1, data);
}
}
}
}
#endif
|
16883d64afc6863de188dbfa5b8419fe61cc1970
|
568362db93a8b900a7815c4fad42768e1531eb0e
|
/src/ANSCommon/ANSArray2D.hpp
|
c9103a2e773dd77811855352be64e8b10ac119a4
|
[] |
no_license
|
Forrest-Z/Samsung_TapelessAGV
|
f5161d6a995cac85a214da0302f8cbab81c3dced
|
99295e2d0bed7edca5421cae2bdf4c8ac02f00b8
|
refs/heads/main
| 2023-03-25T12:55:19.414510
| 2021-03-25T10:26:26
| 2021-03-25T10:26:26
| 397,121,747
| 1
| 3
| null | 2021-08-17T05:53:43
| 2021-08-17T05:53:43
| null |
UTF-8
|
C++
| false
| false
| 3,909
|
hpp
|
ANSArray2D.hpp
|
#pragma once
#include "ANSCommon.h"
template <typename ArrayType>
class CANSArray2D // Declaration and definition of a template class should be written in the same file.
{
private:
// Variables
int m_nSizeX;
int m_nSizeY;
bool m_bInitialized;
public:
// Variables
// ArrayType* data;
ArrayType** data;
// Functions
/**
* @brief Create a grid map.
* @date 2014/10/23
* @param nSizeX
* @param nSizeY
* @return void
*/
inline void create(const int nSizeX, const int nSizeY)
{
int i, j;
// Check size
if(nSizeX <= 0 || nSizeY <= 0)
{
ANS_LOG_ERROR("[ANSArray2D] Size of the array should be larger than 0.", true);
}
// Allocate
if(data)
{
for(i = 0; i < nSizeX; i++)
{
delete [] data[i];
}
delete [] data;
data = 0;
}
// m_pArray = new ArrayType [nSizeX * nSizeY];
data = new ArrayType* [nSizeX];
for(i = 0; i < nSizeX; i++)
{
data[i] = new ArrayType [nSizeY];
}
m_nSizeX = nSizeX;
m_nSizeY = nSizeY;
m_bInitialized = true;
// Initialize
/*
// for(i = 0; i < nSizeX * nSizeY; i++)
for(i = 0; i < nSizeX; i++)
{
for(j = 0; j < nSizeY; j++)
{
m_pArray[i][j] = (ArrayType)0;
}
}
*/
};
/**
* @brief Set value.
* @date 2014/10/23
* @param nx
* @param ny
* @param value
* @return void
*/
inline void set(const int nx, const int ny, ArrayType value)
{
if(data)
{
if(nx >= 0 && nx < m_nSizeX && ny >= 0 && ny < m_nSizeY)
{
// m_pArray[nx + m_nSizeX * ny] = value;
data[nx][ny] = value;
}
else
{
ANS_LOG_ERROR("[ANSArray2D] Access violation", true);
}
}
else
{
ANS_LOG_ERROR("[ANSArray2D] The array is not initialized.", true);
}
};
/**
* @brief Assign values to all elements.
* @date 2014/10/28
* @param value
* @return void
*/
inline void set(ArrayType value)
{
if(data)
{
for(int i = 0; i < m_nSizeX; i++)
{
for(int j = 0; j < m_nSizeY; j++)
{
data[i][j] = value;
// m_pArray[j * m_nSizeX + i] = value;
}
}
}
else
{
ANS_LOG_ERROR("[ANSArray2D] The pointer is not initialized.", true);
}
};
/**
* @brief Get value.
* @date 2014/10/23
* @param nx
* @param ny
* @return ArrayType
*/
inline ArrayType get(const int nx, const int ny)
{
if(data)
{
// return m_pArray[nx + m_nSizeX * ny];
return data[nx][ny];
}
else
{
ANS_LOG_ERROR("[ANSArray2D] The pointer is not initialized.", true);
}
return data[nx][ny];
};
/**
* @brief Return array size (x).
* @date 2014/10/23
* @return int
*/
int get_size_x(void)
{
return m_nSizeX;
}
/**
* @brief Return array size (y).
* @date 2014/10/23
* @return int
*/
int get_size_y(void)
{
return m_nSizeY;
}
/**
* @brief Return initialization status.
* @date 2014/10/28
* @return bool
*/
bool is_initialized(void)
{
return m_bInitialized;
}
/**
* @brief "=" operator
* @date 2014/10/28
* @param arr
* @return CANSArray2D<ArrayType>&
*/
CANSArray2D<ArrayType>& operator =(CANSArray2D<ArrayType>& arr)
{
if(this != &arr)
{
if(m_nSizeX != arr.get_size_x() || m_nSizeY != arr.get_size_y())
{
create(arr.get_size_x(), arr.get_size_y());
}
for(int i = 0; i < m_nSizeX; i++)
{
for(int j = 0; j < m_nSizeY; j++)
{
data[i][j] = arr.get(i, j);
// m_pArray[j * m_nSizeX + i] = arr.get(i, j);
}
}
}
return *this;
}
// Constructor and destructor
CANSArray2D<ArrayType>(void)
: data(0)
, m_nSizeX(0)
, m_nSizeY(0)
, m_bInitialized(false)
{
};
CANSArray2D<ArrayType>(const int nSizeX, const int nSizeY)
: data(0)
, m_nSizeX(0)
, m_nSizeY(0)
, m_bInitialized(false)
{
create(nSizeX, nSizeY);
};
~CANSArray2D<ArrayType>(void)
{
int i;
// Delete
if(data)
{
for(i = 0; i < m_nSizeX; i++)
{
delete [] data[i];
}
delete [] data;
data = 0;
}
};
};
|
58db617618dc3a6723c39a223502994012b5bd2c
|
dc4f48e683c9e4beb72213004118b5277d2cf96e
|
/drawDistributions.cpp
|
eb29fb9f3a0ab6430bbfa3ed2fa644b5c0ad1b1c
|
[] |
no_license
|
jniedzie/disappTracks
|
f585d80e70438fd6f5a395d86d7a08f3fbf09c03
|
cbe9320b26e36b4b2846a6aa240002ae8bf5b277
|
refs/heads/master
| 2021-07-08T16:55:39.870856
| 2020-06-25T13:15:42
| 2020-06-25T13:15:42
| 141,112,155
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,359
|
cpp
|
drawDistributions.cpp
|
#include "EventSet.hpp"
#include "Helpers.hpp"
#include "ConfigManager.hpp"
#include "CutsManager.hpp"
#include <TApplication.h>
string configPath = "configs/analysis.md";
int main(int argc, char* argv[])
{
TApplication theApp("App", &argc, argv);
// All events with initial cuts only
config = ConfigManager(configPath);
EventSet events;
string inputPrefix = "";
if(config.secondaryCategory == "Wmunu") inputPrefix += "Wmunu/";
if(config.secondaryCategory == "Zmunu") inputPrefix += "Zmunu/";
if(config.params["cuts_level"] == 0) inputPrefix += "after_L0/";
else if(config.params["cuts_level"] == 1) inputPrefix += "after_L1/"+config.category;
else{
cout<<"ERROR -- unknown cuts level: "<<config.params["cuts_level"]<<endl;
exit(0);
}
inputPrefix += "/";
events.LoadEventsFromFiles(inputPrefix);
CutsManager cutsManager;
EventCut eventCut;
TrackCut trackCut;
JetCut jetCut;
LeptonCut leptonCut;
cutsManager.GetCuts(eventCut, trackCut, jetCut, leptonCut);
events.ApplyCuts(eventCut, trackCut, jetCut, leptonCut);
events.PrintYields();
cout<<"Drawing plots"<<endl;
if(config.params["draw_standard_plots"]) events.DrawStandardPlots();
if(config.params["draw_per_layer_plots"]) events.DrawPerLayerPlots();
cout<<"Done"<<endl;
theApp.Run();
return 0;
}
|
d62fcdbab4216515c9d83c033d026249cc3ee85b
|
7a1886a5503740a1962e5f5875973c6b94c9bdf5
|
/impl/Tour.cpp
|
fb86ebb42598fd8fed2eb34063a268fbe7115248
|
[] |
no_license
|
herbertmaa/genetic_algorithm
|
11fe230b2c9d1b6434fe3d8995f6306b659fcb71
|
a5b9905efbefb0d492d4352610ca39e99470a5a6
|
refs/heads/master
| 2023-01-28T16:51:44.158925
| 2020-12-07T20:59:19
| 2020-12-07T20:59:19
| 310,985,935
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,430
|
cpp
|
Tour.cpp
|
//
// Created by Herbert Ma on 2020-11-07.
//
#include <random>
#include <algorithm>
#include <iostream>
#include "../headers/Tour.hpp"
#include "../headers/CityList.hpp"
using std::cout;
using std::endl;
using std::swap;
Tour::Tour() {
cities = CityList::get_instance().shuffle();
determine_fitness();
}
Tour::Tour(const Tour &t1, const Tour &t2) {
std::mt19937 e{std::random_device{}()};
std::uniform_int_distribution<int> dist{0, CityList::CITIES_IN_TOUR -1};
int rand = dist(e);
// Get a end point of the Tour 1 to copy from
auto end = t1.cities.begin() + rand;
// Copy from the beginning to the end of the tour
for(auto it = t1.cities.begin(); it <= end; ++it){
cities.push_back(*it);
}
// Fill in the rest of cities vector with cities from T2
for(auto city : t2.cities) {
//If the city is already in T1, do not push into it.
if (!contains_city(city)) {
cities.push_back(city);
}
}
//Determine the fitness of the newly created tour
determine_fitness();
}
Tour::Tour(const Tour &t) {
cities = vector<City *> {t.cities.begin(), t.cities.end()};
fitness = t.fitness;
total_distance = t.total_distance;
determine_fitness();
}
void Tour::swap(Tour &lhs, Tour &rhs) {
lhs.cities.swap(rhs.cities);
std::swap(lhs.fitness, rhs.fitness);
std::swap(lhs.total_distance, rhs.total_distance);
}
ostream &operator<<(ostream &os, const Tour &t) {
os << "Tour distance: " << t.get_tour_distance() << endl;
os << "Tour fitness: " << t.get_fitness() << endl;
for(City* c: t.cities){
os << *c << endl;
}
return os;
}
void Tour::determine_fitness() {
total_distance = 0;
for (auto it = cities.begin(); it != cities.end() - 1; ++it) {
total_distance += get_distance_between_cities(**it, **(it + 1));
}
if (total_distance == 0) throw std::invalid_argument("DIVIDING BY ZERO");
this-> fitness = Tour::RANDOM_SEED / total_distance;
}
bool Tour::operator<(const Tour &t2) const {
return (this->fitness < t2.fitness);
}
void Tour::mutate() {
// Random number generator
std::mt19937 e{std::random_device{}()};
std::uniform_real_distribution<double> dist(0, 1);
// Get a random iterator pointing to a city in the tour
// Random number
for (int i = 0; i < (int) cities.size(); ++i) {
int rand = dist(e);
auto it = cities.begin() + i;
if (rand > MUTATION_RATE) continue;
// Check for cases of the iterator being at the beginning or the end
if (it == cities.end() - 1) {
iter_swap(it, it - 1);
} else if (it == cities.begin()) {
iter_swap(it, it + 1);
} else if (rand < (MUTATION_RATE / 2)) {
iter_swap(it, it - 1);
} else {
iter_swap(it, it + 1);
}
}
// Redetermine the fitness of the tour
determine_fitness();
}
Tour &Tour::operator=(Tour assignment) {
swap(*this, assignment);
return *this;
}
double Tour::get_fitness() const {
if (fitness != 0) return fitness;
throw std::overflow_error("Fitness value is equal to 0");
}
bool Tour::contains_city(City* city) const {
if (std::find(cities.begin(), cities.end(), city) != cities.end()) {
return true;
} else {
return false;
}
}
int Tour::num_cities() const {
return cities.size();
}
|
0920f2e4a91fc72770e700ac46012fce25816f6f
|
adf0421f9256480923bf0e084b5b158fb8a2a652
|
/小结/回文/5.最长回文子串.cpp
|
8aa2ff43d8dfcb3c6a73e99c9b20413e4e32ce92
|
[] |
no_license
|
XAlearnerer/LeetCode
|
d5c6ac850fb73766639e730d0ed9a962166d07a2
|
6bbdac1ccd8e30ba48747877e2f34b5ca97ce844
|
refs/heads/master
| 2020-04-01T01:30:37.673708
| 2019-10-15T02:38:22
| 2019-10-15T02:38:22
| 152,741,487
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,389
|
cpp
|
5.最长回文子串.cpp
|
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
class Solution_ha {
public:
string longestPalindrome(string s) {
if (s.empty()) return "";
if (s.size() == 1) return s;
int pos = 0, len = 0;
for (int i = 0; i < s.size() - 1; ++i)
{
//就是要注意奇偶情况,由于回文串的长度可奇可偶,
//比如 "bob" 是奇数形式的回文,"noon" 就是偶数形式的回文,
//两种形式的回文都要搜索
helper(s, i, i, pos, len);
helper(s, i, i + 1, pos, len);
}
return s.substr(pos, len);
}
void helper(string s, int l, int r, int& pos, int& len)
{
while (l >= 0 && r < s.size() && s[l] == s[r])
{
--l; ++r;
}
if (r - l - 1 > len)
{
pos = l + 1;
len = r - l - 1;
}
}
};
//////////////////////////////////////////////////////////////////////////////
// 其中 dp[i][j] 表示字符串区间[i, j] 是否为回文串,
// 当 i = j 时,只有一个字符,肯定是回文串,
// 如果 i = j + 1,说明是相邻字符,此时需要判断 s[i] 是否等于 s[j],
// 如果i和j不相邻,即 i - j >= 2 时,除了判断 s[i] 和 s[j] 相等之外,
// dp[i + 1][j - 1] 若为真,就是回文串,通过以上分析,可以写出递推式如下:
//
// dp[i, j] = 1 if i == j
//
// = s[i] == s[j] if j = i + 1
// = s[i] == s[j] && dp[i + 1][j - 1] if j > i + 1
class Solution_dp {
public:
string longestPalindrome(string& s) {
if (s.empty()) return "";
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
int left = 0, len = 1;
for (int i = 0; i < n; ++i)
{
dp[i][i] = 1;
for (int j = 0; j < i; ++j)
{
if (i - j < 2)
{
if (s[i] == s[j])
{
dp[j][i] = 1;
if (i - j + 1 > len)
{
len = i - j + 1;
left = j;
}
}
}
else
{
if (s[i] == s[j] && dp[j + 1][i - 1] == 1)
{
dp[j][i] = 1;
if (i - j + 1 > len)
{
len = i - j + 1;
left = j;
}
}
}
}
}
return s.substr(left, len);
}
};
//////////////////////////////////////////////////////////////////////////////
class Solution_mlc_web {
public:
string longestPalindrome(string s) {
string cur = "$#";
for (int i = 0; i < s.size(); ++i) {
cur += s[i];
cur += "#";
}
vector<int> p(cur.size(), 0);
int id = 0, mx = 0;
int resid = 0, reslen = 0;
for (int i = 1; i < cur.size(); ++i)
{
if (mx > i) p[i] = min(p[2 * id - i], mx - i);
else p[i] = 1;
while (cur[p[i] + i] == cur[i - p[i]]) ++p[i];
if (p[i] + i > mx)
{
mx = p[i] + i;
id = i;
}
if (reslen < p[i])
{
reslen = p[i];
resid = i;
}
}
return s.substr((resid - reslen) / 2, reslen - 1);
}
};
//比如 "bob" 是奇数形式的回文,"noon" 就是偶数形式的回文,
//马拉车算法的第一步是预处理,做法是在每一个字符的左右都加上一个特殊字符,
//比如加上 '#',那么
//bob--> #b#o#b#
//noon--> #n#o#o#n#
//这样做的好处是不论原字符串是奇数还是偶数个,处理之后得到的字符串的个数都是奇数个,
//"#b#o#b#",我们很容易看出来以中间的 'o' 为中心的回文串的半径是4,而 "bob"的长度是3,
//"#n#o#o#n#",以最中间的 '#' 为中心的回文串的半径是5,而 "noon" 的长度是4
//
//
//"#1#2#2# 1 #2#2#" 中的位置是7,而半径是6,貌似 7-6=1,
//刚好就是回文子串 "22122" 在原串 "122122" 中的起始位置1。
//那么我们再来验证下 "bob","o" 在 "#b#o#b#" 中的位置是3,但是半径是4,
//这一减成负的了,肯定不对。
//所以我们应该至少把中心位置向后移动一位,才能为0啊,
//那么我们就需要在前面增加一个字符
//////////////////////////////////////////////////////////////////////
//!!! 最长子串的 [长度] 是 [半径] 减1,[起始位置] 是 [中间位置减去半径再除以2] 。
//"$#1#2#2#1#2#2#" : (8 - 6) / 2 = 1;
//"$#b#o#b#" : (4 - 4) / 2 = 0;
//////////////////////////////////////////////////////////////////////
//需要新增两个辅助变量 mx 和 id,
//其中 id 为能延伸到最右端的位置的那个回文子串的中心点位置,
//mx 是回文串能延伸到的最右端的位置,
//需要注意的是,这个 mx 位置的字符不属于回文串,
//所以才能用 mx - i 来更新 p[i] 的长度而不用加1,
//https://www.cnblogs.com/grandyang/p/4475985.html
class Solution {
public:
string longestPalindrome(string& s) {
string cur = "$#";
for (int i = 0; i < s.size(); ++i) {
cur += s[i];
cur += "#";
}
vector<int> p(cur.size(), 0);
int id = 0, mx = 0;
int resid = 0, reslen = 0;
for (int i = 1; i < cur.size(); ++i)
{
if (mx > i)
{
int j = 2 * id - i;
//p[i] = min(p[2 * id - i], mx - i);
if (mx - i > p[j]) p[i] = p[j];
else p[i] = mx - i;
}
else p[i] = 1;
while (cur[p[i] + i] == cur[i - p[i]]) ++p[i];
if (p[i] + i > mx)
{
mx = p[i] + i;
id = i;
}
if (reslen < p[i])
{
reslen = p[i];
resid = i;
}
}
return s.substr((resid - reslen) / 2, reslen - 1);
}
};
//int main()
//{
// string s = "babad";
// Solution n;
// cout << n.longestPalindrome(s) << endl;
// return 0;
//}
|
9b07ab6e53f86cb655dd61b588971cd96c7b3344
|
7e298da72d400995c355b8ab4c6d8d3a63be7e70
|
/src/PID.h
|
2a997bf91e7d33d54b4e15a664ba52ed3ab536ee
|
[
"MIT"
] |
permissive
|
CyberAMS/CarND-PID-Control-Project
|
e25d3a5f48d660abfada0c7a9c81d46190e9dc02
|
1352604e60f426f4b4ec908efc828d90fee7c878
|
refs/heads/master
| 2020-04-17T18:59:01.486851
| 2019-01-26T23:27:05
| 2019-01-26T23:27:05
| 166,849,186
| 0
| 0
|
MIT
| 2019-01-21T16:57:02
| 2019-01-21T16:57:01
| null |
UTF-8
|
C++
| false
| false
| 1,619
|
h
|
PID.h
|
#ifndef PID_H
#define PID_H
#include <string>
#include <limits>
using std::string;
// define constants
const bool bFILEOUTPUT = true;
const string OUTPUT_FILENAME = "out.txt";
const bool TWIDDLE = true;
const unsigned int NUM_CONVERGED_STEPS = 100;
const unsigned int NUM_LOOP_STEPS = 1000;
const double DEFAULT_KP = 0.2;
const double DEFAULT_KI = 0.0001;
const double DEFAULT_KD = 3.0;
const double TWIDDLE_FACTOR = 10.0;
const unsigned int NUM_CHANGE_STATES = 6;
const unsigned int DISPLAY_COLUMN_WIDTH = 16;
class PID {
public:
/**
* Constructor
*/
PID();
/**
* Destructor.
*/
virtual ~PID();
/**
* Initialize PID.
* @param (Kp_, Ki_, Kd_) The initial PID coefficients
*/
void Init(double Kp_, double Ki_, double Kd_);
/**
* Update the PID error variables given cross track error.
* @param cte The current cross track error
*/
void UpdateError(double cte);
/**
* Calculate the total PID error.
* @output The total PID error
*/
double TotalError();
private:
/**
* PID Errors
*/
double p_error = 0.0;
double i_error = 0.0;
double d_error = 0.0;
double error = 0.0;
double best_error = std::numeric_limits<double>::max();
/**
* PID Coefficients
*/
double Kp = DEFAULT_KP;
double Ki = DEFAULT_KP;
double Kd = DEFAULT_KD;
double dKp = DEFAULT_KP / TWIDDLE_FACTOR;
double dKi = DEFAULT_KI / TWIDDLE_FACTOR;
double dKd = DEFAULT_KD / TWIDDLE_FACTOR;
// status variables
bool is_converged = false;
unsigned int converge_steps = 0;
unsigned int full_loop_steps = 0;
unsigned int change = 0;
};
#endif // PID_H
|
3c95fb2a00e123578d3ac26d1b75aa8fae78aa66
|
deba01947163db3f034e23d79378e92665d1a799
|
/coroutine/stream_iter.hpp
|
f432d651a4456a3578c69867a8af6f3e53ffb645
|
[] |
no_license
|
Hexilee/silver-io
|
c8e8b91e866130863d1bfc01a0ba52de7d75fc4e
|
142b2afd808f5733bea601baa8ccedf80841eb07
|
refs/heads/master
| 2020-06-10T09:29:05.881342
| 2019-08-03T06:08:27
| 2019-08-03T06:08:27
| 193,629,106
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,466
|
hpp
|
stream_iter.hpp
|
/*
* Created by 李晨曦 on 2019-07-02.
*/
#ifndef SILVER_IO_STREAM_ITER_HPP
#define SILVER_IO_STREAM_ITER_HPP
#include <iterator>
#include <memory>
#include "future/stream.hpp"
#include "coroutine/coroutine.hpp"
namespace sio::coroutine {
using sio::future::Stream;
using sio::future::Flow;
using sio::future::FlowStatus;
using std::unique_ptr;
template<typename T>
class StreamIter {
Stream<T> &stream;
public:
using Stream = Stream<T>;
using Flow = Flow<T>;
explicit StreamIter(Stream &stream);
static auto await_flow(Stream *stream) -> Flow &&;
class iterator;
auto begin() -> iterator;
auto end() -> iterator;
};
template<typename T>
auto StreamIter<T>::begin() -> StreamIter::iterator {
return StreamIter::iterator(&stream);
}
template<typename T>
auto StreamIter<T>::end() -> StreamIter::iterator {
return StreamIter::iterator(&stream, Flow::Break());
}
template<typename T>
auto StreamIter<T>::await_flow(Stream *stream) -> Flow && {
auto flow = stream->flow();
while (flow.status() == FlowStatus::Pending) {
Coroutine<T>::yield();
flow = stream->flow();
}
return std::move(flow);
}
template<typename T>
class StreamIter<T>::iterator: public std::iterator<std::input_iterator_tag, T, ptrdiff_t, T *, T &&> {
Stream *stream;
Flow current_flow;
public:
explicit iterator(Stream *stream) : stream(stream), current_flow(await_flow(stream)) {
}
iterator(Stream *stream, Flow &&flow) : stream(stream), current_flow(flow) {}
auto operator++() -> iterator & {
current_flow = await_flow(stream);
return *this;
}
auto operator++(int) -> const iterator {
iterator retval = *this;
++(*this);
return retval;
}
auto operator==(const iterator &other) const { return current_flow.status() == other.current_flow.status(); }
auto operator!=(const iterator &other) const { return !(*this == other); }
auto operator*() -> T && { return current_flow.release(); }
};
template<typename T>
StreamIter<T>::StreamIter(Stream &stream):stream(stream) {}
}
#endif //SILVER_IO_STREAM_ITER_HPP
|
698b198fa806b89bdf4e176f7cbb56e72342d63a
|
3b2b885c483e6c1136449644d34a8d7d27340183
|
/src/uCtrlCore/Utility/oshandler.h
|
568900b1a9a0831fee6288b7de905502b2969b04
|
[] |
no_license
|
uCtrl/Software
|
fdf465c123c8fcdc2ee4d1f44271cd44bffa89a1
|
8801b2c3dbac79bd7dddf9052ed376896ef40b85
|
refs/heads/master
| 2016-09-06T04:49:11.701769
| 2015-04-18T03:32:48
| 2015-04-18T03:32:48
| 16,771,925
| 1
| 1
| null | 2015-04-18T03:32:48
| 2014-02-12T15:38:15
|
C++
|
UTF-8
|
C++
| false
| false
| 1,015
|
h
|
oshandler.h
|
#ifndef OSHANDLER_H
#define OSHANDLER_H
#include <QObject>
class OsHandler : public QObject
{
Q_OBJECT
public:
explicit OsHandler(QObject *parent = 0) : QObject(parent) {}
enum OsType
{
Unknown = 0,
Windows = 1,
Mac = 2,
Linux = 3,
Symbian = 4,
Maemo5 = 5,
Maemo6 = 6,
};
Q_INVOKABLE int getOS()
{
#ifdef Q_OS_MAC
return (int)Mac;
#endif
#ifdef Q_OS_WIN
return (int)Windows;
#endif
#ifdef Q_OS_WIN32
return (int)Windows;
#endif
#ifdef Q_OS_LINUX
return (int)Linux;
#endif
#ifdef Q_WS_MAEMO_5
return (int)Maemo5;
#endif
#ifdef Q_WS_MAEMO_6
return (int)Maemo6;
#endif
#ifdef Q_OS_SYMBIAN
return (int)Symbian;
#endif
//No OS type was found
return (int)Unknown;
}
signals:
public slots:
};
#endif // OSHANDLER_H
|
771cf577a6ede3e890bba58f9f14d840d214a162
|
d0fb46aecc3b69983e7f6244331a81dff42d9595
|
/iot/src/model/QueryJobStatisticsResult.cc
|
8b9ab286fe2168b8f165823b053d2dc21ac4f638
|
[
"Apache-2.0"
] |
permissive
|
aliyun/aliyun-openapi-cpp-sdk
|
3d8d051d44ad00753a429817dd03957614c0c66a
|
e862bd03c844bcb7ccaa90571bceaa2802c7f135
|
refs/heads/master
| 2023-08-29T11:54:00.525102
| 2023-08-29T03:32:48
| 2023-08-29T03:32:48
| 115,379,460
| 104
| 82
|
NOASSERTION
| 2023-09-14T06:13:33
| 2017-12-26T02:53:27
|
C++
|
UTF-8
|
C++
| false
| false
| 2,698
|
cc
|
QueryJobStatisticsResult.cc
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/iot/model/QueryJobStatisticsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Iot;
using namespace AlibabaCloud::Iot::Model;
QueryJobStatisticsResult::QueryJobStatisticsResult() :
ServiceResult()
{}
QueryJobStatisticsResult::QueryJobStatisticsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
QueryJobStatisticsResult::~QueryJobStatisticsResult()
{}
void QueryJobStatisticsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["Total"].isNull())
data_.total = std::stoi(dataNode["Total"].asString());
if(!dataNode["Queued"].isNull())
data_.queued = std::stoi(dataNode["Queued"].asString());
if(!dataNode["Sent"].isNull())
data_.sent = std::stoi(dataNode["Sent"].asString());
if(!dataNode["InProgress"].isNull())
data_.inProgress = std::stoi(dataNode["InProgress"].asString());
if(!dataNode["Succeeded"].isNull())
data_.succeeded = std::stoi(dataNode["Succeeded"].asString());
if(!dataNode["Failed"].isNull())
data_.failed = std::stoi(dataNode["Failed"].asString());
if(!dataNode["Rejected"].isNull())
data_.rejected = std::stoi(dataNode["Rejected"].asString());
if(!dataNode["TimeOut"].isNull())
data_.timeOut = std::stoi(dataNode["TimeOut"].asString());
if(!dataNode["Cancelled"].isNull())
data_.cancelled = std::stoi(dataNode["Cancelled"].asString());
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["ErrorMessage"].isNull())
errorMessage_ = value["ErrorMessage"].asString();
}
QueryJobStatisticsResult::Data QueryJobStatisticsResult::getData()const
{
return data_;
}
std::string QueryJobStatisticsResult::getErrorMessage()const
{
return errorMessage_;
}
std::string QueryJobStatisticsResult::getCode()const
{
return code_;
}
bool QueryJobStatisticsResult::getSuccess()const
{
return success_;
}
|
d1fd2defa9bb50bb6a81033743240548f6c90cdb
|
dc4f48e683c9e4beb72213004118b5277d2cf96e
|
/helixTagger.cpp
|
8fbf14a8faac25e1f91a4fc5c49b125a21ec5cda
|
[] |
no_license
|
jniedzie/disappTracks
|
f585d80e70438fd6f5a395d86d7a08f3fbf09c03
|
cbe9320b26e36b4b2846a6aa240002ae8bf5b277
|
refs/heads/master
| 2021-07-08T16:55:39.870856
| 2020-06-25T13:15:42
| 2020-06-25T13:15:42
| 141,112,155
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,302
|
cpp
|
helixTagger.cpp
|
// helixTagger.cpp
//
// Created by Jeremi Niedziela on 25/01/2019.
#include "Helpers.hpp"
#include "Fitter.hpp"
#include "ConfigManager.hpp"
#include "HelixProcessor.hpp"
#include "EventSet.hpp"
#include "Logger.hpp"
string configPath = "configs/helixTagger.md";
xtracks::EDataType dataType = xtracks::kSignal;
vector<int> eventsToSkip = { };
int main(int argc, char* argv[])
{
if(argc != 1 && argc != 5){
Log(0)<<"helixTagger takes no arguments or: output_path events_offset n_events config_path\n";
exit(0);
}
cout.imbue(locale("de_DE"));
// TApplication theApp("App", &argc, argv);
if(argc == 5) configPath = argv[4];
cout<<"Reading config from "<<configPath<<endl;
config = ConfigManager(configPath);
string cutLevel;
if(config.params["cuts_level"]==0) cutLevel = "after_L0/";
if(config.params["cuts_level"]==1) cutLevel = "after_L1/"+config.category+"/";
EventSet events;
int eventOffset = 0;
string outputPath = cutLevel+"afterHelixTagging";
int maxEvents = config.params["max_N_events_signal"];
if(argc == 5){
outputPath = argv[1];
eventOffset = atoi(argv[2]);
maxEvents = atoi(argv[3]);
}
auto fitter = make_unique<Fitter>();
auto start = now();
int nAnalyzedEvents=0;
for(int year : years){
if(!config.params["load_"+to_string(year)]) continue;
cout<<"Runnig for year: "<<year<<endl;
for(ESignal iSig : signals){
if(!config.runSignal[iSig]) continue;
cout<<"Running for signal: "<<iSig<<endl;
for(auto iEvent=eventOffset; iEvent<maxEvents+eventOffset; iEvent++){
if(find(eventsToSkip.begin(), eventsToSkip.end(), iEvent) != eventsToSkip.end()){
Log(2)<<"\n\n=================================================================\n";
Log(2)<<"Skipping event "<<iEvent<<"\n";
continue;
}
events.LoadEventsFromFiles(dataType, iSig, cutLevel, iEvent);
auto event = events.At(dataType, iSig, year, iEvent-eventOffset);
if(!event->HasFriendData()){
Log(2)<<"Warning -- skipping event "<<iEvent<<" as it has no friend info\n";
event->SetWasTagged(false);
continue;
}
cout<<"\n\n=================================================================\n";
cout<<"helixTagger -- processing event "<<iEvent<<"\n";
cout<<"cut level: "<<cutLevel<<"\n";
for(auto &track : event->GetTracks()){
int nTrackerLayers = -1;
if(iSig == kTaggerBackgroundWithPU || iSig == kTaggerBackgroundNoPU){
nTrackerLayers = RandInt(3, 6);
}
Helices fittedHelices = fitter->FitHelices(event->GetClusters(), *track, *event->GetVertex(), nTrackerLayers);
for(auto helix : fittedHelices){
helix.Print();
event->AddHelix(helix);
}
}
event->SetWasTagged(true);
nAnalyzedEvents++;
}
Log(0)<<"N events analyzed: "<<nAnalyzedEvents<<"\n";
if(config.params["save_events"]){
Log(0)<<"Saving events...\n";
events.SaveEventsToFiles(outputPath+"/");
}
Log(0)<<"Time: "<<duration(start, now())<<"\n";
}
}
return 0;
}
|
aac77f9e434b8503c6fc7b84ec661a4aa9af371a
|
9e68427a09768cca7d716885a206d99a6454c959
|
/dummys/dummy.cxx
|
dfb1f771af753a21f7503f5b7ab1fceea88c710c
|
[
"MIT"
] |
permissive
|
jpmckown/eaten-by-a-grue
|
5576983e44e48fa3f590bec491d1eb6fd53d26fa
|
10d28cca0e0850e7849a6fb4b3bb8668f49e230a
|
refs/heads/master
| 2022-11-07T16:55:28.478204
| 2022-07-26T22:25:44
| 2022-07-26T22:25:44
| 146,653,053
| 2
| 0
|
MIT
| 2022-07-26T22:29:15
| 2018-08-29T20:10:16
|
C++
|
UTF-8
|
C++
| false
| false
| 935
|
cxx
|
dummy.cxx
|
#include "dummy.h"
Dummy::Dummy() {
}
Dummy::~Dummy() {
for(auto item : _inventory) delete item;
}
bool Dummy::isDead() {
return _stats.health == 0; // no < because its uint
}
std::vector<Item*> Dummy::inventory() {
return std::vector<Item*>(_inventory); // copy.
}
void Dummy::acquire(Item* item) {
_inventory.push_back(item);
}
void Dummy::addHealth(uint64_t value) {
_stats.health += value;
}
uint64_t Dummy::getHealth() {
return _stats.health;
}
void Dummy::removeHealth(int value) {
if (_stats.health < value){
_stats.health = 0;
return;
}
_stats.health -= value;
}
Dummy::DummyClasses Dummy::dummy_class() {
return _class;
}
std::string Dummy::name() {
switch(_class) {
case Dummy::Mage: return std::string("Mage");
case Dummy::Richard: return std::string("Richard");
case Dummy::Rogue: return std::string("Rogue");
case Dummy::Warrior: return std::string("Warrior");
}
}
|
269eefc3f3891edfee1ab1633a5269d47a79084b
|
6ece37fd821fcd03c31e29345569716aa9a9ce89
|
/src/cflie/CTOC.cpp
|
b79e8949fe9630da329ff9206be2b9c058f377a8
|
[
"BSD-3-Clause"
] |
permissive
|
aholler/libcflie
|
c40d938af5b0478a236a30dd01df638ed1f80df9
|
1f2a9bec81743723593f0255edf5d2c74ec3c9ed
|
refs/heads/master
| 2021-01-22T01:58:01.773561
| 2014-10-28T19:38:52
| 2014-10-28T19:38:52
| 25,839,582
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,477
|
cpp
|
CTOC.cpp
|
// Copyright (c) 2013, Jan Winkler <winkler@cs.uni-bremen.de>
// Copyright (c) 2014 Alexander Holler <holler@ahsoftware.de>
// 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 Universität Bremen nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
/// \author Jan Winkler
/// \author Alexander Holler
#include <algorithm>
#include "cflie/CTOC.h"
using namespace std;
bool CTOC::sendTOCPointerReset() {
CCRTPPacket *crtpPacket = new CCRTPPacket(0x00, m_nPort);
crtpPacket->setChannel(CCRTPPacket::ChannelTOC);
CCRTPPacket *crtpReceived = m_crRadio->sendPacket(crtpPacket, true);
if(crtpReceived) {
delete crtpReceived;
return true;
}
return false;
}
bool CTOC::requestMetaData() {
bool bReturnvalue = false;
CCRTPPacket *crtpPacket = new CCRTPPacket(0x01, m_nPort);
crtpPacket->setChannel(CCRTPPacket::ChannelTOC);
CCRTPPacket *crtpReceived = m_crRadio->sendAndReceive(crtpPacket);
if(crtpReceived->payload()[1] == 0x01) {
m_nItemCount = crtpReceived->payload()[2];
bReturnvalue = true;
}
delete crtpReceived;
return bReturnvalue;
}
bool CTOC::requestItem(int nID, bool bInitial) {
bool bReturnvalue = false;
char cRequest[2];
cRequest[0] = 0x0;
cRequest[1] = nID;
CCRTPPacket *crtpPacket = new CCRTPPacket(cRequest,
(bInitial ? 1 : 2),
m_nPort);
crtpPacket->setChannel(CCRTPPacket::ChannelTOC);
CCRTPPacket *crtpReceived = m_crRadio->sendAndReceive(crtpPacket);
bReturnvalue = this->processItem(crtpReceived);
delete crtpReceived;
return bReturnvalue;
}
bool CTOC::requestItems() {
for(int nI = 0; nI < m_nItemCount; nI++) {
this->requestItem(nI);
}
//this->requestInitialItem();
return true;
}
bool CTOC::processItem(CCRTPPacket *crtpItem) {
if(crtpItem->port() == m_nPort) {
if(crtpItem->channel() == CCRTPPacket::ChannelTOC) {
const char *cData = crtpItem->payload();
if(cData[1] == 0x0) { // Command identification ok?
uint8_t nID = cData[2];
uint8_t nType = cData[3];
string strGroup;
int nI;
for(nI = 4; cData[nI] != '\0'; nI++) {
strGroup += cData[nI];
}
nI++;
string strIdentifier;
for(; cData[nI] != '\0'; nI++) {
strIdentifier += cData[nI];
}
struct TOCElement teNew;
teNew.strIdentifier = strIdentifier;
teNew.strGroup = strGroup;
teNew.nID = nID;
teNew.nType = nType;
teNew.bIsLogging = false;
m_lstTOCElements.push_back(teNew);
cout << (m_nPort == CCRTPPacket::PortParam ? "Parameter" : "Log" ) << " item ID " << int(nID) << ' ' << strGroup << "." << strIdentifier;
if(m_nPort == CCRTPPacket::PortParam)
std::cout << " (" << getParameterTypeName(nType) << ", " <<
(nType & 0xf0 ? "ro)" : "rw)");
else if(m_nPort == CCRTPPacket::PortLogging)
std::cout << " (" << getLogTypeName(nType) << ')';
std::cout << endl;
if (m_nPort == CCRTPPacket::PortParam)
requestParameterValue(nID);
return true;
}
}
}
return false;
}
struct TOCElement CTOC::elementForName(const std::string& strName, bool &bFound) const {
for(list<struct TOCElement>::const_iterator itElement = m_lstTOCElements.begin();
itElement != m_lstTOCElements.end();
itElement++) {
struct TOCElement teCurrent = *itElement;
string strTempFullname = teCurrent.strGroup + "." + teCurrent.strIdentifier;
if(strName == strTempFullname) {
bFound = true;
return teCurrent;
}
}
bFound = false;
struct TOCElement teEmpty;
return teEmpty;
}
struct TOCElement CTOC::elementForID(uint8_t nID, bool &bFound) const {
for(list<struct TOCElement>::const_iterator itElement = m_lstTOCElements.begin();
itElement != m_lstTOCElements.end();
itElement++) {
struct TOCElement teCurrent = *itElement;
if(nID == teCurrent.nID) {
bFound = true;
return teCurrent;
}
}
bFound = false;
struct TOCElement teEmpty;
return teEmpty;
}
int CTOC::idForName(const std::string& strName) const {
bool bFound;
struct TOCElement teResult = elementForName(strName, bFound);
if(bFound) {
return teResult.nID;
}
return -1;
}
int CTOC::typeForName(const std::string& strName) const {
bool bFound;
struct TOCElement teResult = elementForName(strName, bFound);
if(bFound) {
return teResult.nType;
}
return -1;
}
bool CTOC::startLogging(const std::string& strName, const std::string& strBlockName) {
bool bFound;
struct LoggingBlock lbCurrent = this->loggingBlockForName(strBlockName, bFound);
if(bFound) {
struct TOCElement teCurrent = this->elementForName(strName, bFound);
if(bFound) {
char cPayload[5] = {0x01, (char)lbCurrent.nID, (char)teCurrent.nType, (char)teCurrent.nID};
CCRTPPacket *crtpLogVariable = new CCRTPPacket(cPayload, 4, m_nPort);
crtpLogVariable->setChannel(CCRTPPacket::ChannelRead);
CCRTPPacket *crtpReceived = m_crRadio->sendAndReceive(crtpLogVariable, true);
const char *cData = crtpReceived->payload();
bool bCreateOK = false;
if(cData[1] == 0x01 &&
cData[2] == lbCurrent.nID &&
cData[3] == 0x00) {
bCreateOK = true;
} else {
cout << cData[3] << endl;
}
if(crtpReceived) {
delete crtpReceived;
}
if(bCreateOK) {
this->addElementToBlock(lbCurrent.nID, teCurrent.nID);
return true;
}
}
}
return false;
}
bool CTOC::addElementToBlock(uint8_t nBlockID, uint8_t nElementID) {
for(list<struct LoggingBlock>::iterator itBlock = m_lstLoggingBlocks.begin();
itBlock != m_lstLoggingBlocks.end();
itBlock++) {
struct LoggingBlock lbCurrent = *itBlock;
if(lbCurrent.nID == nBlockID) {
(*itBlock).lstElementIDs.push_back(nElementID);
return true;
}
}
return false;
}
struct LoggingBlock CTOC::loggingBlockForName(const std::string& strName, bool &bFound) const {
for(list<struct LoggingBlock>::const_iterator itBlock = m_lstLoggingBlocks.begin();
itBlock != m_lstLoggingBlocks.end();
itBlock++) {
struct LoggingBlock lbCurrent = *itBlock;
if(strName == lbCurrent.strName) {
bFound = true;
return lbCurrent;
}
}
bFound = false;
struct LoggingBlock lbEmpty;
return lbEmpty;
}
struct LoggingBlock CTOC::loggingBlockForID(uint8_t nID, bool &bFound) const {
for(list<struct LoggingBlock>::const_iterator itBlock = m_lstLoggingBlocks.begin();
itBlock != m_lstLoggingBlocks.end();
itBlock++) {
struct LoggingBlock lbCurrent = *itBlock;
if(nID == lbCurrent.nID) {
bFound = true;
return lbCurrent;
}
}
bFound = false;
struct LoggingBlock lbEmpty;
return lbEmpty;
}
bool CTOC::registerLoggingBlock(const std::string& strName, double dFrequency) {
uint8_t nID = 0;
bool bFound;
if(dFrequency > 0) { // Only do it if a valid frequency > 0 is given
this->loggingBlockForName(strName, bFound);
if(bFound) {
this->unregisterLoggingBlock(strName);
}
do {
this->loggingBlockForID(nID, bFound);
if(bFound) {
nID++;
}
} while(bFound);
this->unregisterLoggingBlockID(nID);
double d10thOfMS = (1 / dFrequency) * 1000 * 10;
// char cPayload[4] = {0x00, (nID >> 16) & 0x00ff, nID & 0x00ff, d10thOfMS};
char cPayload[4] = {0x00, (char)nID, (char)d10thOfMS};
CCRTPPacket *crtpRegisterBlock = new CCRTPPacket(cPayload, 3, m_nPort);
crtpRegisterBlock->setChannel(CCRTPPacket::ChannelRead);
CCRTPPacket *crtpReceived = m_crRadio->sendAndReceive(crtpRegisterBlock, true);
const char *cData = crtpReceived->payload();
bool bCreateOK = false;
if(cData[1] == 0x00 &&
cData[2] == nID &&
cData[3] == 0x00) {
bCreateOK = true;
cout << "Registered logging block `" << strName << "'" << endl;
}
if(crtpReceived) {
delete crtpReceived;
}
if(bCreateOK) {
struct LoggingBlock lbNew;
lbNew.strName = strName;
lbNew.nID = nID;
lbNew.dFrequency = dFrequency;
m_lstLoggingBlocks.push_back(lbNew);
return this->enableLogging(strName);
}
}
return false;
}
bool CTOC::enableLogging(const std::string& strBlockName) {
bool bFound;
struct LoggingBlock lbCurrent = this->loggingBlockForName(strBlockName, bFound);
if(bFound) {
double d10thOfMS = (1 / lbCurrent.dFrequency) * 1000 * 10;
char cPayload[3] = {0x03, (char)lbCurrent.nID, (char)d10thOfMS};
CCRTPPacket *crtpEnable = new CCRTPPacket(cPayload, 3, m_nPort);
crtpEnable->setChannel(CCRTPPacket::ChannelRead);
CCRTPPacket *crtpReceived = m_crRadio->sendAndReceive(crtpEnable);
delete crtpReceived;
return true;
}
return false;
}
bool CTOC::unregisterLoggingBlock(const std::string& strName) {
bool bFound;
struct LoggingBlock lbCurrent = this->loggingBlockForName(strName, bFound);
if(bFound) {
return this->unregisterLoggingBlockID(lbCurrent.nID);
}
return false;
}
bool CTOC::unregisterLoggingBlockID(uint8_t nID) {
char cPayload[2] = {0x02, (char)nID};
CCRTPPacket *crtpUnregisterBlock = new CCRTPPacket(cPayload, 2, m_nPort);
crtpUnregisterBlock->setChannel(CCRTPPacket::ChannelRead);
CCRTPPacket *crtpReceived = m_crRadio->sendAndReceive(crtpUnregisterBlock, true);
if(crtpReceived) {
delete crtpReceived;
return true;
}
return false;
}
void CTOC::processParameterPacket(CCRTPPacket& packet)
{
if (packet.port() != CCRTPPacket::PortParam)
return;
if (packet.channel() == CCRTPPacket::ChannelTOC)
return;
const char *cData = packet.payload();
uint8_t id = cData[1];
auto i = std::find_if(m_lstTOCElements.begin(), m_lstTOCElements.end(), [id] (TOCElement e) { return e.nID == id; });
if (i == m_lstTOCElements.end())
throw std::runtime_error("Unknown parameter");
if(packet.payloadLength() > 2 && packet.payloadLength()-2 <= sizeof(i->raw.raw))
std::memcpy(i->raw.raw, cData+2, packet.payloadLength() - 2);
else
throw std::runtime_error("Broken parameter packet");
/*
if (packet.channel() == CCRTPPacket::ChannelRead) {
// Happens after requestParameterValue()
std::cout << "Parameter channel read ID " << int(id) << ' ' << i->strGroup << '.' << i->strIdentifier << std::endl;
}
else if (packet.channel() == CCRTPPacket::ChannelWrite) {
// Happens after setParameterValue()
std::cout << "Parameter channel write ID " << int(id) << ' ' << i->strGroup << '.' << i->strIdentifier << std::endl;
}
*/
}
void CTOC::processLogPacket(CCRTPPacket& packet)
{
if (packet.port() != CCRTPPacket::PortLogging)
return;
if (packet.channel() == CCRTPPacket::ChannelTOC)
return;
const char *cData = packet.payload();
bool bFound;
int nBlockID = cData[1];
struct LoggingBlock lbCurrent = loggingBlockForID(nBlockID, bFound);
if(!bFound)
throw std::runtime_error("Unknown logging block");
unsigned nOffset = 0;
unsigned nByteLength;
for(unsigned nIndex = 0; nIndex < lbCurrent.lstElementIDs.size(); ++nIndex, nOffset += nByteLength) {
int id = elementIDinBlock(nBlockID, nIndex);
auto i = std::find_if(m_lstTOCElements.begin(), m_lstTOCElements.end(), [id] (TOCElement e) { return e.nID == id; });
if (i == m_lstTOCElements.end())
throw std::runtime_error("Unknown log element");
nByteLength = sizeOfLogValue(i->nType);
if(!nByteLength)
throw std::runtime_error("Log value without size");
if(packet.payloadLength() > 5 + nOffset && nByteLength <= sizeof(i->raw.raw))
std::memcpy(i->raw.raw, cData+5+nOffset, nByteLength);
else
throw std::runtime_error("Broken log packet");
}
}
void CTOC::processPackets(list<CCRTPPacket*> lstPackets) {
if(lstPackets.empty())
return;
for(list<CCRTPPacket*>::iterator itPacket = lstPackets.begin();
itPacket != lstPackets.end(); itPacket++) {
CCRTPPacket *crtpPacket = *itPacket;
if (crtpPacket->port() == CCRTPPacket::PortParam) {
processParameterPacket(*crtpPacket);
delete crtpPacket;
continue;
}
if (crtpPacket->port() == CCRTPPacket::PortLogging) {
processLogPacket(*crtpPacket);
delete crtpPacket;
continue;
}
}
}
int CTOC::elementIDinBlock(int nBlockID, unsigned nElementIndex) const {
bool bFound;
struct LoggingBlock lbCurrent = loggingBlockForID(nBlockID, bFound);
if(bFound) {
if(nElementIndex < lbCurrent.lstElementIDs.size()) {
list<int>::const_iterator itID = lbCurrent.lstElementIDs.begin();
advance(itID, nElementIndex);
return *itID;
}
}
return -1;
}
void CTOC::requestParameterValue(uint8_t id)
{
CCRTPPacket *crtpPacket = new CCRTPPacket(id, CCRTPPacket::PortParam);
crtpPacket->setChannel(CCRTPPacket::ChannelRead);
CCRTPPacket *crtpReceived = m_crRadio->sendAndReceive(crtpPacket);
if (!crtpReceived)
throw std::runtime_error("No ack received");
processParameterPacket(*crtpReceived);
delete crtpReceived;
}
|
fadff6df02efdb740a2126e901d5eeb672d35a74
|
2ae0b8d95d439ccfd55ea7933ad4a2994ad0f6c5
|
/src/plugins/template/backend/evaluates_map.cpp
|
2bb18904e6a45b2f15a37bb6750c1ab90425d73d
|
[
"Apache-2.0"
] |
permissive
|
openvinotoolkit/openvino
|
38ea745a247887a4e14580dbc9fc68005e2149f9
|
e4bed7a31c9f00d8afbfcabee3f64f55496ae56a
|
refs/heads/master
| 2023-08-18T03:47:44.572979
| 2023-08-17T21:24:59
| 2023-08-17T21:24:59
| 153,097,643
| 3,953
| 1,492
|
Apache-2.0
| 2023-09-14T21:42:24
| 2018-10-15T10:54:40
|
C++
|
UTF-8
|
C++
| false
| false
| 3,871
|
cpp
|
evaluates_map.cpp
|
// Copyright (C) 2018-2023 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "evaluates_map.hpp"
#include "ops/ops_evaluates.hpp"
OPENVINO_SUPPRESS_DEPRECATED_START
std::vector<float> get_floats(const std::shared_ptr<ngraph::HostTensor>& input, const ngraph::Shape& shape) {
size_t input_size = ngraph::shape_size(shape);
std::vector<float> result(input_size);
switch (input->get_element_type()) {
case ngraph::element::Type_t::bf16: {
ngraph::bfloat16* p = input->get_data_ptr<ngraph::bfloat16>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = float(p[i]);
}
} break;
case ngraph::element::Type_t::f16: {
ngraph::float16* p = input->get_data_ptr<ngraph::float16>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = float(p[i]);
}
} break;
case ngraph::element::Type_t::f32: {
float* p = input->get_data_ptr<float>();
memcpy(result.data(), p, input_size * sizeof(float));
} break;
default:
throw std::runtime_error("Unsupported data type.");
break;
}
return result;
}
std::vector<int64_t> get_integers(const std::shared_ptr<ngraph::HostTensor>& input, const ngraph::Shape& shape) {
size_t input_size = ngraph::shape_size(shape);
std::vector<int64_t> result(input_size);
switch (input->get_element_type()) {
case ngraph::element::Type_t::i8: {
auto p = input->get_data_ptr<int8_t>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = int64_t(p[i]);
}
} break;
case ngraph::element::Type_t::i16: {
auto p = input->get_data_ptr<int16_t>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = int64_t(p[i]);
}
} break;
case ngraph::element::Type_t::i32: {
auto p = input->get_data_ptr<int32_t>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = int64_t(p[i]);
}
} break;
case ngraph::element::Type_t::i64: {
auto p = input->get_data_ptr<int64_t>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = int64_t(p[i]);
}
} break;
case ngraph::element::Type_t::u8: {
auto p = input->get_data_ptr<uint8_t>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = int64_t(p[i]);
}
} break;
case ngraph::element::Type_t::u16: {
auto p = input->get_data_ptr<uint16_t>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = int64_t(p[i]);
}
} break;
case ngraph::element::Type_t::u32: {
auto p = input->get_data_ptr<uint32_t>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = int64_t(p[i]);
}
} break;
case ngraph::element::Type_t::u64: {
auto p = input->get_data_ptr<uint64_t>();
for (size_t i = 0; i < input_size; ++i) {
result[i] = int64_t(p[i]);
}
} break;
default:
throw std::runtime_error("Unsupported data type in op NonMaxSuppression-5");
break;
}
return result;
}
std::vector<int64_t> get_signal_size(const std::vector<std::shared_ptr<ngraph::HostTensor>>& inputs,
size_t num_of_axes) {
if (inputs.size() == 3) {
return get_integers(inputs[2], inputs[2]->get_shape());
}
return std::vector<int64_t>(num_of_axes, static_cast<int64_t>(-1));
}
ngraph::runtime::interpreter::EvaluatorsMap& ngraph::runtime::interpreter::get_evaluators_map() {
static runtime::interpreter::EvaluatorsMap evaluatorsMap{
#define _OPENVINO_OP_REG(NAME, NAMESPACE) {NAMESPACE::NAME::get_type_info_static(), evaluate_node<NAMESPACE::NAME>},
#include "opset_int_tbl.hpp"
#undef _OPENVINO_OP_REG
};
return evaluatorsMap;
}
|
4f9d67cfcd394074d24ba261b7fbcf7d73d24f82
|
f96f9244a9e1e4711c27c6d969e513999c4e84a5
|
/middleware/tools/include/tools/build/task.h
|
f60703812b58f6403efa4528998b7cf6ab24f965
|
[
"MIT"
] |
permissive
|
casualcore/casual
|
88965684f908a46dcc998238aa78726e0143bb05
|
7311cc481f3b823d0c86fc09171fbd17e3c39fc1
|
refs/heads/feature/1.7/main
| 2023-09-04T01:22:09.633159
| 2023-07-07T15:33:29
| 2023-07-18T08:48:49
| 477,282,028
| 14
| 4
|
MIT
| 2023-09-14T07:52:38
| 2022-04-03T08:34:20
|
C++
|
UTF-8
|
C++
| false
| false
| 2,076
|
h
|
task.h
|
//!
//! Copyright (c) 2018, The casual project
//!
//! This software is licensed under the MIT license, https://opensource.org/licenses/MIT
//!
#pragma once
#include "tools/build/model.h"
#include "common/algorithm.h"
#include "common/string.h"
#include "common/serialize/macro.h"
#include <string>
#include <vector>
#include <filesystem>
namespace casual
{
namespace tools
{
namespace build
{
struct Directive
{
std::string compiler = "g++";
std::string output;
// compile & link directives
std::vector< std::string> directives;
std::vector< std::string> libraries;
struct
{
std::vector< std::string> include;
std::vector< std::string> library;
} paths;
bool verbose = false;
bool use_defaults = true;
friend void validate( const Directive& settings);
CASUAL_LOG_SERIALIZE(
CASUAL_SERIALIZE( compiler);
CASUAL_SERIALIZE( output);
CASUAL_SERIALIZE( directives);
CASUAL_SERIALIZE( libraries);
CASUAL_SERIALIZE( paths.include);
CASUAL_SERIALIZE( paths.library);
CASUAL_SERIALIZE( verbose);
CASUAL_SERIALIZE( use_defaults);
)
static auto split( std::vector< std::string>& target)
{
return [&target]( const std::string& value, const std::vector< std::string>& values)
{
auto split_append = [&target]( auto& value)
{
common::algorithm::append( common::string::adjacent::split( value, ' '), target);
};
split_append( value);
common::algorithm::for_each( values, split_append);
};
}
};
void task( const std::filesystem::path& input, const Directive& directive);
} // build
} // tools
} // casual
|
3baa5c9bc5475e751b2d2cb83ed0ebe9351f2f26
|
c39d17f86331dc10e40fc81ab904d5a53dcc9553
|
/Prob3/FunctI.h
|
f110a9c4cefcf760e1320adf6d2d6c42d1b7ceba
|
[] |
no_license
|
chmartin/NumMethods2011
|
40ffc43a7f15a5929099869c842fd6b28ea84b0a
|
8b243eaa28735bd32117725d2234bc2e846247f4
|
refs/heads/master
| 2021-01-01T18:40:39.982331
| 2017-07-26T10:03:53
| 2017-07-26T10:03:53
| 98,404,365
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 120
|
h
|
FunctI.h
|
#ifndef FUNCT_I_H
#define FUNCT_I_H
class FunctI
{
public:
FunctI() {};
Doub operator() (double x);
};
#endif
|
3c45d811c560362aaaf14f27e3eb380a7fe83c75
|
b84aa8a1745f3346f22b9a0ae1c977a244dfb3cd
|
/SDK/RC_TeamHealthContainer_functions.cpp
|
141380e7b23160f53b55c5092ac710f8ae61b4a6
|
[] |
no_license
|
frankie-11/Rogue-SDK-11.8
|
615a9e51f280a504bb60a4cbddb8dfc4de6239d8
|
20becc4b2fff71cfec160fb7f2ee3a9203031d09
|
refs/heads/master
| 2023-01-10T06:00:59.427605
| 2020-11-08T16:13:01
| 2020-11-08T16:13:01
| 311,102,184
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,918
|
cpp
|
RC_TeamHealthContainer_functions.cpp
|
// RogueCompany (4.24) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function TeamHealthContainer.TeamHealthContainer_C.Construct
// (Final)
void UTeamHealthContainer_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function TeamHealthContainer.TeamHealthContainer_C.Construct");
UTeamHealthContainer_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function TeamHealthContainer.TeamHealthContainer_C.UpdateTeammateHealthBars
// (Final)
void UTeamHealthContainer_C::UpdateTeammateHealthBars()
{
static auto fn = UObject::FindObject<UFunction>("Function TeamHealthContainer.TeamHealthContainer_C.UpdateTeammateHealthBars");
UTeamHealthContainer_C_UpdateTeammateHealthBars_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function TeamHealthContainer.TeamHealthContainer_C.HandlePlayerSpawn
// (Final)
void UTeamHealthContainer_C::HandlePlayerSpawn()
{
static auto fn = UObject::FindObject<UFunction>("Function TeamHealthContainer.TeamHealthContainer_C.HandlePlayerSpawn");
UTeamHealthContainer_C_HandlePlayerSpawn_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function TeamHealthContainer.TeamHealthContainer_C.HandlePhaseChnage
// (Final)
void UTeamHealthContainer_C::HandlePhaseChnage()
{
static auto fn = UObject::FindObject<UFunction>("Function TeamHealthContainer.TeamHealthContainer_C.HandlePhaseChnage");
UTeamHealthContainer_C_HandlePhaseChnage_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function TeamHealthContainer.TeamHealthContainer_C.HandleSetupStart
// (Final)
void UTeamHealthContainer_C::HandleSetupStart()
{
static auto fn = UObject::FindObject<UFunction>("Function TeamHealthContainer.TeamHealthContainer_C.HandleSetupStart");
UTeamHealthContainer_C_HandleSetupStart_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function TeamHealthContainer.TeamHealthContainer_C.ExecuteUbergraph_TeamHealthContainer
// (Final)
void UTeamHealthContainer_C::ExecuteUbergraph_TeamHealthContainer()
{
static auto fn = UObject::FindObject<UFunction>("Function TeamHealthContainer.TeamHealthContainer_C.ExecuteUbergraph_TeamHealthContainer");
UTeamHealthContainer_C_ExecuteUbergraph_TeamHealthContainer_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
7af50ddadc482217dbc5e85a4a7a5ada3a4baa27
|
0fa1152e1e434ce9fe9e2db95f43f25675bf7d27
|
/platforms/posix/src/px4/common/print_load.cpp
|
a392fb823fe78c35a04e8d63bcd49c4f497b9097
|
[
"BSD-3-Clause"
] |
permissive
|
PX4/PX4-Autopilot
|
4cc90dccc9285ca4db7f595ac5a7547df02ca92e
|
3d61ab84c42ff8623bd48ff0ba74f9cf26bb402b
|
refs/heads/main
| 2023-08-30T23:58:35.398450
| 2022-03-26T01:29:03
| 2023-08-30T15:40:01
| 5,298,790
| 3,146
| 3,798
|
BSD-3-Clause
| 2023-09-14T17:22:04
| 2012-08-04T21:19:36
|
C++
|
UTF-8
|
C++
| false
| false
| 5,231
|
cpp
|
print_load.cpp
|
/****************************************************************************
*
* Copyright (c) 2015-2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file print_load.cpp
*
* Print the current system load.
*
* @author Lorenz Meier <lorenz@px4.io>
*/
#include <px4_platform_common/posix.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <px4_platform_common/log.h>
#include <px4_platform_common/printload.h>
#include <drivers/drv_hrt.h>
#ifdef __PX4_DARWIN
#include <mach/mach.h>
#endif
#ifdef __PX4_QURT
// dprintf is not available on QURT. Use the usual output to mini-dm.
#define dprintf(_fd, _text, ...) ((_fd) == 1 ? PX4_INFO((_text), ##__VA_ARGS__) : (void)(_fd))
#endif
extern struct system_load_s system_load;
#define CL "\033[K" // clear line
void init_print_load(struct print_load_s *s)
{
s->total_user_time = 0;
s->running_count = 0;
s->blocked_count = 0;
s->new_time = hrt_absolute_time();
s->interval_start_time = s->new_time;
for (size_t i = 0; i < sizeof(s->last_times) / sizeof(s->last_times[0]); i++) {
s->last_times[i] = 0;
}
s->interval_time_us = 0.f;
}
void print_load(int fd, struct print_load_s *print_state)
{
char clear_line[] = CL;
/* print system information */
if (fd == 1) {
dprintf(fd, "\033[H"); /* move cursor home and clear screen */
} else {
memset(clear_line, 0, sizeof(clear_line));
}
#if defined(__PX4_LINUX) || defined(__PX4_CYGWIN) || defined(__PX4_QURT)
dprintf(fd, "%sTOP NOT IMPLEMENTED ON LINUX, QURT, WINDOWS (ONLY ON NUTTX, APPLE)\n", clear_line);
#elif defined(__PX4_DARWIN)
pid_t pid = getpid(); //-- this is the process id you need info for
task_t task_handle;
task_for_pid(mach_task_self(), pid, &task_handle);
task_info_data_t tinfo;
mach_msg_type_number_t th_info_cnt;
th_info_cnt = TASK_INFO_MAX;
kern_return_t kr = task_info(task_handle, TASK_BASIC_INFO, (task_info_t)tinfo, &th_info_cnt);
if (kr != KERN_SUCCESS) {
return;
}
thread_array_t thread_list;
mach_msg_type_number_t th_cnt;
thread_info_data_t th_info_data;
mach_msg_type_number_t thread_info_count;
thread_basic_info_t basic_info_th;
// get all threads of the PX4 main task
kr = task_threads(task_handle, &thread_list, &th_cnt);
if (kr != KERN_SUCCESS) {
PX4_WARN("ERROR getting thread list");
return;
}
long tot_sec = 0;
long tot_usec = 0;
long tot_cpu = 0;
dprintf(fd, "%sThreads: %d total\n",
clear_line,
th_cnt);
for (unsigned j = 0; j < th_cnt; j++) {
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
(thread_info_t)th_info_data, &thread_info_count);
if (kr != KERN_SUCCESS) {
PX4_WARN("ERROR getting thread info");
continue;
}
basic_info_th = (thread_basic_info_t)th_info_data;
if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;
tot_cpu = tot_cpu + basic_info_th->cpu_usage;
}
// char tname[128];
// int ret = pthread_getname_np(pthread_t *thread,
// const char *name, size_t len);
dprintf(fd, "thread %d\t\t %d\n", j, basic_info_th->cpu_usage);
}
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list,
th_cnt * sizeof(thread_t));
if (kr != KERN_SUCCESS) {
PX4_WARN("ERROR cleaning up thread info");
return;
}
#endif
}
void print_load_buffer(char *buffer, int buffer_length, print_load_callback_f cb, void *user,
struct print_load_s *print_state)
{
}
|
7145ad3c2ff87d526128a4086e89d8364109b714
|
dde107dc5985176a030b8aa4423ad88fc4456747
|
/lab25/lab25.cpp
|
b2d627661c382c1c853880cb5adb0c55dbf74550
|
[] |
no_license
|
Tigercore1/CoreyMcDonough-CSCI20-Fall2017
|
23a62623ebb8edbce9238a6d1c424c88618ebe3b
|
8f13f6efef864529b5256e31a5ad9c082525e23c
|
refs/heads/master
| 2021-01-19T16:02:07.846983
| 2017-12-11T08:07:33
| 2017-12-11T08:07:33
| 100,982,987
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,212
|
cpp
|
lab25.cpp
|
//Created By: Corey McDonough
//Created On: 10/3/2017
//This program takes info regarding books and stores them in a class. It then outputs the class through print functions in the class.
#include <iostream>
#include <string>
using namespace std;
// Class book has Set functions that store information about book objects. It has a get that then can return the info,
// and it has a print function that shows all the information about the books stored.
class Book{
public:
void SetTitle(string title){
title_ = title;
}
void SetAuthor(string author){
author_ = author;
}
void SetYear(int year){
year_ = year;
}
string GetTitle() const{
return title_;
}
string GetAuthor() const{
return author_;
}
int GetYear() const{
return year_;
}
void Print(){
cout << "Book: " << title_ << endl;
cout << "Author: " << author_ << endl;
cout << "Copyright Year: " << year_ << endl << endl;
}
private:
string title_;
string author_;
int year_;
};
int main(){
Book book1;
Book book2;
Book book3;
Book book4;
Book book5;
string tit; //temporary variables that store function outputs.
string aut;
int yea = 0;
// Inputs
cout << "BOOK 1" << endl << "---------------------" << endl;
cout << "Enter book title: ";
cin >> tit;
book1.SetTitle(tit);
cout << "Enter book author: ";
cin >> aut;
book1.SetAuthor(aut);
cout << "Enter copyright year: ";
cin >> yea;
book1.SetYear(yea);
cout << endl;
cout << "BOOK 2" << endl << "---------------------" << endl;
cout << "Enter book title: ";
cin >> tit;
book2.SetTitle(tit);
cout << "Enter book author: ";
cin >> aut;
book2.SetAuthor(aut);
cout << "Enter copyright year: ";
cin >> yea;
book2.SetYear(yea);
cout << endl;
cout << "BOOK 3" << endl << "---------------------" << endl;
cout << "Enter book title: ";
cin >> tit;
book3.SetTitle(tit);
cout << "Enter book author: ";
cin >> aut;
book3.SetAuthor(aut);
cout << "Enter copyright year: ";
cin >> yea;
book3.SetYear(yea);
cout << endl;
cout << "BOOK 4" << endl << "---------------------" << endl;
cout << "Enter book title: ";
cin >> tit;
book4.SetTitle(tit);
cout << "Enter book author: ";
cin >> aut;
book4.SetAuthor(aut);
cout << "Enter copyright year: ";
cin >> yea;
book4.SetYear(yea);
cout << endl;
cout << "BOOK 5" << endl << "---------------------" << endl;
cout << "Enter book title: ";
cin >> tit;
book5.SetTitle(tit);
cout << "Enter book author: ";
cin >> aut;
book5.SetAuthor(aut);
cout << "Enter copyright year: ";
cin >> yea;
book5.SetYear(yea);
cout << endl;
//Outputs
cout << "ALL BOOKS" << endl << "---------------------" << endl;
book1.Print();
book2.Print();
book3.Print();
book4.Print();
book5.Print();
}
|
ce9a4acf5248382a86e5885796fd400da9366c7d
|
b155e04232853733a57e4360e76f86a9a5c503e7
|
/src/sfp_ciofunc.t.cpp
|
2d255e3277537e4c9c0dee25afb6cf1f98280389
|
[] |
no_license
|
camio/sbase
|
b7fe740ac9b35eb1170f272b8491c9cf189e1eb5
|
fefc444dc1941c5ccd1651ec901b7bf4363cc4e9
|
refs/heads/master
| 2021-01-23T22:53:42.824756
| 2014-11-13T22:13:29
| 2014-11-13T22:13:29
| 19,886,067
| 9
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 407
|
cpp
|
sfp_ciofunc.t.cpp
|
#include <sfp/ciofunc.t.hpp>
#include <sfp/ciofunc.hpp>
#include <type_traits>
// compile-time checks
static_assert(
std::is_same<sfp::ciofunc<char, int, long>::type,
boost::function<boost::function<boost::function<long()>(int)>(
char)>>::value,
"ciofunc unexpected results");
namespace sfp {
void ciofuncTests(stest::TestCollector& col) {}
}
|
aabac39adf52968f76982de070454e7c0b54eb3b
|
a051a68b11f6c4084aaefb2cde6f8106cfeb234c
|
/asteroids/rock.h
|
7151383bb5c941ee22b34fc4443d0fe14f4af9e1
|
[] |
no_license
|
hpbcrowe/CS-165
|
919d320d6b90281b70537154037ddcc2e0f3c6ab
|
a13a13f43ab5abf9b1f905181a4edad6f39418ea
|
refs/heads/main
| 2023-02-05T04:03:33.754691
| 2020-12-23T06:10:35
| 2020-12-23T06:10:35
| 323,813,166
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,236
|
h
|
rock.h
|
/***********************************************************************
* Header File:
* Rock : The parent class for all rocks
* Author:
* Ben Crowe
* Summary:
* Will be used to make a vector of pointers, so there can be different
* kinds of rocks
************************************************************************/
#ifndef Rock_H
#define Rock_H
constexpr int BIG_Rock_SIZE = 16;
constexpr int MEDIUM_Rock_SIZE = 8;
constexpr int SMALL_Rock_SIZE = 4;
//using namespace rockData;
constexpr int BIG_Rock_SPIN = 2;
constexpr int MEDIUM_Rock_SPIN = 5;
constexpr int SMALL_Rock_SPIN = 10;
// Define the following classes here:
// Rock
// BigRock
// MediumRock
// SmallRock
#include "flyingObject.h"
class Rock : public FlyingObject
{
public:
/************************************************************************************************
* Default Constructor
*
************************************************************************************************/
Rock() { }
/***********************************************************************************************
* Non Default Constructor
*
***********************************************************************************************/
Rock(const Point &point, const Velocity &velocity);
/*************************************************************************************************
* DRAW
* Draw will be a virtual function when derived classes are created.
**************************************************************************************************/
virtual void draw() const = 0;
/*************************************************************************************************
* HIT
* Creates damage
**************************************************************************************************/
virtual int hit() = 0;
/*************************************************************************************************
* SCORE POINTS
* Returns points when rock is hit
**************************************************************************************************/
virtual int scorePoints() = 0;
protected:
int hitPoints;
};
#endif // ROCK_H
|
bde95a05bc9f219b7d6c8190a49d6437c26f0f18
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/admin/snapin/rolemgr/helpmap.cpp
|
c41e69031d9682cf27b0dab36e5387c0d2f6882a
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 2,043
|
cpp
|
helpmap.cpp
|
#define BEGIN_HELP_ARRAY(x) const DWORD g_aHelpIDs_##x[]={ ,
#define END_HELP_ARRAY 0, 0 };
#define ARRAY_ENTRY(x,y) y, IDH_##x_##y,
//IDD_ADD_GROUP
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
ARRAY_ENTRY(IDD_ADD_GROUP,IDC_LIST)
END_HELP_ARRAY
/*
//IDD_ADD_OPERATION
BEGIN_HELP_ARRAY(IDD_ADD_OPERATION)
IDC_LIST, IDH_LIST_ADD_OPERATION,
END_HELP_ARRAY
//IDD_ADD_ROLE_DEFINITION
BEGIN_HELP_ARRAY(IDD_ADD_ROLE_DEFINITION)
IDC_LIST, IDH_LIST_ADD_ROLE_DEFINITION,
END_HELP_ARRAY
//IDD_ADD_TASK
BEGIN_HELP_ARRAY(IDD_ADD_TASK)
IDC_LIST, IDH_LIST_ADD_TASK,
END_HELP_ARRAY
//IDD_ADMIN_MANAGER_ADVANCED_PROPERTY
BEGIN_HELP_ARRAY(IDD_ADMIN_MANAGER_ADVANCED_PROPERTY)
IDC_EDIT_DOMAIN_TIMEOUT, IDH_EDIT_DOMAIN_TIMEOUT,
IDC_EDIT_SCRIPT_ENGINE_TIMEOUT, IDH_EDIT_SCRIPT_ENGINE_TIMEOUT,
IDC_EDIT_MAX_SCRIPT_ENGINE, IDH_EDIT_MAX_SCRIPT_ENGINE,
END_HELP_ARRAY
//IDD_ADMIN_MANAGER_GENERAL_PROPPERTY
BEGIN_HELP_ARRAY(IDD_ADMIN_MANAGER_GENERAL_PROPPERTY)
IDC_EDIT_NAME, IDH_EDIT_NAME,
IDC_EDIT_DESCRIPTION, IDH_EDIT_DESCRIPTION,
IDC_EDIT_STORE_TYPE, IDH_EDIT_STORE_TYPE,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
BEGIN_HELP_ARRAY(IDD_ADD_GROUP)
IDC_LIST, IDH_LIST_ADD_GROUP,
END_HELP_ARRAY
*/
|
0186ec92fdff8147241a966c248d61c1b1faf6a9
|
fef25fa06875a72a506842b85828159de8cd2f61
|
/yesorno.cpp
|
b64c5d8af42ee3e5de7c484bee9ed8337a18990c
|
[] |
no_license
|
DanielRrr/Cpluspluscalculations
|
456ffb061f3783298867985997efb974660aafc5
|
79a18af52e46878af133ee3ab455172c1ccf8940
|
refs/heads/master
| 2021-01-17T06:15:07.601292
| 2016-07-07T10:26:18
| 2016-07-07T10:26:18
| 55,148,527
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 677
|
cpp
|
yesorno.cpp
|
#include <iostream>
#include <string>
using namespace std;
char askYesNo1();
char askYesNo2(string question);
int main()
{
char answer1 = askYesNo1();
cout << "Thanks for answering: " << answer1 << "\n\n";
char answer2 = askYesNo2("Save your game?");
cout << "Thanks for answering: " << answer2 << "\n";
return 0;
}
char askYesNo1()
{
char responsel;
do
{
cout << "Please enter 'y' or 'n': ";
cin >> responsel;
} while (responsel != 'y' && responsel != 'n');
return responsel;
}
char askYesNo2(string question)
{
char response2;
do
{
cout << "question" << " (y/n): ";
cin >> response2;
} while (response2 != 'y' && response2 != 'n');
return response2;
}
|
45d6cd38f1ec84eb76e4483f8030634ab470e801
|
1d98dbc9ee457fe3dd55a5298d703bfab54fc610
|
/FrontAnalyzer.h
|
c5a997139d2ba6a8cef90eb8696a7c6c8871a9c9
|
[] |
no_license
|
rafdp/MeteoProject
|
71cd402c9fedb8336ca0785ebd4574e3dd470845
|
cef569bb3e207092719dd8983fc974323ac70354
|
refs/heads/master
| 2021-01-19T03:13:20.070382
| 2018-07-24T21:26:53
| 2018-07-24T21:26:53
| 44,122,740
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,673
|
h
|
FrontAnalyzer.h
|
#pragma once
#include "includes.h"
struct FloatPOINT
{
float x, y;
void Normalize();
FloatPOINT& operator = (const POINT& that);
FloatPOINT& operator += (const FloatPOINT& that);
};
struct SPOINT_t
{
public:
int x, y;
SPOINT_t ();
SPOINT_t (int x, int y);
SPOINT_t operator - (const SPOINT_t& that);
};
struct NeighbourN_t
{
uint8_t neighbours;
uint8_t n;
void clear ();
};
double Dist(const SPOINT_t& x, const SPOINT_t& y);
SPOINT_t operator + (const SPOINT_t& x, const SPOINT_t& y);
SPOINT_t operator / (const SPOINT_t& x, int y);
struct FrontInfo_t
{
std::vector<SPOINT_t> points_;
std::vector<uint32_t> skeleton0_;
std::vector<POINT> skeleton1_;
SectionsType_t sections_;
std::vector<uint32_t> near_;
int32_t equivalentFront_;
FrontInfo_t();
void clear();
bool empty();
size_t size();
SPOINT_t* data();
void AddPoint(int x, int y);
void Process(MeteoDataLoader* mdl, int slice);
void FillSkeleton0(MeteoDataLoader* mdl, int slice);
void CalculateNear(const std::vector <FrontInfo_t>& data);
void FindEquivalentFront(const std::vector <FrontInfo_t>& data);
};
class FrontAnalyzer : NZA_t
{
std::vector<FrontInfo_t> fronts_;
NeighbourN_t* set_;
MeteoDataLoader* mdl_;
int slice_;
std::vector<uint32_t> toFlush_;
friend class FrontVisualizer;
int32_t NeighbourShift (uint8_t neighbour);
uint8_t InverseNeighbour (uint8_t neighbour);
public:
void ok ();
FrontAnalyzer (MeteoDataLoader* mdl, int slice);
~FrontAnalyzer ();
std::vector<FrontInfo_t>& GetFront();
void AnalyzeCell (int x, int y);
void FlushBadCells ();
void FillFronts (MeteoDataLoader* mdl, int slice);
//void SortFronts ();
};
|
6ce7305e0d0e6988fadbb84db88a0c13d37f5a71
|
f8de825e6a28fc964769d8911ba992b0248c677a
|
/simulations/main.cpp
|
4d9934789ed91310d40a8fd0bf8aebe43e89d281
|
[] |
no_license
|
syedaffan18/research
|
4105b40fc825922e2f43c0b17450024915243a57
|
30e57c7ebd1763a9785718f4f183e3ea8efbf07f
|
refs/heads/master
| 2020-07-18T11:08:47.421607
| 2019-11-13T13:04:25
| 2019-11-13T13:04:25
| 206,234,391
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,839
|
cpp
|
main.cpp
|
//
// main.cpp
// nprotocol
//
// Created by talmac on 8/28/15.
// Copyright (c) 2015 talmac. All rights reserved.
//
#include <bitset>
#include <iostream>
#include <utility>
#include <map>
#include <unordered_map>
#include "CBox.h"
inline bool NLB(const std::bitset<3> xyz,const std::bitset<3> abc)
{
return (xyz[0] | xyz[1] | xyz[2])==(abc[0] ^ abc[1] ^ abc[2]);
}
inline bool tt_2_input(bool input1,bool input2,unsigned functionNo)
{
std::map<std::pair<bool,bool>,bool> tt;
std::bitset<4> bFunction(functionNo);
for(int i=0;i<4;i++)
{
std::bitset<2> b(i);
std::pair<bool,bool> p;
p.first=b[0];
p.second=b[1];
tt[p]=bFunction[3-i];
}
return tt[std::make_pair(input2,input1)];
}
inline bool tt_3_input(bool input1,bool input2,bool input3,unsigned functionNo)
{
std::map<std::tuple<bool,bool,bool>,bool> tt;
std::bitset<8> bFunction(functionNo);
for(int i=0;i<8;i++)
{
std::bitset<3> b(i);
std::tuple<bool,bool,bool> p;
std::get<0>(p)=b[0];
std::get<1>(p)=b[1];
std::get<2>(p)=b[2];
tt[p]=bFunction[7-i];
}
return tt[std::make_tuple(input3,input2,input1)];
}
double nprotocol(unsigned f2,unsigned g2,unsigned h2,unsigned f3,unsigned g3,unsigned h3,CBox &Cb)
{
double prob000=0.0;
double prob011=0.0;
double prob101=0.0;
double prob110=0.0;
double prob=0.0;
int input[]={0,3,5,6};
for (unsigned int i=0;i<4;i++)
{
std::bitset<3> x1_y1_z1(input[i]);
for (unsigned int oNLB1=0;oNLB1<8;oNLB1++)
{
std::bitset<3> outputBox1(oNLB1);
if (NLB(x1_y1_z1,outputBox1))
{
}
else
{
}
std::bitset<3> x2_y2_z2;
x2_y2_z2[0]=tt_2_input(x1_y1_z1[0],outputBox1[0],f2);
x2_y2_z2[1]=tt_2_input(x1_y1_z1[1],outputBox1[1],g2);
x2_y2_z2[2]=tt_2_input(x1_y1_z1[2],outputBox1[2],h2);
for (unsigned int oNLB2=0;oNLB2<8;oNLB2++)
{
std::bitset<3> outputBox2(oNLB2);
if (NLB(x2_y2_z2,outputBox2))
{
}
else
{
}
std::bitset<3> abc;
abc[0]=tt_3_input(x2_y2_z2[0],outputBox1[0],outputBox2[0],f3);
abc[1]=tt_3_input(x2_y2_z2[1],outputBox1[1],outputBox2[1],g3);
abc[2]=tt_3_input(x2_y2_z2[2],outputBox1[2],outputBox2[2],h3);
if (NLB(x1_y1_z1,abc))
{
if (x1_y1_z1.to_ulong()==0)
{
prob000+=(Cb.m_fConditionalProbMatrix[x1_y1_z1.to_ulong()][outputBox1.to_ulong()]*Cb.m_fConditionalProbMatrix[x2_y2_z2.to_ulong()][outputBox2.to_ulong()]);
}
else if (x1_y1_z1.to_ulong()==3)
{
prob011+=Cb.m_fConditionalProbMatrix[x1_y1_z1.to_ulong()][outputBox1.to_ulong()]*Cb.m_fConditionalProbMatrix[x2_y2_z2.to_ulong()][outputBox2.to_ulong()];
}
else if (x1_y1_z1.to_ulong()==5)
{
prob101+=Cb.m_fConditionalProbMatrix[x1_y1_z1.to_ulong()][outputBox1.to_ulong()]*Cb.m_fConditionalProbMatrix[x2_y2_z2.to_ulong()][outputBox2.to_ulong()];
}
else if (x1_y1_z1.to_ulong()==6)
{
prob110+=Cb.m_fConditionalProbMatrix[x1_y1_z1.to_ulong()][outputBox1.to_ulong()]*Cb.m_fConditionalProbMatrix[x2_y2_z2.to_ulong()][outputBox2.to_ulong()];
}
}
else
{
if (x1_y1_z1.to_ulong()==0)
{
prob000-=(Cb.m_fConditionalProbMatrix[x1_y1_z1.to_ulong()][outputBox1.to_ulong()]*Cb.m_fConditionalProbMatrix[x2_y2_z2.to_ulong()][outputBox2.to_ulong()]);
}
else if (x1_y1_z1.to_ulong()==3)
{
prob011-=Cb.m_fConditionalProbMatrix[x1_y1_z1.to_ulong()][outputBox1.to_ulong()]*Cb.m_fConditionalProbMatrix[x2_y2_z2.to_ulong()][outputBox2.to_ulong()];
}
else if (x1_y1_z1.to_ulong()==5)
{
prob101-=Cb.m_fConditionalProbMatrix[x1_y1_z1.to_ulong()][outputBox1.to_ulong()]*Cb.m_fConditionalProbMatrix[x2_y2_z2.to_ulong()][outputBox2.to_ulong()];
}
else if (x1_y1_z1.to_ulong()==6)
{
prob110-=Cb.m_fConditionalProbMatrix[x1_y1_z1.to_ulong()][outputBox1.to_ulong()]*Cb.m_fConditionalProbMatrix[x2_y2_z2.to_ulong()][outputBox2.to_ulong()];
}
}
}
}
}
prob=prob000 + prob011 + prob101 + prob110;
return prob;
}
void iterate_over_space()
{
double value=0.0;
for (unsigned f2=0;f2<1;f2++)
{
for (unsigned g2=3;g2<4;g2++)
{
for (unsigned h2=3;h2<4;h2++)
{
for (unsigned f3=153;f3<154;f3++)
{
for (unsigned g3=102;g3<103;g3++)
{
for (unsigned h3=102;h3<103;h3++)
{
for (double d=-1.0;d<1.01;d+=0.01)
{
for (double e=-1.0;e<1.01;e+=0.01)
{
value=0.0;
CBox Cb(e,d);
value=nprotocol(f2,g2,h2,f3,g3,h3,Cb);
if (fabs(value)>fabs(Cb.m_fGHZ))
std::cout << "f2: " << f2 << " g2: " << g2 << " h2: " << h2 << " f3 " << f3 << " g3: " << g3 << " h3: " << h3 << " delta: " << d << " epsilon: " << e << " GHZ: " << fabs(Cb.m_fGHZ) << " value: " << fabs(value) << "\n";
}
}
}
}
}
}
}
}
}
#include <iostream>
int main(int argc, const char * argv[]) {
iterate_over_space();
return 0;
}
|
7807e6d5089dfe24861046d5c34f8036ff70e5a3
|
16b1c8b7ce69bdb20e5bf571cb58b2645f3b9d9d
|
/GAME1017_EngineTemplate/GAME1017_Template_W01/TextureManager.h
|
9a6b15bb4721ad14ee4fef8f9d35875f39605ee9
|
[] |
no_license
|
BertMarsh/GAME1017_A2_Marshall_Robert
|
3300c0c27d39f8182e094abd6a5bbc6effc1660b
|
07da10f3b68e825a4ee5a841774a4145673b41b9
|
refs/heads/master
| 2022-12-02T22:41:06.496457
| 2020-08-09T13:32:02
| 2020-08-09T13:32:02
| 283,095,593
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 386
|
h
|
TextureManager.h
|
#pragma once
#include <SDL.h>
#include <SDL_image.h>
#include <vector>
#include <string>
class TextureManager
{
public:
static void Init();
static void RegisterTexture(const char* path, const std::string key);
static SDL_Texture* GetTexture(const char* path);
static void Quit();
private:
static std::vector<std::string, SDL_Texture*> v_Textures;
private:
TextureManager();
};
|
98bec48040bb2e0231ec0a4307900fc1ae68db3f
|
5e6cda9a847e8868fec8a7fa0f6193573238f31e
|
/DYNAMICAL PROGRAMMING/TRIANGLE HASH Problem/triangle_hash_problem.cpp
|
2904586a30757863993f6bb93b56c6b469800981
|
[] |
no_license
|
orcchg/StudyProjects
|
33fb2275d182e46a8f5a9578dbbf4566bd7f1013
|
269550e37100e1eacc49a766b5f0db9c2e7ade2d
|
refs/heads/master
| 2020-04-30T17:56:11.268350
| 2014-04-07T10:57:43
| 2014-04-07T10:57:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,475
|
cpp
|
triangle_hash_problem.cpp
|
#include <vector>
#include <list>
#include <iterator>
#include <algorithm>
#include <cmath>
#include <stdio.h>
using std::vector;
using std::list;
using std::sort;
//-----------------------------------------------------------------------------
class CTriangle {
public:
CTriangle() {
sides.resize(3, 0);
}
CTriangle(const CTriangle& rhs):sides(rhs.sides) {}
void canonize();
vector<int> sides;
bool operator == (const CTriangle& rhs) const {
return (sides == rhs.sides);
}
bool operator != (const CTriangle& rhs) const {
return (sides != rhs.sides);
}
private:
int gcd();
int gcd(int m_value, int n_value) const;
void sorting();
};
int CTriangle::gcd(int m_value, int n_value) const {
int m_changeable = m_value;
int n_changeable = n_value;
while (m_changeable > 0 && n_changeable > 0) {
if (m_changeable >= n_changeable) {
m_changeable %= n_changeable;
} else {
n_changeable %= m_changeable;
}
}
if (m_changeable == 0) {
return n_changeable;
}
if (n_changeable == 0) {
return m_changeable;
}
}
void CTriangle::sorting() {
sort(this->sides.begin(), this->sides.end());
}
int CTriangle::gcd() {
sorting();
return gcd(gcd(sides.at(0), sides.at(1)), sides.at(2));
}
void CTriangle::canonize() {
int HOD = gcd();
for (int index = 0; index < 3; ++index) {
sides.at(index) /= HOD;
}
}
//-----------------------------------------------------------------------------
void input(int& length, vector<CTriangle>* triangles) {
scanf("%ld", &length);
triangles->resize(length);
for (int index = 0; index < length; ++index) {
scanf("%ld %ld %ld", &triangles->at(index).sides.at(0),
&triangles->at(index).sides.at(1),
&triangles->at(index).sides.at(2));
triangles->at(index).canonize();
}
}
//-----------------------------------------------------------------------------
bool is_absent(const list<CTriangle>& chains, CTriangle item) {
for (list<CTriangle>::const_iterator it = chains.begin();
it != chains.end();
++it) {
if (*it == item) {
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
int hashTableCreation(int length, const vector<CTriangle>& triangles) {
const int PRIME_NUMBER = 27644437;
const int hash_size = 50007;
int result = 0;
int random_value = static_cast<int>(
static_cast<double>(rand()) / RAND_MAX * (PRIME_NUMBER - 1) + 1);
vector<int> bucket_counter(hash_size, 0);
vector<list<CTriangle> > chains(hash_size);
for (int bucket = 0; bucket < triangles.size(); ++bucket) {
int hash_value = (abs(
triangles[bucket].sides[0] % PRIME_NUMBER +
triangles[bucket].sides[1] * random_value % PRIME_NUMBER +
triangles[bucket].sides[2] * random_value % PRIME_NUMBER * random_value % PRIME_NUMBER)
) % hash_size;
if (is_absent(chains[hash_value], triangles[bucket])) {
chains[hash_value].push_back(triangles[bucket]);
++result;
}
}
return result;
}
//-----------------------------------------------------------------------------
int main() {
srand(239);
int length;
vector<CTriangle> triangles;
input(length, &triangles);
printf("%d", hashTableCreation(length, triangles));
return 0;
}
|
8939461268c87222c9417d57fd803d6c2f09d33d
|
e056fc78a4400d362dbff5968638dffc68386c1e
|
/3-G.Cvrpcount.cpp
|
4c7c0e65c0609eb26e328dabd86211a6ab2b69f5
|
[] |
no_license
|
huyhoangttql/TTUD
|
406624f751eebe544326b14a822c5fef409001bf
|
c5f798f97da0518cd23fda0fed4a07353c34ac3c
|
refs/heads/master
| 2023-04-08T02:51:07.326136
| 2021-04-21T08:40:54
| 2021-04-21T08:40:54
| 359,900,099
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,709
|
cpp
|
3-G.Cvrpcount.cpp
|
#include <iostream>
#define MAX 10005
using namespace std;
int n, K, Q;
int d[MAX];
int load[MAX] = {0};
int x[MAX];
int y[MAX];
int appear[MAX] = {0};
int segement;
int ans = 0;
void input(){
cin >> n >> K >> Q;
for(int i=1; i<=n; i++){
cin >> d[i];
}
}
void solution(){
ans ++;
// for(int i=1; i<=K; i++){
// cout << "Route " << i << ":" << "0 ";
// for(int j = y[i]; j!=0 ; j = x[j]){
// cout << j << " ";
// }
// cout << 0 << endl;
// }
// for(int i=0; i<=n; i++){
// cout << load[i] << " ";
// }
// cout << endl;
}
bool checkx(int v, int k){
if(v>0) {
if(appear[v]) return false;
if(load[k] + d[v] > Q) return false;
}
return true;
}
void tryx(int s, int k){
//thu gia tri X[s] cho lo trinh cua xe k
for(int v=0; v<=n; v++){
if(checkx(v, k)){
x[s] = v;//diem tiep theo cua kiem s la diem v
segement++;
appear[v] = true;
load[k]+= d[v];
if(v==0){
//xe quay ve diem dau
if(k==K){
if(segement == (n+k)) solution();
}
else tryx(y[k+1], k+1);//duyet tiep cho doan k+1, bat dau tu Y[k+1]
}
else tryx(v, k);
segement--;
load[k]-= d[v]; // recover
appear[v] = false;
}
}
}
bool checky(int v, int k){
if(appear[v] ) return false;
if(load[k] + d[v] > Q) return false;
return true;
}
void tryy(int k){
for(int v = y[k-1] + 1; v<= n; v++){
if(checky(v, k)){
y[k] = v;
segement++;
load[k] += d[v];
appear[v] = 1;
if(k==K){
tryx(y[1], 1);
}
else tryy(k+1);
segement--;
load[k] -= d[v];
appear[v] = 0;
}
}
}
int main(){
input();
segement = 0;
y[0] = 0;
tryy(1);
cout << ans;
}
|
e7a34dc6e0d390c2638a4463da27da4e74d88e35
|
0b085287d26e47bff407677479600132abf42728
|
/inherited-from-7zip/CPP/7zip/Common/InMemStream.h
|
adc5aaddb2ca7b7599cbc9c79ba31f1851ca6612
|
[] |
no_license
|
bks/qz7
|
ee717626f111c5bf301e41732f2badf37e6272fa
|
85493103def2959c2c3a68da9b48f9cf74791cc3
|
refs/heads/master
| 2021-01-22T03:39:22.364142
| 2008-12-09T00:35:38
| 2008-12-09T00:35:38
| 75,379
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,779
|
h
|
InMemStream.h
|
// InMemStream.h
#ifndef __INMEMSTREAM_H
#define __INMEMSTREAM_H
#include <stdio.h>
#include "../../Common/MyCom.h"
#include "MemBlocks.h"
class CIntListCheck
{
protected:
int *_data;
public:
CIntListCheck(): _data(0) {}
~CIntListCheck() { FreeList(); }
bool AllocateList(int numItems)
{
FreeList();
if (numItems == 0)
return true;
_data = (int *)::MyAlloc(numItems * sizeof(int));
return (_data != 0);
}
void FreeList()
{
::MyFree(_data);
_data = 0;
}
};
class CResourceList : public CIntListCheck
{
int _headFree;
public:
CResourceList(): _headFree(-1) {}
bool AllocateList(int numItems)
{
FreeList();
if (numItems == 0)
return true;
if (!CIntListCheck::AllocateList(numItems))
return false;
for (int i = 0; i < numItems; i++)
_data[i] = i + 1;
_data[numItems - 1] = -1;
_headFree = 0;
return true;
}
void FreeList()
{
CIntListCheck::FreeList();
_headFree = -1;
}
int AllocateItem()
{
int res = _headFree;
if (res >= 0)
_headFree = _data[res];
return res;
}
void FreeItem(int index)
{
if (index < 0)
return;
_data[index] = _headFree;
_headFree = index;
}
};
class CResourceListMt: public CResourceList
{
NWindows::NSynchronization::CCriticalSection _criticalSection;
public:
NWindows::NSynchronization::CSemaphore Semaphore;
HRes AllocateList(int numItems)
{
if (!CResourceList::AllocateList(numItems))
return E_OUTOFMEMORY;
Semaphore.Close();
return Semaphore.Create(numItems, numItems);
}
int AllocateItem()
{
Semaphore.Lock();
_criticalSection.Enter();
int res = CResourceList::AllocateItem();
_criticalSection.Leave();
return res;
}
void FreeItem(int index)
{
if (index < 0)
return;
_criticalSection.Enter();
CResourceList::FreeItem(index);
_criticalSection.Leave();
Semaphore.Release();
}
};
class CIntQueueMt: public CIntListCheck
{
int _numItems;
int _head;
int _cur;
public:
CIntQueueMt(): _numItems(0), _head(0), _cur(0) {}
NWindows::NSynchronization::CSemaphore Semaphore;
HRes AllocateList(int numItems)
{
FreeList();
if (numItems == 0)
return S_OK;
if (!CIntListCheck::AllocateList(numItems))
return E_OUTOFMEMORY;
_numItems = numItems;
return Semaphore.Create(0, numItems);
}
void FreeList()
{
CIntListCheck::FreeList();
_numItems = 0;
_head = 0;
_cur = 0;
}
void AddItem(int value)
{
_data[_head++] = value;
if (_head == _numItems)
_head = 0;
Semaphore.Release();
// printf("\nRelease prev = %d\n", previousCount);
}
int GetItem()
{
// Semaphore.Lock();
int res = _data[_cur++];
if (_cur == _numItems)
_cur = 0;
return res;
}
};
struct IInMemStreamMtCallback
{
// must be same for all calls
virtual size_t GetBlockSize() = 0;
// Out:
// result != S_OK stops Reading
// if *p = 0, result must be != S_OK;
// Locking is allowed
virtual HRESULT AllocateBlock(void **p) = 0;
virtual void FreeBlock(void *p) = 0;
// It must allow to add at least numSubStreams + 1 ,
// where numSubStreams is value from CInMemStreamMt::Create
// value -1 means End of stream
// Locking is not allowed
virtual void AddStreamIndexToQueue(int index) = 0;
};
struct CStreamInfo
{
CRecordVector<void *> Blocks;
int LastBlockIndex;
size_t LastBlockPos;
bool StreamWasFinished;
int CurBlockIndex;
size_t CurBlockPos;
NWindows::NSynchronization::CCriticalSection *Cs;
NWindows::NSynchronization::CManualResetEvent *CanReadEvent;
HRESULT ExitResult;
CStreamInfo(): Cs(0), CanReadEvent(0), StreamWasFinished(false) { }
~CStreamInfo()
{
delete Cs;
delete CanReadEvent;
// Free();
}
void Create()
{
Cs = new NWindows::NSynchronization::CCriticalSection;
CanReadEvent = new NWindows::NSynchronization::CManualResetEvent;
}
void Free(IInMemStreamMtCallback *callback);
void Init()
{
LastBlockIndex = CurBlockIndex = 0;
CurBlockPos = LastBlockPos = 0;
StreamWasFinished = false;
ExitResult = S_OK;
}
// res must be != S_OK
void Exit(HRESULT res)
{
ExitResult = res;
CanReadEvent->Set();
}
};
class CInMemStreamMt
{
CMyComPtr<ISequentialInStream> _stream;
NWindows::NSynchronization::CCriticalSection CS;
CObjectVector<CStreamInfo> _streams;
int _nextFreeStreamIndex;
int _currentStreamIndex;
UInt64 _subStreamSize;
CResourceListMt _streamIndexAllocator;
// bool _stopReading;
public:
HRESULT Read();
HRESULT ReadResult;
IInMemStreamMtCallback *Callback;
void FreeSubStream(int subStreamIndex);
HRESULT ReadSubStream(int subStreamIndex, void *data, UInt32 size, UInt32 *processedSize, bool keepData);
// numSubStreams: min = 1, good min = numThreads
bool Create(int numSubStreams, UInt64 subStreamSize);
~CInMemStreamMt() { Free(); }
void SetStream(ISequentialInStream *stream) { _stream = stream; }
// to stop reading you must implement
// returning Error in IInMemStreamMtCallback::AllocateBlock
// and then you must free at least one substream
HRes StartReadThread();
void Free();
// you must free at least one substream after that function to unlock waiting.
// void StopReading() { _stopReading = true; }
};
class CInMemStream:
public ISequentialInStream,
public CMyUnknownImp
{
UInt64 _size;
bool _keepData;
public:
int Index;
CInMemStreamMt *mtStream;
void Init(bool keepData = false)
{
_size = 0; _keepData = keepData ;
}
MY_UNKNOWN_IMP
STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
UInt64 GetSize() const { return _size; }
};
#endif
|
14f4844d0ac18e872ee632e763dd59ccee9dbf34
|
01ce8bc9cfe79af46fdde155cecfb6f427fae71c
|
/Source/Graphics/APIs/Vulkan/VertexBufferVulkan.h
|
5b63bb11a5620858758c65059900ab600f8f8c47
|
[] |
no_license
|
TypeBPenguin/EastEngine
|
d0a15e2f4b2ddd0c2dcabb8882c06f5efcf2e480
|
8ca5bc090b24edb209d998f363626c70c285e5cf
|
refs/heads/master
| 2023-02-13T11:08:51.866345
| 2021-01-05T12:00:58
| 2021-01-05T12:00:58
| 110,798,528
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 891
|
h
|
VertexBufferVulkan.h
|
#pragma once
#include "Graphics/Interface/GraphicsInterface.h"
namespace est
{
namespace graphics
{
namespace vulkan
{
class VertexBuffer : public IVertexBuffer
{
public:
VertexBuffer(const uint8_t* pData, uint32_t vertexCount, size_t formatSize, bool isDynamic);
virtual ~VertexBuffer();
public:
virtual uint32_t GetVertexCount() const override { return m_vertexCount; }
virtual uint32_t GetFormatSize() const override { return m_formatSize; }
virtual bool Map(MappedSubResourceData& mappedSubResourceData, bool isDiscard = true) override;
virtual void Unmap() override;
public:
VkBuffer GetBuffer() const { return m_buffer; }
private:
VkBuffer m_buffer{ nullptr };
VkDeviceMemory m_bufferMemory{ nullptr };
VkDeviceSize m_bufferSize{ 0 };
uint32_t m_vertexCount{ 0 };
uint32_t m_formatSize{ 0 };
};
}
}
}
|
6e978fdb063d08f9c7ca6344089b7983d06bc67c
|
ae4741b160ea3524c8e94691e7533f37dc1e64b8
|
/runtime/src/log.cpp
|
1b0a5ae590eb76faf71913c715083c979b516a62
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
DoroteaDudas/Bonsai
|
6721066771294846378d1a17fe5d817c1ec93d00
|
cdf6d6ec7f78d612cfcbfe078f43b96df2118988
|
refs/heads/master
| 2020-03-22T20:03:37.146748
| 2017-07-10T14:38:55
| 2017-07-10T14:38:55
| 140,556,802
| 0
| 0
|
Apache-2.0
| 2018-07-11T10:05:16
| 2018-07-11T10:01:37
|
C++
|
UTF-8
|
C++
| false
| false
| 1,651
|
cpp
|
log.cpp
|
/*
* log.cpp
*
* Created on: Jun 8, 2012
* Author: jbedorf
*/
#ifdef USE_MPI
#include <mpi.h>
#endif
#include <stdarg.h>
#include <log.h>
#include <stdio.h>
#include <string.h>
// ******************************************** //
// These functions add the process ID and total //
// number of processes to the output lines. //
// Mainly for parallel debug purposes. //
// ******************************************** //
#if ENABLE_LOG
#ifdef USE_MPI
#include <mpi.h>
extern bool ENABLE_RUNTIME_LOG;
extern bool PREPEND_RANK;
extern int PREPEND_RANK_PROCID;
extern int PREPEND_RANK_NPROCS;
const char prependPattern[] = {"[Proc: %d (%d)]\t"};
char stderrBUFF[4096];
//Standard out, note we write to a buffer to make
//sure the whole line is output in one flush
extern void prependrankLOG(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
sprintf(stderrBUFF, prependPattern, PREPEND_RANK_PROCID, PREPEND_RANK_NPROCS);
int len = strlen(stderrBUFF);
vsprintf(stderrBUFF+len, fmt, ap);
va_end(ap);
printf("%s",stderrBUFF);
}
extern void prependrankLOGF(const char *fmt, ...)
{
// char stderrBUFF[4096];
va_list ap;
va_start(ap, fmt);
sprintf(stderrBUFF, prependPattern, PREPEND_RANK_PROCID, PREPEND_RANK_NPROCS);
int len = strlen(stderrBUFF);
vsprintf(stderrBUFF+len, fmt, ap);
va_end(ap);
fprintf(stderr, "%s", stderrBUFF);
}
#endif //USEMPI
#endif //ENABLE LOG
|
8b29f2eb712efe799cf912a15ba4e11af3224d92
|
43b30faeb36ae2c94e3b59833ec5c284b16edca9
|
/tcpchatClient.cpp
|
b1e56474dea361edeeddc9b681bde7c30fcea624
|
[] |
no_license
|
tsm9999/CNL
|
5d69c8a43d75226ac8c6eadb11b82adfcb2a23ec
|
14087147240d22e90c04099a6284851806691c98
|
refs/heads/master
| 2020-08-27T22:08:41.411376
| 2019-10-25T18:59:42
| 2019-10-25T18:59:42
| 217,474,973
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,213
|
cpp
|
tcpchatClient.cpp
|
#include<iostream>
#include <sys/socket.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
using namespace std;
#define PORT 3207
#define SERVER_ADDRESS "127.0.0.1"
void die(char *error)
{
perror(error);
exit(1);
}
int main()
{
struct sockaddr_in server_addr;
int sock=socket(AF_INET,SOCK_STREAM,0);
if(sock<0)
cout<<"Server couldn't be created"<<endl;
else
cout<<"Server created successfully"<<endl;
server_addr.sin_addr.s_addr=inet_addr(SERVER_ADDRESS);
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(PORT);
int status=connect(sock,(struct sockaddr*)&server_addr,sizeof(server_addr));
if(status==0)
cout<<"Connect Success";
else
cerr<<"connect"<<endl;
char buffer[256];
while(1)
{
bzero((char*)buffer,256);
cout<<">";
string data;
getline(cin,data);
strcpy(buffer,data.c_str());
send(sock,buffer,strlen(buffer),0);
bzero(buffer,256);
cout<<"Awaiting Server Response"<<endl;
recv(sock,(char*)&buffer,sizeof(buffer),0);
cout<<"Server: "<<buffer<<endl;
}
return 0;
}
|
cc10d30d3f6b1900726920713778d5d98ad064c4
|
d62c168301234071e78d9b80d3adf5f37c6c38f2
|
/main/MinimumPathSum.cpp
|
5a5f3c819a430c2292d44ba11aefe3f12bd14a73
|
[] |
no_license
|
HeHaowei/Leetcode
|
37c0a834df1ec49bb8f1d769492a34cd3b430f53
|
2009aa7f143cdb9655fcf701a2926e087693262b
|
refs/heads/master
| 2021-07-06T21:09:48.775211
| 2020-10-01T16:43:20
| 2020-10-01T16:43:20
| 189,728,446
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,172
|
cpp
|
MinimumPathSum.cpp
|
class Solution {
public:
vector<vector<int>> path;
int minPathSum(vector<vector<int>>& grid) {
int l = grid.size();
int r = grid[0].size();
vector<int> line;
for (int i = 0; i < l; i++) {
path.push_back(line);
for (int j = 0; j < r; j++) {
path[i].push_back(-1);
}
}
return minPath(grid, l - 1, r - 1);
}
int minPath(vector<vector<int>>& grid, int i, int j) {
if (path[i][j] != -1) return path[i][j];
else {
if (i == 0 && j == 0) {
path[i][j] = grid[i][j];
return path[i][j];
}
else if (i == 0) {
path[i][j] = minPath(grid, i, j - 1) + grid[i][j];
return path[i][j];
}
else if (j == 0) {
path[i][j] = minPath(grid, i - 1, j) + grid[i][j];
return path[i][j];
}
else {
path[i][j] = min(minPath(grid, i, j - 1), minPath(grid, i - 1, j)) + grid[i][j];
return path[i][j];
}
}
}
};
|
094bfee312eab8bdcd10d7b55b36804cf31a579d
|
b3e525a3c48800303019adac8f9079109c88004e
|
/nic/sdk/platform/elba/axitrace/msg_undef.inc
|
e74d2175692cce76b2895d5bc074e92a4fc83ea8
|
[] |
no_license
|
PsymonLi/sw
|
d272aee23bf66ebb1143785d6cb5e6fa3927f784
|
3890a88283a4a4b4f7488f0f79698445c814ee81
|
refs/heads/master
| 2022-12-16T21:04:26.379534
| 2020-08-27T07:57:22
| 2020-08-28T01:15:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 142
|
inc
|
msg_undef.inc
|
#include <iostream>
#include "generic.h"
#ifdef MY_MSG
#undef MY_MSG
#undef MY_INFO
#undef MY_ERROR
#undef MY_WARNING
#undef MY_DEBUG
#endif
|
8e50657d84d7490e00158e4a260cca7588459388
|
e9798b50d6b68836225163f89b6cc6abe71840ca
|
/MathAttack/MathAttackDlg.h
|
22d717e850b4c13bba1ba5507de5a8adf926d7b9
|
[
"MIT"
] |
permissive
|
gajduk/math-attack
|
3da77ea827943f15bb1f01b1508d382ab4721a6f
|
71cd9e8b73f2c4001c193a90af328f0be83dd198
|
refs/heads/master
| 2021-01-18T21:23:09.684560
| 2016-04-12T10:10:28
| 2016-04-12T10:10:28
| 29,317,911
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,314
|
h
|
MathAttackDlg.h
|
// MathAttackDlg.h : header file
//
#pragma once
#include "afxwin.h"
// CMathAttackDlg dialog
class CMathAttackDlg : public CDialog
{
private:
int x[5];
int y[5];
bool postoi[5];
int broj1[5];
int broj2[5];
int operacija[5];
int rezultat[5];
int brzina;
bool izlez;
// Construction
public:
CMathAttackDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_MATHATTACK_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
int m_pogodeni;
afx_msg void OnBnClickedButton3();
afx_msg void OnTimer(UINT_PTR nIDEvent);
BOOL m_sobiranje;
BOOL m_odzemanje;
BOOL m_mnozenje;
BOOL m_delenje;
int vreme;
afx_msg void OnBnClickedCancel();
protected:
virtual void OnOK();
virtual void OnCancel();
public:
afx_msg void OnBnClickedButton4();
afx_msg void incSpeed();
afx_msg void decSpeed();
afx_msg void updateOperations();
afx_msg void incFreq();
afx_msg void decFreq();
afx_msg void start();
CString m_rez;
// afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
};
|
bedd230abc19054b28c61d37b6ad28c8772799fa
|
1dd459ea5b00ebcb4e539af3f5ba8fe4d0b5710f
|
/monoExpanderMotor.h
|
d65ba1a55977228c1fa12dcbf2567190ae57227c
|
[] |
no_license
|
pfeuh/monoExpander
|
6d0bc0783088556e01147990a5dbbe9413b96284
|
38954ebe5cdee4e6fd9c164d2d0c79e9705d0721
|
refs/heads/master
| 2020-07-12T07:00:57.003069
| 2019-08-28T19:38:52
| 2019-08-28T19:38:52
| 204,564,404
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,324
|
h
|
monoExpanderMotor.h
|
#ifndef monoExpanderMotor_H
#define monoExpanderMotor_H
/*
* file : monoExpanderMotor.h
* Copyright (c) pfeuh <ze.pfeuh@gmail>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Arduino.h>
#define MONO_EXPANDER_MOTOR_VERSION "1.00"
#define MONO_EXPANDER_NB_MIDI_NOTES 128
#define MONO_EXPANDER_NB_MIDI_NOTE_MASK 127
#define MONO_EXPANDER_NOTHING_PLAYING 255
#define MONO_EXPANDER_MOTOR_NB_BYTES (sizeof(byte) * 5)
#define MONO_EXPANDER_MOTOR_EEPROM_BASE 0
#define MONO_EXPANDER_PRIORITY_LOWEST 0
#define MONO_EXPANDER_PRIORITY_HIGHEST 1
#define MONO_EXPANDER_GATE_LOGIC_POSITIVE 0
#define MONO_EXPANDER_GATE_LOGIC_NEGATIVE 1
#define MONO_EXPANDER_MOTOR_GATE_ON 1
#define MONO_EXPANDER_MOTOR_GATE_OFF 0
// factory default parameter
#define MONO_EXPANDER_MOTOR_FACTORY_CHANNEL 1
#define MONO_EXPANDER_MOTOR_FACTORY_OMNI 1
#define MONO_EXPANDER_MOTOR_FACTORY_TRANSPOSITION 0
#define MONO_EXPANDER_MOTOR_FACTORY_PRIORITY MONO_EXPANDER_PRIORITY_HIGHEST
#define MONO_EXPANDER_MOTOR_FACTORY_GATE_MODE MONO_EXPANDER_PRIORITY_HIGHEST
class MONO_EXPANDER_MOTOR
{
public:
void begin(int audio_pin, int gate_pin);
// motor itself
void noteOn(byte channel, byte note, byte velocity);
void noteOff(byte channel, byte note, byte velocity);
void setGeneratorOn_CB(void (*generator_on_CB)());
void setGeneratorOff_CB(void (*generator_off_CB)());
// parameters getters & setters
byte getChannel();
void setChannel(byte _channel);
byte getTransposition();
void setTransposition(byte _tranposition);
bool getOmni();
void setOmni(bool _omni);
byte getPriority();
void setPriority(byte _priority);
byte getGateLogic();
void setGateLogic(byte gate_logic);
// parameters storage
void loadParameters();
void saveParameters();
void restoreFactoryParameters();
private:
int audioPin;
int gatePin;
byte currentlyPlayingNote;
bool busyMap[MONO_EXPANDER_NB_MIDI_NOTES];
void (*generatorOn_CB)();
void (*generatorOff_CB)();
// this bytes should be saved in EEPROM
byte configData[MONO_EXPANDER_MOTOR_NB_BYTES];
bool messageReceived(byte channel);
void startGenerate(byte note);
void stopGenerate();
void restartPreviousNote(byte note);
void registerNote(byte note);
void unregisterNote(byte note);
void clearBusyMap();
bool busyMapIsEMpty();
byte transpose(byte note);
};
#endif
|
fcbf9dd15462bcbaca6cfd27d9e5644524167167
|
7e22725944fb5024ace01a533af24d89b67c4f48
|
/400-499/473.matchsticks-to-square.cpp
|
9a724d2e9a0c2357343eed072f2f1fe1561c8ee5
|
[] |
no_license
|
egg0315/LeetCode
|
8746892eea594f86cf86184b10849129c819e813
|
e4361f897ea8694d2e60953a6cb3a9dca54edb65
|
refs/heads/master
| 2020-07-22T14:09:35.243206
| 2019-11-05T08:33:30
| 2019-11-05T08:33:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 945
|
cpp
|
473.matchsticks-to-square.cpp
|
/*
* @lc app=leetcode id=473 lang=cpp
*
* [473] Matchsticks to Square
* Note : use nested dfs instead of four parallel dfs
*/
class Solution {
public:
bool makesquare(vector<int> &nums) {
int total = accumulate(begin(nums), end(nums), 0);
if (total == 0)
return false;
if (total % 4)
return false;
total /= 4;
vector<bool> used(nums.size(), false);
return dfs(nums, used, 0, total, total, 0);
}
bool dfs(vector<int> &nums, vector<bool> &used, int start, int remain,
int target, int edge) {
if (edge == 4)
return true;
if (remain == 0) {
return dfs(nums, used, 0, target, target, edge + 1);
}
for (int i = start; i < nums.size(); ++i) {
if (!used[i] && remain >= nums[i]) {
used[i] = true;
if (dfs(nums, used, i + 1, remain - nums[i], target, edge))
return true;
used[i] = false;
}
}
return false;
}
};
|
baa4420aeb049f6dbb6a14b07dec62a575094c99
|
3093fcb62e374191f65bdfe9f503b81dad2ee06d
|
/matrixes.h
|
f6013dc8afaebd2609fe056b087507a54efb2f3e
|
[] |
no_license
|
misabelber/Math
|
c6ac51b44bf6f1934a2075ea99dfef952d9a5170
|
e2c2b42bbf0fe94ea9b9bb94578f805ceae29a22
|
refs/heads/master
| 2020-03-15T06:53:57.725875
| 2018-05-04T08:35:41
| 2018-05-04T08:35:41
| 132,017,692
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,852
|
h
|
matrixes.h
|
#pragma once
#include <vector>
/****************************************************************
Matrix and vector stuff:
- vector are represented with an array
- matric is a vector of vector
- operations are done on the array itself
****************************************************************/
typedef double Number;
typedef std::vector<Number> V; // Vector
typedef std::vector<V> M; // Matrx
typedef std::vector<M> VM; // Vector of Matrixes
void init(V &v,const int size); // Initialize a vector
void init(M &m,const int rows,const int columns); // Initialize a matrix
void mult(M &v1,V &v2,V &o); // Matrix product
Number mult(V &v1,V &v2); // Scalar product
void mult(V &v,Number n); // Vector scaling
void mult(M &a, M &b, M &c);
void add(V &a,V &b,V &o);
void add_(V &a,V &b); // Add in place
void add(M &A, M& B, M &C);
void add_col(M &m); // Growing in columns
void add_row(M &m); // Growing in rows
void normalize(V &v);
// Sepecial operators for rotations
void rotZ(V &v,Number rad);
void rotY(V &v,Number rad);
void transpose(M &a, M &b);
//int cholesky(M &a, M &c);
void invert(M &A, M &invA);
void cholesky(M &m,M &l);
void solvell(M &m,V a, V &solution);
void solvelt(M &m,V a, V &solution);
Number solvecholesky(M &m,V &b,V &x,Number &logdet); // Conjugate gradient solvinf of mx=b. Returns the solution and the log |det|
Number solvecholesky(M &m,V &b,V &x){Number dummy;return solvecholesky(m,b,x,dummy);} // Conjugate gradient solvinf of mx=b.
// Matrix solution
double solve(M &m,V &b,V &x, Number prec=1e-6, bool print=false); // Conjugate gradient solvinf of mx=b. Return 1 if failed
double solvepositive(M &m,V &b,V &x, Number prec=1e-6, bool print=false);
bool my_solve(M &m,V &b,V &x,Number prec=1e-6);
|
619a390c6e9a18af113f015acc3b125ce33d74d0
|
5d83739af703fb400857cecc69aadaf02e07f8d1
|
/Archive2/c0/017094895cf3ba/main.cpp
|
100e8418610ce6fc8f1ba55084d488c6cd25397c
|
[] |
no_license
|
WhiZTiM/coliru
|
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
|
2c72c048846c082f943e6c7f9fa8d94aee76979f
|
refs/heads/master
| 2021-01-01T05:10:33.812560
| 2015-08-24T19:09:22
| 2015-08-24T19:09:22
| 56,789,706
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,427
|
cpp
|
main.cpp
|
#include <chrono>
#include <iostream>
#include <type_traits>
#include <utility>
// Executes fn with arguments args and returns the time needed
// and the result of f if it is not void
template <class Fn, class... Args>
auto timer(Fn fn, Args... args)
-> std::pair<double, decltype(fn(args...))> {
static_assert(!std::is_void<decltype(fn(args...))>::value,
"Call timer_void if return type is void!");
auto start = std::chrono::high_resolution_clock::now();
auto ret = fn(args...);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
return { elapsed_seconds.count(), ret };
}
// If fn returns void, only the time is returned
template <class Fn, class... Args>
double timer_void(Fn fn, Args... args) {
static_assert(std::is_void<decltype(fn(args...))>::value,
"Call timer for non void return type");
auto start = std::chrono::high_resolution_clock::now();
fn(args...);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
return elapsed_seconds.count();
}
void fun (std::size_t max) {
int a,b,c;
for (int i = 0; i < max; i++) {
a = 1234 + 5678 + i;
b = 1234 * 5678 + i;
c=1234/2+i;
}
}
int main () {
std::cout << timer_void(fun,2e6) << "\n"
<< timer_void(fun,2e8);
}
|
5f24066f60226be3b028d76d713339dcf93caea0
|
1befd4ed97a1541e9615e3514695063e87a71d36
|
/_Kap 11 - Klassen/Klasse Bruch.cpp
|
1a6c0ca652d4e3d6705d9e0e340ce982c9baf4d1
|
[] |
no_license
|
ProfJust/TIN
|
08b3ea63d57f00e699574cb610197a02c20551c9
|
e851ac005088d32b5f90fb49e65f825e10a375d4
|
refs/heads/master
| 2021-11-26T05:05:48.736772
| 2021-11-24T17:57:25
| 2021-11-24T17:57:25
| 166,380,877
| 1
| 1
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 3,004
|
cpp
|
Klasse Bruch.cpp
|
// Klasse Bruch.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//neue Version 27.11.2016
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
class Bruch
{
public:
Bruch() { zaehler = 0; nenner = 1; } // Standardkonstruktor
~Bruch() { } // Destruktor
Bruch(int z, int n) { // Konstruktor mit Parametern
zaehler = z; if (n != 0) nenner = n; else nenner = 1;
}
int GetNenner() { return nenner; }
int GetZaehler() { return zaehler; }
void SetNenner(int p) { if (p != 0) nenner = p; }
void SetZaehler(int long p) { zaehler = p; }
void Addiere(int);
Bruch operator+(int);
void Addiere(Bruch);
Bruch operator+(Bruch);
Bruch operator/(int);
void Zeige();
void Erweitere(int);
private:
int zaehler;
int nenner;
};
void Bruch::Zeige()
{
cout << setw(3) << zaehler << " / " << nenner << endl;
}
void Bruch::Erweitere(int faktor)
{
zaehler *= faktor;
nenner *= faktor;
}
// Zweimal die Funktion Addiere, aber mit verschiedenen Parametern
// ---> mit integer
void Bruch::Addiere(int summand)
{
zaehler += summand*nenner;
}
// ---> mit einem Bruch
void Bruch::Addiere(Bruch summand)
{
zaehler = zaehler*summand.GetNenner()
+ summand.GetZaehler()*nenner;
nenner = nenner * summand.GetNenner();
}
//--- Überladen des "+"-Zeichens als Operator für die Addition einer ganzen Zahl zu einem Bruch ---
Bruch Bruch::operator+(int summand)
{
Addiere(summand);
return *this;
}
//--- Überladen des "+"-Zeichens als Operator für die Addition zweier Brüche ---
Bruch Bruch::operator+(Bruch summand)
{
Addiere(summand);
return *this;
}
Bruch Bruch::operator/(int divisor)
{
if (divisor == 0) throw 0;
nenner *= divisor;
return *this;
}
//--------------------------------------------------------------------------
Bruch b1(1, 2), b2(1, 4);
int main() {
try {
cout << "b1 und b2 - Werte nach Konstruktor " << endl;
b1.Zeige();
b2.Zeige();
b1 = b1 + b2;
b1.Zeige();
b1 = b1 + 1;
b1.Zeige();
b1 / 0;
system("pause");
return(0);
}
catch (int errNo) {
if (errNo == 0) cout << "Div by Zero "<<endl;
system("pause");
}
return(0);
}
/*b1.Addiere(b2);
b1.Zeige();
b1.Addiere(1);
b1.Zeige();*/
////--- Methoden der Klasse aufrufen Objekt.Methode(Parameter) ---
//Bruch b1, b2;
//b1.SetZaehler(1);
//b1.SetNenner(2);
//b2.SetZaehler(5);
//b2.SetNenner(6);
//printf("\n b1 ");
//b1.Zeige();
//cout << "\n b2 ";
//
//cout << "\n b1 erweitert mit 3 ";
//b1.Erweitere(3);
//b1.Zeige();
//// Versehentliche Veränderung von b1.nenner
// // durch falschen Vergleichsoperator:
//if (b1.nenner == b2.nenner) {
// cout << "\n Gemeinsamer Nenner: ", b1.nenner;
//}
//cout << "\n Bruch b1 nach Fehler"
//b1.zeige();
//if (b1.GetNenner() == b2.GetNenner()) {
// cout << "\n Gemeinsamer Nenner: ", b1.GetNenner();
//}
|
9d21691dbcb9162b881235cfcce6f75dc955f433
|
e5f3b27692ec3185389c784ca003c42fa4fa7f34
|
/Minesweeper/GameBoard.h
|
d20b6d07244466fe5e200342103e4e47a89209c0
|
[] |
no_license
|
robertberry-zz/Minesweeper
|
dfcf96a20a134917fa6853cd73214e20aed5779e
|
cd13a97b661fccbf265028c8c505e727ed3d6512
|
refs/heads/master
| 2023-03-01T23:21:31.195833
| 2013-12-26T16:14:46
| 2013-12-26T16:14:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,968
|
h
|
GameBoard.h
|
//
// GameBoard.h
// Minesweeper
//
// Created by Robert Berry on 24/12/2013.
// Copyright (c) 2013 Robert Berry. All rights reserved.
//
#ifndef __Minesweeper__GameBoard__
#define __Minesweeper__GameBoard__
#include "Cell.h"
#include <vector>
class GameBoard {
private:
bool mGameOver;
int mColumns;
int mRows;
int mHiddenCells;
int mMines;
std::vector< std::vector<Cell> > mCells;
/**
* If x, y is hidden, reveal it. Do flood reveal if necessary. Return score accrued.
*/
int reveal(int x, int y);
/**
* Horizontal sweep of the board. Step (-1 or +1) determines direction. Return score accrued.
*/
int sweep(int x, int y, int step);
int drain(int x, int y);
/**
* Set n random cells to contain mines
*/
void populateMines(int n);
public:
/**
* Create game board of given number of rows and columns with given number of randomly placed mines
*/
GameBoard(int rows, int columns, int mines);
/**
* How many mines neighbour x, y
*/
int getNeighbouringMines(int x, int y);
/**
* Cell x, y (by copy)
*/
Cell getCell(int x, int y);
/**
* Set cell x, y
*/
void setCell(int x, int y, Cell cell);
/**
* Number of rows
*/
int getRows();
/**
* Number of columns
*/
int getColumns();
/**
* Whether the game is over
*/
bool getIsGameOver();
/**
* Whether the player has won the game
*/
bool getIsGameWon();
/**
* Trigger click behaviour for x, y. Return score accrued.
*/
int onClick(int x, int y);
/**
* Trigger right click behaviour for x, y
*/
void onRightClick(int x, int y);
/**
* Is x, y within the bounds of the board?
*/
bool validCoordinate(int x, int y);
};
#endif /* defined(__Minesweeper__GameBoard__) */
|
27575ecb2ad648b7c52bec52706a87a00f7008fd
|
53060989254d20ad6fc48d9ad4935bb4f93bd6bd
|
/IOCPSession.cpp
|
2f6cb60410531a1e0bc20870bbae9d08cf58a6b2
|
[] |
no_license
|
JTK95/IOCPServer
|
b2c9491604493dfb4f7416fc6b895bac63d220ea
|
39db884cb555989e4b70197c0ab3009914f12fb0
|
refs/heads/main
| 2023-04-14T08:53:08.946988
| 2021-04-26T03:12:15
| 2021-04-26T03:12:15
| 361,597,811
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 11,361
|
cpp
|
IOCPSession.cpp
|
#include "pch.h"
#include "IOCPSession.h"
IoData::IoData()
:_ioType(IO_OPERATION::IO_ERROR)
{
memset(&_overlapped, 0, sizeof(_overlapped));
this->Clear();
}
IoData::~IoData()
{}
//------------------------------------------------------------------------
// IoData 멤버를 0으로 초기화
//------------------------------------------------------------------------
void IoData::Clear()
{
_buffer.fill(0);
_totalBytes = 0;
_currentBytes = 0;
}
//------------------------------------------------------------------------
// IO가 더 필요한지 체크
//------------------------------------------------------------------------
BOOL IoData::needMoreIO(size_t transferSize)
{
_currentBytes += transferSize;
if (_currentBytes < _totalBytes)
{
return TRUE;
}
return FALSE;
}
//------------------------------------------------------------------------
// _totalBytes를 설정하고 설정 되어있을 시 무시 후 패킷 크기 반환
//------------------------------------------------------------------------
int IoData::setupTotalBytes()
{
int offset = 0;
int packetLen[1] = { 0, };
if (_totalBytes == 0)
{
//---------------------------------------------------------------------------
// 여기서 _buffer.data()는 해당 인덱스의 데이터의 값이 반환되는게 아니라,
// 배열의 첫번째 주소를 반환한다
//---------------------------------------------------------------------------
memcpy_s((void*)packetLen, sizeof(packetLen), (const void*)_buffer.data(), sizeof(packetLen));
_totalBytes += (size_t)packetLen[0];
}
else
{
memcpy_s((void*)packetLen, sizeof(packetLen), (const void*)_buffer.data(), sizeof(packetLen));
_totalBytes += (size_t)packetLen[0];
return offset;
}
offset += sizeof(packetLen);
return offset;
}
//------------------------------------------------------------------------
// 현재까지 온 버퍼, 길이, 버퍼를 리턴함
//------------------------------------------------------------------------
WSABUF IoData::wsabuf()
{
WSABUF wsaBuf;
wsaBuf.buf = _buffer.data() + _currentBytes;
wsaBuf.len = (ULONG)(_totalBytes - _currentBytes);
return wsaBuf;
}
//------------------------------------------------------------------------
// _buffer에 stream의 크기를 헤더로, 버퍼를 뒤에 추가해주는 패킷 만듬,
// _totalBytes 갱신
//------------------------------------------------------------------------
BOOL IoData::SetData(Stream& stream)
{
this->Clear();
if (_buffer.max_size() <= stream.size())
{
printf_s("IoData::SetData() packet over size [%llu]byte\n", stream.size());
//SLog(L"! packet size too bif [%d]byte", stream.size());
return FALSE;
}
const size_t packetHeaderSize = sizeof(int);
int offset = 0;
// _buffer의 첫번째 주소 반환
char* buf = _buffer.data();
// 헤더 크기 + 실제 데이터 크기
int packetLen[1] = { packetHeaderSize + stream.size() };
// insert packet len
memcpy_s(buf + offset, _buffer.max_size(), packetLen, packetHeaderSize);
offset += packetHeaderSize;
// insert packet data
memcpy_s(buf + offset, _buffer.max_size(), stream.data(), stream.size());
offset += stream.size();
_totalBytes = offset;
return TRUE;
}
size_t* IoData::GetCurrentBytes()
{
return &_currentBytes;
}
size_t* IoData::GetTotalBytes()
{
return &_totalBytes;
}
std::array<char, 1024 * 10>* IoData::GetBuffer()
{
return &_buffer;
}
void IoData::SetTotalBytes(size_t setTotalBytes)
{
_totalBytes = setTotalBytes;
}
size_t IoData::TotalBytes()
{
return _totalBytes;
}
IO_OPERATION& IoData::type()
{
return _ioType;
}
char* IoData::data()
{
return _buffer.data();
}
LPWSAOVERLAPPED IoData::overlapped()
{
return &_overlapped;
}
void IoData::SetType(IO_OPERATION type)
{
_ioType = type;
}
//---------------------------------------------------------------------
// IOCPSession class
//---------------------------------------------------------------------
IOCPSession::IOCPSession()
:Session()
{
//this->Initialize();
InitializeSRWLock(&_lock);
//memset(&_mainBuffer, 0, sizeof(_mainBuffer));
memset(&_socketData, 0, sizeof(SOCKET_DATA));
_ioData[(int)(IO_OPERATION::IO_READ)].SetType(IO_OPERATION::IO_READ);
_ioData[(int)(IO_OPERATION::IO_WRITE)].SetType(IO_OPERATION::IO_WRITE);
}
void IOCPSession::CheckErrorIO(DWORD ret)
{
// IO 에러 체크
if (ret == SOCKET_ERROR && (WSAGetLastError() != ERROR_IO_PENDING))
{
printf_s("IOCPSession::CheckErrorIO() socket error : %d\n", WSAGetLastError());
//SLog(L"! socket error : %d", WSAGetLastError());
}
}
//---------------------------------------------------------------------
// 소켓 recv 해주고 에러 체크
//---------------------------------------------------------------------
void IOCPSession::Recv(WSABUF wsaBuf)
{
DWORD flags = 0;
DWORD recvBytes = 0;
DWORD errorCode = WSARecv
(
_socketData._socket, // 연결 소켓
&wsaBuf, // wsabuf 구조체 배열을 가리키는 포인터
1, // wsabuf의 구조체 개수
&recvBytes, // 데이터 입력이 완료되면, 읽은 데이터의 바이트 크기를 받음
&flags, // 함수의 호출 방식을 지정
_ioData[(int)(IO_OPERATION::IO_READ)].overlapped(), // 오버랩 설정
NULL
);
this->CheckErrorIO(errorCode);
}
//---------------------------------------------------------------------
// 입출력 체크, wsabuf recv, totalbytes 설정
//---------------------------------------------------------------------
bool IOCPSession::IsRecving(size_t transferSize)
{
if (_ioData[(int)(IO_OPERATION::IO_READ)].needMoreIO(transferSize))
{
this->Recv(_ioData[(int)(IO_OPERATION::IO_READ)].wsabuf());
_ioData[(int)(IO_OPERATION::IO_READ)].setupTotalBytes();
return true;
}
return false;
}
//---------------------------------------------------------------------
// 데이터 분석, 분석한 대로 패킷을 얻어와 Package를 만들어 내보내는 역할
//---------------------------------------------------------------------
Package* IOCPSession::OnRecv(size_t transferSize)
{
int offset = 0;
size_t packetLen = 0;
size_t* packetSize = nullptr;
size_t checkDataBuffer = 0;
// offset에 totalbyte 설정
offset += _ioData[(int)(IO_OPERATION::IO_READ)].setupTotalBytes();
// _currentByte 설정
if (this->IsRecving(transferSize))
{
return nullptr;
}
// buf로 받은 패킷을 main버퍼로 복사
memcpy_s(&_mainBuffer + _mainBufferOffset, sizeof(_mainBuffer) - _mainBufferOffset,
_ioData[(int)(IO_OPERATION::IO_READ)].GetBuffer(), *_ioData[(int)(IO_OPERATION::IO_READ)].GetCurrentBytes());
// 복사한 만큼 offset을 이동
_mainBufferOffset += *_ioData[(int)(IO_OPERATION::IO_READ)].GetCurrentBytes();
_ioData[(int)(IO_OPERATION::IO_READ)].SetTotalBytes(_mainBufferOffset);
while (true)
{
// packetLen을 보고 _mainBuffer안에 패킷을 처리하는 구문
if (sizeof(packetLen) > _mainBufferOffset)
{
// _mainBuffer안에 읽을 내용이 없을 때 break;
//puts("IOCPSession::OnRecv() no Data in _mainBuffer");
//SLog(L"no Data in _mainBuffer");
break;
}
memcpy(&packetLen, &_mainBuffer, sizeof(int));
// GetTotalBytes() 앞에 헤더만 읽어서 진정한 totalbyte라고 할수 없음
if (packetLen > *_ioData[(int)(IO_OPERATION::IO_READ)].GetTotalBytes())
{
puts("IOCPSession::OnRecv() not enough Data to read packet in _mainBuffer");
//SLog(L"not enough Data to read packet in _mainBuffer");
break;
}
const size_t packetHeaderSize = sizeof(int);
int packetDataSize = (int)(packetLen - packetHeaderSize);
BYTE packetData[200] = { 0, };
// packetData에 _mainBuffer에 있는 패킷의 데이터만큼 잘라서 넣어준다
memcpy(packetData, _mainBuffer + offset, packetDataSize);
Packet* packet = PacketAnalyzer::GetInstance()->Analyzer((const char*)packetData, packetDataSize);
if (packet == nullptr)
{
printf_s("IOCPSession::OnRecv() Invalid packet [%d]\n", packet->type());
//SLog(L"! [%d],invalid packet", packet->type());
this->OnClose(true);
_ioData[(int)(IO_OPERATION::IO_READ)].SetTotalBytes(_mainBufferOffset);
break;
}
//printf_s("packet type : %d\n", packet->type());
//SLog(L"%d", packet->type());
Package* package = new Package(this, packet);
if (packet != NULL)
{
// packetStrorage에 넣는 구문
this->PutPackage(package);
}
memcpy(_mainBuffer, _mainBuffer + packetLen, sizeof(_mainBuffer) - packetLen);
_mainBufferOffset -= packetLen;
_ioData[(int)(IO_OPERATION::IO_READ)].SetTotalBytes(_mainBufferOffset);
}
this->RecvStandBy();
return NULL;
}
//---------------------------------------------------------------------
// _ioData[IO_READ] 버퍼 초기화, 소켓을 recv상태로 바꿔줌
// wsabuf 셋팅
//---------------------------------------------------------------------
void IOCPSession::RecvStandBy()
{
_ioData[(int)(IO_OPERATION::IO_READ)].Clear();
WSABUF wsaBuf;
wsaBuf.buf = _ioData[(int)(IO_OPERATION::IO_READ)].data();
wsaBuf.len = SOCKET_BUF_SIZE;
this->Recv(wsaBuf);
}
//---------------------------------------------------------------------
// wsaBuf 송신, 에러 체크
//---------------------------------------------------------------------
void IOCPSession::Send(WSABUF wsaBuf)
{
DWORD flags = 0;
DWORD sendBytes;
DWORD errorCode = WSASend
(
_socketData._socket,
&wsaBuf,
1,
&sendBytes,
flags,
_ioData[(int)(IO_OPERATION::IO_WRITE)].overlapped(),
NULL
);
this->CheckErrorIO(errorCode);
}
//---------------------------------------------------------------------
// 패킷 보내기 // on이면 패킷 송신
//---------------------------------------------------------------------
void IOCPSession::OnSend(size_t transferSize)
{
if (_ioData[(int)(IO_OPERATION::IO_WRITE)].needMoreIO(transferSize))
{
this->Send(_ioData[(int)(IO_OPERATION::IO_WRITE)].wsabuf());
}
}
//---------------------------------------------------------------------
// packet데이터를 _ioData 형태로 변형 후 send함
//---------------------------------------------------------------------
void IOCPSession::SendPacket(Packet* packet)
{
Stream stream;
packet->Encoding(stream);
if (!_ioData[(int)(IO_OPERATION::IO_WRITE)].SetData(stream))
{
return;
}
WSABUF wsaBuf;
wsaBuf.buf = _ioData[(int)(IO_OPERATION::IO_WRITE)].data();
wsaBuf.len = stream.size() + 4;// sizeof(int)
this->Send(wsaBuf);
}
bool IOCPSession::IsEmpty()
{
bool temp;
AcquireSRWLockShared(&_lock);
temp = _packageStorage.empty();
ReleaseSRWLockShared(&_lock);
return temp;
}
void IOCPSession::PutPackage(Package* package)
{
AcquireSRWLockExclusive(&_lock);
_packageStorage.push_back(package);
ReleaseSRWLockExclusive(&_lock);
}
Package* IOCPSession::PopPackage()
{
Package* temp;
AcquireSRWLockExclusive(&_lock);
temp = _packageStorage.front();
_packageStorage.pop_front();
ReleaseSRWLockExclusive(&_lock);
return temp;
}
|
c39bc0e29d42b12262691c0b6f7fd632e389eccf
|
07a41d98b4000326eb6e5b20e0115f71fb17854c
|
/interfacesimulator.h
|
9d4b70eab0b7d5e5012035d4672c5e5c600aa358
|
[
"MIT"
] |
permissive
|
mxsshao/nsb-sdd-lunar
|
c0022625a3b92497ac6855a20477841c95305531
|
14407a8f8d2ee9e1945285abbd5112d114020b2a
|
refs/heads/master
| 2020-04-14T07:14:45.515172
| 2019-01-08T09:14:26
| 2019-01-08T09:14:26
| 163,707,469
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,081
|
h
|
interfacesimulator.h
|
#pragma once
#include "global.h"
#include "statesimulator.h"
class CInterfaceSimulator : public Event::Handler
{
protected:
CInterfaceSimulator() {};
private:
ALLEGRO_FONT* font;
ALLEGRO_BITMAP* panel;
ALLEGRO_BITMAP* panelBG;
ALLEGRO_BITMAP* overhead;
float y;
float width;
float height;
ALLEGRO_BITMAP* throttle;
ALLEGRO_SAMPLE* switchSound;
ALLEGRO_BITMAP* switchUp;
ALLEGRO_BITMAP* switchDown;
float switchWidth;
float switchHeight;
ALLEGRO_BITMAP* nosmoking;
ALLEGRO_BITMAP* seatbelt;
float indicatorX;
float indicatorY;
float indicatorWidth;
float indicatorHeight;
Controls::Button* buttonNoSmoking;
Controls::Button* buttonSeatbelt;
ALLEGRO_BITMAP* warningEngine;
ALLEGRO_BITMAP* warning200;
ALLEGRO_BITMAP* warning100;
ALLEGRO_BITMAP* warning50;
ALLEGRO_BITMAP* warning40;
ALLEGRO_BITMAP* warning30;
ALLEGRO_BITMAP* warning20;
ALLEGRO_BITMAP* warning10;
ALLEGRO_SAMPLE* sound200;
ALLEGRO_SAMPLE* sound100;
ALLEGRO_SAMPLE* sound50;
ALLEGRO_SAMPLE* sound40;
ALLEGRO_SAMPLE* sound30;
ALLEGRO_SAMPLE* sound20;
ALLEGRO_SAMPLE* sound10;
ALLEGRO_SAMPLE* sound5;
float warningWidth;
bool w200;
bool w100;
bool w50;
bool w40;
bool w30;
bool w20;
bool w10;
bool w5;
bool fuelWarning;
bool fuelEmpty;
bool engineFailure;
bool bankAngle;
bool overSpeed;
bool sinkRate;
ALLEGRO_BITMAP* imageWarning;
ALLEGRO_BITMAP* imageWarningOn;
ALLEGRO_BITMAP* imageCaution;
ALLEGRO_BITMAP* imageCautionOn;
ALLEGRO_BITMAP* imageAvion;
ALLEGRO_BITMAP* imageAvionOn;
Controls::Button* buttonWarning;
Controls::Button* buttonCaution;
Controls::Button* buttonAvion;
void ButtonHoverEnter();
void ButtonHoverLeave();
void ButtonSwitchChanged();
void ButtonAvionChanged();
ALLEGRO_SAMPLE* victory;
void Retry();
void Exit();
public:
static CInterfaceSimulator MInterfaceSimulator;
void Load();
void Init();
void Resize();
void Cleanup();
void HandleEvents();
void Render();
bool GetFuelWarning() {return fuelWarning;};
bool GetFuelEmpty() {return fuelEmpty;};
void Pause();
void Crash();
void Landed();
};
|
f20c3f146f33592f37292fa9a7860d98c0b2f3c7
|
0408d086a3fd502113588a61b36755fe23f55b10
|
/code/16471 작은 수 내기.cpp
|
54ecb316cea5f6bf43cbfecd797478a9c5c46f58
|
[] |
no_license
|
dwax1324/baekjoon
|
6dfcf62f2b1643480b16777c37f4e5d711b932d9
|
3a6daf8a66dbb304af8a4002989c081dcffc831d
|
refs/heads/main
| 2023-04-03T03:56:50.410972
| 2021-03-29T11:51:30
| 2021-03-29T11:51:30
| 310,809,466
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 656
|
cpp
|
16471 작은 수 내기.cpp
|
// date: Wed Feb 24 17:00:52 2021
// author: dwax1324
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
//#define int int64_t
using namespace std;typedef pair<int,int> pii;typedef tuple<int,int,int> tii; typedef long long ll;
int32_t main(){ios_base::sync_with_stdio(0);cin.tie(0);
int N; cin >> N;
deque<int> v(N),v2(N);
for(int i=0; i< N; i++) cin >> v[i];
for(int i=0; i< N; i++) cin >> v2[i];
sort(all(v2));
sort(all(v));
int idx=0, idx2=0;
int cnt=0;
while(1){
if(idx == N || idx2==N) break;
if(v2[idx] > v[idx2]){
idx++;idx2++;cnt++;
}else{
idx++;
}
}
if(cnt >= (N+1)/2) cout << "YES";
else cout << "NO";
}
|
156779d7e8f2d39a4361cd434ebf84f8057edc29
|
99cf7ed46654fabf55b4bd0a4e16eb512177e5c3
|
/Projects/fluids_3d/Multiphase_Fire_Examples/MULTIPHASE_FIRE_EXAMPLES_UNIFORM.h
|
d0c836ae9a9f5a21e02a42ea9e97ff21af8f1555
|
[] |
no_license
|
byrantwithyou/PhysBAM
|
095d0483673f8ca7cee04390e98b7f5fa8d230ca
|
31d8fdc35dbc5ed90d6bd4fd266eb76e7611c4a5
|
refs/heads/master
| 2022-03-29T06:20:32.128928
| 2020-01-21T15:15:26
| 2020-01-21T15:15:26
| 187,265,883
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 20,125
|
h
|
MULTIPHASE_FIRE_EXAMPLES_UNIFORM.h
|
//#####################################################################
// Copyright 2005, Frank Losasso
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class MULTIPHASE_FIRE_EXAMPLES_UNIFORM
//#####################################################################
#ifndef __MULTIPHASE_FIRE_EXAMPLES_UNIFORM__
#define __MULTIPHASE_FIRE_EXAMPLES_UNIFORM__
#include <Tools/Interpolation/INTERPOLATION_CURVE.h>
#include <Tools/Parsing/PARAMETER_LIST.h>
#include <Grid_Tools/Computations/SMOOTH_UNIFORM.h>
#include <Grid_PDE/Boundaries/BOUNDARY.h>
#include <Geometry/Level_Sets/EXTRAPOLATION_UNIFORM.h>
#include <Dynamics/Level_Sets/PARTICLE_LEVELSET_EVOLUTION_MULTIPLE_UNIFORM.h>
#include <Dynamics/Solids_And_Fluids/SOLIDS_FLUIDS_EXAMPLE_UNIFORM.h>
namespace PhysBAM{
template<class TV>
class MULTIPHASE_FIRE_EXAMPLES_UNIFORM:public SOLIDS_FLUIDS_EXAMPLE_UNIFORM<TV>
{
typedef typename TV::SCALAR T;typedef VECTOR<int,TV::m> TV_INT;
public:
typedef SOLIDS_FLUIDS_EXAMPLE_UNIFORM<TV> BASE;
using BASE::fluids_parameters;using BASE::solids_parameters;using BASE::data_directory;using BASE::Adjust_Phi_With_Source;
using BASE::last_frame;using BASE::frame_rate;using BASE::write_output_files;using BASE::Get_Source_Reseed_Mask;using BASE::Get_Source_Velocities;
using BASE::viewer_dir;using BASE::restart;using BASE::solid_body_collection;using BASE::test_number;
using BASE::user_last_frame;
RIGID_BODY_COLLECTION<TV>& rigid_body_collection;
int air_region;
CYLINDER<T> inner_cylinder1,middle_cylinder1,outer_cylinder1;
CYLINDER<T> inner_cylinder2,middle_cylinder2,outer_cylinder2;
T source_shutoff_time;
T sphere_drop_time;
T reaction_bandwidth;
bool pseudo_dirichlet;
MULTIPHASE_FIRE_EXAMPLES_UNIFORM(const STREAM_TYPE stream_type_input,PARSE_ARGS& parse_args)
:SOLIDS_FLUIDS_EXAMPLE_UNIFORM<TV>(stream_type_input,parse_args,0,fluids_parameters.FIRE),
rigid_body_collection(solid_body_collection.rigid_body_collection),pseudo_dirichlet(false)
{
parse_args.Add("-pseudo_dirichlet",&pseudo_dirichlet,"pseudo_dirichlet");
parse_args.Parse();
fluids_parameters.Initialize_Number_Of_Regions(Number_Of_Regions(test_number));
fluids_parameters.write_particles=true;
PARAMETER_LIST parameters;
fluids_parameters.use_reacting_flow=true;
fluids_parameters.domain_walls[0][0]=true;fluids_parameters.domain_walls[0][1]=true;fluids_parameters.domain_walls[1][1]=false;fluids_parameters.domain_walls[1][0]=true;
fluids_parameters.domain_walls[2][0]=true;fluids_parameters.domain_walls[2][1]=true;
if(!user_last_frame) last_frame=512;
if(!this->user_frame_rate) frame_rate=96;
fluids_parameters.temperature_container.Set_Ambient_Temperature(T(283.15));fluids_parameters.temperature_container.Set_Cooling_Constant((T)4000);
fluids_parameters.density_container.Set_Ambient_Density(0);
fluids_parameters.temperature_products=3000;fluids_parameters.temperature_fuel=298;
fluids_parameters.temperature_buoyancy_constant=0;
fluids_parameters.use_vorticity_confinement_fuel=fluids_parameters.use_vorticity_confinement=false;
fluids_parameters.write_debug_data=fluids_parameters.write_velocity=true;
if(test_number==1){
fluids_parameters.incompressible_iterations=100;
fluids_parameters.densities(1)=(T)1000;fluids_parameters.densities(2)=(T)1;
fluids_parameters.normal_flame_speeds(1,2)=fluids_parameters.normal_flame_speeds(2,1)=(T).0003;
fluids_parameters.fuel_region(1)=true;
fluids_parameters.use_flame_speed_multiplier=true;
fluids_parameters.confinement_parameters(2)=(T).2;
air_region=2;}
else if(test_number==2){
fluids_parameters.incompressible_iterations=100;
fluids_parameters.reseeding_frame_rate=10;
fluids_parameters.densities(1)=(T)1000;fluids_parameters.densities(2)=(T)800;fluids_parameters.densities(3)=(T)2000;fluids_parameters.densities(4)=(T)1;
fluids_parameters.normal_flame_speeds(2,4)=fluids_parameters.normal_flame_speeds(4,2)=(T).0003;
fluids_parameters.normal_flame_speeds(3,4)=fluids_parameters.normal_flame_speeds(4,3)=(T).0001;
fluids_parameters.fuel_region(2)=true;fluids_parameters.fuel_region(3)=true;
fluids_parameters.viscosities(3)=50;
fluids_parameters.implicit_viscosity=true;
fluids_parameters.use_flame_speed_multiplier=true;
fluids_parameters.confinement_parameters(4)=(T).2;
fluids_parameters.temperature_buoyancy_constant=(T)0.01;
if(pseudo_dirichlet) fluids_parameters.pseudo_dirichlet_regions(4)=true;
inner_cylinder1.Set_Endpoints(VECTOR<T,3>(0,(T).55,(T).3),VECTOR<T,3>((T).1,(T).55,(T).3));inner_cylinder1.radius=(T).06;
middle_cylinder1.Set_Endpoints(VECTOR<T,3>(0,(T).55,(T).3),VECTOR<T,3>((T).1,(T).55,(T).3));middle_cylinder1.radius=(T).09;
outer_cylinder1.Set_Endpoints(VECTOR<T,3>(0,(T).55,(T).3),VECTOR<T,3>((T).099,(T).55,(T).3));outer_cylinder1.radius=(T).1;
source_shutoff_time=(T)2.5+(T)1e-5;
sphere_drop_time=(T)2.9+(T)1e-5;
air_region=4;}
else if(test_number==3){
fluids_parameters.implicit_viscosity_iterations=50;
fluids_parameters.implicit_viscosity=true;
if(!this->user_frame_rate) frame_rate=48;
fluids_parameters.densities(1)=(T)2000;
fluids_parameters.viscosities(1)=(T)200;
fluids_parameters.densities(2)=(T)2000;
fluids_parameters.viscosities(2)=(T)200;
fluids_parameters.densities(3)=(T)1000;
fluids_parameters.densities(4)=(T)50;
//fluids_parameters.surface_tensions(4,1)=fluids_parameters.surface_tensions(1,4)=(T)50;
//fluids_parameters.surface_tensions(4,2)=fluids_parameters.surface_tensions(2,4)=(T)50;
fluids_parameters.surface_tensions(4,3)=fluids_parameters.surface_tensions(3,4)=(T)10;
fluids_parameters.normal_flame_speeds(1,2)=fluids_parameters.normal_flame_speeds(2,1)=(T).01;
fluids_parameters.normal_flame_speeds(1,1)=fluids_parameters.normal_flame_speeds(2,2)=(T).01;
fluids_parameters.fuel_region(1)=true;
fluids_parameters.fuel_region(2)=true;
fluids_parameters.use_flame_speed_multiplier=true;
fluids_parameters.reseeding_frame_rate=5;
//fluids_parameters.cfl/=2;
reaction_bandwidth=2;
inner_cylinder1.Set_Endpoints(VECTOR<T,3>(0,(T).2,(T).5),VECTOR<T,3>((T).1,(T).2,(T).5));inner_cylinder1.radius=(T).1;
outer_cylinder1.Set_Endpoints(VECTOR<T,3>(0,(T).2,(T).5),VECTOR<T,3>((T).099,(T).2,(T).5));outer_cylinder1.radius=(T).11;
inner_cylinder2.Set_Endpoints(VECTOR<T,3>((T).9,(T).2,(T).5),VECTOR<T,3>((T)1,(T).2,(T).5));inner_cylinder2.radius=(T).1;
outer_cylinder2.Set_Endpoints(VECTOR<T,3>((T).899,(T).2,(T).5),VECTOR<T,3>((T)1,(T).2,(T).5));outer_cylinder2.radius=(T).11;}
else if(test_number==4){
fluids_parameters.incompressible_iterations=100;
fluids_parameters.reseeding_frame_rate=10;
fluids_parameters.densities(1)=(T)1000;fluids_parameters.densities(2)=(T)800;fluids_parameters.densities(3)=(T)2000;fluids_parameters.densities(4)=(T)1;
fluids_parameters.normal_flame_speeds(2,4)=fluids_parameters.normal_flame_speeds(4,2)=(T).0003;
fluids_parameters.normal_flame_speeds(3,4)=fluids_parameters.normal_flame_speeds(4,3)=(T).0001;
fluids_parameters.fuel_region(2)=true;fluids_parameters.fuel_region(3)=true;
fluids_parameters.viscosities(3)=50;
fluids_parameters.implicit_viscosity=true;
fluids_parameters.use_flame_speed_multiplier=true;
fluids_parameters.confinement_parameters(4)=(T).2;
fluids_parameters.temperature_buoyancy_constant=(T)0.01;
if(pseudo_dirichlet) fluids_parameters.pseudo_dirichlet_regions(4)=true;
inner_cylinder1.Set_Endpoints(VECTOR<T,3>(0,(T).55,(T).3),VECTOR<T,3>((T).1,(T).55,(T).3));inner_cylinder1.radius=(T).06;
middle_cylinder1.Set_Endpoints(VECTOR<T,3>(0,(T).55,(T).3),VECTOR<T,3>((T).1,(T).55,(T).3));middle_cylinder1.radius=(T).09;
outer_cylinder1.Set_Endpoints(VECTOR<T,3>(0,(T).55,(T).3),VECTOR<T,3>((T).099,(T).55,(T).3));outer_cylinder1.radius=(T).1;
source_shutoff_time=(T)2.5+(T)1e-5;
sphere_drop_time=(T)2.9+(T)1e-5;
air_region=4;}
}
virtual ~MULTIPHASE_FIRE_EXAMPLES_UNIFORM()
{}
//#####################################################################
// Function Number_Of_Regions
//#####################################################################
static int Number_Of_Regions(int test_number)
{
if(test_number==1) return 2;
if(test_number==2) return 4;
if(test_number==3) return 4;
LOG::cout<<"Unrecognized example: "<<test_number<<std::endl;
assert(false);exit(0);
}
//#####################################################################
// Function Initialize_Bodies
//#####################################################################
void Initialize_Bodies() override
{
}
//#####################################################################
// Function Get_Flame_Speed_Multiplier
//#####################################################################
void Get_Flame_Speed_Multiplier(const T dt,const T time) override
{
ARRAY<T,FACE_INDEX<TV::m> >& flame_speed_multiplier=fluids_parameters.incompressible->projection.flame_speed_multiplier;
flame_speed_multiplier.Fill(0);
if(test_number==1){
for(FACE_ITERATOR<TV> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next())
if((T).45<iterator.Location().x && iterator.Location().x<=(T).55 && (TV::m==2 || ((T).45<iterator.Location().z && iterator.Location().z<=(T).55)))
flame_speed_multiplier.Component(iterator.Axis())(iterator.Face_Index())=1;}
else if(test_number==2){
for(FACE_ITERATOR<TV> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next())
if(time<sphere_drop_time && SPHERE<TV>(VECTOR<T,3>((T).25,(T).6,(T).75),(T).08).Lazy_Inside(iterator.Location()))
flame_speed_multiplier.Component(iterator.Axis())(iterator.Face_Index())=1;}
else if(test_number==3){
ARRAY<ARRAY<T,VECTOR<int,3> > >& phis=fluids_parameters.particle_levelset_evolution_multiple->phis;
T reaction_bandwidth_times_edge_length=reaction_bandwidth*fluids_parameters.grid->dX.Min();
ARRAY<T,TV_INT>& phi1=phis(1);
//LEVELSET<TV> levelset1(fluids_parameters.grid,phi1);
//levelset1.Set_Band_Width(2*reaction_bandwidth_times_edge_length+fluids_parameters.grid.dX.Min());levelset1.Fast_Marching_Method();
ARRAY<T,TV_INT>& phi2=phis(2);
//LEVELSET<TV> levelset2(fluids_parameters.grid,phi2);
//levelset2.Set_Band_Width(2*reaction_bandwidth_times_edge_length+fluids_parameters.grid.dX.Min());levelset2.Fast_Marching_Method();
for(FACE_ITERATOR<TV> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){
VECTOR<int,3> cell1=iterator.First_Cell_Index(),cell2=iterator.Second_Cell_Index();
T face_phi1=(T).5*(phi1(cell1)+phi1(cell2)),face_phi2=(T).5*(phi2(cell1)+phi2(cell2));
if(face_phi1<reaction_bandwidth_times_edge_length && face_phi2<reaction_bandwidth_times_edge_length){
T min_phi=min(face_phi1,face_phi2);
flame_speed_multiplier.Component(iterator.Axis())(iterator.Face_Index())=clamp(reaction_bandwidth_times_edge_length+min_phi,(T)0,(T)1);}}
return;}
T ignition_temperature=1075; // 1100 is .5 as fast as 1000, 1150 is .25 as fast as 1000.
ARRAY<T,TV_INT> temp_temperature(fluids_parameters.grid->Domain_Indices(3));
BOUNDARY<TV,T> boundary;boundary.Fill_Ghost_Cells(*fluids_parameters.grid,fluids_parameters.temperature_container.temperature,temp_temperature,dt,time,3);
SMOOTH::Smooth<T,TV::m>(temp_temperature,5,0);
if(fluids_parameters.mpi_grid) fluids_parameters.mpi_grid->Exchange_Boundary_Cell_Data(temp_temperature,1);
for(FACE_ITERATOR<TV> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){
T face_temperature=(T).5*(temp_temperature(iterator.First_Cell_Index())+temp_temperature(iterator.Second_Cell_Index()));
if(face_temperature>ignition_temperature) flame_speed_multiplier.Component(iterator.Axis())(iterator.Face_Index())=clamp((T).01*(face_temperature-ignition_temperature),(T)0,(T)1);}
}
//#####################################################################
// Function Set_Ghost_Density_And_Temperature_Inside_Flame_Core
//#####################################################################
void Set_Ghost_Density_And_Temperature_Inside_Flame_Core() override
{
if(test_number==3) return;
ARRAY<T,TV_INT> phi;LEVELSET<TV> levelset(*fluids_parameters.grid,phi);
ARRAY<T,FACE_INDEX<TV::m> >& flame_speed_multiplier=fluids_parameters.incompressible->projection.flame_speed_multiplier;
TEMPERATURE_CONTAINER<TV>& temperature=fluids_parameters.temperature_container;
DENSITY_CONTAINER<TV>& density=fluids_parameters.density_container;
fluids_parameters.particle_levelset_evolution_multiple->particle_levelset_multiple.levelset_multiple.Get_Single_Levelset(fluids_parameters.fuel_region,levelset,false);
T bandwidth=2*fluids_parameters.grid->dX.Min();
for(CELL_ITERATOR<TV> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){TV_INT index=iterator.Cell_Index();
T cell_flame_speed_multiplier=0;
for(int i=0;i<TV::m;i++)
cell_flame_speed_multiplier+=flame_speed_multiplier.Component(i)(iterator.First_Face_Index(i))+flame_speed_multiplier.Component(i)(iterator.Second_Face_Index(i));
cell_flame_speed_multiplier/=2*TV::m;
if(-phi(index)<0){
if(-bandwidth<-phi(index) && fluids_parameters.particle_levelset_evolution_multiple->Levelset(air_region).phi(index)<bandwidth){
temperature.temperature(index)=LINEAR_INTERPOLATION<T,T>::Linear(temperature.ambient_temperature,fluids_parameters.temperature_products,cell_flame_speed_multiplier);
density.density(index)=LINEAR_INTERPOLATION<T,T>::Linear(density.ambient_density,fluids_parameters.density,cell_flame_speed_multiplier);}
else temperature.temperature(index)=temperature.ambient_temperature;}}
}
//#####################################################################
// Function Initialize_Phi
//#####################################################################
void Initialize_Phi() override
{
ARRAY<ARRAY<T,TV_INT>>& phis=fluids_parameters.particle_levelset_evolution_multiple->phis;
if(test_number==1){
for(CELL_ITERATOR<TV> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next())
phis(1)(iterator.Cell_Index())=iterator.Location().y-(T).2;
phis(2).Copy(-1,phis(1));}
if(test_number==2){
for(CELL_ITERATOR<TV> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){
TV X=iterator.Location();TV_INT cell=iterator.Cell_Index();
phis(1)(cell)=X.y-(T).2;
phis(2)(cell)=1;
phis(3)(cell)=SPHERE<TV>(VECTOR<T,3>((T).25,(T).6,(T).75),(T).08).Signed_Distance(X);
phis(4)(cell)=-min(phis(1)(cell),phis(2)(cell),phis(3)(cell));}}
if(test_number==3){
for(CELL_ITERATOR<TV> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){
VECTOR<T,3> X=iterator.Location();VECTOR<int,3> cell=iterator.Cell_Index();
phis(1)(cell)=1;
phis(2)(cell)=1;
phis(3)(cell)=X.y-(T).35;
phis(4)(cell)=-min(phis(1)(cell),phis(2)(cell),phis(3)(cell));}}
}
//#####################################################################
// Function Initialize_Advection
//#####################################################################
void Initialize_Advection() override
{
fluids_parameters.Use_No_Fluid_Coupling_Defaults();
}
//#####################################################################
// Function Adjust_Phi_With_Sources
//#####################################################################
bool Adjust_Phi_With_Sources(const T time) override
{
if(test_number==2){
if(time<source_shutoff_time) Adjust_Phi_With_Source(inner_cylinder1,2,MATRIX<T,4>::Identity_Matrix());
else if(time<source_shutoff_time+((T)1./frame_rate)) Adjust_Phi_With_Source(inner_cylinder1,4,MATRIX<T,4>::Identity_Matrix());
if(time<sphere_drop_time) Adjust_Phi_With_Source(SPHERE<TV>(VECTOR<T,3>((T).25,(T).6,(T).75),(T).08),3,MATRIX<T,4>::Identity_Matrix());}
if(test_number==3){
Adjust_Phi_With_Source(inner_cylinder1,1,MATRIX<T,4>::Identity_Matrix());
Adjust_Phi_With_Source(inner_cylinder2,2,MATRIX<T,4>::Identity_Matrix());
ARRAY<ARRAY<T,VECTOR<int,3> > >& phis=fluids_parameters.particle_levelset_evolution_multiple->phis;
T reaction_seed_bandwidth=(T).5*reaction_bandwidth*fluids_parameters.grid->dX.Min();
for(CELL_ITERATOR<TV> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){
VECTOR<int,3> cell=iterator.Cell_Index();
T band=max(fabs(phis(1)(cell)),fabs(phis(2)(cell)))-reaction_seed_bandwidth;
int region1,region2;T min_phi1,min_phi2;
fluids_parameters.particle_levelset_evolution_multiple->particle_levelset_multiple.levelset_multiple.Two_Minimum_Regions(cell,region1,region2,min_phi1,min_phi2);
if(min_phi1<-3*fluids_parameters.grid->dX.Min()) continue;
//if(!(region1==1 && region2==2 || region1==2 && region2==1)) continue;
phis(1)(cell)=max(phis(1)(cell),-band);
phis(2)(cell)=max(phis(2)(cell),-band);
phis(3)(cell)=max(phis(3)(cell),-band);
phis(4)(cell)=min(phis(4)(cell),band);}}
return false;
}
//#####################################################################
// Function Get_Source_Reseed_Mask
//#####################################################################
void Get_Source_Reseed_Mask(ARRAY<bool,VECTOR<int,3> >*& cell_centered_mask,const T time) override
{
bool first=true;
if(test_number==2 && time<source_shutoff_time){
Get_Source_Reseed_Mask(inner_cylinder1,MATRIX<T,4>::Identity_Matrix(),cell_centered_mask,first);first=false;}
}
//#####################################################################
// Function Get_Source_Velocities
//#####################################################################
void Get_Source_Velocities(ARRAY<T,FACE_INDEX<TV::m> >& face_velocities,ARRAY<bool,FACE_INDEX<TV::m> >& psi_N,const T time) override
{
if(test_number==2){
Get_Source_Velocities(outer_cylinder1,MATRIX<T,4>::Identity_Matrix(),VECTOR<T,3>());
if(time<source_shutoff_time)
Get_Source_Velocities(middle_cylinder1,MATRIX<T,4>::Identity_Matrix(),VECTOR<T,3>(2.5,0,0));
if(time<sphere_drop_time)
Get_Source_Velocities(SPHERE<TV>(VECTOR<T,3>((T).25,(T).6,(T).75),(T).08),MATRIX<T,4>::Identity_Matrix(),VECTOR<T,3>());}
if(test_number==3){
Get_Source_Velocities(outer_cylinder1,MATRIX<T,4>::Identity_Matrix(),VECTOR<T,3>());
Get_Source_Velocities(outer_cylinder2,MATRIX<T,4>::Identity_Matrix(),VECTOR<T,3>());
Get_Source_Velocities(inner_cylinder1,MATRIX<T,4>::Identity_Matrix(),VECTOR<T,3>((T).2,0,0));
Get_Source_Velocities(inner_cylinder2,MATRIX<T,4>::Identity_Matrix(),VECTOR<T,3>(-(T).2,0,0));}
}
//#####################################################################
};
}
#endif
|
5d19366dfe505f0e4c652fa089e57b8663c99d3f
|
72e2e38d8c640a2a036cce733146070f99ff5312
|
/include/systems/RenderSystem.h
|
bb87086236c037ab16978488b95dea8f051723f1
|
[] |
no_license
|
Morrantho/dynecs
|
80041399ba361ec77afe52666af892330b5ee7ff
|
3ff59b32d34e21fdd7e0edfbaa94a86ad68d654a
|
refs/heads/master
| 2020-04-07T04:06:14.885102
| 2018-11-19T00:55:24
| 2018-11-19T00:55:24
| 158,039,976
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 255
|
h
|
RenderSystem.h
|
#ifndef DX_RENDERSYSTEM_H
#define DX_RENDERSYSTEM_H
namespace dx
{
class RenderSystem : public dx::System
{
public:
RenderSystem(unsigned long mask): System(mask) {}
void Tick()
{
}
void Render()
{
}
};
}
#endif // DX_RENDERSYSTEM_H
|
7ffddf11e2ba81ca459221d9dc270d3f49fb3104
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/curl/gumtree/curl_repos_function_1465_curl-7.51.0.cpp
|
3154cec5e2520994709ade0768e54c52e80e187f
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 173
|
cpp
|
curl_repos_function_1465_curl-7.51.0.cpp
|
static unsigned __int64 smb_swap64(unsigned __int64 x)
{
return ((unsigned __int64) smb_swap32((unsigned int) x) << 32) |
smb_swap32((unsigned int) (x >> 32));
}
|
83c4b473b5da17038afe43081040d4a66ab0186d
|
52331ef2679a899d98826b7308305daf16d90a1d
|
/src/game_shared/towers/BaseTower.h
|
6029b8fea95902810e15c564679f8e0981cf17de
|
[] |
no_license
|
joetex/SourceTowers
|
2ab7f27f9c464eaa4f41388b53fa070452ad976c
|
f9e40c60ca0362fad663cd21da95cbfdf1f217fa
|
refs/heads/master
| 2021-05-29T01:02:05.127433
| 2015-03-20T08:04:16
| 2015-03-20T08:04:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,963
|
h
|
BaseTower.h
|
#ifndef TOWER_ENTITY_H
#define TOWER_ENTITY_H
#ifdef CLIENT_DLL
#define CBaseTower C_BaseTower
#define CSDKPlayer C_SDKPlayer
#endif
#include "towers/BaseClickable.h"
//#include "towers/BaseProjectile.h"
#include "towers/tower_shareddef.h"
class CSDKPlayer;
class CBaseTower : public CBaseClickable
{
public:
CBaseTower();
~CBaseTower(){};
DECLARE_CLASS( CBaseTower, CBaseClickable );
DECLARE_NETWORKCLASS();
#ifdef CLIENT_DLL
void Spawn( void );
void ClientThink( void );
//Selection Drawing Helpers
void DrawCircle( const char *szMaterial, const Vector &origin, int radius, Vector vColor=Vector(1,1,1), float alpha=1 );
void DrawCircle( const Vector &origin, bool buildable );
CBaseEntity *FindByGroup( CBaseEntity *pEnt, int collisionGroup );
void DrawSurroundingTowerPalettes(const Vector &origin);
inline bool ShouldCheck() { return (GetOwnerEntity() == C_BasePlayer::GetLocalPlayer()); };
//Add ourselves to players list of their towers.
virtual void OnDataChanged( DataUpdateType_t updateType );
//Predict our origin so we don't get laggy movements!
virtual const Vector& GetRenderOrigin( void );
Vector m_vecRadiusCenter;
bool m_bHasOwner;
bool m_bDrawPalette;
//Draw our selection/hover displays
virtual void PreDraw( C_SDKPlayer *localPlayer, bool bSelected, bool bHovered );
virtual void PostDraw( C_SDKPlayer *localPlayer, bool bSelected, bool bHovered );
virtual void OnHover( CSDKPlayer *sdkPlayer );
virtual void Selected( CSDKPlayer *sdkPlayer );
void ClearPalettes();
#else
virtual void FireProjectile( CBaseEntity *pEnemy ) =0;
virtual void Spawn( void );
virtual bool Upgrade( void );
virtual int Sell( void );
virtual int Cost( void );
virtual void AddLevel( const char *szModel, int cost, int radius, int damage, int speed, float attackrate, const QAngle &angle = QAngle(0,0,0));
virtual void UpdateTower();
virtual void SeekEnemy();
static CBaseTower *CreateTower( CBaseEntity *pOwner, int type )//const char *weapName )
{
if(type < 0 || type > MAX_TOWERS)
return NULL;
CBaseTower *pObject = (CBaseTower *)CreateEntityByName( g_TowerTypes[type] );//static_cast< CMKSProjectile * > (CreateEntityByName( ItemWeaponNames[curweap] ) );
if(!pObject)
return NULL;
pObject->Spawn();
pObject->SetOwnerEntity( pOwner );
return pObject;
}
#endif
void BuildingPlacement( CSDKPlayer *pPlayer );
virtual void OnBuilt( CSDKPlayer *pPlayer );
virtual int GetClickType() { return CLICK_BUILDING; };
void TraceBBox( const Vector& start, const Vector& end, ITraceFilter *pFilter, trace_t& pm );
//Accessors
public:
bool IsSelected() { return m_bSelected; };
bool IsBuilt() { return m_bBuilt; };
void SetBuilt( bool built ) { m_bBuilt = built; };
float GetNextAttack() { return m_flNextAttackTime; };
int GetRadius() { return m_iRadius; };
int GetLevel() { return m_iLevel; };
int GetMaxLevel() { return m_iMaxLevel; };
bool IsMaxLevel() { return m_iMaxLevel == m_iLevel; }
int GetTowerType() { return m_iTowerType; };
int GetUpgradeCost() { return m_iUpgradeCost; };
int GetProjDamage() { return m_iDamage; };
int GetProjSpeed() { return m_iSpeed; };
//Variables
public:
CUtlVector< char * >m_szModels;
CNetworkVar( int, m_iMaxLevel );
CNetworkVar( bool, m_bSelected );
CNetworkVar( bool, m_bBuilt );
float m_flNextAttackTime;
CNetworkVar( int, m_iTowerType );
CNetworkVar( int, m_iUpgradeCost);
CNetworkVar( int, m_iRadius );
CNetworkVar( int, m_iLevel );
CNetworkVar( int, m_iDamage );
CNetworkVar( int, m_iSpeed );
CNetworkVar( float, m_flAttackDelay );
CUtlVector< LevelInfo_t >m_sLevelInfo;
bool m_bCanBuild;
char *m_szName;
int m_iTowerID;
};
//Create a list of selectables in this filter, don't touch anything.
class CTraceFilterSELECTABLEMULTI : public CTraceFilter
{
DECLARE_CLASS_NOBASE( CTraceFilterSELECTABLEMULTI );
public:
CTraceFilterSELECTABLEMULTI() {};
virtual bool ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
{
CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity );
if(pEntity)
if ( pEntity->GetFlags() & FL_IS_SELECTABLE )
{
m_pSelected.AddToTail( pEntity );
return false;
}
return false;
}
virtual TraceType_t GetTraceType() const
{
return TRACE_ENTITIES_ONLY;
}
private:
CUtlVector< CBaseEntity * >m_pSelected;
};
//Single target selecting
class CTraceFilterSELECTABLE : public CTraceFilter
{
DECLARE_CLASS_NOBASE( CTraceFilterSELECTABLE );
public:
CTraceFilterSELECTABLE() {};
virtual bool ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
{
CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity );
if(pEntity)
if ( pEntity->GetFlags() & FL_IS_SELECTABLE )
return true;
return false;
}
virtual TraceType_t GetTraceType() const
{
return TRACE_EVERYTHING;
}
};
//Used to find ground to place our entities, and nothing else.
class CTraceFilterWORLDSPECIAL : public CTraceFilter
{
DECLARE_CLASS_NOBASE( CTraceFilterWORLDSPECIAL );
public:
CTraceFilterWORLDSPECIAL( IHandleEntity *pEnt )
{
m_pOriginalEnt = pEnt;
};
virtual bool ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
{
if(!pHandleEntity)
return false;
if(m_pOriginalEnt == pHandleEntity)
return false;
CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity );
if(pEntity)
{
int collision = pEntity->GetCollisionGroup();
if( collision == COLLISION_GROUP_TOWERS_PATH )
return true;
if(pEntity->IsBSPModel())
return true;
}
return false;
}
virtual TraceType_t GetTraceType() const
{
return TRACE_EVERYTHING;
}
private:
IHandleEntity *m_pOriginalEnt;
};
//Used to find if our tower is in a buildable location.
class CTraceFilterCHECKBUILD : public CTraceFilter
{
DECLARE_CLASS_NOBASE( CTraceFilterCHECKBUILD );
public:
CTraceFilterCHECKBUILD( IHandleEntity *pEnt )
{
m_pOriginalEnt = pEnt;
m_bCanBuild = true;
};
virtual bool ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
{
if(pHandleEntity == m_pOriginalEnt)
return false;
CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity );
if(pEntity)
{
int collision = pEntity->GetCollisionGroup();
if( collision == COLLISION_GROUP_TOWERS_NOBUILD || collision == COLLISION_GROUP_TOWER )
{
m_bCanBuild = false;
}
if(collision == COLLISION_GROUP_TOWERS_PATH )
{
m_bCanBuild = false;
return true;
}
if(pEntity->IsBSPModel())
return true;
}
return false;
}
virtual TraceType_t GetTraceType() const
{
return TRACE_EVERYTHING;
}
public:
bool m_bCanBuild;
IHandleEntity *m_pOriginalEnt;
};
inline CBaseTower *ToBaseTower( CBaseEntity *pEntity )
{
if ( !pEntity || pEntity->GetCollisionGroup() != COLLISION_GROUP_TOWER )
return NULL;
#ifdef _DEBUG
Assert( dynamic_cast<CBaseTower*>( pEntity ) != 0 );
#endif
return static_cast< CBaseTower* >( pEntity );
}
#endif //TOWER_ENTITY_H
|
d3d8f1b12d7dbb8e9d5bf28dce021c8b9027431a
|
3e9586251881de92404aa4ba875d82598c024020
|
/src/WindSpd.h
|
9bd758464222b95145f2a4de62f916fd7f8ba938
|
[] |
no_license
|
ArcticSnowSky/MeteoStation
|
b138d336e2491b403b77047cbacd7b1e87890e2d
|
af0353bf4e2df87b33836ec178944b6ba5cb6056
|
refs/heads/master
| 2023-05-31T21:21:36.334975
| 2021-06-14T17:57:35
| 2021-06-14T17:57:35
| 376,912,998
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 688
|
h
|
WindSpd.h
|
#ifndef __WIND_SPD_H__
#define __WIND_SPD_H__
#include <Arduino.h>
//#include "utils.h"
class WindSpd {
public:
static float calcWindSpd_ms(unsigned long impulse, unsigned long time_ms) {
return time_ms > 0 ? WindSpd::windFaktor_ms * impulse / time_ms : 0;
}
static float calcWindSpd_kmh(unsigned long impulse, unsigned long time_ms) {
return time_ms > 0 ? WindSpd::windFaktor_kmh * impulse / time_ms : 0;
}
protected:
static constexpr float windFaktor_ms = 8640; // Anemometer: 1 imp /sec = 8.64m/s. Faktor = 2.4 * 3.6 * 1000
static constexpr float windFaktor_kmh= 2400; // Anemometer: 1 imp /sec = 2.4km/h. Faktor = 2.4 * 1000
};
#endif
|
d38e61bafff8b7a5aaabad852da2cd974e5023b9
|
66864fc26b43f66169f6fc4518cf332842da5408
|
/final/GPS.cpp
|
268985b6d7e529754fc801b7a24b048cdb897315
|
[] |
no_license
|
benoitphilippe/GPS_arduino
|
54e9a8b75195d79396f5a0427b6e985a9dcd3533
|
0a5e86b789be797db3a708238d727950a43ee360
|
refs/heads/master
| 2020-03-10T12:44:27.674677
| 2018-06-20T17:33:49
| 2018-06-20T17:33:49
| 129,384,486
| 0
| 1
| null | 2018-06-12T15:24:23
| 2018-04-13T10:04:03
|
C++
|
UTF-8
|
C++
| false
| false
| 3,790
|
cpp
|
GPS.cpp
|
#include "GPS.h"
/**
* Finaly, after experimentation, all the angle stuffs are useless.
* It is more convenient to limit DISTANCE_ERROR_TOLERANCE to 2 metters
* in order to detect absence of movement.
* This code can evaluate with precision total disctance by local movement.
*/
bool getGPSData(){
static unsigned long timeLastMesure = 0; // control time
static float m_flat = 0.0f, m_flon = 0.0f; // medium position computes in acquisition time
static float m_falt = 0.0f; // la moyenne de l'altitude
static byte npoints = 0; // points number in acquisition
float l_flat, l_flon; // in fonction latitude and longitude
float l_falt;
while (ss.available())
{
char c = ss.read();
//Serial.write(c); // uncomment this line if you want to see the GPS data flowing
if (gps.encode(c)){ // Did a new valid sentence come in?
if (millis() - timeLastMesure > ACQUISITION_TIME){ // over acquisition time
gps.f_get_position(&l_flat, &l_flon, &age); // get current position
l_falt = gps.f_altitude(); // get current altitude
// update one last time medium position
if (npoints == 0){ // first point case
m_flat = l_flat;
m_flon = l_flon;
m_falt = l_falt;
}
else{ // computes medium position
npoints++;
// medium position : m_Xk = m_X(k-1) + (Xk - m_X(k-1))/k
m_flat = m_flat + (l_flat - m_flat)/((float)npoints);
m_flon = m_flon + (l_flon - m_flon)/((float)npoints);
m_falt = m_falt + (l_falt - m_falt)/((float)npoints);
}
gps.get_datetime(&date, &time, &age);// time in hhmmsscc, date in ddmmyy
timeLastMesure = millis(); // update time mesure
// get distance between two points
if (flat != 0.0f && flon != 0.0f){
l_distance = TinyGPS::distance_between(m_flat, m_flon, flat, flon);
// check for validity of distance
if(l_distance < DISTANCE_ERROR_TOLERANCE){ // distance is low
l_distance = 0; // we suppose position is'nt moving
}
}
// update last medium position with new medium position
flat = m_flat;
flon = m_flon;
falt = m_falt;
npoints = 0; // reset medium computage
return true; // notify next position is ready
}
else { // in acquisition time
gps.f_get_position(&l_flat, &l_flon, &age); // get current position
l_falt = gps.f_altitude(); // get current altitude
// add position in medium position, and statdard deviation
if (npoints == 0){ // first point case
// initiate all datas
m_flat = l_flat;
m_flon = l_flon;
m_falt = l_falt;
npoints++;
}
else{ // computes medium position
npoints++;
// m_Xk = m_X(k-1) + (Xk - m_X(k-1))/k
m_flat = m_flat + (l_flat - m_flat)/((float)npoints);
m_flon = m_flon + (l_flon - m_flon)/((float)npoints);
m_falt = m_falt + (l_falt - m_falt) / ((float)npoints);
}
// still in acquisition time, so no data to return yet
return false;
}
}
}
// no valid sentence come in
return false;
}
|
79475f8b56ea052579acf7f6a227cec7b1856f5c
|
4875e9e457a5c8d97a9bacf45d5b328d96c3cb19
|
/src/main/g8/appFW/appFW.cpp
|
343e26a1871a881fd8c9c76229c01ab09d1fb9bc
|
[] |
no_license
|
domdere/cppSkeleton.g8
|
c292c30ec1e666908d9193e84204e466b51ac380
|
705e5094599acd16f9093e3e7512701e8e437244
|
refs/heads/master
| 2021-01-17T07:09:12.398006
| 2013-09-10T03:36:45
| 2013-09-10T03:36:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 36
|
cpp
|
appFW.cpp
|
#include "appFW/consoleAppMain.hpp"
|
6b70de95d7fbf250145910cca2ff9da4d48ff506
|
e28f2a1e39f48015f5ec62b71c3ec5a93ad5573e
|
/oj/poj/poj_2337.cpp
|
c871b7fdea24b996975fc71a8ebfbe66c043ece9
|
[] |
no_license
|
james47/acm
|
22678d314bcdc3058f235443281a5b4abab2660d
|
09ad1bfc10cdd0af2d56169a0bdb8e0f22cba1cb
|
refs/heads/master
| 2020-12-24T16:07:28.284304
| 2016-03-13T15:16:48
| 2016-03-13T15:16:48
| 38,529,014
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,961
|
cpp
|
poj_2337.cpp
|
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct edge{
int from, to, u;
char str[50];
bool operator < (const edge a) const{
return strcmp(str, a.str) < 0;
}
} e[2000];
int n, cnt, ru[30], ch[30], f[30];
char ans[1500][50];
bool c[30];
int getf(int x)
{
if (x == f[x]) return x;
f[x] = getf(f[x]);
return f[x];
}
void unionxy(int x, int y)
{
int xroot = getf(x),
yroot = getf(y);
f[xroot] = yroot;
}
void dfs(int st)
{
for (int i = 0; i < n; i ++){
if (e[i].from == st && !e[i].u){
e[i].u = true;
dfs(e[i].to);
strcpy(ans[cnt], e[i].str);
cnt++;
}
}
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
memset(c, 0, sizeof(c));
memset(ru, 0, sizeof(ru));
memset(ch, 0, sizeof(ch));
for (int i = 0; i < 26; i++)
f[i] = i;
for (int i = 0; i < n; i++){
scanf("%s", e[i].str);
int x = e[i].str[0] - 'a',
y = e[i].str[strlen(e[i].str)-1] - 'a';
e[i].from = x;
e[i].to = y;
e[i].u = false;
ch[x]++; ru[y]++;
c[x] = true; c[y] = true;
unionxy(x, y);
}
cnt = 0;
for (int i = 0 ; i < 26; i++)
if (c[i] && f[i] == i) cnt ++;
if (cnt > 1){
puts("***");
continue;
}
sort(e, e+n);
/*wa
int st = 0;
for (int i = 25; i >= 0; i--)
if (c[i] && ch[i] - ru[i] == 1) st = i;
cnt = 0;
*/
int flag1 = 0, flag2 = 0, key = 0;
int st, ed;
for (int t = 25; t >= 0; t--){
if (ch[t] == ru[t] + 1){
st = t;
flag1++;
}
else if (ru[t] == ch[t]+1){
ed = t;
flag2++;
}
else if (ru[t] == ch[t]){
if (ch[t] != 0 and flag1 == 0){
st = t, ed = t;
}
}
else key = 1;
}
if (flag1 > 1 or flag2 > 1)
key = 1;
else if (flag1 != flag2)
key = 1;
if (key == 1){
printf("***\n");
continue;
}
cnt = 0;
dfs(st);
if (cnt < n)
puts("***");
else{
for (int i = n-1; i > 0; i--)
printf("%s.", ans[i]);
printf("%s\n", ans[0]);
}
}
return 0;
}
|
dab99d5e0cf527d52f4525665d9a72f599c1d8fc
|
ac2be8e393231d3fa39eac94e50e5a0519749eb2
|
/Dismembered Worlds/Game.cpp
|
66cf20e75d16268e4f9d36d1bdef7c37caadc216
|
[
"MIT"
] |
permissive
|
sushiPlague/dismembered-worlds
|
9bb33949d36d4cefcafcf0055432bfb071ef7df4
|
d5d15eadd2f1d6a23e1125dc010ca49c6a7390b6
|
refs/heads/master
| 2022-12-27T14:59:20.317059
| 2020-09-25T09:07:07
| 2020-09-25T09:07:07
| 289,286,789
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,163
|
cpp
|
Game.cpp
|
#include "Game.h"
#include "MapParser.h"
#include "Camera.h"
#include "Enemy.h"
Game* Game::instance = nullptr;
Game::Game()
{}
Game::~Game()
{}
bool Game::init(const char* title)
{
bool isInitialized = true;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
isInitialized = false;
}
else
{
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);
gWindow = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, window_flags);
if (gWindow == NULL)
{
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
isInitialized = false;
}
else
{
SDL_Surface* gameIcon = IMG_Load("assets/icons/dismembered-worlds-icon.png");
if (gameIcon == NULL)
{
printf("Game icon could not be loaded! SDL_Error: %s\n", SDL_GetError());
}
else
{
SDL_SetWindowIcon(gWindow, gameIcon);
}
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (gRenderer == NULL)
{
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
isInitialized = false;
}
else
{
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
isInitialized = false;
}
else
{
if (!MapParser::getInstance()->loadMap())
{
printf("Failed to load the map!\n");
}
map = MapParser::getInstance()->getMap("map0");
TextureManager::getInstance()->parseTextures("assets/textures.xml");
Aoi* aoi = new Aoi(new Properties("aoi_idle", 100, 350, 200, 200));
//Enemy* skeleton = new Enemy("skeleton", new Properties("skeleton_idle", 300, 350, 200, 200));
gameObjects.push_back(aoi);
//gameObjects.push_back(skeleton);
Camera::getInstance()->setTarget(aoi->getOrigin());
isRunning = true;
}
}
}
}
return isInitialized;
}
void Game::handleEvents()
{
EventHandler::getInstance()->listen();
}
void Game::render()
{
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(gRenderer);
TextureManager::getInstance()->draw("background", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 1.37, 1.37, 0.4);
map->render();
for (auto& gameObject : gameObjects)
{
gameObject->draw();
}
SDL_RenderPresent(gRenderer);
}
void Game::update()
{
float dt = Time::getInstance()->getDeltaTime();
map->update();
for (auto& gameObject : gameObjects)
{
gameObject->update(dt);
}
Camera::getInstance()->update(dt);
}
void Game::clean()
{
//Destroy window
SDL_DestroyRenderer(gRenderer);
SDL_DestroyWindow(gWindow);
gWindow = NULL;
gRenderer = NULL;
//Destroy game objects
for (auto& gameObject : gameObjects)
{
gameObject->clean();
}
//Destroy textures
TextureManager::getInstance()->clean();
//Quit SDL subsystems
IMG_Quit();
SDL_Quit();
}
void Game::quit()
{
isRunning = false;
}
Game* Game::getInstance()
{
return instance = (instance != nullptr) ? instance : new Game();
}
|
25d0f48b3552df58aa19e71630edddf2983842d0
|
2e72b9eedf6737745263e4d34ffa0b1e1e7a39f1
|
/block1/main.cpp
|
3e3507e382626082bed07cc7950bab93712ef776
|
[] |
no_license
|
20190524/structrue
|
0b819c959bb7952ca88914c38058ed548df459c2
|
747cb9c9b27cb90afa36564f00229239d94933d9
|
refs/heads/master
| 2020-12-02T05:17:55.542447
| 2019-12-30T11:20:41
| 2019-12-30T11:20:41
| 230,902,403
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,520
|
cpp
|
main.cpp
|
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<blocklist.h>
//区块结构
#define M 2000000
int main()
{
//读入文件block
FILE *fp;
FILE *tfp;
BlockList Block_L;
BlockP bp;
int num=LoadBlockData(fp,Block_L);// 存好区块链了
printf("%d\n",num);
// bp=Block_L.head->next;
// while (bp) {
// printf("%d %ld\n",bp->block_ID,bp->block_timestamp);
// bp=bp->next;
// }
LoadTradeData(tfp,Block_L);//建好树了
// bp=Block_L.head->next;
// while (bp) {
// printf("%d %ld %.4f\n",bp->block_ID,bp->block_timestamp,bp->Trade->data.Amount);
// bp=bp->next;
// }
char checkID[35];
printf("Which ID do you want to check?\n");
scanf("%s",checkID);//字符串形式输入不用加&
getchar();
printf("Which time slot do you want to check?\n");
int startID,endID;
scanf("%d%d",&startID,&endID);
getchar();
//找区块间的相应信息
int sum=0;
bp=Block_L.head->next;
while (bp) {
if(bp->block_ID==startID)break;
bp=bp->next;
}
LookUpRecord(checkID,bp->block_ID,Block_L,sum,M);
while (bp->block_ID!=endID) {
bp=bp->next;
//计算一个区块中的记录数
LookUpRecord(checkID,bp->block_ID,Block_L,sum,M);
}
printf("total records' number is: %d\n",sum);
printf("please tell your k's value:\n");
int k;
scanf("%d",&k);
sum=0;
bp=Block_L.head->next;//重复查找一次,返回排名前k的记录
while (bp) {
if(bp->block_ID==startID)break;
bp=bp->next;
}
LookUpRecord(checkID,bp->block_ID,Block_L,sum,k);
if(sum<k)
{
while (bp->block_ID!=endID) {
bp=bp->next;
//计算一个区块中的记录数
LookUpRecord(checkID,bp->block_ID,Block_L,sum,k);
}
}
printf("now we are calculating an account's total money!\n"
"please tell me who do you want to know?\n");
char account[35];
scanf("%s",account);
getchar();
int xid;
printf("what time do you want to stop?\n");
scanf("%d",&xid);
double totalmoney=0;
bp=Block_L.head->next;
while (bp->block_ID!=xid) {
LookUpRecord(account,bp->block_ID,Block_L,totalmoney);//这有个致命错误,导致重复运算
bp=bp->next;
}
LookUpRecord(account,xid,Block_L,totalmoney);
printf("total money is:%.4f\n",totalmoney);
//土豪榜(๑•̀ㅂ•́)و✧
printf("Do you want to know the rich list ?\n"
"pleaese tell me your k's value:\n");
int richnum;
scanf("%d",&richnum);
printf("And tell me the last time you want to end with :\n");
int endtime;
scanf("%d",&endtime);
//先用链表存,再转换为树,最后遍历输出
RichList richman;
InitListR(richman);
BuildRichList(richman,endtime,Block_L);//建好土豪链表
// RichP rpt;
// rpt=richman.head->next;
// while (rpt) {
// printf("%s %f\n",rpt->name,rpt->procession);
// rpt=rpt->next;
// }
//开始建土豪树
//建好树就把土豪链表删去!
RichTree richtree=NULL;
CreatRichTree(richman,richtree);
TraverseRichTree(richtree,PrintRichList);
DestroyRichList(richman);
//再计算一次
//创建区块链
//读入文件data
//初始化区块中的交易数据
//
return 0;
}
|
2cbffcec83ea4a6c449b334ad46567332cf66014
|
2c00ef31a20e58643130f6546e4997d564abe6c5
|
/src/alien.h
|
c60f170b317fb7f94d079b9962e0131eba75eca5
|
[] |
no_license
|
troyanlp/CppND-Capstone-Space-Invaders
|
8b477149ed5f76b80790022ab740d91b000f025b
|
3679456071cfdb5ef70c3992a276002e77cda631
|
refs/heads/master
| 2023-03-14T03:35:34.062484
| 2021-02-24T21:20:49
| 2021-02-24T21:20:49
| 342,037,837
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,082
|
h
|
alien.h
|
#pragma once
#include "entity.h"
#include "bullet.h"
#include "shooter.h"
#include "stdlib.h"
#include <random>
class Alien : public Shooter{
public:
enum class DirectionX {
kLeft = -1,
kNone = 0,
kRight = 1
};
enum class DirectionY {
kNone = 0,
kDown = 1
};
Alien(int grid_width, int grid_height, int x, int y, bool shoot = false) :
Shooter(grid_width, grid_height, x, y),
canShoot(shoot)
{}
bool canShoot;
void Update();
bool BeenShot(std::unique_ptr<Bullet> &bullet) override;
bool ReachedPlayer();
std::unique_ptr<Bullet> Shoot() override;
static bool ChangeDirection();
static void IncreaseLevel();
private:
static bool changeDirection;
static double shooting_probability;
static double speed;
static DirectionX directionX;
static DirectionY directionY;
static int GenerateRandom();
static std::random_device device;
static std::mt19937 generator;
static std::uniform_int_distribution<int> distribution;
};
|
e6735bbbb3a8f818520cf9718e1d8e204ab4c143
|
200613ed3a6e1328bb40f77759fa656c0a874c77
|
/src/App/Classes/Game/BaiJiaLe/GameSceneUI/GameClockNode.cpp
|
da90d47db41a29b5d3184f64ac8593afbf0ce6ae
|
[] |
no_license
|
iuvei/ChessGameApp
|
eb57164a8a8e41490a5ee70dda8fc323028a8db6
|
a8765f4f90954cc6281a98b7f243be0afc50689c
|
refs/heads/master
| 2020-04-19T19:30:38.562729
| 2018-01-06T16:52:49
| 2018-01-06T16:52:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,227
|
cpp
|
GameClockNode.cpp
|
//
// GameClockNode.cpp
// HLDouDiZhu
//
// Created by zhong on 2/24/16.
//
//
#include "GameClockNode.h"
#include "GameClockNode.h"
USING_NS_CC;
USING_BJL_NAMESPACE;
GameClockNode::GameClockNode():
m_spClock(nullptr),
m_atlasLeft(nullptr),
m_nLeft(0),
m_enCountDownTag(bjl_kDefaultCountDown)
{
}
GameClockNode::~GameClockNode()
{
}
bool GameClockNode::init()
{
bool bRes = false;
do
{
CC_BREAK_IF(!Node::init());
m_spClock = Sprite::createWithSpriteFrameName("bg_clock.png");
if (nullptr != m_spClock)
{
this->addChild(m_spClock);
}
m_atlasLeft = cocos2d::ui::TextAtlas::create("", "game/game_timenum.png", 18, 24, "0");
this->addChild(m_atlasLeft);
this->stopCountDown();
bRes = true;
} while (false);
return bRes;
}
void GameClockNode::startCountDown(const int &nLeft,const CLOCKNODE_CALLBACK &fun,const bjl_enCountDownTag &countTag)
{
this->setVisible(true);
m_nLeft = nLeft;
m_funCallBack = fun;
m_enCountDownTag = countTag;
char buf[64];
if (m_nLeft < 10)
{
sprintf(buf,"0%d",m_nLeft);
}
else
{
sprintf(buf,"%d",m_nLeft);
}
m_atlasLeft->setString(buf);
if (!this->isScheduled(SEL_SCHEDULE(&GameClockNode::countDown)))
{
this->schedule(SEL_SCHEDULE(&GameClockNode::countDown),1.0f);
}
}
void GameClockNode::stopCountDown()
{
this->setVisible(false);
m_nLeft = 0;
m_funCallBack = nullptr;
m_enCountDownTag = bjl_kDefaultCountDown;
if (this->isScheduled(SEL_SCHEDULE(&GameClockNode::countDown)))
{
this->unschedule(SEL_SCHEDULE(&GameClockNode::countDown));
}
m_atlasLeft->setString("");
}
void GameClockNode::countDown(float dt)
{
--m_nLeft;
char buf[64] = "";
if (m_nLeft < 10)
{
sprintf(buf,"0%d",m_nLeft);
}
else
{
sprintf(buf,"%d",m_nLeft);
}
m_atlasLeft->setString(buf);
if (3 >= m_nLeft && m_funCallBack)
{
m_funCallBack(this,m_enCountDownTag);
m_funCallBack = nullptr;
}
if (0 >= m_nLeft )
{
stopCountDown();
}
}
|
70ae28e5d2c1c4e33c0510b79ed68f42538f9c63
|
c4bd0bf2c177d89d33529b7105e796fce557f283
|
/Second_work/Products.h
|
77bd85cd650674548842744ea1f29e6b1f473b39
|
[] |
no_license
|
G1veng/SortingOfArray
|
4d7d41362de492d70b804e2fa4ce64e47a3deb59
|
f8fd53095e21e50b0aa7e45f985ce5ab416017f8
|
refs/heads/master
| 2023-06-08T02:04:47.394996
| 2021-07-03T09:20:31
| 2021-07-03T09:20:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 557
|
h
|
Products.h
|
#pragma once
#include "product.h"
#include "input_output.h"
#include "work_with_files.h"
enum class type_of_inputs {
mainFunction,
manualInput,
randomInput,
fileInput,
testOfProgram
};
class ProductsOfConsoleInput final : public Product {
public:
ProductsOfConsoleInput();
Carray* get_input() override;
};
class ProductsOfFileInput final : public Product {
public:
ProductsOfFileInput();
Carray* get_input() override;
};
class ProductsOfRandomInput final : public Product {
public:
ProductsOfRandomInput();
Carray* get_input() override;
};
|
232b2e9ce7c58e011d2fd7fe94de9154da929c44
|
e850e0117e57435465ef260ff981df149abdba41
|
/Problemas/Amigos/2.cpp
|
7cd2e3706e3771226aebdfacc7cf3ba3a75988d5
|
[] |
no_license
|
ldorelli/curso_de_verao_maratona_icmc
|
a23a651bca9764a574db0b7c9b8fb1571ebf488d
|
b5498896bfcf14d156e4aa6801aa7cdb969099e3
|
refs/heads/master
| 2016-08-05T05:42:31.700555
| 2015-02-23T23:56:51
| 2015-02-23T23:56:51
| 30,255,176
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 947
|
cpp
|
2.cpp
|
// Bruno Sanches, 2014
#include <cstdio>
#include <vector>
#include <utility>
#include <cstring>
#include <cstdlib>
#include <map>
#include <iostream>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <set>
#include <assert.h>
#include <bitset>
using namespace std;
#define pb push_back
#define mp make_pair
#define S second
#define F first
#define INF 0x3f3f3f3f
#define ll long long
#define mod (ll)10e9
#define B 33
#define MAX 200010
#define eps 1e-7
#define ull unsigned long long
#define sync ios :: sync_with_stdio(0)
typedef vector<int> vi;
typedef pair<int,int>ii;
typedef vector<ii> vii;
map<int,int> m;
int x,y,n;
int main(void){
while(scanf("%d",&n) != EOF){
m.clear();
for(int i=0; i<n; ++i){
scanf("%d%d",&x,&y);
m[x]++; m[y]++;
}
for(map<int,int> :: iterator it = m.begin(); it != m.end(); ++it)
printf("%d %d\n",it->F, it->S);
printf("*\n");
}
return 0;
}
|
b41fb9050f57a0b41d8d2e915269b8c274e168b3
|
27fbce7c075cd9f4cee7e1250e82cd56a7699c02
|
/tests/idl4/explicit_ints/main.cpp
|
8dfce66e3770a0dfeeb838c82caf787cf0055bee
|
[
"MIT"
] |
permissive
|
jwillemsen/taox11
|
fe11af6a7185c25d0f236b80c608becbdbf3c8c3
|
f16805cfdd5124d93d2426094191f15e10f53123
|
refs/heads/master
| 2023-09-04T18:23:46.570811
| 2023-08-14T19:50:01
| 2023-08-14T19:50:01
| 221,247,177
| 0
| 0
|
MIT
| 2023-09-04T14:53:28
| 2019-11-12T15:14:26
|
C++
|
UTF-8
|
C++
| false
| false
| 3,077
|
cpp
|
main.cpp
|
/**
* @file main.cpp
* @author Johnny Willemsen
*
* @brief CORBA C++11 client application for testing int8/uint8
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#include "testC.h"
#include "testlib/taox11_testlog.h"
template <typename IntType>
void
expect_equals (bool &any_failed, const char *name, IntType actual, IntType expected)
{
if (actual != expected)
{
TAOX11_TEST_ERROR << "ERROR: For " << name << " expected " << expected << " , actual " << actual
<< std::endl;
any_failed = true;
}
}
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
bool any_failed = false;
expect_equals<uint8_t> (any_failed, "u8_max", u8_max, 255);
expect_equals<int8_t> (any_failed, "i8_min", i8_min, -128);
expect_equals<int8_t> (any_failed, "i8_max", i8_max, 127);
expect_equals<uint16_t> (any_failed, "u16_max", u16_max, 65535);
expect_equals<int16_t> (any_failed, "i16_min", i16_min, -32768);
expect_equals<int16_t> (any_failed, "i16_max", i16_max, 32767);
expect_equals<uint32_t> (any_failed, "u32_max", u32_max, 4294967295);
expect_equals<int32_t> (any_failed, "i32_min", i32_min, -2147483647 - 1);
expect_equals<int32_t> (any_failed, "i32_max", i32_max, 2147483647);
expect_equals<uint64_t> (any_failed, "u64_max", u64_max, 18446744073709551615ULL);
//expect_equals<int64_t> (any_failed, "i64_min", i64_min, -9223372036854775807LL - 1);
expect_equals<int64_t> (any_failed, "i64_max", i64_max, 9223372036854775807LL);
//
// expect_equals<uint8_t> (any_failed, "u8_min_overflow", u8_min_overflow, u8_max);
// expect_equals<int8_t> (any_failed, "i8_min_overflow", i8_min_overflow, i8_max);
// expect_equals<uint8_t> (any_failed, "u8_max_overflow", u8_max_overflow, 0);
// expect_equals<int8_t> (any_failed, "i8_max_overflow", i8_max_overflow, i8_min);
//
// expect_equals<uint8_t> (any_failed, "u8_max_negate", u8_max_negate, 0);
// expect_equals<int8_t> (any_failed, "i8_max_negate", i8_max_negate, i8_min);
expect_equals<uint8_t> (any_failed, "u8_e1", u8_e1, 2);
expect_equals<uint8_t> (any_failed, "u8_e2", u8_e2, 4);
expect_equals<uint8_t> (any_failed, "u8_e3", u8_e3, 12);
expect_equals<uint8_t> (any_failed, "u8_e4", u8_e4, 3);
expect_equals<uint8_t> (any_failed, "u8_e5", u8_e5, 7);
expect_equals<uint8_t> (any_failed, "u8_e6", u8_e6, 1);
expect_equals<uint8_t> (any_failed, "u8_e7", u8_e7, 1);
expect_equals<uint8_t> (any_failed, "u8_e8", u8_e8, 16);
expect_equals<uint8_t> (any_failed, "u8_e9", u8_e9, 8);
expect_equals<int8_t> (any_failed, "i8_e1", i8_e1, -2);
expect_equals<int8_t> (any_failed, "i8_e2", i8_e2, 4);
expect_equals<int8_t> (any_failed, "i8_e3", i8_e3, 12);
expect_equals<int8_t> (any_failed, "i8_e4", i8_e4, 3);
expect_equals<int8_t> (any_failed, "i8_e5", i8_e5, 7);
expect_equals<int8_t> (any_failed, "i8_e6", i8_e6, 1);
expect_equals<int8_t> (any_failed, "i8_e7", i8_e7, 1);
expect_equals<int8_t> (any_failed, "i8_e8", i8_e8, 16);
expect_equals<int8_t> (any_failed, "i8_e9", i8_e9, 8);
return any_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
|
aed8d483834d29d8c74833b9e647de32392b50ee
|
ec9efe0040e2fad8c552dcd81796fe4263576a2b
|
/src/Algorithms/maze/constexpr_random.test.cpp
|
625a002637b0a10e01172e5c1a742afa462f35a6
|
[] |
no_license
|
menuet/experiments
|
5a9be1c40b2ac123c99e71136e311ddd5b48bf0e
|
ac34c3d4f940e94eb8ed0527830fb3f7135e286b
|
refs/heads/master
| 2020-12-12T05:37:18.527925
| 2020-05-09T22:51:20
| 2020-05-09T22:51:20
| 34,752,991
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 252
|
cpp
|
constexpr_random.test.cpp
|
#include "constexpr_random.hpp"
#include <catch2/catch.hpp>
TEST_CASE("constexpr random")
{
maze::PCG pcg{maze::build_time_seed()};
const auto value = maze::distribution(pcg, 0U, 100U);
REQUIRE(value >= 0);
REQUIRE(value <= 100);
}
|
aaab441f1abce8f02f901848df82b3758afbda53
|
068bbc24f87caf24465946841b964b232402ea08
|
/subsequence/execs/UCR_MON_nolb/UCR_MON_nolb.cpp
|
c477d839427334d75cb621811961a337a9790fb0
|
[
"BSD-3-Clause"
] |
permissive
|
HerrmannM/paper-2021-EAPElasticDist
|
d64e1223f1e4993624edadc2bf86bc9a180f5187
|
a3dfbc73399ddecdf677b353937a4a6215f0a8a1
|
refs/heads/master
| 2023-07-31T22:56:39.060671
| 2021-09-16T02:17:53
| 2021-09-16T02:17:53
| 328,804,771
| 1
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 15,714
|
cpp
|
UCR_MON_nolb.cpp
|
/***********************************************************************/
/************************* DISCLAIMER **********************************/
/***********************************************************************/
/** **/
/** This suite is a modification of the UCR Suite and, consequently, **/
/** follows the same copyright (Transcribed below, without any change)**/
/** **/
/** This modified version is the responsability of Matthieu Herrmann **/
/** and Geoff I. Webb. **/
/** **/
/***********************************************************************/
/***********************************************************************/
/***********************************************************************/
/** This UCR Suite software is copyright protected © 2012 by **/
/** Thanawin Rakthanmanon, Bilson Campana, Abdullah Mueen, **/
/** Gustavo Batista and Eamonn Keogh. **/
/** **/
/** Unless stated otherwise, all software is provided free of charge. **/
/** As well, all software is provided on an "as is" basis without **/
/** warranty of any kind, express or implied. Under no circumstances **/
/** and under no legal theory, whether in tort, contract,or otherwise,**/
/** shall Thanawin Rakthanmanon, Bilson Campana, Abdullah Mueen, **/
/** Gustavo Batista, or Eamonn Keogh be liable to you or to any other **/
/** person for any indirect, special, incidental, or consequential **/
/** damages of any character including, without limitation, damages **/
/** for loss of goodwill, work stoppage, computer failure or **/
/** malfunction, or for any and all other damages or losses. **/
/** **/
/** If you do not agree with these terms, then you you are advised to **/
/** not use this software. **/
/***********************************************************************/
/***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <iostream>
#include <vector>
#define dist(x,y) ((x-y)*(x-y))
#define INF 1e20 //Pseudo Infitinte number for this code
#define POSITIVE_INFINITY 1e20 //Pseudo Infitinte number for this code
using namespace std;
/// Data structure for sorting the query
typedef struct Index
{ double value;
int index;
} Index;
/// Sorting function for the query, sort by abs(z_norm(q[i])) from high to low
int comp(const void *a, const void* b)
{ Index* x = (Index*)a;
Index* y = (Index*)b;
return abs(y->value) - abs(x->value); // high to low
}
/** Square distances between two doubles */
inline double square_dist(double v1, double v2) {
double d = v1 - v2;
return d * d;
}
/** Unsigned arithmetic:
* Given an 'index' and a 'window', get the start index corresponding to std::max(0, index-window) */
inline std::size_t cap_start_index_to_window(std::size_t index, std::size_t window){
if(index>window){ return index-window; } else { return 0; }
}
/** Unsigned arithmetic:
* Given an 'index', a 'window' and an 'end', get the stop index corresponding to std::min(end, index+window+1).
* The expression index+window+1 is illegal for any index>0 as window could be MAX-1
* */
inline std::size_t cap_stop_index_to_window_or_end(std::size_t index, std::size_t window, std::size_t end){
// end-window is valid when window<end
if(window<end && index+1<end-window){ return index + window + 1; } else { return end; }
}
double dtw(
const double *lines,
const double *cols,
int l,
int w,
double bsf
)
{
// 1) --- Create the upper bound from bsf and a margin
const double UB = bsf;
// 2) --- Alias in line/column concept: we only allocate for the columns, using the smallest possible dimension.
const size_t nbcols = l;
const size_t nblines = l;
// 3) --- Cap the windows.
if (w > nblines) { w = nblines; }
// 4) --- Buffers allocations
// Add an extra column for the "matrix border" condition, init to +INF.
// Using an unique contiguous array. Base indices are:
// 'c' for the current row,
// 'p' for the previous one
std::vector<double> buffers_v((1+nbcols) * 2, POSITIVE_INFINITY);
double *buffers = buffers_v.data();
size_t c{1}, p{nbcols+2}; // Account for the extra column (in front)
// 5) --- Computation of DTW
buffers[c-1] = 0;
size_t next_start{0};
size_t pruning_point{0};
for(size_t i=0; i<nblines; ++i) {
// --- --- --- --- Swap and variables init
std::swap(c, p);
const double li = lines[i];
const std::size_t jStop = cap_stop_index_to_window_or_end(i, w, nbcols);
const std::size_t jStart = std::max(cap_start_index_to_window(i, w), next_start);
std::size_t next_pruning_point = jStart; // Next pruning point init at the start of the line
std::size_t j = jStart;
next_start = jStart;
// --- --- --- --- Init the first column
buffers[c+j-1] = POSITIVE_INFINITY;
double cost = POSITIVE_INFINITY;
// --- --- --- --- Compute DTW up to the pruning point while advancing next_start: diag and top
for(; j==next_start && j < pruning_point; ++j) {
const auto d = square_dist(li, cols[j]);
cost = std::min(buffers[p + j - 1], buffers[p + j]) + d;
buffers[c + j] = cost;
if(cost<=UB){ next_pruning_point = j + 1;} else { ++next_start; }
}
// --- --- --- --- Compute DTW up to the pruning point without advancing next_start: prev, diag, top
for(; j < pruning_point; ++j) {
const auto d = square_dist(li, cols[j]);
cost = std::min(cost, std::min(buffers[p + j - 1], buffers[p + j])) + d;
buffers[c + j] = cost;
if(cost<=UB){ next_pruning_point = j + 1;}
}
// --- --- --- --- Compute DTW at "pruning_point": 2 cases
if(j<jStop){
const auto d = square_dist(li, cols[j]);
if(j==next_start){ // Advancing next start: only diag. Done if v>UB.
cost = buffers[p + j - 1] + d;
buffers[c + j] = cost;
if(cost<=UB){ next_pruning_point = j + 1;} else {return POSITIVE_INFINITY; }
} else { // Not advancing next start: at least a path possible in previous cells.
cost = std::min(cost, buffers[p + j - 1]) + d;
buffers[c + j] = cost;
if(cost<=UB){ next_pruning_point = j + 1;}
}
++j;
} else if(j==next_start) { return POSITIVE_INFINITY; }
// --- --- --- --- Compute DTW after "pruning_point": prev. Go on while we advance the next pruning point.
for(;j==next_pruning_point && j<jStop;++j){
const auto d = square_dist(li, cols[j]);
cost = cost + d;
buffers[c + j] = cost;
if(cost<=UB){ ++next_pruning_point; }
}
pruning_point=next_pruning_point;
}// End for i loop
// 6) --- If the pruning_point did not reach the number of columns, we pruned something
if(pruning_point != nbcols){ return POSITIVE_INFINITY; } else {
return buffers[c+nbcols-1];
}
}
/// Print function for debugging
void printArray(double *x, int len)
{ for(int i=0; i<len; i++)
printf(" %6.2lf",x[i]);
printf("\n");
}
/// If expected error happens, teminated the program.
void error(int id)
{
if(id==1)
printf("ERROR : Memory can't be allocated!!!\n\n");
else if ( id == 2 )
printf("ERROR : File not Found!!!\n\n");
else if ( id == 3 )
printf("ERROR : Can't create Output File!!!\n\n");
else if ( id == 4 )
{
printf("ERROR : Invalid Number of Arguments!!!\n");
printf("Command Usage: UCR_DTW.exe data-file query-file m R\n\n");
printf("For example : UCR_DTW.exe data.txt query.txt 128 0.05\n");
}
exit(1);
}
/// Main Function
int main( int argc , char *argv[] )
{
FILE *fp; /// data file pointer
FILE *qp; /// query file pointer
double bsf; /// best-so-far
double *t, *q; /// data array and query array
int *order; ///new order of the query
double *u, *l, *qo, *uo, *lo,*tz,*cb, *cb1, *cb2,*u_d, *l_d;
double d;
long long i , j;
double ex , ex2 , mean, std;
int m=-1, r=-1;
long long loc = 0;
double t1,t2;
int kim = 0,keogh = 0, keogh2 = 0;
double dist=0, lb_kim=0, lb_k=0, lb_k2=0;
double *buffer, *u_buff, *l_buff;
Index *Q_tmp;
/// For every EPOCH points, all cummulative values, such as ex (sum), ex2 (sum square), will be restarted for reducing the floating point error.
int EPOCH = 100000;
/// If not enough input, display an error.
if (argc<=3)
error(4);
/// read size of the query
if (argc>3)
m = atol(argv[3]);
/// read warping windows
if (argc>4)
{ double R = atof(argv[4]);
if (R<=1)
r = floor(R*m);
else
r = floor(R);
}
fp = fopen(argv[1],"r");
if( fp == NULL )
error(2);
qp = fopen(argv[2],"r");
if( qp == NULL )
error(2);
/// start the clock
t1 = clock();
/// malloc everything here
q = (double *)malloc(sizeof(double)*m);
if( q == NULL )
error(1);
qo = (double *)malloc(sizeof(double)*m);
if( qo == NULL )
error(1);
uo = (double *)malloc(sizeof(double)*m);
if( uo == NULL )
error(1);
lo = (double *)malloc(sizeof(double)*m);
if( lo == NULL )
error(1);
order = (int *)malloc(sizeof(int)*m);
if( order == NULL )
error(1);
Q_tmp = (Index *)malloc(sizeof(Index)*m);
if( Q_tmp == NULL )
error(1);
u = (double *)malloc(sizeof(double)*m);
if( u == NULL )
error(1);
l = (double *)malloc(sizeof(double)*m);
if( l == NULL )
error(1);
cb = (double *)malloc(sizeof(double)*m);
if( cb == NULL )
error(1);
cb1 = (double *)malloc(sizeof(double)*m);
if( cb1 == NULL )
error(1);
cb2 = (double *)malloc(sizeof(double)*m);
if( cb2 == NULL )
error(1);
u_d = (double *)malloc(sizeof(double)*m);
if( u == NULL )
error(1);
l_d = (double *)malloc(sizeof(double)*m);
if( l == NULL )
error(1);
t = (double *)malloc(sizeof(double)*m*2);
if( t == NULL )
error(1);
tz = (double *)malloc(sizeof(double)*m);
if( tz == NULL )
error(1);
buffer = (double *)malloc(sizeof(double)*EPOCH);
if( buffer == NULL )
error(1);
u_buff = (double *)malloc(sizeof(double)*EPOCH);
if( u_buff == NULL )
error(1);
l_buff = (double *)malloc(sizeof(double)*EPOCH);
if( l_buff == NULL )
error(1);
/// Read query file
bsf = INF;
i = 0;
j = 0;
ex = ex2 = 0;
while(fscanf(qp,"%lf",&d) != EOF && i < m)
{
ex += d;
ex2 += d*d;
q[i] = d;
i++;
}
fclose(qp);
/// Do z-normalize the query, keep in same array, q
mean = ex/m;
std = ex2/m;
std = sqrt(std-mean*mean);
for( i = 0 ; i < m ; i++ )
q[i] = (q[i] - mean)/std;
/// Sort the query one time by abs(z-norm(q[i]))
for( i = 0; i<m; i++)
{
Q_tmp[i].value = q[i];
Q_tmp[i].index = i;
}
qsort(Q_tmp, m, sizeof(Index),comp);
/// also create another arrays for keeping sorted envelop
for( i=0; i<m; i++)
{ int o = Q_tmp[i].index;
order[i] = o;
qo[i] = q[o];
uo[i] = u[o];
lo[i] = l[o];
}
free(Q_tmp);
/// Initial the cummulative lower bound
for( i=0; i<m; i++)
{ cb[i]=0;
cb1[i]=0;
cb2[i]=0;
}
i = 0; /// current index of the data in current chunk of size EPOCH
j = 0; /// the starting index of the data in the circular array, t
ex = ex2 = 0;
bool done = false;
int it=0, ep=0, k=0;
long long I; /// the starting index of the data in current chunk of size EPOCH
while(!done)
{
/// Read first m-1 points
ep=0;
if (it==0)
{ for(k=0; k<m-1; k++)
if (fscanf(fp,"%lf",&d) != EOF)
buffer[k] = d;
}
else
{ for(k=0; k<m-1; k++)
buffer[k] = buffer[EPOCH-m+1+k];
}
/// Read buffer of size EPOCH or when all data has been read.
ep=m-1;
while(ep<EPOCH)
{ if (fscanf(fp,"%lf",&d) == EOF)
break;
buffer[ep] = d;
ep++;
}
/// Data are read in chunk of size EPOCH.
/// When there is nothing to read, the loop is end.
if (ep<=m-1) { done = true; }
else {
/// Just for printing a dot for approximate a million point. Not much accurate.
if (it%(1000000/(EPOCH-m+1))==0)
fprintf(stderr,".");
/// Do main task here..
ex=0; ex2=0;
for(i=0; i<ep; i++)
{
/// A bunch of data has been read and pick one of them at a time to use
d = buffer[i];
/// Calcualte sum and sum square
ex += d;
ex2 += d*d;
/// t is a circular array for keeping current data
t[i%m] = d;
/// Double the size for avoiding using modulo "%" operator
t[(i%m)+m] = d;
/// Start the task when there are more than m-1 points in the current chunk
if( i >= m-1 )
{
mean = ex/m;
std = ex2/m;
std = sqrt(std-mean*mean);
/// compute the start location of the data in the current circular array, t
j = (i+1)%m;
/// the start location of the data in the current chunk
I = i-(m-1);
/// Take another linear time to compute z_normalization of t.
/// Note that for better optimization, this can merge to the previous function.
for(k=0;k<m;k++) { tz[k] = (t[(k+j)] - mean)/std; }
/// Compute DTW and early abandoning if possible
dist = dtw(tz, q, m, r, bsf);
if( dist < bsf )
{ /// Update bsf
/// loc is the real starting location of the nearest neighbor in the file
bsf = dist;
loc = (it)*(EPOCH-m+1) + i-m+1;
}
/// Reduce obsolute points from sum and sum square
ex -= t[j];
ex2 -= t[j]*t[j];
}
}
/// If the size of last chunk is less then EPOCH, then no more data and terminate.
if (ep<EPOCH)
done=true;
else
it++;
}
}
i = (it)*(EPOCH-m+1) + ep;
fclose(fp);
free(q);
free(u);
free(l);
free(uo);
free(lo);
free(qo);
free(cb);
free(cb1);
free(cb2);
free(tz);
free(t);
free(l_d);
free(u_d);
free(l_buff);
free(u_buff);
t2 = clock();
printf("\n");
/// Note that loc and i are long long.
cout << "Location : " << loc << endl;
cout << "Distance : " << sqrt(bsf) << endl;
cout << "Data Scanned : " << i << endl;
cout << "Total Execution Time : " << (t2-t1)/CLOCKS_PER_SEC << " sec" << endl;
/// printf is just easier for formating ;)
printf("\n");
printf("Pruned by LB_Kim : %6.2f%%\n", ((double) kim / i)*100);
printf("Pruned by LB_Keogh : %6.2f%%\n", ((double) keogh / i)*100);
printf("Pruned by LB_Keogh2 : %6.2f%%\n", ((double) keogh2 / i)*100);
printf("DTW Calculation : %6.2f%%\n", 100-(((double)kim+keogh+keogh2)/i*100));
return 0;
}
|
a9eb8198bacf9c03dd91b9748898ceeed569473a
|
d24bf511265096983cf11c1336a2c08d42846df4
|
/include/not.h
|
54e81988c4d9790db7f178ae9ee5b535af43ede7
|
[] |
no_license
|
MagnusCaligo/NEAT-C-
|
cf822745ed38608be2d2af66af396cef3089e3b5
|
32db83261ee1e7d4dfd7605d170b837baa852e51
|
refs/heads/master
| 2021-09-01T02:00:28.146576
| 2017-12-24T09:15:52
| 2017-12-24T09:15:52
| 112,784,040
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 76
|
h
|
not.h
|
#include <iostream>
#include "NEAT.h"
using namespace std;
void runNot();
|
46b95d036babde13b491f8460b35783aa2a674d2
|
705c7223bc1f33f0c86a1344efbbcc53f3e0bb46
|
/src/world/map.cpp
|
77e4cd455db9d03712f8c3366477468310ee5e64
|
[] |
no_license
|
andregri/minecraft
|
050594271ec6f3d3bf93e42f9deedd94842635ea
|
39963edb4fa261ba3e06a57524ed770c9120e833
|
refs/heads/master
| 2023-03-25T13:17:54.157374
| 2021-03-19T22:17:19
| 2021-03-19T22:18:04
| 346,765,158
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,930
|
cpp
|
map.cpp
|
#include "world/map.h"
#include <cmath>
#include <iostream>
#include <fstream>
#include <ostream>
#include <string>
#include <cstdint>
#include <noise/noise.h>
#include <noise/noiseutils.h>
namespace world {
Map::Map() :
m_numRows(0),
m_numCols(0),
m_maxElevation(0),
m_seaLevel(0),
m_filepath("") {}
Map::Map(int rows, int cols, int levels, const std::string& filepath) :
m_numRows(rows),
m_numCols(cols),
m_maxElevation(levels),
m_seaLevel( levels/10 ),
m_filepath(filepath)
{
generate();
}
/*
Determine if a cube located at (row,col,e) is visible or not due to the
surrounding cubes
*/
bool Map::isVisible(int row, int col, int e) const
{
if ( col == 0 || col == m_numCols - 1 || row == 0 || row == m_numRows - 1 ) {
return true;
}
if ( e == m_elevation.at(row).at(col) ) {
return true;
}
if (e <= m_elevation.at(row-1).at(col) && // front
e <= m_elevation.at(row+1).at(col) && // back
e <= m_elevation.at(row).at(col+1) && // right
e <= m_elevation.at(row).at(col-1) // left
) {
return false;
}
return true;
}
int Map::rows() const {
return m_numRows;
}
int Map::cols() const {
return m_numCols;
}
int Map::maxElevation() const {
return m_maxElevation;
}
int Map::elevation(int row, int col) const
{
return m_elevation.at(row).at(col);
}
int Map::seaLevel() const {
return m_seaLevel;
}
void Map::generate() {
noise::module::Perlin perlineNoise;
for (int row = 0; row < m_numRows; ++row) {
std::vector<int> rowValues;
for (int col = 0; col < m_numCols; ++col) {
// nc, nr are constrained in [-0.5; +0.5]
double nc = static_cast<double>(col) / m_numCols - 0.5f;
double nr = static_cast<double>(row) / m_numRows - 0.5f;
// noise with octves
double e = 1 * perlineNoise.GetValue(1 * nc, 1 * nr, 0.0f)
+ 0.5 * perlineNoise.GetValue(2 * nc, 2 * nr, 0.0f)
+ 0.25 * perlineNoise.GetValue(4 * nc, 4 * nr, 0.0f);
// normalize
e /= (1 + 0.5 + 0.25);
//
rowValues.push_back( static_cast<int>( pow(e, 2) * m_maxElevation) );
}
m_elevation.push_back( rowValues );
}
}
bool Map::load(const std::string& filepath)
{
m_filepath = filepath;
std::ifstream inFile(m_filepath);
if (!inFile) return false;
std::string s;
inFile >> s;
m_numRows = std::stoi(s);
inFile >> s;
m_numCols = std::stoi(s);
inFile >> s;
m_maxElevation = std::stoi(s);
m_seaLevel = m_maxElevation / 10;
for (int row = 0; row < m_numRows; ++row) {
std::vector<int> rowValues;
for (int col = 0; col < m_numCols; ++col) {
inFile >> s;
rowValues.push_back( std::stoi(s) );
}
m_elevation.push_back( rowValues );
}
return true;
}
void Map::save() const
{
std::ofstream outFile(m_filepath);
outFile << m_numRows << '\n';
outFile << m_numCols << '\n';
outFile << m_maxElevation << '\n';
for (int row = 0; row < m_numRows; ++row) {
for (int col = 0; col < m_numCols; ++col) {
outFile << m_elevation.at(row).at(col) << '\n';
}
}
}
void Map::savePPM() const
{
std::ofstream outFile(m_filepath + ".ppm", std::ios::binary);
outFile << "P6\n" << m_numCols << " " << m_numRows << "\n" << m_maxElevation << "\n";
for (int row = 0; row < m_numRows; ++row) {
for (int col = 0; col < m_numCols; ++col) {
uint8_t color = static_cast<uint8_t>( (float)m_elevation.at(row).at(col) / m_maxElevation * 255 );
outFile << static_cast<char>(color)
<< static_cast<char>(color)
<< static_cast<char>(color);
}
}
outFile.close();
}
}
|
cdedd970ccebc51c9c837a519d4d26f1659503e2
|
62dd40004b34fd615f565877cba3de6660a0a131
|
/删除链表中的节点/删除链表中的节点/main.cpp
|
a22ef25ad591c293c1cc201b2a4022d651c1f34d
|
[] |
no_license
|
info3781/leetcode
|
9eea32834f8f7efc0a6ff0fa370b562adf972fa9
|
aee86b3500397fe1c4b37acaa9fff1267b4e9192
|
refs/heads/master
| 2020-09-15T06:11:30.182021
| 2019-12-13T02:24:35
| 2019-12-13T02:24:35
| 223,364,789
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,040
|
cpp
|
main.cpp
|
//
// main.cpp
// 删除链表中的节点
//
// Created by Info on 2019/11/29.
// Copyright © 2019 Info. All rights reserved.
//
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
//请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
//
//现有一个链表 -- head = [4,5,1,9],它可以表示为:
//
//
//
//
//
//示例 1:
//
//输入: head = [4,5,1,9], node = 5
//输出: [4,1,9]
//解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
//示例 2:
//
//输入: head = [4,5,1,9], node = 1
//输出: [4,5,9]
//解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
//
//
//说明:
//
//链表至少包含两个节点。
//链表中所有节点的值都是唯一的。
//给定的节点为非末尾节点并且一定是链表中的一个有效节点。
//不要从你的函数中返回任何结果。
struct ListNode {
int val;
ListNode *next;
};
ListNode* constructNode(int val) {
ListNode* node = new ListNode();
node->next = nullptr;
node->val = val;
return node;
}
void contactNode(ListNode* node, ListNode* nextNode) {
if (node != nullptr) {
node->next = nextNode;
}
}
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode* dnode = node->next;
node->val = node->next->val;
node->next = node->next->next;
delete dnode;
dnode = nullptr;
}
};
int main(int argc, const char * argv[]) {
ListNode* node1 = constructNode(4);
ListNode* node2 = constructNode(5);
ListNode* node3 = constructNode(1);
ListNode* node4 = constructNode(9);
contactNode(node1, node2);
contactNode(node2, node3);
contactNode(node3, node4);
Solution *solution = new Solution();
solution->deleteNode(node2);
return 0;
}
|
34325427f5cee43d7273321428ad7ed124838e13
|
ac0f6f69a967b4aefbcb037231def4941a5afce6
|
/Exam cpp/09.11.2020 ООП exam prog.cpp
|
7cea2dc5153caa6707de534c91d8daf8b50ca78c
|
[] |
no_license
|
BaronFenix/cpp-HomeWorks
|
7c4333db6194beb69aea506fe0007c123b104b5b
|
599de4cef6f3eeb8a3ac8cacb5f40dafce6c1e98
|
refs/heads/main
| 2023-02-22T23:00:20.495813
| 2021-01-31T13:42:12
| 2021-01-31T13:42:12
| 334,645,687
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,184
|
cpp
|
09.11.2020 ООП exam prog.cpp
|
#include "examHeader.h"
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
using namespace std;
system("Color 0C");
fenix::AdminMode wowo;
fenix::GuestMode doode; // guest DarthFenix : qwerty123
wowo.setAdmin();
// doode.log_in();
doode.log_in(); // вот и весь мэин)) а дальше перелет по функциям. даже незнаю хорошо это или плохо. ну по крайней мере не понятно
int input = 8, answer = 12;
cout << "= " << (static_cast<double>(input) / static_cast<double>(answer)) * 100;
//wowo.menuTest(); // good
//wowo.startTest("C++ basic.txt");
wowo.showLastResult();
fenix::crypton xxx;
//doode.outputLoginData();
// wowo.addTest();
// fenix::AdminMode::setTest("sss");
//cout << xxx.encrypt("ADMUH") << endl;
// cout << xxx.encrypt("I7aPoJIb") << endl;
cout << "\n\n\n";
cout << xxx.decryption("І·ѕ¦»") << endl;
cout << xxx.decryption("єД’Јњ№є‘") << endl;
return 0;
}
|
b253d7f0b2baf9260b5dd6bbb2907f908e3f2786
|
9749fef18c3f49e1fa80a9d7c8b19dfc60a68e08
|
/New_UVA/429.cpp
|
eb59e9040ee0c3ff10540ee00409763dbcf12c1a
|
[] |
no_license
|
showkat2203/UVa
|
afe6c033dee6ac7206d37d1aa86b95ff81fdb1e2
|
c250ff440925cb9799d96d87a47987b7d970ce2e
|
refs/heads/master
| 2021-07-07T04:45:22.846632
| 2017-10-05T12:47:07
| 2017-10-05T12:47:07
| 105,883,975
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,042
|
cpp
|
429.cpp
|
#include <bits/stdc++.h>
using namespace std ;
map < string, vector < string > > mp ;
//map < string, vector < string > > :: iterator it ;
vector < string > v ;
map < string , int > cost ;
void bfs(string a)
{
queue < string > q ;
cost[a] = 0 ;
q.push(a) ;
string m, n ;
int i ;
while( !q.empty() )
{
m = q.front(), q.pop() ;
for( i = 0; i < mp[m].size(); i++)
{
n = mp[m][i] ;
if( cost[n] == 0 )
{
cost[n] = cost[m] + 1 ;
q.push(n) ;
}
}
}
}
bool check(string a, string b)
{
int cnt = 0, i ;
if( a.length() == b.length() )
{
for( i = 0; i < a.length(); ++i)
if( a[i] != b[i] )
cnt++;
if( cnt > 1 )
return false ;
return true ;
}
return false ;
}
int main()
{
int tst, i, j, k, l , m, n ;
char a[1200] ;
scanf("%d", &tst) ;
//getchar() ;
string tmp ;
while(tst--)
{
while ( cin >> tmp && tmp != "*" ) v.push_back(tmp) ;
for( i = 0; i < v.size(); ++i)
for( j = 0; j < v.size(); ++j)
if( i != j )
if( check( v[i], v[j] ))
mp[v[i]].push_back(v[j]) ;
getchar() ;
string b, c ;
char bb[1500] , cc[1500] ;
while( gets(a) && a[0] != '\0' )
{
sscanf(a, "%s %s", bb, cc) ;
b = bb, c = cc ;
for( i = 0; i < v.size(); i++)
cost[v[i]] = 0 ;
bfs(b) ;
printf("%s %s %d\n", b.c_str() , c.c_str(), cost[c]) ;
}
if( tst )
printf("\n") ;
// for( it = mp.begin(); it != mp.end(); ++it)
// {
// printf("%s -> ", it->first.c_str()) ;
// for( i = 0; i < mp[it->first].size(); ++i)
// {
// printf("%s ", mp[it->first][i].c_str()) ;
// }
// puts("") ;
// }
}
return 0 ;
}
|
9b86f3cc6f418979e6e5736f745b3f34486d46a1
|
2a78545bf5f1b8705630695026a167aadb006ae3
|
/pb-lib/pblib/encoder/sorting_merging.cpp
|
0a180a174991f63a043276f20acaf921c16bc02e
|
[
"MIT"
] |
permissive
|
chisui/haskell-ipasir
|
5f232aedec28d885494314fa9120e5f3c3ad04f3
|
2add0efe0ab29d03000f5afd8e87ad5655e0c7d2
|
refs/heads/master
| 2021-01-19T13:22:20.079802
| 2017-10-11T12:51:44
| 2017-10-11T12:51:44
| 88,081,360
| 2
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,211
|
cpp
|
sorting_merging.cpp
|
#include <math.h>
#include "sorting_merging.h"
#include <climits>
using namespace std;
namespace PBLib
{
vector<vector<int32_t> > Sorting::s_auxs;
map< pair<int32_t,int32_t>, int64_t> Sorting::recursive_sorter_values;
map< tuple<int32_t,int32_t,int32_t>, int64_t> Sorting::recursive_sorter_l_values;
map< tuple<int32_t,int32_t,int32_t>, int64_t> Sorting::recursive_merger_values;
void Sorting::recursive_sorter(int m, int l, const vector< int32_t >& input, ClauseDatabase& formula, AuxVarManager& auxvars, vector< int32_t >& output, ImplicationDirection direction)
{
int n = input.size();
assert(output.size() == 0);
assert(n > 1);
assert(m <= n);
vector<int32_t> tmp_lits_a;
vector<int32_t> tmp_lits_b;
vector<int32_t> tmp_lits_o1;
vector<int32_t> tmp_lits_o2;
for (int i = 0; i < l; ++i)
tmp_lits_a.push_back(input[i]);
for (int i = l; i < n; ++i)
tmp_lits_b.push_back(input[i]);
assert(tmp_lits_a.size() + tmp_lits_b.size() == n);
sort(m,tmp_lits_a, formula, auxvars, tmp_lits_o1, direction);
sort(m,tmp_lits_b, formula, auxvars, tmp_lits_o2, direction);
merge(m, tmp_lits_o1, tmp_lits_o2, formula, auxvars, output, direction);
assert(tmp_lits_o1.size() == min(l,m));
assert(tmp_lits_o2.size() == min(n-l,m));
assert(output.size() == m);
}
void Sorting::recursive_sorter(int m, const vector< int32_t >& input, ClauseDatabase& formula, AuxVarManager& auxvars, vector< int32_t >& output, ImplicationDirection direction)
{
assert(m > 0);
assert(input.size() > 0);
output.clear();
int n = input.size();
assert(n > 1);
int l = 1;
if (n > 100) // avoid long calculations and stack overflows
l = n / 2;
else
{
int64_t min_value = recursive_sorter_value(m,n, l, direction);
for (int i = 2; i < n; ++i)
{
int64_t value = recursive_sorter_value(m,n, i, direction);
if (value < min_value)
{
l = i;
min_value = value;
}
}
}
recursive_sorter(m,l,input, formula, auxvars, output, direction);
}
void Sorting::counter_sorter(int k, const vector< int32_t >& x, ClauseDatabase& formula, AuxVarManager& auxvars, vector< int32_t >& output, ImplicationDirection direction)
{
int n = x.size();
s_auxs.clear(); // TODO remove
s_auxs.resize(n, vector<int32_t>(k));
for (int j = 0; j < k; ++j)
{
for (int i = j; i < n; ++i)
{
s_auxs[i][j] = auxvars.getVariable();
}
}
vector<vector<int32_t> > const & s = s_auxs;
if (direction == INPUT_TO_OUTPUT || direction == BOTH)
{
for (int i = 0; i < n; ++i)
{
formula.addClause(-x[i], s[i][0]);
if (i > 0)
formula.addClause(-s[i-1][0], s[i][0]);
}
for (int j = 1; j < k; ++j)
{
for (int i = j; i < n; ++i)
{
formula.addClause(-x[i], -s[i-1][j-1], s[i][j]);
if (i > j)
formula.addClause(-s[i-1][j], s[i][j]);
}
}
}
assert(direction == INPUT_TO_OUTPUT);
// if (direction == OUTPUT_TO_INPUT || direction == BOTH)
// {
// for (int j = 1; j < k; ++j)
// {
// for (int i = j; i < n; ++i)
// {
// formula.addClause(-s[i][j], s[i-1][j], x[i]);
// formula.addClause(-s[i][j], s[i-1][j], s[i-1][j-1]);
// }
// }
//
// formula.addClause(-s[0][0],x[0]);
// }
output.clear();
for (int i = 0; i < k; ++i)
output.push_back(s[n-1][i]);
}
void Sorting::direct_sorter(int m, const vector< int32_t >& input, ClauseDatabase& formula, AuxVarManager& auxvars, vector< int32_t >& output, ImplicationDirection direction)
{
assert(direction == INPUT_TO_OUTPUT);
int n = input.size();
assert(n < 20);
int bitmask = 1;
vector<int32_t> clause;
output.clear();
for (int i = 0; i < m; ++i)
output.push_back(auxvars.getVariable());
while (bitmask < pow(2,n))
{
int count = 0;
clause.clear();
for (int i = 0; i < n; ++i)
{
if ( (1 << i) & bitmask )
{
count++;
if (count > m)
break;
clause.push_back(-input[i]);
}
}
assert(count > 0);
if (count <= m)
{
clause.push_back(output[count-1]);
formula.addClause(clause);
}
bitmask++;
}
}
void Sorting::sort(int m, const vector< int32_t >& input, ClauseDatabase& formula, AuxVarManager& auxvars, vector< int32_t >& output, ImplicationDirection direction)
{
assert(m >= 0);
if (m == 0)
{
output.clear();
return;
}
int n = input.size();
if (m > n)
m = n; // normalize
if (n == 0)
{
output.clear();
return;
}
if (n == 1)
{
output.clear();
output.push_back(input[0]);
return;
}
if (n == 2)
{
output.clear();
int32_t o1 = auxvars.getVariable();
if (m == 2)
{
int32_t o2 = auxvars.getVariable();
comparator(input[0], input[1], o1, o2, formula, direction);
output.push_back(o1);
output.push_back(o2);
}
else
{
assert(m == 1);
comparator(input[0], input[1], o1, formula, direction);
output.push_back(o1);
}
return;
}
if (direction != INPUT_TO_OUTPUT)
{
recursive_sorter(m, input, formula, auxvars, output, direction);
return;
}
int64_t counter = counter_sorter_value(m,n, direction);
int64_t direct = direct_sorter_value(m,n, direction);
int64_t recursive = recursive_sorter_value(m,n, direction);
if (counter < direct && counter < recursive)
{
counter_sorter(m, input, formula, auxvars, output, direction);
}
else
if (direct < counter && direct < recursive)
{
direct_sorter(m, input, formula, auxvars, output, direction);
}
else
{
recursive_sorter(m, input, formula, auxvars, output, direction);
}
}
void Sorting::recursive_merger(int c, vector<int32_t> const & input_a, int a, vector<int32_t> const & input_b, int b, ClauseDatabase & formula, AuxVarManager & auxvars, vector<int32_t> & output, ImplicationDirection direction)
{
assert(input_a.size() > 0);
assert(input_b.size() > 0);
assert(c > 0);
output.clear();
if (a > c)
a = c;
if (b > c)
b = c;
if (c == 1)
{
int32_t y = auxvars.getVariable();
comparator(input_a[0], input_b[0], y, formula, direction);
output.push_back(y);
return;
}
if (a == 1 && b == 1)
{
assert(c == 2);
int32_t y1 = auxvars.getVariable();
int32_t y2 = auxvars.getVariable();
comparator(input_a[0], input_b[0], y1, y2, formula, direction);
output.push_back(y1);
output.push_back(y2);
return;
}
vector<int32_t> odd_merge;
vector<int32_t> even_merge;
vector<int32_t> tmp_lits_odd_a;
vector<int32_t> tmp_lits_odd_b;
vector<int32_t> tmp_lits_even_a;
vector<int32_t> tmp_lits_even_b;
for (int i = 0; i < a; i = i + 2)
tmp_lits_odd_a.push_back(input_a[i]);
for (int i = 0; i < b; i = i + 2)
tmp_lits_odd_b.push_back(input_b[i]);
for (int i = 1; i < a; i = i + 2)
tmp_lits_even_a.push_back(input_a[i]);
for (int i = 1; i < b; i = i + 2)
tmp_lits_even_b.push_back(input_b[i]);
merge(c/2 + 1, tmp_lits_odd_a, tmp_lits_odd_b, formula, auxvars, odd_merge, direction);
merge(c/2, tmp_lits_even_a, tmp_lits_even_b, formula, auxvars, even_merge, direction);
assert(odd_merge.size() > 0);
output.push_back(odd_merge[0]);
int i = 1;
int j = 0;
while (true)
{
if (i < odd_merge.size() && j < even_merge.size())
{
if (output.size() + 2 <= c)
{
int32_t z0 = auxvars.getVariable();
int32_t z1 = auxvars.getVariable();
comparator(odd_merge[i], even_merge[j], z0, z1, formula, direction);
output.push_back(z0);
output.push_back(z1);
if (output.size() == c)
break;
}
else
if (output.size() + 1 == c)
{
int32_t z0 = auxvars.getVariable();
comparator(odd_merge[i], even_merge[j], z0, formula, direction);
output.push_back(z0);
break;
}
}
else
if (i >= odd_merge.size() && j >= even_merge.size())
break; // should never occure since we catch: if (output.size() == c) break; (with c at most n)
else
if (i >= odd_merge.size())
{
assert(j == even_merge.size() - 1);
output.push_back(even_merge.back());
break;
}
else
{
assert(i == odd_merge.size() - 1);
output.push_back(odd_merge.back());
break;
}
i++;
j++;
}
assert(output.size() == a + b || output.size() == c);
}
void Sorting::direct_merger(int m, const vector< int32_t >& input_a, const vector< int32_t >& input_b, ClauseDatabase& formula, AuxVarManager& auxvars, vector< int32_t >& output, ImplicationDirection direction)
{
assert(direction == INPUT_TO_OUTPUT);
int a = input_a.size();
int b = input_b.size();
int n = a + b;
for (int i = 0; i < m; ++i)
output.push_back(auxvars.getVariable());
int j = m < a ? m : a;
for (int i = 0; i < j; ++i)
{
formula.addClause(-input_a[i], output[i]);
}
j = m < b ? m : b;
for (int i = 0; i < j; ++i)
{
formula.addClause(-input_b[i], output[i]);
}
for (int i = 0; i < a; ++i)
{
for (int j = 0; j < b; ++j)
{
if (i+j+1 < m)
formula.addClause(-input_a[i], -input_b[j], output[i+j+1]);
}
}
}
void Sorting::merge(int m, const vector< int32_t >& input_a, const vector< int32_t >& input_b, ClauseDatabase& formula, AuxVarManager& auxvars, vector< int32_t >& output, PBLib::Sorting::ImplicationDirection direction)
{
assert(m >= 0);
if (m == 0)
{
output.clear();
return;
}
int a = input_a.size();
int b = input_b.size();
int n = a + b;
if (m > n)
m = n; // normalize
if (a == 0 || b == 0)
{
output.clear();
output = a == 0 ? input_b : input_a;
return;
}
if (direction != INPUT_TO_OUTPUT)
{
recursive_merger(m, input_a, input_a.size(), input_b, input_b.size(), formula, auxvars, output, direction);
return;
}
int64_t direct = direct_merger_value(m,a,b, direction);
int64_t recursive = recursive_merger_value(m,a,b, direction);
if (direct < recursive)
{
direct_merger(m, input_a, input_b, formula, auxvars, output, direction);
}
else
{
recursive_merger(m, input_a, input_a.size(), input_b, input_b.size(), formula, auxvars, output, direction);
}
}
void Sorting::comparator(const int32_t x1, const int32_t x2, const int32_t y, ClauseDatabase& formula, ImplicationDirection direction)
{
assert(x1 != x2);
if (direction == INPUT_TO_OUTPUT || direction == BOTH)
{
formula.addClause(-x1, y);
formula.addClause(-x2, y);
}
if (direction == OUTPUT_TO_INPUT || direction == BOTH)
{
formula.addClause(-y, x1, x2);
}
}
void Sorting::comparator(const int32_t x1, const int32_t x2, const int32_t y1, const int32_t y2, ClauseDatabase& formula, ImplicationDirection direction)
{
assert(x1 != x2);
assert(y1 != y2);
if (direction == INPUT_TO_OUTPUT || direction == BOTH)
{
formula.addClause(-x1, y1);
formula.addClause(-x2, y1);
formula.addClause(-x1,-x2, y2);
}
if (direction == OUTPUT_TO_INPUT || direction == BOTH)
{
formula.addClause(-y1, x1, x2);
formula.addClause(-y2, x1);
formula.addClause(-y2, x2);
}
}
int64_t Sorting::value_function(int num_clauses, int num_variables)
{
return num_clauses;
}
int64_t Sorting::direct_merger_value(int m, int a, int b, ImplicationDirection direction)
{
return value_function((a+b)*m-(m*m-m)/2-(a*a-a)/2-(b*b-b)/2, m);
}
int64_t Sorting::recursive_sorter_value(int m, int n, int l, ImplicationDirection direction)
{
auto entry = recursive_sorter_l_values.find(tuple<int32_t,int32_t,int32_t>(m,n,l));
if (entry != recursive_sorter_l_values.end())
return entry->second;
PBConfig config = make_shared<PBConfigClass>();
CountingClauseDatabase formula(config);
AuxVarManager auxvars(n+1);
vector<int32_t> input, output;
for (int i = 0; i < n; ++i)
input.push_back(i+1);
recursive_sorter(m,l,input, formula, auxvars, output, direction);
int64_t value = value_function(formula.getNumberOfClauses(), auxvars.getBiggestReturnedAuxVar() - n);
recursive_sorter_l_values[tuple<int32_t,int32_t,int32_t>(m,n,l)] = value;
return value;
}
int64_t Sorting::recursive_merger_value(int m, int a, int b, ImplicationDirection direction)
{
auto entry = recursive_merger_values.find(tuple<int32_t,int32_t,int32_t>(m,a,b));
if (entry != recursive_merger_values.end())
return entry->second;
PBConfig config = make_shared<PBConfigClass>();
CountingClauseDatabase formula(config);
AuxVarManager auxvars(a+b+1);
vector<int32_t> input_a, input_b, output;
for (int i = 0; i < a; ++i)
input_a.push_back(i+1);
for (int i = 0; i < b; ++i)
input_b.push_back(i+a+1);
recursive_merger(m,input_a, a, input_b, b, formula, auxvars, output, direction);
int64_t value = value_function(formula.getNumberOfClauses(), auxvars.getBiggestReturnedAuxVar() - a -b);
recursive_merger_values[tuple<int32_t,int32_t,int32_t>(m,a,b)] = value;
return value;
}
int64_t Sorting::recursive_sorter_value(int m, int n, ImplicationDirection direction)
{
auto entry = recursive_sorter_values.find(pair<int32_t,int32_t>(m,n));
if (entry != recursive_sorter_values.end())
return entry->second;
PBConfig config = make_shared<PBConfigClass>();
CountingClauseDatabase formula(config);
AuxVarManager auxvars(n+1);
vector<int32_t> input, output;
for (int i = 0; i < n; ++i)
input.push_back(i+1);
recursive_sorter(m,input, formula, auxvars, output, direction);
int64_t value = value_function(formula.getNumberOfClauses(), auxvars.getBiggestReturnedAuxVar() - n);
recursive_sorter_values[pair<int32_t,int32_t>(m,n)] = value;
return value;
}
int64_t Sorting::counter_sorter_value(int m, int n, ImplicationDirection direction)
{
return value_function(2*n+(m-1)*(2*(n-1)-1)-(m-2)-2*((m-1)*(m-2)/2), m*n-m*(m-1)/2);
}
int64_t Sorting::direct_sorter_value(int m, int n, ImplicationDirection direction)
{
if (n > 30)
return LLONG_MAX;
return value_function(pow(2,n) - 1, m);
}
}
|
966140a1b98019209ff92bbae31a4d7200262c52
|
ccc02f0ef4e423496fdb2857997d15b8d011391a
|
/unistor/bench/unistor_bench/UnistorBenchApp.cpp
|
275c0623bc6451c2ece4c99b99fa96ebcd05880a
|
[] |
no_license
|
mbsky/cwx-kv
|
e40659ae4668be283139b727fe812fad16cb00c8
|
7372026e76749bd43f7d927fe6d7d71f6b70850f
|
refs/heads/master
| 2020-04-15T01:17:25.452039
| 2012-10-10T14:02:57
| 2012-10-10T14:02:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,549
|
cpp
|
UnistorBenchApp.cpp
|
#include "UnistorBenchApp.h"
#include "CwxSocket.h"
///构造函数
UnistorBenchApp::UnistorBenchApp(){
m_threadPool = NULL;
m_eventHandler = NULL;
}
///析构函数
UnistorBenchApp::~UnistorBenchApp(){
}
///初始化APP,加载配置文件
int UnistorBenchApp::init(int argc, char** argv){
string strErrMsg;
///首先调用架构的init
if (CwxAppFramework::init(argc, argv) == -1) return -1;
///若没有通过-f指定配置文件,则采用默认的配置文件
if ((NULL == this->getConfFile()) || (strlen(this->getConfFile()) == 0)){
this->setConfFile("unistor_bench.cnf");
}
///加载配置文件
if (0 != m_config.loadConfig(getConfFile())){
CWX_ERROR((m_config.getError()));
return -1;
}
///设置输出运行日志的level
setLogLevel(CwxLogger::LEVEL_ERROR|CwxLogger::LEVEL_INFO|CwxLogger::LEVEL_WARNING);
return 0;
}
//init the Enviroment before run.0:success, -1:failure.
int UnistorBenchApp::initRunEnv(){
///设置时钟的刻度,最小为1ms,此为1s。
this->setClick(1000);//1s
//set work dir
this->setWorkDir(this->m_config.m_strWorkDir.c_str());
//Set log file
this->setLogFileNum(LOG_FILE_NUM);
this->setLogFileSize(LOG_FILE_SIZE*1024*1024);
///调用架构的initRunEnv,使设置的参数生效
if (CwxAppFramework::initRunEnv() == -1 ) return -1;
//output config
m_config.outputConfig();
CWX_UINT16 i=0;
//建立配置文件中设置的、与echo服务的连接
for (i=0; i<m_config.m_unConnNum; i++){
//create conn
if (0 > this->noticeTcpConnect(SVR_TYPE_RECV,
0,
this->m_config.m_listen.getHostName().c_str(),
this->m_config.m_listen.getPort(),
false,
1,
2,
UnistorBenchApp::setSockAttr,
this))
{
CWX_ERROR(("Can't connect the service: addr=%s, port=%d",
this->m_config.m_listen.getHostName().c_str(),
this->m_config.m_listen.getPort()));
return -1;
}
}
//注册handle
m_eventHandler = new UnistorEventHandler(this);
this->getCommander().regHandle(SVR_TYPE_RECV, m_eventHandler);
//启动线程
m_threadPool = new CwxThreadPool(2,
1,
getThreadPoolMgr(),
&getCommander());
CwxTss** pTss = new CwxTss*[1];
pTss[0] = new UnistorTss();
((UnistorTss*)pTss[0])->init();
///启动线程。
if ( 0 != m_threadPool->start(pTss)){
CWX_ERROR(("Failure to start thread pool"));
return -1;
}
return 0;
}
///信号处理函数
void UnistorBenchApp::onSignal(int signum){
switch(signum){
case SIGQUIT:
CWX_INFO(("Recv exit signal, exit right now."));
this->stop();
break;
default:
///其他信号,忽略
CWX_INFO(("Recv signal=%d, ignore it.", signum));
break;
}
}
///echo服务的连接建立响应函数
int UnistorBenchApp::onConnCreated(CwxAppHandler4Msg& conn, bool& , bool& ){
CwxMsgBlock* msg = CwxMsgBlockAlloc::malloc(0);
msg->event().setSvrId(conn.getConnInfo().getSvrId());
msg->event().setHostId(conn.getConnInfo().getHostId());
msg->event().setConnId(conn.getConnInfo().getConnId());
msg->event().setEvent(CwxEventInfo::CONN_CREATED);
m_threadPool->append(msg);
return 0;
}
///echo回复的消息响应函数
int UnistorBenchApp::onRecvMsg(CwxMsgBlock* msg,
CwxAppHandler4Msg& conn,
CwxMsgHead const& header,
bool& )
{
msg->event().setSvrId(conn.getConnInfo().getSvrId());
msg->event().setHostId(conn.getConnInfo().getHostId());
msg->event().setConnId(conn.getConnInfo().getConnId());
msg->event().setEvent(CwxEventInfo::RECV_MSG);
msg->event().setMsgHeader(header);
msg->event().setTimestamp(CwxDate::getTimestamp());
m_threadPool->append(msg);
return 0;
}
///设置连接的属性
int UnistorBenchApp::setSockAttr(CWX_HANDLE handle, void* arg){
UnistorBenchApp* app = (UnistorBenchApp*)arg;
if (app->m_config.m_listen.isKeepAlive()){
if (0 != CwxSocket::setKeepalive(handle,
true,
CWX_APP_DEF_KEEPALIVE_IDLE,
CWX_APP_DEF_KEEPALIVE_INTERNAL,
CWX_APP_DEF_KEEPALIVE_COUNT))
{
CWX_ERROR(("Failure to set listen addr:%s, port:%u to keep-alive, errno=%d",
app->m_config.m_listen.getHostName().c_str(),
app->m_config.m_listen.getPort(),
errno));
return -1;
}
}
int flags= 1;
if (setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)) != 0){
CWX_ERROR(("Failure to set listen addr:%s, port:%u NODELAY, errno=%d",
app->m_config.m_listen.getHostName().c_str(),
app->m_config.m_listen.getPort(),
errno));
return -1;
}
struct linger ling= {0, 0};
if (setsockopt(handle, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)) != 0)
{
CWX_ERROR(("Failure to set listen addr:%s, port:%u LINGER, errno=%d",
app->m_config.m_listen.getHostName().c_str(),
app->m_config.m_listen.getPort(),
errno));
return -1;
}
return 0;
}
void UnistorBenchApp::destroy(){
if (m_threadPool){
m_threadPool->stop();
delete m_threadPool;
m_threadPool = NULL;
}
if (m_eventHandler)
{
delete m_eventHandler;
m_eventHandler = NULL;
}
CwxAppFramework::destroy();
}
|
10266e92af6c53d97796de5bfc686e110b5b86cd
|
fc409bb39543d5c89baad42ec719aba458056c27
|
/AdventOfCode2020/AdventOfCodeDays.h
|
5481234c3d2f2e0ac872c4d84e24d2371af0b248
|
[] |
no_license
|
AmonJG/AdventOfCode2020
|
0b07e54a096a23e8d847f75fed4f68868689b94e
|
e01a74c5cfda18770b1b6365d5f548389b3bf00d
|
refs/heads/main
| 2023-02-03T08:32:26.895150
| 2020-12-21T22:46:11
| 2020-12-21T22:48:26
| 317,689,384
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,707
|
h
|
AdventOfCodeDays.h
|
#pragma once
#include "AdventOfCodeTask.h"
class AdventOfCodeTask1Day1 : public AdventOfCodeTask { public: AdventOfCodeTask1Day1(); };
class AdventOfCodeTask2Day1 : public AdventOfCodeTask { public: AdventOfCodeTask2Day1(); };
class AdventOfCodeTask1Day2 : public AdventOfCodeTask { public: AdventOfCodeTask1Day2(); };
class AdventOfCodeTask2Day2 : public AdventOfCodeTask { public: AdventOfCodeTask2Day2(); };
class AdventOfCodeTask1Day3 : public AdventOfCodeTask { public: AdventOfCodeTask1Day3(); };
class AdventOfCodeTask2Day3 : public AdventOfCodeTask { public: AdventOfCodeTask2Day3(); };
class AdventOfCodeTask1Day4 : public AdventOfCodeTask { public: AdventOfCodeTask1Day4(); };
class AdventOfCodeTask2Day4 : public AdventOfCodeTask { public: AdventOfCodeTask2Day4(); };
class AdventOfCodeTask1Day5 : public AdventOfCodeTask { public: AdventOfCodeTask1Day5(); };
class AdventOfCodeTask2Day5 : public AdventOfCodeTask { public: AdventOfCodeTask2Day5(); };
class AdventOfCodeTask1Day6 : public AdventOfCodeTask { public: AdventOfCodeTask1Day6(); };
class AdventOfCodeTask2Day6 : public AdventOfCodeTask { public: AdventOfCodeTask2Day6(); };
class AdventOfCodeTask1Day7 : public AdventOfCodeTask { public: AdventOfCodeTask1Day7(); };
class AdventOfCodeTask2Day7 : public AdventOfCodeTask { public: AdventOfCodeTask2Day7(); };
class AdventOfCodeTask1Day8 : public AdventOfCodeTask { public: AdventOfCodeTask1Day8(); };
class AdventOfCodeTask2Day8 : public AdventOfCodeTask { public: AdventOfCodeTask2Day8(); };
class AdventOfCodeTask1Day9 : public AdventOfCodeTask { public: AdventOfCodeTask1Day9(); };
class AdventOfCodeTask2Day9 : public AdventOfCodeTask { public: AdventOfCodeTask2Day9(); };
class AdventOfCodeTask1Day10 : public AdventOfCodeTask { public: AdventOfCodeTask1Day10(); };
class AdventOfCodeTask2Day10 : public AdventOfCodeTask { public: AdventOfCodeTask2Day10(); };
class AdventOfCodeTask1Day11 : public AdventOfCodeTask { public: AdventOfCodeTask1Day11(); };
class AdventOfCodeTask2Day11 : public AdventOfCodeTask { public: AdventOfCodeTask2Day11(); };
class AdventOfCodeTask1Day12 : public AdventOfCodeTask { public: AdventOfCodeTask1Day12(); };
class AdventOfCodeTask2Day12 : public AdventOfCodeTask { public: AdventOfCodeTask2Day12(); };
class AdventOfCodeTask1Day13 : public AdventOfCodeTask { public: AdventOfCodeTask1Day13(); };
class AdventOfCodeTask2Day13 : public AdventOfCodeTask { public: AdventOfCodeTask2Day13(); };
class AdventOfCodeTask1Day14 : public AdventOfCodeTask { public: AdventOfCodeTask1Day14(); };
class AdventOfCodeTask2Day14 : public AdventOfCodeTask { public: AdventOfCodeTask2Day14(); };
class AdventOfCodeTask1Day15 : public AdventOfCodeTask { public: AdventOfCodeTask1Day15(); };
class AdventOfCodeTask2Day15 : public AdventOfCodeTask { public: AdventOfCodeTask2Day15(); };
class AdventOfCodeTask1Day16 : public AdventOfCodeTask { public: AdventOfCodeTask1Day16(); };
class AdventOfCodeTask2Day16 : public AdventOfCodeTask { public: AdventOfCodeTask2Day16(); };
class AdventOfCodeTask1Day17 : public AdventOfCodeTask { public: AdventOfCodeTask1Day17(); };
class AdventOfCodeTask2Day17 : public AdventOfCodeTask { public: AdventOfCodeTask2Day17(); };
class AdventOfCodeTask1Day18 : public AdventOfCodeTask { public: AdventOfCodeTask1Day18(); };
class AdventOfCodeTask2Day18 : public AdventOfCodeTask { public: AdventOfCodeTask2Day18(); };
class AdventOfCodeTask1Day19 : public AdventOfCodeTask { public: AdventOfCodeTask1Day19(); };
class AdventOfCodeTask2Day19 : public AdventOfCodeTask { public: AdventOfCodeTask2Day19(); };
class AdventOfCodeTask1Day20 : public AdventOfCodeTask { public: AdventOfCodeTask1Day20(); };
class AdventOfCodeTask2Day20 : public AdventOfCodeTask { public: AdventOfCodeTask2Day20(); };
class AdventOfCodeTask1Day21 : public AdventOfCodeTask { public: AdventOfCodeTask1Day21(); };
class AdventOfCodeTask2Day21 : public AdventOfCodeTask { public: AdventOfCodeTask2Day21(); };
class AdventOfCodeTask1Day22 : public AdventOfCodeTask { public: AdventOfCodeTask1Day22(); };
class AdventOfCodeTask2Day22 : public AdventOfCodeTask { public: AdventOfCodeTask2Day22(); };
class AdventOfCodeTask1Day23 : public AdventOfCodeTask { public: AdventOfCodeTask1Day23(); };
class AdventOfCodeTask2Day23 : public AdventOfCodeTask { public: AdventOfCodeTask2Day23(); };
class AdventOfCodeTask1Day24 : public AdventOfCodeTask { public: AdventOfCodeTask1Day24(); };
class AdventOfCodeTask2Day24 : public AdventOfCodeTask { public: AdventOfCodeTask2Day24(); };
class AdventOfCodeTask1Day25 : public AdventOfCodeTask { public: AdventOfCodeTask1Day25(); };
class AdventOfCodeTask2Day25 : public AdventOfCodeTask { public: AdventOfCodeTask2Day25(); };
|
edce19294a8a1f878eb86bb4212b7f2144ac0f95
|
1321f626a38f5e9e4a837e8d307cfcbbe82599dd
|
/hardwareManager.h
|
44651e98753f85394cf27855326bfa6f82385153
|
[] |
no_license
|
tobiaseydam/MotDetCode
|
5795b8cf67f6bfb406adcb8923477cfe0bed603c
|
e117233e76e687b3e045093c15d40d9c82b64223
|
refs/heads/master
| 2020-04-01T07:50:53.905374
| 2018-11-24T17:12:50
| 2018-11-24T17:12:50
| 153,006,450
| 0
| 0
| null | 2018-11-24T16:30:15
| 2018-10-14T18:38:58
|
C++
|
UTF-8
|
C++
| false
| false
| 2,491
|
h
|
hardwareManager.h
|
#ifndef HARDWAREMANAGER_H
#define HARDWAREMANAGER_H
#include <WString.h>
#include <Arduino.h>
#include <WiFi.h>
#include <OneWire.h>
class HardwareList;
#include "asyncSM.h"
enum eHardwareType{
RELAY,
INPUT230V,
TELEMETRY,
ONEWIRE
};
class HardwareIO{
protected:
String _name;
eHardwareType _type;
String _mqttFragment;
String _webDesc;
public:
String getName();
eHardwareType getType();
String getMqttFragment();
String getMqttTopic();
String getWebDesc();
virtual String getStringState();
};
enum eState{
ON,
OFF
};
class HardwareRelay: public HardwareIO{
protected:
int _pin;
public:
HardwareRelay(int pin, String name, String mqttFragment);
void setState(eState state);
void setStringState(char* state);
eState getState();
String getStringState();
};
class Hardware230VSensor: public HardwareIO{
protected:
int _pin;
boolean changed;
eState lastState = OFF;
public:
Hardware230VSensor(int pin, String name, String mqttFragment);
eState getState();
String getValue();
String getStringState();
boolean hasChanged();
void read();
};
class Hardware1WireSensor: public HardwareIO{
protected:
int _pin;
OneWire* ds;
byte addr[16][8];
byte numDev = 0;
float _getSensorValue(byte k);
public:
Hardware1WireSensor(int pin, String name, String mqttFragment);
String getValue();
String getStringState();
byte getNumDevs();
String _getAddr(byte k);
};
class HardwareTele: public HardwareIO{
private:
String (*_getVal)();
public:
HardwareTele(String name, String mqttFragment, String (*getVal)(), String webDesc);
String getValue();
String getStringState();
};
class HardwareList{
protected:
static const int _len = 9;
HardwareIO* _list[_len];
public:
int getLen();
HardwareIO* getElement(int i);
HardwareList();
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.