blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b718cdaaf6cb52632a566960ef066a6f14d66f4c | d90658a33da4f273f5c6c5c4a9c522987c5221f0 | /include/PBE/System/Time.h | 6915a849f2ae598c188020480c02a0422acf80a5 | [] | no_license | rkBrunecz/projectJR | adb02860bdcb6aca096a1670c6a5ac472dd24426 | 8205eb5dbe15eab416eda68f30564d8cbc37f3b7 | refs/heads/master | 2020-04-06T07:12:44.188680 | 2016-11-09T08:36:16 | 2016-11-09T08:36:16 | 41,326,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 834 | h | /*
Time.h
This class is designed simply to be a convient way to contain time in hours, minutes, and seconds. It allows for code to be much
more readable when using time to perform calculations. The class is meant to only be a container, and the data within should never
need to be modified.
@author Randall Brunecz
@version 1.0 9/22/2016
*/
#ifndef Time_H
#define Time_H
namespace pb
{
class Time
{
public:
short hours, minutes, seconds;
// Constructor
Time() : hours(0), minutes(0), seconds(0) {};
Time(short hours, short minutes, short seconds) : hours(hours), minutes(minutes), seconds(seconds) {};
// Operators
friend bool operator==(const Time& t1, const Time& t2)
{
if (t1.hours == t2.hours && t1.minutes == t2.minutes && t1.seconds == t2.seconds)
return true;
return false;
}
};
}
#endif | [
"rkbrunecz@gmail.com"
] | rkbrunecz@gmail.com |
81966059967de5a16f04b86aa05b5223c2b79acd | 5a8a21f1b241d13c8294312700728a913e4e9900 | /C++/647_PalindromicSubstrings.cpp | 1382edbbe94f9d64e4e4ef606c7cd5a59f46d71d | [] | no_license | iamzay/leetcode | 251d2b4fd5a9be1d3dbb34a0807b23f73938e2df | c1e72b6a78949f01822feeac6db24e793d5530d6 | refs/heads/master | 2020-12-30T13:29:14.063837 | 2018-10-15T03:10:56 | 2018-10-15T03:10:56 | 91,225,387 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | cpp | class Solution {
public:
int countSubstrings(string s) {
int n=s.size();
for(int i=0;i<n;++i){
extendPalindromic(s,i,i);
extendPalindromic(s,i,i+1);
}
return res;
}
private:
void extendPalindromic(string &s,int left,int right){
int n=s.size();
for(;left>=0&&right<n&&s[left]==s[right];--left,++right)
++res;
}
int res;
};
| [
"zayhust@gmail.com"
] | zayhust@gmail.com |
e4dd3a1aaeabcc5003152e6ce5a77cbc8d93fc7f | b0980ec24dd4f0d708d3ce228c327bedc254d617 | /modules/Players/Hand.cpp | a2b7d5783406db95fa39accf6534eeb2b596217d | [] | no_license | 11asa11/BlackJack | 9a06cdac5d6ad9124efd67b484b88de9fa3df93a | d932a3ddfb5eb18d8eabb85ef2b061120d0ee667 | refs/heads/master | 2022-11-30T04:33:48.436412 | 2020-08-10T21:05:46 | 2020-08-10T21:05:46 | 281,374,801 | 0 | 0 | null | 2020-08-10T21:05:47 | 2020-07-21T11:08:01 | CMake | UTF-8 | C++ | false | false | 477 | cpp | #include "Hand.h"
Hand::Hand() {}
void Hand::takeCard(Card& card) {
h_cards.push_back(card);
}
std::vector<std::string> Hand::showInfo() {
std::vector<std::string> vec;
for (auto& i : h_cards) {
vec.push_back(i.Info());
}
return vec;
}
std::size_t Hand::values() {
std::size_t val = 0;
for (auto& i : h_cards) {
val += i.getValue_Info();
}
return val;
}
void Hand::clear() {
h_cards.clear();
}
std::size_t Hand::number_cards() {
return h_cards.size();
} | [
"serega_kozm@mail.ru"
] | serega_kozm@mail.ru |
a083436f0c40e6b302b218d542a877a06a9c076d | 8f19529b08737ac993f7d4ddcf98353648382512 | /src/zoneserver/model/gameobject/ability/GraveStoneable.h | fb02e8753a069378c5a4194a121c5f022e11aaf9 | [
"MIT"
] | permissive | mark-online/server | 86023ce6a9a988b1559b696d07cb349b2bafad8f | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | refs/heads/master | 2020-08-25T09:18:13.919661 | 2019-12-15T02:39:19 | 2019-12-15T02:39:19 | 216,990,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 711 | h | #pragma once
namespace gideon { namespace zoneserver { namespace gc {
class PlayerGraveStoneController;
}}} // namespace gideon { namespace zoneserver { namespace gc {
namespace gideon { namespace zoneserver { namespace go {
/**
* @class GraveStoneable
* 바석을 사용할수 있다
*/
class GraveStoneable
{
public:
virtual ~GraveStoneable() {}
public:
virtual std::unique_ptr<gc::PlayerGraveStoneController> createPlayerGraveStoneController() = 0;
public:
virtual gc::PlayerGraveStoneController& getPlayerGraveStoneController() = 0;
virtual const gc::PlayerGraveStoneController& getPlayerGraveStoneController() const = 0;
};
}}} // namespace gideon { namespace zoneserver { namespace go {
| [
"kcando@gmail.com"
] | kcando@gmail.com |
a27aa415e353cc394ad2684a0e43a02bf2f6511a | 482891b0c9b2a023a447d88c5ae70a7ce198c7ac | /StRoot/St_ctf_Maker/St_ctf_Maker.h | 45e7c741904df97a6db244d320a49e59c85e553a | [
"MIT"
] | permissive | xiaohaijin/RHIC-STAR | 7aed3075035f4ceaba154718b0660c74c1355a82 | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | refs/heads/master | 2020-03-28T12:31:26.190991 | 2018-10-28T16:07:06 | 2018-10-28T16:07:06 | 148,306,863 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,780 | h | // $Id: St_ctf_Maker.h,v 1.9 2014/08/06 11:43:54 jeromel Exp $
// $Log: St_ctf_Maker.h,v $
// Revision 1.9 2014/08/06 11:43:54 jeromel
// Suffix on literals need to be space (later gcc compiler makes it an error) - first wave of fixes
//
// Revision 1.8 2003/09/10 19:47:44 perev
// ansi corrs
//
// Revision 1.7 1999/07/15 13:57:49 perev
// cleanup
//
// Revision 1.6 1999/03/11 03:55:07 perev
// new schema
//
// Revision 1.5 1999/02/23 21:25:43 llope
// fixed histograms, added 1/beta vs p
//
// Revision 1.4 1999/02/06 00:15:47 fisyak
// Add adc/tdc histograms
//
// Revision 1.3 1999/01/25 23:39:13 fisyak
// Add tof
//
// Revision 1.2 1999/01/02 19:08:14 fisyak
// Add ctf
//
// Revision 1.1 1999/01/01 02:39:38 fisyak
// Add ctf Maker
//
// Revision 1.7 1998/10/31 00:25:45 fisyak
// Makers take care about branches
//
// Revision 1.6 1998/10/06 18:00:31 perev
// cleanup
//
// Revision 1.5 1998/08/26 12:15:13 fisyak
// Remove asu & dsl libraries
//
// Revision 1.4 1998/08/14 15:25:58 fisyak
// add options
//
// Revision 1.3 1998/08/10 02:32:07 fisyak
// Clean up
//
// Revision 1.2 1998/07/20 15:08:15 fisyak
// Add tcl and tpt
//
#ifndef STAR_St_ctf_Maker
#define STAR_St_ctf_Maker
//////////////////////////////////////////////////////////////////////////
// //
// St_ctf_Maker virtual base class for Maker //
// //
//////////////////////////////////////////////////////////////////////////
#ifndef StMaker_H
#include "StMaker.h"
#endif
class St_ctg_geo;
class St_ctg_slat_phi;
class St_ctg_slat_eta;
class St_ctg_slat;
class St_cts_mpara;
class TH1F;
class TH2F;
class St_ctf_Maker : public StMaker {
private:
Bool_t drawinit;
St_ctg_geo *m_ctb; //!
St_ctg_slat_phi *m_ctb_slat_phi; //!
St_ctg_slat_eta *m_ctb_slat_eta; //!
St_ctg_slat *m_ctb_slat; //!
St_cts_mpara *m_cts_ctb; //!
St_ctg_geo *m_tof; //!
St_ctg_slat_phi *m_tof_slat_phi; //!
St_ctg_slat_eta *m_tof_slat_eta; //!
St_ctg_slat *m_tof_slat; //!
St_cts_mpara *m_cts_tof; //!
protected:
TH1F *m_adcc; //!
TH1F *m_adct; //!
TH2F *m_tsvsp; //!
TH2F *m_tsvsp1; //!
public:
St_ctf_Maker(const char *name="ctf");
virtual ~St_ctf_Maker();
virtual Int_t Init();
virtual Int_t Make();
virtual const char *GetCVS() const
{static const char cvs[]="Tag $Name: SL18c $ $Id: St_ctf_Maker.h,v 1.9 2014/08/06 11:43:54 jeromel Exp $ built " __DATE__ " " __TIME__ ; return cvs;}
ClassDef(St_ctf_Maker,0) //StAF chain virtual base class for Makers
};
#endif
| [
"xiaohaijin@outlook.com"
] | xiaohaijin@outlook.com |
0ff08b1a18d5bca59db635bf9e0c9e7e9709c444 | 49157e78433379b48391567b5893374a3f57d3cd | /Game/game.cpp | e30c321bad264ab53571b5c8211c48499b6c68b2 | [
"MIT"
] | permissive | harrymcalpine/LemmingsGroupProject | 9eccbdb865f0e061da12bb82a3102566c2dd7d95 | c023b83e1a300f78cacad67ff8ee65884a7ffa06 | refs/heads/master | 2021-01-22T17:38:58.317863 | 2016-07-05T23:36:00 | 2016-07-05T23:36:00 | 62,676,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,528 | cpp | #include "game.h"
#include "GameData.h"
#include "drawdata.h"
#include "DrawData2D.h"
#include "gameobject.h"
#include "ObjectList.h"
#include "helper.h"
#include <windows.h>
#include <time.h>
#include "DDSTextureLoader.h"
#include <d3d11shader.h>
#include "ObjectsManager.h"
#include "VBplane.h"
#include "RenderTarget.h"
#include "Cursor.h"
#include "Boundingbox.h"
#include "ImageGO2D.h"
using namespace DirectX;
Game::Game(ID3D11Device* _pd3dDevice, HWND _hWnd, HINSTANCE _hInstance) :m_playTime(0), m_fxFactory(nullptr), m_states(nullptr)
{
//Create DirectXTK spritebatch stuff
ID3D11DeviceContext* pd3dImmediateContext;
_pd3dDevice->GetImmediateContext(&pd3dImmediateContext);
m_DD2D = new DrawData2D();
m_DD2D->m_Sprites.reset(new SpriteBatch(pd3dImmediateContext));
m_DD2D->m_Font.reset(new SpriteFont(_pd3dDevice, L"italic.spritefont"));
m_playTime = 0;
//seed the random number generator
srand((UINT)time(NULL));
//Direct Input Stuff
m_hWnd = _hWnd;
m_pKeyboard = nullptr;
m_pDirectInput = nullptr;
HRESULT hr = DirectInput8Create(_hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDirectInput, NULL);
hr = m_pDirectInput->CreateDevice(GUID_SysKeyboard, &m_pKeyboard, NULL);
hr = m_pKeyboard->SetDataFormat(&c_dfDIKeyboard);
hr = m_pKeyboard->SetCooperativeLevel(m_hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
hr = m_pDirectInput->CreateDevice(GUID_SysMouse, &m_pMouse, NULL);
hr = m_pMouse->SetDataFormat(&c_dfDIMouse);
hr = m_pMouse->SetCooperativeLevel(m_hWnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
//create GameData struct and populate its pointers
m_GD = new GameData;
m_GD->m_keyboardState = m_keyboardState;
m_GD->m_prevKeyboardState = m_prevKeyboardState;
m_GD->m_GS = GS_LOGO;
m_GD->m_mouseState = &m_mouseState;
//set up DirectXTK Effects system
m_fxFactory = new EffectFactory(_pd3dDevice);
//Tell the fxFactory to look to the correct build directory to pull stuff in from
#ifdef DEBUG
((EffectFactory*)m_fxFactory)->SetDirectory(L"../Debug");
#else
((EffectFactory*)m_fxFactory)->SetDirectory(L"../Release");
#endif
// Create other render resources here
m_states = new CommonStates(_pd3dDevice);
//init render system for VBGOs
VBGO::Init(_pd3dDevice);
//find how big my window is to correctly calculate my aspect ratio
RECT rc;
GetClientRect(m_hWnd, &rc);
m_GD->width = rc.right - rc.left;
m_GD->height = rc.bottom - rc.top;
float AR = (float)m_GD->width / (float)m_GD->height;
//create a base camera
m_cam = new Camera(0.25f * XM_PI, AR, 1.0f, 10000.0f, Vector3::UnitY, Vector3(0.0f, 0.0f, -1000.0f));
m_cam->SetPos(Vector3(0.0f, 0.0f, 100.0f));
m_GameObjects.push_back(m_cam);
//create a base light
m_light = new Light(Vector3(0.0f, 100.0f, 160.0f), Color(1.0f, 1.0f, 1.0f, 1.0f), Color(0.5f, 0.5f, 0.5f, 1.0f));
m_GameObjects.push_back(m_light);
//create DrawData struct and populate its pointers
m_DD = new DrawData;
m_DD->m_pd3dImmediateContext = nullptr;
m_DD->m_states = m_states;
m_DD->m_cam = m_cam;
m_DD->m_light = m_light;
//add a player
Player* pPlayer = new Player("BirdModelV1.cmo", _pd3dDevice, m_fxFactory);
m_GameObjects.push_back(pPlayer);
//add a secondary camera
m_TPScam = new TPSCamera(0.25f * XM_PI, AR, 1.0f, 10000.0f, pPlayer, Vector3::UnitY, Vector3(0.0f, 10.0f, 50.0f));
m_GameObjects.push_back(m_TPScam);
Terrain* terrain = new Terrain("table.cmo", _pd3dDevice, m_fxFactory, Vector3(100.0f, 0.0f, 100.0f), 80.0f, 0.0f, 0.0f, 0.25f * Vector3::One);
//m_GameObjects.push_back(terrain);
Cursor* cursor = new Cursor("Cursor", _pd3dDevice, ANIMATION_PASS);
cursor->SetPos(Vector2(400, 300));
m_GameObjectMouse.push_back(cursor);
VBCube* cube = new VBCube();
cube->init(11, _pd3dDevice);
cube->SetPos(Vector3(100.0f, 0.0f, 0.0f));
cube->SetScale(1.0f);
//m_GameObjects.push_back(cube);
ImageGO2D* Level = new ImageGO2D("Level1", _pd3dDevice, FIRST_PASS);
Level->SetPos(Vector2(400, 350));
m_Terrain.push_back(Level);
ObjectsManager* m_OM = new ObjectsManager(_pd3dDevice, 5, 5, 5);
m_GD->m_OM = m_OM;
m_lemManager = new LemmingManager("SpawnerDDS", _pd3dDevice, 20, ANIMATION_PASS, 100.0f);
m_lemManager->SetPos(Vector2(400, 350));
m_GameObject2Ds.push_back(m_lemManager);
//RENDER TARGET INFORMATION AND THE PLANE IT IS LOADED ONTO
m_RD = new RenderTarget(_pd3dDevice, m_GD->width, m_GD->height);
m_GD->m_RD = m_RD;
VBPlane* LBox = new VBPlane();
LBox->init(100, _pd3dDevice, m_RD->GetShaderResourceView());
LBox->SetPos(Vector3(100.0f, 0.0f, -10.0f));
LBox->SetScale(1.0f);
m_GameObjects.push_back(LBox);
m_SecRD = new RenderTarget(_pd3dDevice, m_GD->width, m_GD->height);
m_GD->m_SecRD = m_SecRD;
VBPlane* GamePlane = new VBPlane();
GamePlane->init(100, _pd3dDevice, m_SecRD->GetShaderResourceView());
GamePlane->SetPos(Vector3(0.0f, 0.0f, -50.0f));
GamePlane->SetScale(1.0f);
m_GameObjects.push_back(GamePlane);
m_buttonManager = new ButtonManager(_pd3dDevice, ANIMATION_PASS);
m_GameObject2DsScreen.push_back(m_buttonManager);
#pragma endregion
#pragma region LogoScreen
ImageGO2D* LogoState = new ImageGO2D("lemmings_logo", _pd3dDevice, ANIMATION_PASS);
LogoState->SetPos(Vector2(400, 100));
m_GameObjectLogo.push_back(LogoState);
ImageGO2D* TeamLogo = new ImageGO2D("Team Logo", _pd3dDevice, ANIMATION_PASS);
TeamLogo->SetPos(Vector2(400, 350));
m_GameObjectLogo.push_back(TeamLogo);
ImageGO2D* Background = new ImageGO2D("Soil-Background", _pd3dDevice, ANIMATION_PASS);
Background->SetPos(Vector2(0, 0));
m_GameObjectLogo.push_front(Background);
#pragma endregion
#pragma region Options
ImageGO2D* optionsState = new ImageGO2D("lemmings_logo", _pd3dDevice, ANIMATION_PASS);
optionsState->SetPos(Vector2(400, 100));
m_GameObjectOptions.push_back(optionsState);
ImageGO2D* TeamLogo2 = new ImageGO2D("Team Logo", _pd3dDevice, ANIMATION_PASS);
TeamLogo2->SetPos(Vector2(400, 350));
m_GameObjectOptions.push_back(TeamLogo2);
ImageGO2D* Background2 = new ImageGO2D("Soil-Background", _pd3dDevice, ANIMATION_PASS);
Background2->SetPos(Vector2(0, 0));
m_GameObjectOptions.push_front(Background2);
#pragma endregion
#pragma region GameOver
ImageGO2D* TeamLogo3 = new ImageGO2D("Team Logo", _pd3dDevice, ANIMATION_PASS);
TeamLogo3->SetPos(Vector2(400, 350));
m_GameObjectOptions.push_back(TeamLogo3);
ImageGO2D* Background3 = new ImageGO2D("Soil-Background", _pd3dDevice, ANIMATION_PASS);
Background3->SetPos(Vector2(0, 0));
m_GameObjectOptions.push_front(Background3);
#pragma endregion
}
Game::~Game()
{
//delete Game Data & Draw Data
delete m_GD;
delete m_DD;
//tidy up VBGO render system
VBGO::CleanUp();
//tidy away Direct Input Stuff
if (m_pKeyboard)
{
m_pKeyboard->Unacquire();
m_pKeyboard->Release();
}
if (m_pMouse)
{
m_pMouse->Unacquire();
m_pMouse->Release();
}
if (m_pDirectInput)
{
m_pDirectInput->Release();
}
//get rid of the game objects here
for (list<GameObject *>::iterator it = m_GameObjects.begin(); it != m_GameObjects.end(); it++)
{
delete (*it);
}
m_GameObjects.clear();
//and the 2D ones
for (list<GameObject2D *>::iterator it = m_GameObject2Ds.begin(); it != m_GameObject2Ds.end(); it++)
{
delete (*it);
}
m_GameObject2Ds.clear();
//and the 2D Screen ones
for (list<GameObject2D *>::iterator it = m_GameObject2DsScreen.begin(); it != m_GameObject2DsScreen.end(); it++)
{
delete (*it);
}
m_GameObject2DsScreen.clear();
//clear away CMO render system
delete m_states;
delete m_fxFactory;
delete m_DD2D;
}
bool Game::Update()
{
//Poll Keyboard & Mouse
ReadInput();
//calculate frame time-step dt for passing down to game objects
DWORD currentTime = GetTickCount();
m_GD->m_dt = min((float)(currentTime - m_playTime) / 1000.0f, 0.1f);
m_playTime = currentTime;
//if paused press return to exit
if (m_GD->m_GS == GS_PAUSE)
{
if (m_keyboardState[DIK_RETURN] & 0x80)
{
return false;
}
}
if (m_GD->m_GS == GS_LOGO)
{
idleTimer -= m_GD->m_dt;
if (m_keyboardState[DIK_X] & 0x80)
{
m_GD->m_GS = GS_OPTIONS;
idleTimer = 30.0f;
}
if (idleTimer <= 0.1f)
{
m_GD->m_GS = GS_OPTIONS;
idleTimer = 30.0f;
}
}
if ((m_GD->m_lemmingsKilled + m_GD->m_lemmingsSaved) == 20)
{
m_GD->m_GS = GS_GAME_OVER;
idleTimer = 30.0f;
m_GD->m_lemmingsKilled = 0;
m_GD->m_lemmingsSaved = 0;
}
if (m_GD->m_GS == GS_GAME_OVER)
{
idleTimer -= m_GD->m_dt;
if (m_keyboardState[DIK_X] & 0x80)
{
m_GD->m_GS = GS_OPTIONS;
idleTimer = 30.0f;
}
if (idleTimer <= 0.1f)
{
m_GD->m_GS = GS_OPTIONS;
idleTimer = 30.0f;
}
}
if (m_GD->m_GS == GS_OPTIONS)
{
idleTimer -= m_GD->m_dt;
if (m_keyboardState[DIK_RETURN] & 0x80)
{
m_GD->m_GS = GS_ATTRACT;
idleTimer = 30.0f;
}
if (idleTimer <= 0.1f)
{
m_GD->m_GS = GS_ATTRACT;
idleTimer = 30.0f;
}
if (m_keyboardState[DIK_ESCAPE] & 0x80)
{
return false;
}
}
//lock the cursor to the centre of the window
RECT window;
GetWindowRect(m_hWnd, &window);
// SetCursorPos((window.left + window.right) >> 1, (window.bottom + window.top) >> 1);
if (m_GD->m_GS == GS_LOGO)
{
//update all objects
for (list<GameObject2D *>::iterator it = m_GameObjectLogo.begin(); it != m_GameObjectLogo.end(); it++)
{
(*it)->Tick(m_GD);
}
for (list<GameObject2D *>::iterator it = m_GameObjectMouse.begin(); it != m_GameObjectMouse.end(); it++)
{
(*it)->Tick(m_GD);
}
}
if (m_GD->m_GS == GS_OPTIONS)
{
//update all objects
for (list<GameObject2D *>::iterator it = m_GameObjectOptions.begin(); it != m_GameObjectOptions.end(); it++)
{
(*it)->Tick(m_GD);
}
for (list<GameObject2D *>::iterator it = m_GameObjectMouse.begin(); it != m_GameObjectMouse.end(); it++)
{
(*it)->Tick(m_GD);
}
}
if (m_GD->m_GS == GS_GAME_OVER)
{
//update all objects
for (list<GameObject2D *>::iterator it = m_GameObjectGameOver.begin(); it != m_GameObjectGameOver.end(); it++)
{
(*it)->Tick(m_GD);
}
for (list<GameObject2D *>::iterator it = m_GameObjectMouse.begin(); it != m_GameObjectMouse.end(); it++)
{
(*it)->Tick(m_GD);
}
}
if ((m_GD->m_GS == GS_ATTRACT) || (m_GD->m_GS == GS_PLAY_TPS_CAM) || (m_GD->m_GS == GS_PAUSE))
{
//On Escape press pauses, if paused pressing esc will unpause
if ((m_keyboardState[DIK_ESCAPE] & 0x80) && !(m_prevKeyboardState[DIK_ESCAPE] & 0x80))
{
if (m_GD->m_GS == GS_PAUSE)
{
m_GD->m_GS = GS_ATTRACT;
}
else
{
m_GD->m_GS = GS_PAUSE;
}
}
//apply selected job to selected lemmings
m_lemManager->ApplyJob(m_buttonManager->CheckButtons(m_GD));
//update all objects
for (list<GameObject *>::iterator it = m_GameObjects.begin(); it != m_GameObjects.end(); it++)
{
(*it)->Tick(m_GD);
}
for (list<GameObject2D *>::iterator it = m_GameObjectMouse.begin(); it != m_GameObjectMouse.end(); it++)
{
(*it)->Tick(m_GD);
}
for (list<GameObject2D *>::iterator it = m_GameObject2DsScreen.begin(); it != m_GameObject2DsScreen.end(); it++)
{
(*it)->Tick(m_GD);
}
if (m_GD->m_GS != GS_PAUSE)
{
for (list<GameObject2D *>::iterator it = m_GameObject2Ds.begin(); it != m_GameObject2Ds.end(); it++)
{
(*it)->Tick(m_GD);
}
}
}
//system("cls");
// cout << m_GD->m_GS << " " << idleTimer;
//idleTimer -= m_GD->m_dt;
return true;
}
void Game::Render(ID3D11DeviceContext* _pd3dImmediateContext)
{
//set immediate context of the graphics device
m_DD->m_pd3dImmediateContext = _pd3dImmediateContext;
//set which camera to be used
m_DD->m_cam = m_cam;
if (m_GD->m_GS == GS_PLAY_TPS_CAM)
{
m_DD->m_cam = m_TPScam;
}
//update the constant buffer for the rendering of VBGOs
VBGO::UpdateConstantBuffer(m_DD);
if (m_GD->m_GS == GS_LOGO)
{
m_DD2D->m_Pass = ANIMATION_PASS;
//update all objects
m_DD2D->m_Sprites->Begin(SpriteSortMode_Deferred);// , m_states->Additive());
for (list<GameObject2D *>::iterator it = m_GameObjectLogo.begin(); it != m_GameObjectLogo.end(); it++)
{
(*it)->Draw(m_DD2D);
//m_DD2D->m_Font->DrawString(m_DD2D->m_Sprites.get(), Helper::charToWChar("Logo State"), Vector2(0, 0), Colors::Yellow);
m_DD2D->m_Font->DrawString(m_DD2D->m_Sprites.get(), Helper::charToWChar("Press X To Go To The Menu"), Vector2(150, 500), Colors::Yellow);
}
m_DD2D->m_Sprites->End();
}
if (m_GD->m_GS == GS_GAME_OVER)
{
m_DD2D->m_Pass = ANIMATION_PASS;
//update all objects
m_DD2D->m_Sprites->Begin(SpriteSortMode_Deferred);// , m_states->Additive());
for (list<GameObject2D *>::iterator it = m_GameObjectLogo.begin(); it != m_GameObjectLogo.end(); it++)
{
(*it)->Draw(m_DD2D);
//m_DD2D->m_Font->DrawString(m_DD2D->m_Sprites.get(), Helper::charToWChar("Logo State"), Vector2(0, 0), Colors::Yellow);
m_DD2D->m_Font->DrawString(m_DD2D->m_Sprites.get(), Helper::charToWChar("Game Over!"), Vector2(150, 100), Colors::Yellow);
m_DD2D->m_Font->DrawString(m_DD2D->m_Sprites.get(), Helper::charToWChar("Press X To Go To The Menu"), Vector2(150, 500), Colors::Yellow);
}
m_DD2D->m_Sprites->End();
}
if (m_GD->m_GS == GS_OPTIONS)
{
m_DD2D->m_Pass = ANIMATION_PASS;
//update all objects
m_DD2D->m_Sprites->Begin(SpriteSortMode_Deferred);// , m_states->Additive());
for (list<GameObject2D *>::iterator it = m_GameObjectOptions.begin(); it != m_GameObjectOptions.end(); it++)
{
(*it)->Draw(m_DD2D);
//m_DD2D->m_Font->DrawString(m_DD2D->m_Sprites.get(), Helper::charToWChar("Options State"), Vector2(0, 0), Colors::Yellow);
m_DD2D->m_Font->DrawString(m_DD2D->m_Sprites.get(), Helper::charToWChar("Press Enter To Play The Game"), Vector2(150, 500), Colors::Yellow);
m_DD2D->m_Font->DrawString(m_DD2D->m_Sprites.get(), Helper::charToWChar("Or ESC To Exit The Game"), Vector2(150, 550), Colors::Yellow);
}
m_DD2D->m_Sprites->End();
}
if ((m_GD->m_GS == GS_ATTRACT) || (m_GD->m_GS == GS_PLAY_TPS_CAM) || (m_GD->m_GS == GS_PAUSE))
{
for (list<GameObject *>::iterator it = m_GameObjects.begin(); it != m_GameObjects.end(); it++)
{
(*it)->Draw(m_DD);
}
if (firstPass)
{
m_DD2D->m_Pass = FIRST_PASS;
if (m_RD->GetMapped())
{
m_RD->Unmap(m_DD->m_pd3dImmediateContext);
};
m_RD->Begin(m_DD->m_pd3dImmediateContext);
m_DD2D->m_Sprites->Begin(SpriteSortMode_Deferred);// , m_states->Additive());
for (list<GameObject2D *>::iterator it = m_Terrain.begin(); it != m_Terrain.end(); it++)
{
(*it)->Draw(m_DD2D);
}
ImageGO2D* terrain = new ImageGO2D(m_RD->GetShaderResourceView(), ANIMATION_PASS);
m_GameObject2Ds.push_back(terrain);
m_DD2D->m_Sprites->End();
m_RD->End(m_DD->m_pd3dImmediateContext);
m_RD->Map(m_DD->m_pd3dImmediateContext);
firstPass = false;
}
//Delete Pass
//Anything Drawn in here will render as deleted space, taking chunks out of
m_DD2D->m_Pass = DELETE_PASS;
if (m_RD->GetMapped())
{
m_RD->Unmap(m_DD->m_pd3dImmediateContext);
};
m_RD->Begin(m_DD->m_pd3dImmediateContext);
m_DD2D->m_Sprites->Begin(SpriteSortMode_Texture, m_RD->GetDigBlend());
for (list<GameObject2D *>::iterator it = m_GameObject2Ds.begin(); it != m_GameObject2Ds.end(); it++)
{
(*it)->Draw(m_DD2D);
}
m_GD->m_OM->AddHoles(m_DD2D);
m_DD2D->m_Sprites->End();
m_RD->End(m_DD->m_pd3dImmediateContext);
m_RD->Map(m_DD->m_pd3dImmediateContext);
m_SecRD->ClearRenderTarget(_pd3dImmediateContext, 0.0f, 0.0f, 0.0f, 0.0f);
m_DD2D->m_Pass = ANIMATION_PASS;
if (m_SecRD->GetMapped())
{
m_SecRD->Unmap(m_DD->m_pd3dImmediateContext);
};
m_SecRD->Begin(m_DD->m_pd3dImmediateContext);
m_DD2D->m_Sprites->Begin(SpriteSortMode_Deferred);
for (list<GameObject2D *>::iterator it = m_GameObject2Ds.begin(); it != m_GameObject2Ds.end(); it++)
{
(*it)->Draw(m_DD2D);
}
m_GD->m_OM->AddBricks(m_DD2D); //Brick McAddems
m_DD2D->m_Sprites->End();
m_SecRD->End(m_DD->m_pd3dImmediateContext);
m_SecRD->Map(m_DD->m_pd3dImmediateContext);
m_DD2D->m_Sprites->Begin();
for (list<GameObject2D *>::iterator it = m_GameObject2DsScreen.begin(); it != m_GameObject2DsScreen.end(); it++)
{
(*it)->Draw(m_DD2D);
m_DD2D->m_Font->DrawString(m_DD2D->m_Sprites.get(), Helper::charToWChar("To exit press ESC then Enter"), Vector2(100, 100), Colors::Yellow);
}
m_DD2D->m_Sprites->End();
}
m_DD2D->m_Sprites->Begin();
for (list<GameObject2D *>::iterator it = m_GameObjectMouse.begin(); it != m_GameObjectMouse.end(); it++)
{
(*it)->Draw(m_DD2D);
}
m_DD2D->m_Sprites->End();
//drawing text screws up the Depth Stencil State, this puts it back again!
_pd3dImmediateContext->OMSetDepthStencilState(m_states->DepthDefault(), 0);
}
bool Game::ReadInput()
{
//copy over old keyboard state
memcpy(m_prevKeyboardState, m_keyboardState, sizeof(unsigned char) * 256);
//clear out previous state
ZeroMemory(&m_keyboardState, sizeof(unsigned char) * 256);
ZeroMemory(&m_mouseState, sizeof(DIMOUSESTATE));
// Read the keyboard device.
HRESULT hr = m_pKeyboard->GetDeviceState(sizeof(m_keyboardState), (LPVOID)&m_keyboardState);
if (FAILED(hr))
{
// If the keyboard lost focus or was not acquired then try to get control back.
if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
{
m_pKeyboard->Acquire();
}
else
{
return false;
}
}
// Read the Mouse device.
hr = m_pMouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&m_mouseState);
if (FAILED(hr))
{
// If the Mouse lost focus or was not acquired then try to get control back.
if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
{
m_pMouse->Acquire();
}
else
{
return false;
}
}
return true;
} | [
"harry.mcalpine@gmail.com"
] | harry.mcalpine@gmail.com |
4cf62cffd727b7784b6c947dd494f2ce76b3f2e1 | 9b3a997b5f1abec0fb21a7b416ae941cab25b563 | /gateway_tools_ping/main.cpp | db9633833bd08efeca98402cef549a43aef6e35f | [
"MIT"
] | permissive | denghe/xxlib_simple_cpp | af12eea8404c1bff0ab74507b69f0a9b346d31f9 | 6aa72124c08e85ff1771bf717b1ea4e4b319c16e | refs/heads/master | 2023-03-11T19:07:12.593272 | 2021-03-02T17:10:03 | 2021-03-02T17:10:03 | 267,041,171 | 4 | 4 | null | 2021-03-02T17:10:03 | 2020-05-26T12:48:43 | C++ | UTF-8 | C++ | false | false | 13,529 | cpp | #include "xx_epoll_kcp.h"
#include "config.h"
#include "xx_data_rw.h"
#include "xx_logger.h"
#include "xx_signal.h"
#include "xx_chrono.h"
/*
通过 tcp & kcp 连接到网关,不停的一发一收 相似字节数的 ping 包,测试传输稳定性。
计算出延迟, 超时就断线重连,记录日志并按小时统计
*/
namespace EP = xx::Epoll;
// 汇总信息
struct NetInfo {
uint64_t totalRunSeconds = 0;
uint64_t pingCount = 0;
uint64_t pingSum = 0;
uint64_t minPing = 10000;
uint64_t maxPing = 0;
uint64_t goodCount = 0;
uint64_t lagCount250 = 0;
uint64_t lagCount500 = 0;
uint64_t lagCount1000 = 0;
uint64_t lagCount1500 = 0;
uint64_t lagCount2000 = 0;
uint64_t lagCount2500 = 0;
uint64_t lagCount3000 = 0;
uint64_t lagCount5000 = 0;
uint64_t lagCount7000 = 0;
uint64_t dialCount = 0;
[[nodiscard]] std::string ToString() const {
return xx::ToString("runSeconds: ", totalRunSeconds, ", dialCount: ", dialCount, ", ping avg = ", (pingSum / pingCount + 1), ", min = ", minPing, ", max = ", maxPing,
", <250 = ", goodCount, ", 250 = ", lagCount250, ", 500 = ", lagCount500, ", 1000 = ", lagCount1000, ", 1500 = ", lagCount1500, ", 2000 = ",
lagCount2000, ", 2500 = ", lagCount2500, ", 3000 = ", lagCount3000, ", 5000 = ", lagCount5000, ", 7000+ = ", lagCount7000);
}
void Clear() {
memset(this, 0, sizeof(*this));
minPing = 10000;
}
void Calc(int64_t const& ms) {
if (ms > maxPing) maxPing = ms;
if (ms < minPing) minPing = ms;
pingSum += ms;
if (ms <= 250) goodCount++;
if (ms > 250) lagCount250++;
if (ms > 500) lagCount500++;
if (ms > 1000) lagCount1000++;
if (ms > 1500) lagCount1500++;
if (ms > 2000) lagCount2000++;
if (ms > 2500) lagCount2500++;
if (ms > 3000) lagCount3000++;
if (ms > 5000) lagCount5000++;
if (ms > 7000) lagCount7000++;
pingCount++;
}
};
NetInfo tni, kni;
struct KcpPeer : EP::KcpPeer {
using BT = EP::KcpPeer;
using BT::BT;
std::string logPrefix = "KCP: ";
NetInfo *ni = &kni;
// 预填好的每次发的包
xx::Data pkg;
// 发包时间(拿来算ping)
std::chrono::steady_clock::time_point lastSendTP;
// Accept 事件中调用下以初始化一些东西
inline void Init() {
// 在 pkg 中填充一个合法的 内部指令包. 网关收到后会立刻 echo 回来并续命
xx::DataWriter dw(pkg);
pkg.Resize(4);
dw.WriteFixed((uint32_t) 0xFFFFFFFF);
dw.WriteBuf("12345678901234567890123456789012345678901234567890", 50);
*(uint32_t *) pkg.buf = pkg.len - sizeof(uint32_t);
// 加持
Hold();
// 记录日志
LOG_SIMPLE(logPrefix, "connected. wait open...");
// 设置超时时间
SetTimeoutSeconds(10);
// 开始等 open
lastSendTP = std::chrono::steady_clock::now();
}
inline void SendPing() {
this->BT::Send(pkg.buf, pkg.len);
Flush();
}
inline void Receive() override {
// 取出指针备用
auto buf = recv.buf;
auto end = recv.buf + recv.len;
uint32_t dataLen = 0;
uint32_t serverId = 0;
// 确保包头长度充足
while (buf + sizeof(dataLen) <= end) {
// 取长度
dataLen = *(uint32_t *) buf;
// 长度异常则断线退出( 不含地址? 超长? 256k 不够可以改长 )
if (dataLen > 1024 * 256) {
Close(-__LINE__, " Peer Receive if (dataLen < sizeof(addr) || dataLen > 1024 * 256)");
return;
}
// 数据未接收完 就 跳出
if (buf + sizeof(dataLen) + dataLen > end) break;
// 跳到数据区开始调用处理回调
buf += sizeof(dataLen);
{
// 取出地址( 手机上最好用 memcpy )
serverId = *(uint32_t *) buf;
// 包类型判断
if (serverId == 0xFFFFFFFFu) {
// 内部指令
ReceiveCommand(buf + sizeof(serverId), dataLen - sizeof(serverId));
} else {
// 普通包. serverId 打头
ReceivePackage(serverId, buf + sizeof(serverId), dataLen - sizeof(serverId));
}
// 如果当前类实例已自杀则退出
if (!Alive()) return;
}
// 跳到下一个包的开头
buf += dataLen;
}
// 移除掉已处理的数据( 将后面剩下的数据移动到头部 )
recv.RemoveFront(buf - recv.buf);
}
void ReceiveCommand(char *const &buf, size_t const &len) {
// 算 ping, 日志, 续命, 再发
auto &&now = std::chrono::steady_clock::now();
auto &&ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastSendTP).count();
LOG_SIMPLE(logPrefix, "ping = ", ms);
lastSendTP = now;
SetTimeoutSeconds(10);
SendPing();
// 统计
ni->Calc(ms);
}
inline void ReceivePackage(uint32_t const &serverId, char *const &buf, size_t const &len) {
// 忽略
}
inline bool Close(int const &reason, char const *const &desc) override {
if (this->BT::Close(reason, desc)) {
LOG_SIMPLE(logPrefix, "Close reason = ", reason, ", desc = ", desc);
DelayUnhold();
return true;
}
return false;
}
};
struct KcpDialer : EP::KcpDialer<KcpPeer> {
using EP::KcpDialer<KcpPeer>::KcpDialer;
inline void Connect(std::shared_ptr<KcpPeer> const &peer) override {
if (!peer) {
LOG_ERROR("KcpDialer Dial Timeout.");
return; // 没连上
}
peer->Init();
}
};
/*********************************************************************************************************/
// TCP 和 KCP 代码几乎相同
/*********************************************************************************************************/
struct TcpPeer : EP::TcpPeer {
using BT = EP::TcpPeer;
using BT::BT;
std::string logPrefix = "TCP: ";
NetInfo *ni = &tni;
// 预填好的每次发的包
xx::Data pkg;
// 发包时间(拿来算ping)
std::chrono::steady_clock::time_point lastSendTP;
// Accept 事件中调用下以初始化一些东西
inline void Init() {
// 在 pkg 中填充一个合法的 内部指令包. 网关收到后会立刻 echo 回来并续命
xx::DataWriter dw(pkg);
pkg.Resize(4);
dw.WriteFixed((uint32_t) 0xFFFFFFFF);
dw.WriteBuf("12345678901234567890123456789012345678901234567890", 50);
*(uint32_t *) pkg.buf = pkg.len - sizeof(uint32_t);
// 加持
Hold();
// 记录日志
LOG_SIMPLE(logPrefix, "connected. wait open...");
// 设置超时时间
SetTimeoutSeconds(10);
// 开始等 open
lastSendTP = std::chrono::steady_clock::now();
}
inline void SendPing() {
this->BT::Send(pkg.buf, pkg.len);
Flush();
}
inline void Receive() override {
// 取出指针备用
auto buf = recv.buf;
auto end = recv.buf + recv.len;
uint32_t dataLen = 0;
uint32_t serverId = 0;
// 确保包头长度充足
while (buf + sizeof(dataLen) <= end) {
// 取长度
dataLen = *(uint32_t *) buf;
// 长度异常则断线退出( 不含地址? 超长? 256k 不够可以改长 )
if (dataLen > 1024 * 256) {
Close(-__LINE__, " Peer Receive if (dataLen < sizeof(addr) || dataLen > 1024 * 256)");
return;
}
// 数据未接收完 就 跳出
if (buf + sizeof(dataLen) + dataLen > end) break;
// 跳到数据区开始调用处理回调
buf += sizeof(dataLen);
{
// 取出地址( 手机上最好用 memcpy )
serverId = *(uint32_t *) buf;
// 包类型判断
if (serverId == 0xFFFFFFFFu) {
// 内部指令
ReceiveCommand(buf + sizeof(serverId), dataLen - sizeof(serverId));
} else {
// 普通包. serverId 打头
ReceivePackage(serverId, buf + sizeof(serverId), dataLen - sizeof(serverId));
}
// 如果当前类实例已自杀则退出
if (!Alive()) return;
}
// 跳到下一个包的开头
buf += dataLen;
}
// 移除掉已处理的数据( 将后面剩下的数据移动到头部 )
recv.RemoveFront(buf - recv.buf);
}
void ReceiveCommand(char *const &buf, size_t const &len) {
// 算 ping, 日志, 续命, 再发
auto &&now = std::chrono::steady_clock::now();
auto &&ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastSendTP).count();
LOG_SIMPLE(logPrefix, "ping = ", ms);
lastSendTP = now;
SetTimeoutSeconds(10);
SendPing();
// 统计
ni->Calc(ms);
}
inline void ReceivePackage(uint32_t const &serverId, char *const &buf, size_t const &len) {
// 忽略
}
inline bool Close(int const &reason, char const *const &desc) override {
if (this->BT::Close(reason, desc)) {
LOG_SIMPLE(logPrefix, "Close reason = ", reason, ", desc = ", desc);
DelayUnhold();
return true;
}
return false;
}
};
struct TcpDialer : EP::TcpDialer<TcpPeer> {
using EP::TcpDialer<TcpPeer>::TcpDialer;
// 指向当前连接
std::weak_ptr<TcpPeer> currentPeer;
inline void Connect(std::shared_ptr<TcpPeer> const &peer) override {
if (!peer) {
LOG_SIMPLE("TcpDialer Dial Timeout.");
return; // 没连上
}
currentPeer = peer;
peer->Init();
}
};
struct Client : EP::Context {
using EP::Context::Context;
std::shared_ptr<TcpDialer> tcpDialer;
std::shared_ptr<KcpDialer> kcpDialer;
std::shared_ptr<EP::GenericTimer> dialTimer;
int Run() override {
xx::ScopeGuard sg1([&] {
dialTimer.reset();
kcpDialer->Stop();
kcpDialer.reset();
tcpDialer->Stop();
tcpDialer.reset();
holdItems.clear();
assert(shared_from_this().use_count() == 2);
});
xx::MakeTo(tcpDialer, shared_from_this());
for (auto &&da : config.dialAddrs) {
if (da.protocol != "tcp") continue;
tcpDialer->AddAddress(da.ip, da.port);
}
xx::MakeTo(kcpDialer, shared_from_this());
if (int r = kcpDialer->MakeFD()) {
throw std::runtime_error("kcpDialer->MakeFD() failed");
} else {
for (auto &&da : config.dialAddrs) {
if (da.protocol != "kcp") continue;
kcpDialer->AddAddress(da.ip, da.port);
}
}
xx::MakeTo(dialTimer, shared_from_this());
dialTimer->onTimeout = [this] {
if (!tcpDialer->Busy() && !tcpDialer->currentPeer.lock()) {
LOG_SIMPLE("TcpDialer dial begin.");
++tni.dialCount;
tcpDialer->DialSeconds(5);
}
if (!kcpDialer->Busy() && kcpDialer->cps.size() < 1) {
LOG_SIMPLE("KcpDialer dial begin.");
++kni.dialCount;
kcpDialer->DialSeconds(5);
}
dialTimer->SetTimeout(1);
};
dialTimer->SetTimeout(1);
SetFrameRate(100);
return this->EP::Context::Run();
}
};
int main(int argc, char const *argv[]) {
// 禁掉 SIGPIPE 信号避免因为连接关闭出错
xx::IgnoreSignal();
// 加载配置
ajson::load_from_file(::config, "config.json");
// 显示配置内容
std::cout << ::config << std::endl;
bool running = true;
std::thread t([&] {
std::ofstream ofs;
ofs.open("sum.txt", std::ios_base::app);
if (ofs.fail()) {
std::cerr << "ERROR!!! open sum.txt failed" << std::endl;
}
ofs << "begin time( UTC ): " << xx::ToString(xx::Now()) << std::endl;
ofs.flush();
while (running) {
// 每小时结存一次
for (int i = 0; i < 60; ++i) {
// 每分钟输出一次
std::this_thread::sleep_for(std::chrono::seconds(60));
tni.totalRunSeconds += 60;
LOG_SIMPLE("TCP: ", tni.ToString());
kni.totalRunSeconds += 60;
LOG_SIMPLE("KCP: ", kni.ToString());
}
ofs << "time( UTC ): " << xx::ToString(xx::Now()) << std::endl;
ofs << "TCP: " << tni.ToString() << std::endl;
ofs << "KCP: " << kni.ToString() << std::endl;
ofs.flush();
memset(&tni, 0, sizeof(tni));
tni.minPing = 10000;
memset(&kni, 0, sizeof(kni));
kni.minPing = 10000;
}
});
// 运行
auto &&r = xx::Make<Client>()->Run();
running = false;
t.join();
return r;
}
| [
"denghe@hotmail.com"
] | denghe@hotmail.com |
3a78cec73f9ce0857db2a76b7be9cc7de193d1f5 | 051a4db48a1c18ed4ac5262a9b91cb9445e39776 | /TECS_condensed/3_compiler_part3_CodeGen/jackCompilerPart2_cpp/jackCompilerPart2_cpp/handleClassDefinition.cpp | c924a47c6bff40cc41f4842f520a2edba7c62fba | [] | no_license | wh1pch81n/code_projects_portfolio | cd45f5bc67952f94c3bb14551cf39e9e8d0e8082 | a7789b8b4931980ba3a4d27209c4d080f8868126 | refs/heads/master | 2021-01-15T19:28:15.150278 | 2013-09-14T00:37:01 | 2013-09-14T00:37:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,187 | cpp | #include "handleClassDefinition.h"
void handleClassDefinition(string line){
if (isClassDefinitionBegin(line)) {
//todo: change the fd such that stdout goes to a dot VM file
//with the same name as the class
//
//implement here:(status not done)(open af file for writing)
//
for (incFilePtr(); !isClassDefinitionEnd(getCurrLine()); incFilePtr()) {
if (contains(getCurrLine(), "<keyword>", " class ")) {
}else if(contains(getCurrLine(),"<identifier>", "class#def")){
setClassFileName();
}else if(contains(getCurrLine(), "<symbol>", " { ")){
//count number of class variables
setClassVarNum();
handleClassDefinition(getCurrLine());
}else{
error("unexpected Item in class");
}
}
//todo:close the file for writing and prepare for a
//second class def in the current file.
FileList::clearClassFileName(); //reset values when class definition finishes up
FileList::resetClassVarNum();
}elif(contains(line, "<symbol>", " { ")){
for(incFilePtr(); !contains(getCurrLine(), "<symbol>", " } "); incFilePtr()) {
// printf("class name: %s num class var: %d\n", class_fileName.c_str(), class_Var_num);
// error("for fun");
if (contains(getCurrLine(), "<classVarDec>")) {
//move past all field or static declarations
handleClassVarDec(getCurrLine());
}elif(contains(getCurrLine(), "<subroutineDec>")){
CurrFunctionKind::num_of_if = 0;
CurrFunctionKind::num_of_while = 0;
handleSubroutineDec(getCurrLine());
}else{
error("expected either classVarDec or subroutineDec");
}
}
}else{
error("expected class definition");
}
}
void handleClassVarDec(std::string line){
if (isClassVarDecBegin(line)) {
//since the number has already been counted
//This function shall imply verify that it was given propper stuff
for (incFilePtr(); !isClassVarDecEnd(getCurrLine()); incFilePtr()) {
if (contains(getCurrLine(), "<keyword>")) {}
elif(isIdentifier(getCurrLine())){}
elif(contains(getCurrLine(), "<symbol>", " , ")){}
elif(contains(getCurrLine(), "<symbol>", " ; ")){}
else{
error("unexpected stuff in classVarDec");
}
}
}else{
error("exprected classVarDec");
}
} | [
"wh1pch81n@gmail.com"
] | wh1pch81n@gmail.com |
3ca14c13ad34fecbe9f6f10f14c4ddaf5cdeac6e | 819875a388d7caf6795941db8104f4bf72677b90 | /content/shell/.svn/text-base/shell_browser_context.cc.svn-base | 8c824532a0f7086468b557e5d1a501166cb6c982 | [
"BSD-3-Clause"
] | permissive | gx1997/chrome-loongson | 07b763eb1d0724bf0d2e0a3c2b0eb274e9a2fb4c | 1cb7e00e627422577e8b7085c2d2892eda8590ae | refs/heads/master | 2020-04-28T02:04:13.872019 | 2012-08-16T10:09:25 | 2012-08-16T10:09:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,537 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/shell_browser_context.h"
#include "base/bind.h"
#include "base/environment.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/threading/thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/geolocation_permission_context.h"
#include "content/public/browser/speech_recognition_preferences.h"
#include "content/shell/shell_download_manager_delegate.h"
#include "content/shell/shell_resource_context.h"
#include "content/shell/shell_url_request_context_getter.h"
#if defined(OS_WIN)
#include "base/base_paths_win.h"
#elif defined(OS_LINUX)
#include "base/nix/xdg_util.h"
#elif defined(OS_MACOSX)
#include "base/base_paths_mac.h"
#endif
using content::BrowserThread;
namespace content {
namespace {
#if defined(OS_LINUX)
const char kDotConfigDir[] = ".config";
const char kXdgConfigHomeEnvVar[] = "XDG_CONFIG_HOME";
#endif
class ShellGeolocationPermissionContext : public GeolocationPermissionContext {
public:
ShellGeolocationPermissionContext() {
}
// GeolocationPermissionContext implementation).
virtual void RequestGeolocationPermission(
int render_process_id,
int render_view_id,
int bridge_id,
const GURL& requesting_frame,
base::Callback<void(bool)> callback) OVERRIDE {
NOTIMPLEMENTED();
}
virtual void CancelGeolocationPermissionRequest(
int render_process_id,
int render_view_id,
int bridge_id,
const GURL& requesting_frame) OVERRIDE {
NOTIMPLEMENTED();
}
private:
DISALLOW_COPY_AND_ASSIGN(ShellGeolocationPermissionContext);
};
class ShellSpeechRecognitionPreferences : public SpeechRecognitionPreferences {
public:
ShellSpeechRecognitionPreferences() {
}
// Overridden from SpeechRecognitionPreferences:
virtual bool FilterProfanities() const OVERRIDE {
return false;
}
virtual void SetFilterProfanities(bool filter_profanities) OVERRIDE {
}
private:
DISALLOW_COPY_AND_ASSIGN(ShellSpeechRecognitionPreferences);
};
} // namespace
ShellBrowserContext::ShellBrowserContext() {
InitWhileIOAllowed();
}
ShellBrowserContext::~ShellBrowserContext() {
if (resource_context_.get()) {
BrowserThread::DeleteSoon(
BrowserThread::IO, FROM_HERE, resource_context_.release());
}
}
void ShellBrowserContext::InitWhileIOAllowed() {
#if defined(OS_WIN)
CHECK(PathService::Get(base::DIR_LOCAL_APP_DATA, &path_));
path_ = path_.Append(std::wstring(L"content_shell"));
#elif defined(OS_LINUX)
scoped_ptr<base::Environment> env(base::Environment::Create());
FilePath config_dir(base::nix::GetXDGDirectory(env.get(),
kXdgConfigHomeEnvVar,
kDotConfigDir));
path_ = config_dir.Append("content_shell");
#elif defined(OS_MACOSX)
CHECK(PathService::Get(base::DIR_APP_DATA, &path_));
path_ = path_.Append("Chromium Content Shell");
#else
NOTIMPLEMENTED();
#endif
if (!file_util::PathExists(path_))
file_util::CreateDirectory(path_);
}
FilePath ShellBrowserContext::GetPath() {
return path_;
}
bool ShellBrowserContext::IsOffTheRecord() const {
return false;
}
DownloadManager* ShellBrowserContext::GetDownloadManager() {
if (!download_manager_.get()) {
download_manager_delegate_ = new ShellDownloadManagerDelegate();
download_manager_ = DownloadManager::Create(download_manager_delegate_,
NULL);
download_manager_delegate_->SetDownloadManager(download_manager_.get());
download_manager_->Init(this);
}
return download_manager_.get();
}
net::URLRequestContextGetter* ShellBrowserContext::GetRequestContext() {
if (!url_request_getter_) {
url_request_getter_ = new ShellURLRequestContextGetter(
GetPath(),
BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO),
BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE));
}
return url_request_getter_;
}
net::URLRequestContextGetter*
ShellBrowserContext::GetRequestContextForRenderProcess(
int renderer_child_id) {
return GetRequestContext();
}
net::URLRequestContextGetter*
ShellBrowserContext::GetRequestContextForMedia() {
return GetRequestContext();
}
ResourceContext* ShellBrowserContext::GetResourceContext() {
if (!resource_context_.get()) {
resource_context_.reset(new ShellResourceContext(
static_cast<ShellURLRequestContextGetter*>(GetRequestContext())));
}
return resource_context_.get();
}
GeolocationPermissionContext*
ShellBrowserContext::GetGeolocationPermissionContext() {
if (!geolocation_permission_context_) {
geolocation_permission_context_ =
new ShellGeolocationPermissionContext();
}
return geolocation_permission_context_;
}
SpeechRecognitionPreferences*
ShellBrowserContext::GetSpeechRecognitionPreferences() {
if (!speech_recognition_preferences_.get())
speech_recognition_preferences_ = new ShellSpeechRecognitionPreferences();
return speech_recognition_preferences_.get();
}
bool ShellBrowserContext::DidLastSessionExitCleanly() {
return true;
}
quota::SpecialStoragePolicy* ShellBrowserContext::GetSpecialStoragePolicy() {
return NULL;
}
} // namespace content
| [
"loongson@Loong.(none)"
] | loongson@Loong.(none) | |
a3881c01dc09d5d50440635d78d522ac7b2bd441 | 45013c1f26b4080f8bdef1cd10d1a105f01701b7 | /src/stdafx.h | 830bf81e4b81cd38df83756806d773fd62e29e48 | [] | no_license | y3nr1ng/stack-transposer | 581e34ffe34080d5cb2382f7763db3b9172c73d6 | 3a9714b2ec2cee80ae90323122c8670c3cfe0a6a | refs/heads/master | 2022-11-26T10:53:18.342408 | 2018-06-08T05:36:39 | 2018-06-08T05:36:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | h | #pragma once
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
#include <cstdint>
#define BOOST_FILESYSTEM_VERSION 3
// Do not use deprecated features.
#ifndef BOOST_FILESYSTEM_NO_DEPRECATED
#define BOOST_FILESYSTEM_NO_DEPRECATED
#endif
#ifndef BOOST_SYSTEM_NO_DEPRECATED
#define BOOST_SYSTEM_NO_DEPRECATED
#endif
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem; | [
"windows.linux.mac@gmail.com"
] | windows.linux.mac@gmail.com |
b33596f3d3e0ca9aeba7e9683f5fea74a22b1053 | a782e8b77eb9a32ffb2c3f417125553693eaee86 | /src/developer/memory/metrics/tests/summary_unittest.cc | 2037d5fa5270005436b42529eb640e039df199cd | [
"BSD-3-Clause"
] | permissive | xyuan/fuchsia | 9e5251517e88447d3e4df12cf530d2c3068af290 | db9b631cda844d7f1a1b18cefed832a66f46d56c | refs/heads/master | 2022-06-30T17:53:09.241350 | 2020-05-13T12:28:17 | 2020-05-13T12:28:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,931 | cc | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/memory/metrics/summary.h"
#include <gtest/gtest.h>
#include "src/developer/memory/metrics/capture.h"
#include "src/developer/memory/metrics/tests/test_utils.h"
namespace memory {
namespace test {
using SummaryUnitTest = testing::Test;
TEST_F(SummaryUnitTest, Single) {
// One process, one vmo.
Capture c;
TestUtils::CreateCapture(&c, {
.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
},
.processes =
{
{.koid = 2, .name = "p1", .vmos = {1}},
},
});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
EXPECT_EQ(1U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, TwoVmos) {
// One process, two vmos with same name.
Capture c;
TestUtils::CreateCapture(&c, {
.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
{.koid = 2, .name = "v1", .committed_bytes = 100},
},
.processes =
{
{.koid = 2, .name = "p1", .vmos = {1, 2}},
},
});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(200U, sizes.private_bytes);
EXPECT_EQ(200U, sizes.scaled_bytes);
EXPECT_EQ(200U, sizes.total_bytes);
EXPECT_EQ(1U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(200U, sizes.private_bytes);
EXPECT_EQ(200U, sizes.scaled_bytes);
EXPECT_EQ(200U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, TwoVmoNames) {
// One process, two vmos with different names.
Capture c;
TestUtils::CreateCapture(&c, {
.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
{.koid = 2, .name = "v2", .committed_bytes = 100},
},
.processes = {{.koid = 2, .name = "p1", .vmos = {1, 2}}},
});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(200U, sizes.private_bytes);
EXPECT_EQ(200U, sizes.scaled_bytes);
EXPECT_EQ(200U, sizes.total_bytes);
EXPECT_EQ(2U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
sizes = ps.GetSizes("v2");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, Parent) {
// One process, two vmos with different names, one is child.
Capture c;
TestUtils::CreateCapture(
&c, {
.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
{.koid = 2, .name = "v2", .committed_bytes = 100, .parent_koid = 1},
},
.processes = {{.koid = 2, .name = "p1", .vmos = {2}}},
});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(200U, sizes.private_bytes);
EXPECT_EQ(200U, sizes.scaled_bytes);
EXPECT_EQ(200U, sizes.total_bytes);
EXPECT_EQ(2U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
sizes = ps.GetSizes("v2");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, TwoProcesses) {
// Two processes, with different vmos.
Capture c;
TestUtils::CreateCapture(&c, {.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
{.koid = 2, .name = "v2", .committed_bytes = 100},
},
.processes = {
{.koid = 2, .name = "p1", .vmos = {1}},
{.koid = 3, .name = "p2", .vmos = {2}},
}});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(3U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
EXPECT_EQ(1U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
ps = process_summaries.at(2);
EXPECT_EQ(3U, ps.koid());
EXPECT_STREQ("p2", ps.name().c_str());
sizes = ps.sizes();
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
EXPECT_EQ(1U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v2");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, TwoProcessesShared) {
// Two processes, with same vmos.
Capture c;
TestUtils::CreateCapture(&c, {.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
},
.processes = {
{.koid = 2, .name = "p1", .vmos = {1}},
{.koid = 3, .name = "p2", .vmos = {1}},
}});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(3U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(50U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
EXPECT_EQ(1U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(50U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
ps = process_summaries.at(2);
EXPECT_EQ(3U, ps.koid());
EXPECT_STREQ("p2", ps.name().c_str());
sizes = ps.sizes();
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(50U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
EXPECT_EQ(1U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(50U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, TwoProcessesChild) {
// Two processes, with one vmo shared through parantage.
Capture c;
TestUtils::CreateCapture(
&c, {.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
{.koid = 2, .name = "v2", .committed_bytes = 100, .parent_koid = 1},
},
.processes = {
{.koid = 2, .name = "p1", .vmos = {1}},
{.koid = 3, .name = "p2", .vmos = {2}},
}});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(3U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(50U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
EXPECT_EQ(1U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(50U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
ps = process_summaries.at(2);
EXPECT_EQ(3U, ps.koid());
EXPECT_STREQ("p2", ps.name().c_str());
sizes = ps.sizes();
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(150U, sizes.scaled_bytes);
EXPECT_EQ(200U, sizes.total_bytes);
EXPECT_EQ(2U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(50U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
sizes = ps.GetSizes("v2");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, MissingParent) {
// Child VMO with parent koid that's not found.
Capture c;
TestUtils::CreateCapture(
&c, {.vmos =
{
{.koid = 2, .name = "v2", .committed_bytes = 100, .parent_koid = 1},
},
.processes = {
{.koid = 2, .name = "p1", .vmos = {2}},
}});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
ProcessSummary ps = process_summaries.at(1);
EXPECT_STREQ("p1", ps.name().c_str());
EXPECT_EQ(2U, ps.koid());
Sizes sizes = ps.sizes();
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
sizes = ps.GetSizes("v2");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, Kernel) {
// Test kernel stats.
Capture c;
TestUtils::CreateCapture(&c, {
.kmem =
{
.wired_bytes = 10,
.total_heap_bytes = 20,
.mmu_overhead_bytes = 30,
.ipc_bytes = 40,
.other_bytes = 50,
.vmo_bytes = 60,
},
});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(1U, process_summaries.size());
ProcessSummary ps = process_summaries.at(0);
EXPECT_EQ(ProcessSummary::kKernelKoid, ps.koid());
EXPECT_STREQ("kernel", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(210U, sizes.private_bytes);
EXPECT_EQ(210U, sizes.scaled_bytes);
EXPECT_EQ(210U, sizes.total_bytes);
EXPECT_EQ(6U, ps.name_to_sizes().size());
sizes = ps.GetSizes("wired");
EXPECT_EQ(10U, sizes.private_bytes);
EXPECT_EQ(10U, sizes.scaled_bytes);
EXPECT_EQ(10U, sizes.total_bytes);
sizes = ps.GetSizes("heap");
EXPECT_EQ(20U, sizes.private_bytes);
EXPECT_EQ(20U, sizes.scaled_bytes);
EXPECT_EQ(20U, sizes.total_bytes);
sizes = ps.GetSizes("mmu");
EXPECT_EQ(30U, sizes.private_bytes);
EXPECT_EQ(30U, sizes.scaled_bytes);
EXPECT_EQ(30U, sizes.total_bytes);
sizes = ps.GetSizes("ipc");
EXPECT_EQ(40U, sizes.private_bytes);
EXPECT_EQ(40U, sizes.scaled_bytes);
EXPECT_EQ(40U, sizes.total_bytes);
sizes = ps.GetSizes("other");
EXPECT_EQ(50U, sizes.private_bytes);
EXPECT_EQ(50U, sizes.scaled_bytes);
EXPECT_EQ(50U, sizes.total_bytes);
sizes = ps.GetSizes("vmo");
EXPECT_EQ(60U, sizes.private_bytes);
EXPECT_EQ(60U, sizes.scaled_bytes);
EXPECT_EQ(60U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, KernelVmo) {
// Test kernel that kernel vmo memory that isn't found in
// user space vmos is listed under the kernel.
Capture c;
TestUtils::CreateCapture(&c, {
.kmem =
{
.vmo_bytes = 110,
},
.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
},
.processes =
{
{.koid = 2, .name = "p1", .vmos = {1}},
},
});
Summary s(c);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
ProcessSummary ps = process_summaries.at(0);
EXPECT_EQ(ProcessSummary::kKernelKoid, ps.koid());
EXPECT_STREQ("kernel", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(10U, sizes.private_bytes);
EXPECT_EQ(10U, sizes.scaled_bytes);
EXPECT_EQ(10U, sizes.total_bytes);
sizes = ps.GetSizes("vmo");
EXPECT_EQ(10U, sizes.private_bytes);
EXPECT_EQ(10U, sizes.scaled_bytes);
EXPECT_EQ(10U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, NameMatch) {
// One process, two vmos with same name.
Capture c;
TestUtils::CreateCapture(
&c, {
.vmos =
{
{.koid = 1, .name = "blob-12a", .committed_bytes = 100},
{.koid = 2, .name = "blob-de", .committed_bytes = 100},
{.koid = 3, .name = "pthread_t:0x59853000/TLS=0x548", .committed_bytes = 100},
{.koid = 4, .name = "thrd_t:0x59853000/TLS=0x548", .committed_bytes = 100},
{.koid = 5, .name = "data:libfoo.so", .committed_bytes = 100},
{.koid = 6, .name = "", .committed_bytes = 100},
{.koid = 7, .name = "scudo:primary", .committed_bytes = 100},
{.koid = 8, .name = "scudo:secondary", .committed_bytes = 100},
{.koid = 9, .name = "foo", .committed_bytes = 100},
{.koid = 10, .name = "initial-thread", .committed_bytes = 100},
{.koid = 11, .name = "libfoo.so.1", .committed_bytes = 100},
},
.processes =
{
{.koid = 2, .name = "p1", .vmos = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}},
},
});
Summary s(c, Summary::kNameMatches);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(1100U, sizes.private_bytes);
EXPECT_EQ(7U, ps.name_to_sizes().size());
EXPECT_EQ(200U, ps.GetSizes("[blobs]").private_bytes);
EXPECT_EQ(300U, ps.GetSizes("[stacks]").private_bytes);
EXPECT_EQ(100U, ps.GetSizes("[data]").private_bytes);
EXPECT_EQ(100U, ps.GetSizes("[unnamed]").private_bytes);
EXPECT_EQ(200U, ps.GetSizes("[scudo]").private_bytes);
EXPECT_EQ(100U, ps.GetSizes("foo").private_bytes);
EXPECT_EQ(100U, ps.GetSizes("[libraries]").private_bytes);
}
TEST_F(SummaryUnitTest, AllUndigested) {
// One process, two vmos with different names.
Capture c;
TestUtils::CreateCapture(&c, {
.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
{.koid = 2, .name = "v2", .committed_bytes = 100},
},
.processes = {{.koid = 2, .name = "p1", .vmos = {1, 2}}},
});
Namer namer({});
Summary s(c, &namer, {1, 2});
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(200U, sizes.private_bytes);
EXPECT_EQ(200U, sizes.scaled_bytes);
EXPECT_EQ(200U, sizes.total_bytes);
EXPECT_EQ(2U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
sizes = ps.GetSizes("v2");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, OneUndigested) {
// One process, two vmos with different names.
Capture c;
TestUtils::CreateCapture(&c, {
.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
{.koid = 2, .name = "v2", .committed_bytes = 100},
},
.processes = {{.koid = 2, .name = "p1", .vmos = {1, 2}}},
});
Namer namer({});
Summary s(c, &namer, {1});
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
EXPECT_EQ(1U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, TwoProcessesOneUndigested) {
// Two processes, with different vmos.
Capture c;
TestUtils::CreateCapture(&c, {.vmos =
{
{.koid = 1, .name = "v1", .committed_bytes = 100},
{.koid = 2, .name = "v2", .committed_bytes = 100},
},
.processes = {
{.koid = 2, .name = "p1", .vmos = {1}},
{.koid = 3, .name = "p2", .vmos = {2}},
}});
Namer namer({});
Summary s(c, &namer, {1});
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(2U, process_summaries.size());
// Skip kernel summary.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(2U, ps.koid());
EXPECT_STREQ("p1", ps.name().c_str());
Sizes sizes = ps.sizes();
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
EXPECT_EQ(1U, ps.name_to_sizes().size());
sizes = ps.GetSizes("v1");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
}
TEST_F(SummaryUnitTest, Pools) {
// One process, two vmos with same name.
Capture c;
TestUtils::CreateCapture(
&c, {.vmos =
{
{.koid = 1, .name = "SysmemContiguousPool", .committed_bytes = 400},
{.koid = 2, .name = "ContiguousChild", .size_bytes = 300, .parent_koid = 1},
{.koid = 3, .name = "ContiguousGrandchild", .size_bytes = 100, .parent_koid = 2},
{.koid = 4, .name = "ContiguousGrandchild", .size_bytes = 50, .parent_koid = 2},
},
.processes =
{
{.koid = 10, .name = "p1", .vmos = {1, 2}},
{.koid = 20, .name = "p2", .vmos = {3}},
{.koid = 30, .name = "p3", .vmos = {4}},
},
.rooted_vmo_names = Capture::kDefaultRootedVmoNames});
Summary s(c, Summary::kNameMatches);
auto process_summaries = TestUtils::GetProcessSummaries(s);
ASSERT_EQ(4U, process_summaries.size());
// Skip kernel summary.
// SysmemContiguousPool will be left with 100 bytes, shared by all three processes.
// ContiguousChild will be left with 150 bytes, shared by all three processes.
// p2 will have a private ContiguousGrandchild VMO of 100 bytes.
// p3 will have a private ContiguousGrandchild VMO of 50 bytes.
ProcessSummary ps = process_summaries.at(1);
EXPECT_EQ(10U, ps.koid());
Sizes sizes = ps.sizes();
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(250U / 3, sizes.scaled_bytes);
EXPECT_EQ(250U, sizes.total_bytes);
sizes = ps.GetSizes("SysmemContiguousPool");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(100U / 3, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
sizes = ps.GetSizes("ContiguousChild");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(150U / 3, sizes.scaled_bytes);
EXPECT_EQ(150U, sizes.total_bytes);
ps = process_summaries.at(2);
EXPECT_EQ(20U, ps.koid());
sizes = ps.sizes();
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U + 250U / 3, sizes.scaled_bytes);
EXPECT_EQ(100U + 250U, sizes.total_bytes);
sizes = ps.GetSizes("SysmemContiguousPool");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(100U / 3, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
sizes = ps.GetSizes("ContiguousChild");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(150U / 3, sizes.scaled_bytes);
EXPECT_EQ(150U, sizes.total_bytes);
sizes = ps.GetSizes("ContiguousGrandchild");
EXPECT_EQ(100U, sizes.private_bytes);
EXPECT_EQ(100U, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
ps = process_summaries.at(3);
EXPECT_EQ(30U, ps.koid());
sizes = ps.sizes();
EXPECT_EQ(50U, sizes.private_bytes);
EXPECT_EQ(50U + 250U / 3, sizes.scaled_bytes);
EXPECT_EQ(50U + 250U, sizes.total_bytes);
sizes = ps.GetSizes("SysmemContiguousPool");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(100U / 3, sizes.scaled_bytes);
EXPECT_EQ(100U, sizes.total_bytes);
sizes = ps.GetSizes("ContiguousChild");
EXPECT_EQ(0U, sizes.private_bytes);
EXPECT_EQ(150U / 3, sizes.scaled_bytes);
EXPECT_EQ(150U, sizes.total_bytes);
sizes = ps.GetSizes("ContiguousGrandchild");
EXPECT_EQ(50U, sizes.private_bytes);
EXPECT_EQ(50U, sizes.scaled_bytes);
EXPECT_EQ(50U, sizes.total_bytes);
}
} // namespace test
} // namespace memory
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e435f833e1716145cb9f13310c97deba2ac12b8a | f212f7cd115d723bf872c63f0b24cc800fe26514 | /11799.cpp | a0fd99c7c13ab1a26c4546cd47f67e05214ef322 | [] | no_license | JorgeRo95/UVA-ONline-Judge | faefc2e0e6bc1bcd99ff5874fa7341337ce1c5f4 | 27392d5eb88c38a862b15f5d2605272a394bb9ba | refs/heads/master | 2020-12-08T02:21:04.517087 | 2020-01-09T16:55:58 | 2020-01-09T16:55:58 | 232,858,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | cpp | #include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main() {
int tests, caseTest = 0;
cin >> tests;
while (tests--) {
int scaryBeing, maxSpeed = 0;
cin >> scaryBeing;
while(scaryBeing--) {
int speed;
if(scanf("%d", &speed), speed > maxSpeed)
maxSpeed = speed;
}
printf("Case %d: %d\n", ++caseTest, maxSpeed);
}
} | [
"jorgerodrigo2013@gmail.com"
] | jorgerodrigo2013@gmail.com |
a87142279cb5aedb844c88c116ee1f557fc97f31 | 89d3c395e6ad2fd8658f4f2b517f15d203284ce4 | /include/tao/pegtl/config.hpp | 9b1b8854c1b737c7e8c13d8b19e62dc32eef3a85 | [
"MIT"
] | permissive | mason-bially/PEGTL | 12c74bcc84427ec15dcacc4c39d3d5fc0bd1a7c6 | 5eda0c4f2f0e04e781a6a17dcdededf7b35431c8 | refs/heads/master | 2022-08-17T05:10:43.330253 | 2019-07-09T23:03:20 | 2022-08-14T00:52:50 | 196,083,631 | 0 | 0 | MIT | 2019-07-09T21:04:23 | 2019-07-09T21:04:23 | null | UTF-8 | C++ | false | false | 286 | hpp | // Copyright (c) 2017-2022 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONFIG_HPP
#define TAO_PEGTL_CONFIG_HPP
#if !defined( TAO_PEGTL_NAMESPACE )
#define TAO_PEGTL_NAMESPACE tao::pegtl
#endif
#endif
| [
"d.frey@gmx.de"
] | d.frey@gmx.de |
491a56b794b2fb17cb26bc3efc4ac290b04c06ca | 5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e | /main/source/src/numeric/geometry/hashing/SixDHasher.fwd.hh | bf5f5a1397bd458270edcaafbbcb4b22cc0f0c76 | [] | no_license | MedicaicloudLink/Rosetta | 3ee2d79d48b31bd8ca898036ad32fe910c9a7a28 | 01affdf77abb773ed375b83cdbbf58439edd8719 | refs/heads/master | 2020-12-07T17:52:01.350906 | 2020-01-10T08:24:09 | 2020-01-10T08:24:09 | 232,757,729 | 2 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 2,572 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file /numeric/geometry/hashing/SixDHasher.fwd.hh
/// @brief Forward declaration for classes in 6D hasher
/// @author Alex Zanghellini (zanghell@u.washington.edu)
/// @author Andrew Leaver-Fay (aleaverfay@gmail.com), porting to mini
#ifndef INCLUDED_numeric_geometry_hashing_SixDHasher_fwd_hh
#define INCLUDED_numeric_geometry_hashing_SixDHasher_fwd_hh
// Package headers
// Project headers
#include <numeric/types.hh>
// Utility headers
#include <utility/pointer/owning_ptr.hh>
// Boost headers
#include <utility/fixedsizearray1.fwd.hh>
namespace numeric {
namespace geometry {
namespace hashing {
typedef utility::fixedsizearray1< numeric::Size, 3 > Size3;
typedef utility::fixedsizearray1< numeric::Size, 4 > Size4;
typedef utility::fixedsizearray1< numeric::Real, 6 > Real6;
typedef utility::fixedsizearray1< numeric::Size, 6 > Size6;
typedef utility::fixedsizearray1< numeric::Size, 3 > Bin3D;
typedef utility::fixedsizearray1< numeric::Real, 3 > Real3;
typedef utility::fixedsizearray1< numeric::Size, 6 > Bin6D;
typedef utility::fixedsizearray1< platform::SSize, 6 > SBin6D;
typedef Bin3D xyzbin;
typedef Bin3D eulerbin;
struct Bin3D_equals;
struct Bin3D_hash;
typedef Bin3D center_of_mass_binned;
typedef Bin3D euler_angles_binned;
typedef Bin3D_equals euler_equals;
typedef Bin3D_hash euler_hash;
typedef Bin3D_equals xyzbin_hash;
typedef Bin3D_hash xyzbin_equals;
//typedef boost::unordered_map< euler_angles_binned, MatchSetOP, euler_hash, euler_equals > EulerHash;
//typedef utility::pointer::owning_ptr< EulerHash > EulerHashOP;
//typedef boost::unordered_map< center_of_mass_binned, EulerHashOP, xyzbin_hash, xyzbin_equals > SixDHash
//typedef utility::pointer::owning_ptr< SixDHash > SixDHashOP;
struct bin_index_hasher;
class SixDCoordinateBinner;
typedef utility::pointer::shared_ptr< SixDCoordinateBinner > SixDCoordinateBinnerOP;
typedef utility::pointer::shared_ptr< SixDCoordinateBinner const > SixDCoordinateBinnerCOP;
} //hashing
} //geometry
} //numeric
#endif
| [
"36790013+MedicaicloudLink@users.noreply.github.com"
] | 36790013+MedicaicloudLink@users.noreply.github.com |
15d08e51de21103d8a14efec8fc9a89aa5ab171e | e7aa683f6d0331ffbf61d51d98b6d271be92eaee | /University 3rd Year OpenGL Assignement/raaCGAssignment1-2012/raaCGAssignment1-2012.cpp | a3828e8a20523d9f3a57289e483b9401c39d3269 | [] | no_license | maxhap/University-OpenGL2.0-OSG | 60e8fd9e6b79ef500acc1181f89a87280fb59bf5 | e7a1a6c1fbb3716411ce197f18dfd3bcc25c7aeb | refs/heads/master | 2016-09-10T14:27:41.775455 | 2014-09-12T08:42:36 | 2014-09-12T08:42:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,894 | cpp | // raaCGAssignment1-2012.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "raaCGAssignment1-2012.h"
#include <Windows.h>
#include "maSceneIO.h"
/*------------------------------------------------------------*/
//Rob Variables
/*------------------------------------------------------------*/
int g_iWidth=0;
int g_iHeight=0;
unsigned long g_ulGrid=0;
int g_iMainMenu=0;
int g_iNavMenu=0;
int g_iMainMenuLight=0;
int g_iMainMenuObject=0;
raaCamera g_Camera;
/*------------------------------------------------------------*/
//Max Variables
/*------------------------------------------------------------*/
maStructList* _plSceneList;
maStructList* _plCurrentSceneList;
maStruListElement* _pCurrentSceneElement;
unsigned int _uiCurrentScene;
float _fIdelRotationValue = 0;
//display lists
GLuint _gluiWireframeDL;
GLuint _gluiSolidDL;
//file selection
const int OBJECTFILTER = 0;
const int TEXTUREFILTER = 1;
const int SCENEFILTER = 2;
//for glut menu
int _iAddMenu;
const int _iAddTriangle = 1;
const int _iAddLitTeapot = 2;
const int _iAddLitSphere = 3;
const int _iAddPossLight = 4;
const int _iAddSmileyQuad = 20;
const int _iAddClientCube = 21;
int _iSceneControlMenu;
const int _iAddFromObjectFile = 10;
const int _iForwardScene = 11;
const int _iBackScene = 12;
const int _iClearScene = 5;
const int _iSaveScene = 22;
const int _iLoadScene = 23;
int _iAddSeletionControlsMenu;
const int _iRotateX = 6;
const int _iRotateY = 7;
const int _iRotateZ = 8;
const int _iRemoveObjects = 9;
const int _iTogleWireFrameMode = 50;
//light menu
int _iAddLightControlsMenu;
const int _iTogleLightOnOff = 123123;
// Picking Stuff
#define RENDER 1
#define SELECT 2
#define BUFSIZE 1024
GLuint selectBuf[BUFSIZE];
GLint _uiHits;
int _iMode = RENDER;
int _iCursorX;
int _iCursorY;
//camera stuff
unsigned int _uiRecalcuateSelectionLookAt;
unsigned int _uiEploreMode;
unsigned int _uiFlySet = 0;
int main(int argc, char* argv[])
{
mathsInit();
glutInit(&argc, argv);
// create a glut window
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(1200,1000);
glutCreateWindow("raaCGAssignment");
// my init function
init();
max_init();
// associate functions with glut actions
glutDisplayFunc(display); // display function
glutIdleFunc(idle); // simulation loop
glutReshapeFunc(reshape); // reshape function
glutKeyboardFunc(keyboard); // basic keyboard entry
glutSpecialFunc(sKeyboard); // extended keyboard function
glutMouseFunc(mouse); // mouse events
glutMotionFunc(motion); // mouse motion
build_menu();
// hand control over to glut
glutMainLoop();
return 0;
}
void build_menu()
{
// build glut menu
g_iNavMenu=glutCreateMenu(navMenu);
glutAddMenuEntry("Explore", csg_uiExplore);
glutAddMenuEntry("Fly", csg_uiFly);
_iAddMenu = glutCreateMenu( objectMenu );
glutAddMenuEntry( "Triangle", _iAddTriangle );
glutAddMenuEntry( "Lit Teapot", _iAddLitTeapot );
glutAddMenuEntry( "Lit Sphere", _iAddLitSphere );
glutAddMenuEntry( "Positioned Light", _iAddPossLight );
glutAddMenuEntry( "Add Object File (.obj)", _iAddFromObjectFile );
glutAddMenuEntry( "Add Textured Quad (.bmp)", _iAddSmileyQuad );
glutAddMenuEntry( "Add Client Cube", _iAddClientCube );
_iSceneControlMenu = glutCreateMenu( objectMenu );
glutAddMenuEntry( "Clear Scene", _iClearScene );
glutAddMenuEntry( "Forward Scene", _iForwardScene );
glutAddMenuEntry( "Back Scene", _iBackScene );
glutAddMenuEntry( "Save Scene", _iSaveScene );
glutAddMenuEntry( "Load Scene", _iLoadScene );
g_iMainMenu=glutCreateMenu( objectMenu );
glutAddSubMenu("Navigation", g_iNavMenu);
glutAddSubMenu( "Add Object", _iAddMenu );
glutAddSubMenu( "Scene Controls", _iSceneControlMenu );
glutAttachMenu(GLUT_MIDDLE_BUTTON);
//build glut light menu
g_iMainMenuLight = glutCreateMenu( objectMenu );
glutAddMenuEntry( "Toggle Light", _iTogleLightOnOff );
glutAddMenuEntry( "Remove Light", _iRemoveObjects );
_iAddSeletionControlsMenu = glutCreateMenu( objectMenu );
glutAddMenuEntry( "Rotate X", _iRotateX );
glutAddMenuEntry( "Rotate Y", _iRotateY );
glutAddMenuEntry( "Rotate Z", _iRotateZ );
glutAddMenuEntry( "Remove Objects", _iRemoveObjects );
glutAddMenuEntry( "Toggle Wire Frame", _iTogleWireFrameMode );
//object menu
g_iMainMenuObject = glutCreateMenu( objectMenu );
glutAddSubMenu( "Object Controls", _iAddSeletionControlsMenu );
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
applyCamera(g_Camera);
glCallList(g_ulGrid);
glPushAttrib(GL_ALL_ATTRIB_BITS);
// add scene rendering code here
max_render();
glPopAttrib();
glFlush();
glutSwapBuffers();
}
void idle()
{
_fIdelRotationValue += 0.1;
if(g_Camera.m_bMotion) camRot(g_Camera, 0.0001f*g_Camera.m_afMouseDisp[0], 0.0001f*g_Camera.m_afMouseDisp[1]);
glutPostRedisplay();
}
void reshape(int iWidth, int iHeight)
{
g_iWidth=iWidth;
g_iHeight=iHeight;
glViewport(0, 0, iWidth, iHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(30.0f, ((float)iWidth)/((float)iHeight), 1.0f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
void keyboard(unsigned char c, int iXPos, int iYPos)
{
switch(c)
{
case 'w':
case 'W':
if(glutGetModifiers() & GLUT_ACTIVE_SHIFT) camPanVert(g_Camera, 0.1f);
else camTravel(g_Camera, -0.1f);
break;
case 's':
case 'S':
if(glutGetModifiers() & GLUT_ACTIVE_SHIFT) camPanVert(g_Camera, -0.1f);
else camTravel(g_Camera, 0.1f);
break;
case 'a':
case 'A':
if(glutGetModifiers() & GLUT_ACTIVE_SHIFT) camPanHori(g_Camera, -0.1f);
break;
case 'd':
case 'D':
if(glutGetModifiers() & GLUT_ACTIVE_SHIFT) camPanHori(g_Camera, 0.1f);
break;
case 'r':
case 'R':
camInit(g_Camera);
break;
case 27:
break;
}
glutPostRedisplay();
}
void sKeyboard(int iC, int iXPos, int iYPos)
{
switch(iC)
{
case GLUT_KEY_UP:
if(glutGetModifiers() & GLUT_ACTIVE_SHIFT) camPanVert(g_Camera, 0.1f);
else camTravel(g_Camera, -0.8f);
break;
case GLUT_KEY_DOWN:
if(glutGetModifiers() & GLUT_ACTIVE_SHIFT) camPanVert(g_Camera, -0.1f);
else camTravel(g_Camera, 0.8f);
break;
case GLUT_KEY_LEFT:
if(glutGetModifiers() & GLUT_ACTIVE_SHIFT) camPanHori(g_Camera, -0.1f);
else camRot( g_Camera, -0.05f, 0.0f );
break;
case GLUT_KEY_RIGHT:
if(glutGetModifiers() & GLUT_ACTIVE_SHIFT) camPanHori(g_Camera, 0.1f);
else camRot( g_Camera, 0.05f, 0.0f );
break;
}
glutPostRedisplay();
}
void mouse(int iKey, int iEvent, int iXPos, int iYPos)
{
if(iKey==GLUT_LEFT_BUTTON && iEvent==GLUT_DOWN)
{
g_Camera.m_bMotion=true;
g_Camera.m_aiLastMousePos[0]=iXPos;
g_Camera.m_aiLastMousePos[1]=iYPos;
g_Camera.m_afMouseDisp[0]=0.0f;
g_Camera.m_afMouseDisp[1]=0.0f;
}
else if(iKey==GLUT_RIGHT_BUTTON && iEvent==GLUT_DOWN)
{
// suggest this is where you implement selection
_iCursorX = iXPos;
_iCursorY = iYPos;
_iMode = SELECT;
}
else if(iKey==GLUT_LEFT_BUTTON && iEvent==GLUT_UP)
{
g_Camera.m_bMotion=false;
}
}
void motion(int iXPos, int iYPos)
{
if(g_Camera.m_bMotion)
{
g_Camera.m_afMouseDisp[0]=(((float)iXPos)-((float)g_Camera.m_aiLastMousePos[0]));
g_Camera.m_afMouseDisp[1]=-(((float)iYPos)-((float)g_Camera.m_aiLastMousePos[1]));
glutPostRedisplay();
}
}
void init()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
glEnable( GL_LIGHT0 );
makeGrid(g_ulGrid, 100.0f, 100.0f, 100, 100);
camInit(g_Camera);
}
void mainMenu(int i)
{
switch( i )
{
case _iClearScene: remove_all_shapes( *_plCurrentSceneList ); break;
}
}
void navMenu(int i)
{
float* pfAvPos = get_average_selected_possition( *_plCurrentSceneList );
switch(i)
{
case 1:
_uiFlySet = 1;
_uiEploreMode = 0;
break;
default:
_uiFlySet = 0;
_uiEploreMode = 1;
_uiRecalcuateSelectionLookAt = 1;
break;
}
delete pfAvPos;
}
/*
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Max Stuff
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
void selection_menu( unsigned int iMenuToSet )
{
switch ( iMenuToSet )
{
case 0: glutSetMenu( g_iMainMenu ); break;
case 1: glutSetMenu( g_iMainMenuLight );break;
case 2: glutSetMenu( g_iMainMenuObject );break;
}
glutAttachMenu( GLUT_MIDDLE_BUTTON );
}
/*--------------------------------------------
Author: Max Ashton
Description: Uses the win api to open a dialog box for file selection.
Filters passed by id then converted using switch to limit file types
----------------------------------------------*/
std::string getFileName( unsigned int filter )
{
TCHAR szFilters[] = _T( "All Files (*.*)\0*.*\0\0" );
TCHAR szFiltersObject[] = _T( "Object Files(*.obj)\0*.obj\0\0" );
TCHAR szFiltersScene[] = _T( "Scene Files (*.scn)\0*.scn\0\0" );
TCHAR szFiltersTexture[] = _T( "Bitmap Files (*.bmp)\0*.bmp\0\0" );
TCHAR szFilePathName[_MAX_PATH] = _T("");
OPENFILENAME ofn = {0};
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = NULL;
switch( filter )
{
case OBJECTFILTER: ofn.lpstrFilter = szFiltersObject; break;
case SCENEFILTER: ofn.lpstrFilter = szFiltersScene; break;
case TEXTUREFILTER: ofn.lpstrFilter = szFiltersTexture; break;
default: ofn.lpstrFilter = szFilters; break;
}
ofn.lpstrFile = szFilePathName; // This will the file name
ofn.nMaxFile = _MAX_PATH;
ofn.lpstrTitle = _T( "Open File" );
ofn.Flags = OFN_FILEMUSTEXIST;
// Bring up the dialog, and choose the file
::GetOpenFileName(&ofn);
char buffer[200];
for( int i = 0; i < 200; i++ )
{
buffer[i] = NULL;
}
wcstombs( buffer, ofn.lpstrFile, sizeof( buffer ) );
return buffer;
}
/*--------------------------------------------
Author: Max Ashton
Description: Uses the win api to open a dialog box for file selection.
Filters passed by id then converted using switch to limit file types
----------------------------------------------*/
std::string getSaveFileName( unsigned int filter )
{
TCHAR szFilters[] = _T( "All Files (*.*)\0*.*\0\0" );
TCHAR szFiltersObject[] = _T( "Object File (*.obj)\0*.obj\0\0" );
TCHAR szFiltersScene[] = _T( "Scene Files(*.scn)\0*.scn\0\0" );
TCHAR szFiltersTexture[] = _T( "Bitmap Files(*.bmp)\0*.bmp\0\0" );
TCHAR szFilePathName[_MAX_PATH] = _T("");
OPENFILENAME ofn = {0};
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = NULL;
switch( filter )
{
case OBJECTFILTER: ofn.lpstrFilter = szFiltersObject; break;
case SCENEFILTER: ofn.lpstrFilter = szFiltersScene; break;
case TEXTUREFILTER: ofn.lpstrFilter = szFiltersTexture; break;
default: ofn.lpstrFilter = szFilters; break;
}
ofn.lpstrFile = szFilePathName; // This will the file name
ofn.nMaxFile = _MAX_PATH;
ofn.lpstrTitle = _T( "Save File" );
ofn.Flags = OFN_FILEMUSTEXIST;
// Bring up the dialog, and choose the file
::GetSaveFileName(&ofn);
char buffer[200];
for( int i = 0; i < 200; i++ )
{
buffer[i] = NULL;
}
wcstombs( buffer, ofn.lpstrFile, sizeof( buffer ) );
return buffer;
}
/*--------------------------------------------
Author: Max Ashton
Description: Using a switch statement the correct functions are called based of whats returned by the
glut menu
----------------------------------------------*/
void objectMenu( int i )
{
float* ofPossition = new float[4];
vecProject( g_Camera.m_fVP, g_Camera.m_fVD, 20, ofPossition );
switch( i )
{
case _iAddTriangle: add_triangle( *_plCurrentSceneList, ofPossition[0], ofPossition[1], ofPossition[2] ); break;
case _iAddLitTeapot: add_lit_teapot( *_plCurrentSceneList, ofPossition[0], ofPossition[1], ofPossition[2] ); break;
case _iAddLitSphere: add_lit_sphere( *_plCurrentSceneList, ofPossition[0], ofPossition[1], ofPossition[2] ); break;
case _iAddPossLight: add_possitioned_light( *_plCurrentSceneList, ofPossition[0], ofPossition[1], ofPossition[2] ); break;
case _iAddFromObjectFile: add_model( *_plCurrentSceneList, ofPossition[0], ofPossition[1], ofPossition[2], getFileName( OBJECTFILTER ) );break;
case _iAddSmileyQuad: add_smiley_quad( *_plCurrentSceneList, ofPossition[0], ofPossition[1], ofPossition[2], getFileName( TEXTUREFILTER ), 300, 300 );break;
case _iAddClientCube: add_client_cube( *_plCurrentSceneList, ofPossition[0], ofPossition[1], ofPossition[2] ); break;
//scene control
case _iClearScene: remove_all_shapes( *_plCurrentSceneList ); break;
case _iForwardScene: forward_scene(); break;
case _iBackScene: back_scene(); break;
case _iSaveScene: save_scene( *_plCurrentSceneList, getSaveFileName( SCENEFILTER ) );break;
case _iLoadScene: load_scene( *_plCurrentSceneList, getFileName( SCENEFILTER ) );
//selection menu
case _iRotateX: set_rotate( *_plCurrentSceneList, ROTATEX, ROTATE );break;
case _iRotateY: set_rotate( *_plCurrentSceneList, ROTATEY, ROTATE );break;
case _iRotateZ: set_rotate( *_plCurrentSceneList, ROTATEZ, ROTATE );break;
case _iRemoveObjects: remove_selected_shapes( *_plCurrentSceneList );break;
case _iTogleWireFrameMode: togel_wire_frame_for_selected( *_plCurrentSceneList );break;
case _iTogleLightOnOff: togel_light_for_selected( *_plCurrentSceneList );break;
default: std::cout << "No operation specified";
}
delete ofPossition;
}
/*--------------------------------------------
Author: Max Ashton
Description: Initialize the lists/scenes and add a few starter objects
also global initialize display lists
----------------------------------------------*/
void max_init()
{
create_drawmode_displaylists();
_uiEploreMode = 0;
_plSceneList = new maStructList();
add_element_tail( *_plSceneList, new maStructList(), LISTOFLISTS );
_pCurrentSceneElement = _plSceneList->_psListTail;
_plCurrentSceneList = ( maStructList* ) ( _pCurrentSceneElement->_pvData );
add_triangle( *_plCurrentSceneList, 0.0f, 0.0f, -10.0f );
add_triangle( *_plCurrentSceneList, 0.0f, 3.0f, -10.0f );
add_triangle( *_plCurrentSceneList, 0.0f, 6.0f, -10.0f );
};
/*--------------------------------------------
Author: Max Ashton
Description: Move the back the scene by getting the after node from the current sceneElement
if at tail of list add a new item to tail increasing list
----------------------------------------------*/
void forward_scene()
{
_uiCurrentScene++;
if( _pCurrentSceneElement->_psNext == NULL )
{
add_element_tail( *_plSceneList, new maStructList(), LISTOFLISTS );
std::cout << "New scene added to tail";
}
_pCurrentSceneElement = _pCurrentSceneElement->_psNext;
_plCurrentSceneList = ( maStructList* ) ( _pCurrentSceneElement->_pvData );
std::cout << "Current Scene: " << _uiCurrentScene << "\n";
}
/*--------------------------------------------
Author: Max Ashton
Description: Move the back the scene by getting the before node from the current sceneElement
if at head of list add a new item to head increasing list
----------------------------------------------*/
void back_scene()
{
if( _uiCurrentScene != 0 )
{
_uiCurrentScene--;
}
if( _pCurrentSceneElement->_psBefore == NULL )
{
add_element_head( *_plSceneList, new maStructList(), LISTOFLISTS );
std::cout << "New scene added to head";
}
_pCurrentSceneElement = _pCurrentSceneElement->_psBefore;
_plCurrentSceneList = ( maStructList* ) ( _pCurrentSceneElement->_pvData );
std::cout << "Current Scene: " << _uiCurrentScene << "\n";
}
void set_camera()
{
if( _uiEploreMode != 0 )
{
if( _uiRecalcuateSelectionLookAt != 0 )
{
_uiRecalcuateSelectionLookAt = 0;
float* pfAvPos = get_average_selected_possition( *_plCurrentSceneList );
camToExplore(g_Camera, pfAvPos, 40, display);
}
}
else
{
if( _uiFlySet != 0 )
{
_uiFlySet = 0;
camToFly( g_Camera );
}
}
}
/*--------------------------------------------
Author: Max Ashton
Description: My rendering function called at the end of robs rendering function
Adds an ambient light to the enter scene.
Handles picking if the picking mode has been activated ( right mouse click )
----------------------------------------------*/
void max_render()
{
//determin camera type based on selection
set_camera();
//move this update to proper glut function
update_objects( *_plCurrentSceneList );
glPushMatrix();
//Add ambient light
GLfloat ambientColor[] = {0.2f, 0.2f, 0.2f, 1.0f}; //Color (0.2, 0.2, 0.2)
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);
if ( _plCurrentSceneList->_iListSize > 0 && _iMode == SELECT)
{
start_picking();
}
//
draw_list();
if ( _plCurrentSceneList->_iListSize > 0 &&_iMode == SELECT )
{
stop_picking();
}
glPopMatrix();
}
/*--------------------------------------------
Author: Max Ashton
Description: Rotates the matrix on the x and y axis
data stored in a pointer array size 3
----------------------------------------------*/
void rotate_matrix( float* pfData )
{
//x y z
glRotatef( pfData[0], 1.0f, 0.0f, 0.0f );
glRotatef( pfData[1], 0.0f, 1.0f, 0.0f );
glRotatef( pfData[2], 0.0f, 0.0f, 1.0f );
}
/*--------------------------------------------
Author: Max Ashton
Description: Sets the attributes to draw in wire frame mode
function called create_drawmode_displaylists
----------------------------------------------*/
void draw_in_wireframe()
{
glPolygonMode( GL_FRONT, GL_LINE );
glPolygonMode( GL_BACK, GL_LINE );
}
/*--------------------------------------------
Author: Max Ashton
Description: Sets the attributes to draw in wire solid mode
function called from create_drawmode_displaylists
----------------------------------------------*/
void draw_in_solid()
{
glPolygonMode( GL_FRONT, GL_FILL );
glPolygonMode( GL_BACK, GL_FILL );
}
void create_drawmode_displaylists()
{
_gluiWireframeDL = glGenLists(1);
glNewList( _gluiWireframeDL, GL_COMPILE );
draw_in_wireframe();
glEndList();
_gluiSolidDL = glGenLists(1);
glNewList( _gluiSolidDL, GL_COMPILE );
draw_in_solid();
glEndList();
}
/*--------------------------------------------
Author: Max Ashton
Description: Draw a triangle with no lighting
gl used to disable lighting and enable blending for use of colors
simple glbeing and gl end used to set colour and vertices.
Translation and rotation applied before drawing so object appears in correct place at
the rotated orientation.
----------------------------------------------*/
void draw_traingle( ObjectData* pvData )
{
glPushMatrix();
glDisable( GL_LIGHTING );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
pvData->basicData->iDrawWireFrame ? glCallList( _gluiWireframeDL ) : glCallList( _gluiSolidDL );
glTranslatef( pvData->basicData->pfPossitionData[0], pvData->basicData->pfPossitionData[1], pvData->basicData->pfPossitionData[2] );
rotate_matrix( pvData->basicData->faRoataionData );
glBegin( GL_TRIANGLES );
glNormal3f( 0.25f, 0.25f, 1.0f );
glColor3f( 0.9f, 0.0f, 0.0f );
glVertex4f( -1.0f, 0.0f, 0.0f, 1.0f );
glColor3f( 0.0f, 0.9f, 0.0f );
glVertex4f( 1.0f, 0.0f, 0.0f, 1.0f );
glColor3f( 0.0f, 0.0f, 0.9f );
glVertex4f( 0.0f, 1.0f, 0.0f, 1.0f );
glEnd();
glDisable( GL_BLEND );
glEnable(GL_LIGHTING );
glPopMatrix();
}
/*--------------------------------------------
Author: Max Ashton
Description: Simply call glut's function to draw a sphere
Material values come from info stored in the list.
Translation and rotation applied before drawing so object appears in correct place at
the rotated orientation.
----------------------------------------------*/
void draw_lit_sphere( ObjectData* pvData )
{
glPushMatrix();
pvData->basicData->iDrawWireFrame ? glCallList( _gluiWireframeDL ) : glCallList( _gluiSolidDL );
glPushAttrib( GL_ALL_ATTRIB_BITS );
glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT,
pvData->pfAmbiantMaterialData );
glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, pvData->pfDiffusedMaterialData );
glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, pvData->pfSpectularMaterialData );
glMaterialf( GL_FRONT_AND_BACK, GL_SHININESS, 100.0f );
glTranslatef( pvData->basicData->pfPossitionData[0], pvData->basicData->pfPossitionData[1], pvData->basicData->pfPossitionData[2] );
rotate_matrix( pvData->basicData->faRoataionData );
glutSolidSphere( 1.0f * pvData->basicData->fScale, 20.0f, 20.0f );
glPopAttrib();
glPopMatrix();
}
/*--------------------------------------------
Author: Max Ashton
Description: Simply call glut's function to draw a teapot
Material values come from info stored in the list.
Translation and rotation applied before drawing so object appears in correct place at
the rotated orientation.
----------------------------------------------*/
void draw_lit_teapot( ObjectData* pvData )
{
glPushMatrix();
pvData->basicData->iDrawWireFrame ? glCallList( _gluiWireframeDL ) : glCallList( _gluiSolidDL );
glPushAttrib( GL_ALL_ATTRIB_BITS );
glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, pvData->pfAmbiantMaterialData );
glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, pvData->pfDiffusedMaterialData );
glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, pvData->pfSpectularMaterialData );
glMaterialf( GL_FRONT_AND_BACK, GL_SHININESS, 100.0f );
glTranslatef( pvData->basicData->pfPossitionData[0], pvData->basicData->pfPossitionData[1], pvData->basicData->pfPossitionData[2] );
rotate_matrix( pvData->basicData->faRoataionData );
glutSolidTeapot( 1.0f );
glPopAttrib();
glPopMatrix();
}
/*--------------------------------------------
Author: Max Ashton
Description: Simply call glut's function to draw a sphere
Material calues come from info stored in the list.
Translation and rotation applied before drawing so object appears in correct place at
the rotated orientation in this case it is the same as the original object that is selected.
----------------------------------------------*/
void draw_selection_sphere( float* pfPossitionData, float fScale )
{
glPushMatrix();
glPolygonMode( GL_FRONT, GL_LINE );
glPolygonMode( GL_BACK, GL_LINE );
GLfloat am[] = {0.0f, 1.0f, 0.0f, 0.0f};
GLfloat diff[] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat spec[] = {0.0f, 0.0f, 0.0f, 0.0f};
//DISPLIST
glPushMatrix();
glPushAttrib( GL_ALL_ATTRIB_BITS );
glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, am);
glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, diff);
glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, spec );
glMaterialf( GL_FRONT_AND_BACK, GL_SHININESS, 100.0f );
glTranslatef( pfPossitionData[0], pfPossitionData[1], pfPossitionData[2] );
glRotatef( _fIdelRotationValue, 0.0f, 1.0f, 0.0f );
glutSolidSphere( 1.5f * fScale, 20.0f, 20.0f );
glPopAttrib();
glPopMatrix();
glPolygonMode( GL_FRONT, GL_FILL );
glPolygonMode( GL_BACK, GL_FILL );
glPopMatrix();
}
/*--------------------------------------------
Author: Max Ashton
Description: Using a switch statement the correct GLlight is used based on my light ID held in the list
Translation and rotation applied before drawing so object appears in correct place at
the rotated orientation.
A simple sphere is then drawn using the light located but slightly lower
----------------------------------------------*/
void draw_possitioned_light( ObjectData* pvData )
{
float light = pvData->basicData->iObjectID;
//Add positioned light
GLfloat lightColor0[] = {pvData->pfDiffusedMaterialData[0], pvData->pfDiffusedMaterialData[1], pvData->pfDiffusedMaterialData[2], pvData->pfDiffusedMaterialData[3]};
GLfloat lightPos0[] = {pvData->basicData->pfPossitionData[0], pvData->basicData->pfPossitionData[1] + 5.0f, pvData->basicData->pfPossitionData[2], pvData->basicData->pfPossitionData[3]};
switch( pvData->basicData->uiLightID )
{
case 0:
if( pvData->basicData->uiLightOn != 0 )
{
glEnable( GL_LIGHT0 );
glLightfv( GL_LIGHT0, GL_DIFFUSE, lightColor0 );
glLightfv( GL_LIGHT0, GL_POSITION, lightPos0 );
}
else
{
glDisable( GL_LIGHT0 );
}
break;
case 1:
if( pvData->basicData->uiLightOn != 0 )
{
glEnable( GL_LIGHT1 );
glLightfv( GL_LIGHT1, GL_DIFFUSE, lightColor0 );
glLightfv( GL_LIGHT1, GL_POSITION, lightPos0 );
}
else
{
glDisable( GL_LIGHT1 );
}
break;
case 2:
if( pvData->basicData->uiLightOn != 0 )
{
glEnable( GL_LIGHT2 );
glLightfv( GL_LIGHT2, GL_DIFFUSE, lightColor0 );
glLightfv( GL_LIGHT2, GL_POSITION, lightPos0 );
}
else
{
glDisable( GL_LIGHT2 );
}
break;
case 3:
if( pvData->basicData->uiLightOn != 0 )
{
glEnable( GL_LIGHT3 );
glLightfv( GL_LIGHT3, GL_DIFFUSE, lightColor0 );
glLightfv( GL_LIGHT3, GL_POSITION, lightPos0 );
}
else
{
glDisable( GL_LIGHT3 );
}
break;
case 4:
if( pvData->basicData->uiLightOn != 0 )
{
glEnable( GL_LIGHT4 );
glLightfv( GL_LIGHT4, GL_DIFFUSE, lightColor0 );
glLightfv( GL_LIGHT4, GL_POSITION, lightPos0 );
}
else
{
glDisable( GL_LIGHT4 );
}
break;
case 5:
if( pvData->basicData->uiLightOn != 0 )
{
glEnable( GL_LIGHT5 );
glLightfv( GL_LIGHT5, GL_DIFFUSE, lightColor0 );
glLightfv( GL_LIGHT5, GL_POSITION, lightPos0 );
}
else
{
glDisable( GL_LIGHT5 );
}
break;
}
draw_lit_sphere( pvData );
}
/*--------------------------------------------
Author: Max Ashton
Description: Texture mapped to a simple quad consisting of 4 vertices glbegin and glend
used to specify vertices
----------------------------------------------*/
void draw_textured_quad( ObjectData* pvData )
{
glPushMatrix();
pvData->basicData->iDrawWireFrame ? glCallList( _gluiWireframeDL ) : glCallList( _gluiSolidDL );
glEnable( GL_TEXTURE_2D );
glBindTexture( GL_TEXTURE_2D, pvData->guiTextureID );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glTranslatef( pvData->basicData->pfPossitionData[0], pvData->basicData->pfPossitionData[1], pvData->basicData->pfPossitionData[2] );
rotate_matrix( pvData->basicData->faRoataionData );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glBegin(GL_QUADS);
glColor3f( 1.0f, 1.0f, 1.0f );
glNormal3f( 0.0, 0.0f, 1.0f);
glTexCoord2f( 0.0f, 0.0f );
glVertex3f( -1.0f, -1.0f * pvData->fAspectRatio, 0.0f );
glTexCoord2f( 1.0f, 0.0f );
glVertex3f( 1.0f, -1.0f * pvData->fAspectRatio, 0.0f );
glTexCoord2f( 1.0f, 1.0f );
glVertex3f( 1.0f, 1.0f * pvData->fAspectRatio, 0.0f );
glTexCoord2f( 0.0f, 1.0f );
glVertex3f( -1.0f, 1.0f * pvData->fAspectRatio, 0.0f );
glEnd();
glDisable( GL_TEXTURE_2D );
glPopMatrix();
}
/*--------------------------------------------
Author: Max Ashton
Description: Cube using client side gl functions. 8 x 3 glfloat array constructed to pass the cuves vertices and then 6 x 6
indices's array created to tell opengl which vertices to use
----------------------------------------------*/
GLfloat aVertices[] = {-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f};
GLubyte aIndices[] = {0,1,2, 2,3,0,
0,3,4, 4,5,0,
0,5,6, 6,1,0,
1,6,7, 7,2,1,
7,4,3, 3,2,7,
4,7,6, 6,5,4};
unsigned int bNormalsCalculated = 0;
GLfloat aNormals[] = {0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f};
/* Normal Calculation
0. Normalize ( Cross(0,3) + Cross(0,1) + Cross(0,5) )
1. Normalize ( Cross(1,2) + Cross(1,6) + Cross(1,0) )
2. Normalize ( Cross(2,1) + Cross(2,3) + Cross(2,7) )
3. Normalize ( Cross(3,4) + Cross(3,2) + Cross(3,0) )
4. Normalize ( Cross(4,3) + Cross(4,7) + Cross(4,5) )
5. Normalize ( Cross(5,4) + Cross(5,0) + Cross(5,6) )
6. Normalize ( Cross(6,7) + Cross(6,1) + Cross(6,5) )
7. Normalize ( Cross(6,2) + Cross(7,6) + Cross(7,4) )
*/
void calculate_cube_normals()
{
float* pfV1 = new float[4];
float* pfV2 = new float[4];
float* pfOutcome1 = new float[4];
float* pfOutcome2 = new float[4];
float* pfOutcome3 = new float[4];
float* pfAddRes = new float[4];
float* pfAddRes2 = new float[4];
float* pfNormalized = new float[4];
//0
pfV1[0] = aVertices[0];
pfV1[1] = aVertices[1];
pfV1[2] = aVertices[2];
pfV2[0] = aVertices[9];
pfV2[1] = aVertices[10];
pfV2[2] = aVertices[11];
vecCrossProduct( pfV1, pfV2, pfOutcome1 );
pfV2[0] = aVertices[3];
pfV2[1] = aVertices[4];
pfV2[2] = aVertices[5];
vecCrossProduct( pfV1, pfV2, pfOutcome2 );
pfV2[0] = aVertices[16];
pfV2[1] = aVertices[17];
pfV2[2] = aVertices[18];
vecCrossProduct( pfV1, pfV2, pfOutcome3 );
vecAdd( pfOutcome1, pfOutcome2, pfAddRes );
vecAdd( pfAddRes, pfOutcome3, pfAddRes2 );
vecNormalise( pfAddRes2, pfNormalized );
aNormals[0] = pfNormalized[0];
aNormals[1] = pfNormalized[1];
aNormals[2] = pfNormalized[2];
//1
pfV1[0] = aVertices[3];
pfV1[1] = aVertices[4];
pfV1[2] = aVertices[5];
pfV2[0] = aVertices[6];
pfV2[1] = aVertices[7];
pfV2[2] = aVertices[8];
vecCrossProduct( pfV1, pfV2, pfOutcome1 );
pfV2[0] = aVertices[18];
pfV2[1] = aVertices[19];
pfV2[2] = aVertices[20];
vecCrossProduct( pfV1, pfV2, pfOutcome2 );
pfV2[0] = aVertices[0];
pfV2[1] = aVertices[1];
pfV2[2] = aVertices[2];
vecCrossProduct( pfV1, pfV2, pfOutcome3 );
vecAdd( pfOutcome1, pfOutcome2, pfAddRes );
vecAdd( pfAddRes, pfOutcome3, pfAddRes );
vecNormalise( pfAddRes, pfNormalized );
aNormals[3] = pfNormalized[0];
aNormals[4] = pfNormalized[1];
aNormals[5] = pfNormalized[2];
//2
pfV1[0] = aVertices[6];
pfV1[1] = aVertices[7];
pfV1[2] = aVertices[8];
pfV2[0] = aVertices[3];
pfV2[1] = aVertices[4];
pfV2[2] = aVertices[5];
vecCrossProduct( pfV1, pfV2, pfOutcome1 );
pfV2[0] = aVertices[9];
pfV2[1] = aVertices[10];
pfV2[2] = aVertices[11];
vecCrossProduct( pfV1, pfV2, pfOutcome2 );
pfV2[0] = aVertices[21];
pfV2[1] = aVertices[22];
pfV2[2] = aVertices[23];
vecCrossProduct( pfV1, pfV2, pfOutcome3 );
vecAdd( pfOutcome1, pfOutcome2, pfAddRes );
vecAdd( pfAddRes, pfOutcome3, pfAddRes );
vecNormalise( pfAddRes, pfNormalized );
aNormals[6] = pfNormalized[0];
aNormals[7] = pfNormalized[1];
aNormals[8] = pfNormalized[2];
//3
pfV1[0] = aVertices[9];
pfV1[1] = aVertices[10];
pfV1[2] = aVertices[11];
pfV2[0] = aVertices[12];
pfV2[1] = aVertices[13];
pfV2[2] = aVertices[14];
vecCrossProduct( pfV1, pfV2, pfOutcome1 );
pfV2[0] = aVertices[6];
pfV2[1] = aVertices[7];
pfV2[2] = aVertices[8];
vecCrossProduct( pfV1, pfV2, pfOutcome2 );
pfV2[0] = aVertices[0];
pfV2[1] = aVertices[1];
pfV2[2] = aVertices[2];
vecCrossProduct( pfV1, pfV2, pfOutcome3 );
vecAdd( pfOutcome1, pfOutcome2, pfAddRes );
vecAdd( pfAddRes, pfOutcome3, pfAddRes );
vecNormalise( pfAddRes, pfNormalized );
aNormals[9] = pfNormalized[0];
aNormals[10] = pfNormalized[1];
aNormals[11] = pfNormalized[2];
//4
pfV1[0] = aVertices[12];
pfV1[1] = aVertices[13];
pfV1[2] = aVertices[14];
pfV2[0] = aVertices[9];
pfV2[1] = aVertices[10];
pfV2[2] = aVertices[11];
vecCrossProduct( pfV1, pfV2, pfOutcome1 );
pfV2[0] = aVertices[21];
pfV2[1] = aVertices[22];
pfV2[2] = aVertices[23];
vecCrossProduct( pfV1, pfV2, pfOutcome2 );
pfV2[0] = aVertices[15];
pfV2[1] = aVertices[16];
pfV2[2] = aVertices[17];
vecCrossProduct( pfV1, pfV2, pfOutcome3 );
vecAdd( pfOutcome1, pfOutcome2, pfAddRes );
vecAdd( pfAddRes, pfOutcome3, pfAddRes );
vecNormalise( pfAddRes, pfNormalized );
aNormals[12] = pfNormalized[0];
aNormals[13] = pfNormalized[1];
aNormals[14] = pfNormalized[2];
//5
pfV1[0] = aVertices[15];
pfV1[1] = aVertices[16];
pfV1[2] = aVertices[17];
pfV2[0] = aVertices[12];
pfV2[1] = aVertices[13];
pfV2[2] = aVertices[14];
vecCrossProduct( pfV1, pfV2, pfOutcome1 );
pfV2[0] = aVertices[0];
pfV2[1] = aVertices[1];
pfV2[2] = aVertices[2];
vecCrossProduct( pfV1, pfV2, pfOutcome2 );
pfV2[0] = aVertices[18];
pfV2[1] = aVertices[19];
pfV2[2] = aVertices[20];
vecCrossProduct( pfV1, pfV2, pfOutcome3 );
vecAdd( pfOutcome1, pfOutcome2, pfAddRes );
vecAdd( pfAddRes, pfOutcome3, pfAddRes );
vecNormalise( pfAddRes, pfNormalized );
aNormals[15] = pfNormalized[0];
aNormals[16] = pfNormalized[1];
aNormals[17] = pfNormalized[2];
// 6
pfV1[0] = aVertices[18];
pfV1[1] = aVertices[19];
pfV1[2] = aVertices[20];
pfV2[0] = aVertices[21];
pfV2[1] = aVertices[22];
pfV2[2] = aVertices[23];
vecCrossProduct( pfV1, pfV2, pfOutcome1 );
pfV2[0] = aVertices[3];
pfV2[1] = aVertices[4];
pfV2[2] = aVertices[5];
vecCrossProduct( pfV1, pfV2, pfOutcome2 );
pfV2[0] = aVertices[15];
pfV2[1] = aVertices[16];
pfV2[2] = aVertices[17];
vecCrossProduct( pfV1, pfV2, pfOutcome3 );
vecAdd( pfOutcome1, pfOutcome2, pfAddRes );
vecAdd( pfAddRes, pfOutcome3, pfAddRes );
vecNormalise( pfAddRes, pfNormalized );
aNormals[18] = pfNormalized[0];
aNormals[19] = pfNormalized[1];
aNormals[20] = pfNormalized[2];
// 7
pfV1[0] = aVertices[21];
pfV1[1] = aVertices[22];
pfV1[2] = aVertices[23];
pfV2[0] = aVertices[6];
pfV2[1] = aVertices[7];
pfV2[2] = aVertices[8];
vecCrossProduct( pfV1, pfV2, pfOutcome1 );
pfV2[0] = aVertices[18];
pfV2[1] = aVertices[19];
pfV2[2] = aVertices[20];
vecCrossProduct( pfV1, pfV2, pfOutcome2 );
pfV2[0] = aVertices[12];
pfV2[1] = aVertices[13];
pfV2[2] = aVertices[14];
vecCrossProduct( pfV1, pfV2, pfOutcome3 );
vecAdd( pfOutcome1, pfOutcome2, pfAddRes );
vecAdd( pfAddRes, pfOutcome3, pfAddRes );
vecNormalise( pfAddRes, pfNormalized );
aNormals[21] = pfNormalized[0];
aNormals[22] = pfNormalized[1];
aNormals[23] = pfNormalized[2];
delete pfV1;
delete pfV2;
delete pfOutcome1;
delete pfOutcome2;
delete pfOutcome3;
delete pfAddRes;
delete pfAddRes2;
delete pfNormalized;
}
void draw_client_cube( ObjectData* pvData )
{
glPushMatrix();
pvData->basicData->iDrawWireFrame ? glCallList( _gluiWireframeDL ) : glCallList( _gluiSolidDL );
glTranslatef( pvData->basicData->pfPossitionData[0], pvData->basicData->pfPossitionData[1], pvData->basicData->pfPossitionData[2] );
rotate_matrix( pvData->basicData->faRoataionData );
//calculate normals
if( bNormalsCalculated == 0 )
{
bNormalsCalculated = 1;
calculate_cube_normals();
}
glEnableClientState( GL_VERTEX_ARRAY );
glVertexPointer( 3, GL_FLOAT, 0, aVertices );
glNormalPointer( GL_FLOAT, 0, aNormals );
glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, aIndices );
glDisableClientState( GL_VERTEX_ARRAY );
glPopMatrix();
}
/*--------------------------------------------
Author: Max Ashton
Description: Model drawn by looping through faces and mapping the face values to vertices stored in
the vertices array. This function uses a display list to store the model on the graphics card.
The display list gets build the first time the model is drawn this value is then stored in the list
data.
----------------------------------------------*/
void draw_model( ModelData* pmData )
{
// if create list create list
if( pmData->uiDisplalyListIndex == 0 )
{
GLuint index = glGenLists(1);
pmData->uiDisplalyListIndex = index;
glNewList( index, GL_COMPILE );
for( unsigned int i = 0; i < pmData->uiNoOfFaces; i++ )
{
//if position 4 = 0 then there are only 3 vertecies for the face
if( pmData->pmfFaces[i].pfVerticies[3] == -1 )
{
//vertices come from map
glBegin( GL_TRIANGLES );
glNormal3fv( pmData->pfNormalData[pmData->pmfFaces[i].pfNormals[0] -1] );
glVertex3fv( pmData->pfVertexData[pmData->pmfFaces[i].pfVerticies[0] -1] );
glNormal3fv( pmData->pfNormalData[pmData->pmfFaces[i].pfNormals[1] -1] );
glVertex3fv( pmData->pfVertexData[pmData->pmfFaces[i].pfVerticies[1] -1] );
glNormal3fv( pmData->pfNormalData[pmData->pmfFaces[i].pfNormals[2] -1] );
glVertex3fv( pmData->pfVertexData[pmData->pmfFaces[i].pfVerticies[2] -1] );
glEnd();
}
else
{
glBegin( GL_QUADS );
glNormal3fv(pmData->pfNormalData[pmData->pmfFaces[i].pfNormals[0] -1]);
glVertex3fv( pmData->pfVertexData[pmData->pmfFaces[i].pfVerticies[0] -1] );
glNormal3fv( pmData->pfNormalData[pmData->pmfFaces[i].pfNormals[1] -1] );
glVertex3fv( pmData->pfVertexData[pmData->pmfFaces[i].pfVerticies[1] -1] );
glNormal3fv( pmData->pfNormalData[pmData->pmfFaces[i].pfNormals[2] -1] );
glVertex3fv( pmData->pfVertexData[pmData->pmfFaces[i].pfVerticies[2] -1] );
glNormal3fv( pmData->pfNormalData[pmData->pmfFaces[i].pfNormals[3] -1] );
glVertex3fv( pmData->pfVertexData[pmData->pmfFaces[i].pfVerticies[3] -1] );
glEnd();
}
}
glEndList();
}
pmData->basicData->iDrawWireFrame ? glCallList( _gluiWireframeDL ) : glCallList( _gluiSolidDL );
glTranslatef( pmData->basicData->pfPossitionData[0], pmData->basicData->pfPossitionData[1], pmData->basicData->pfPossitionData[2] );
rotate_matrix( pmData->basicData->faRoataionData );
glCallList( pmData->uiDisplalyListIndex );
}
/*--------------------------------------------
Author: Max Ashton
Description: Loop through the list telling all the objects to be drawn by calling the function pointer;
Casting is used to retrieve the correct data from the list_item as models use a different structure than
primitive shapes
----------------------------------------------*/
void draw_list()
{
bool bEndOfList = false;
int iCurrentVertecie = 0;
maStruListElement* pvCurrentVertice = _plCurrentSceneList->_psListHead;
while( !bEndOfList && _plCurrentSceneList->_iListSize > 0 )
{
//draw object and set "name" for selection process
glPushMatrix();
if( pvCurrentVertice->dataType == OBJECT )
{
glPushName( ( ( ObjectData* ) pvCurrentVertice->_pvData )->basicData->iObjectID );
( ( ObjectData* ) pvCurrentVertice->_pvData )->pDrawFunc( ( ObjectData* ) pvCurrentVertice->_pvData );
if( ( ( ObjectData* ) pvCurrentVertice->_pvData )->basicData->iSelected != 0 )
{
draw_selection_sphere( ( ( ObjectData* ) pvCurrentVertice->_pvData )->basicData->pfPossitionData, ( ( ObjectData* ) pvCurrentVertice->_pvData )->basicData->fScale );
}
}
else
{
glPushName( ( ( ModelData* ) pvCurrentVertice->_pvData )->basicData->iObjectID );
( ( ModelData* ) pvCurrentVertice->_pvData )->pDrawFunc( ( ModelData* ) pvCurrentVertice->_pvData );
if( ( ( ModelData* ) pvCurrentVertice->_pvData )->basicData->iSelected != 0 )
{
draw_selection_sphere( ( ( ModelData* ) pvCurrentVertice->_pvData )->basicData->pfPossitionData, ( ( ModelData* ) pvCurrentVertice->_pvData )->basicData->fScale );
}
}
glPopName();
glPopMatrix();
if( pvCurrentVertice == _plCurrentSceneList->_psListTail )
{
bEndOfList = true;
}
else
{
pvCurrentVertice = pvCurrentVertice->_psNext;
}
}
}
/*--------------------------------------------
Author: Max Ashton
Description: Remove all shapes to clean up
----------------------------------------------*/
void max_cleanup()
{
remove_all_shapes( *_plCurrentSceneList );
}
/*--------------------------------------------
Author: Max Ashton
Description: creates a frustum down the sight of the mouse pointer ( -z axis ) to determine object under the mouse
----------------------------------------------*/
void start_picking()
{
GLint agiViewport[4];
float fRatio;
glSelectBuffer( BUFSIZE, selectBuf );
glGetIntegerv( GL_VIEWPORT, agiViewport );
glRenderMode( GL_SELECT );
glInitNames();
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
gluPickMatrix( _iCursorX, agiViewport[3] - _iCursorY ,5 , 5, agiViewport );
fRatio = ( agiViewport[2] + 0.0 ) / agiViewport[3];
gluPerspective( 30.0f, fRatio, 1.0f, 1000.0f );
glMatrixMode( GL_MODELVIEW );
}
/*--------------------------------------------
Author: Max Ashton
Description: flushes the selection buffer for hits
----------------------------------------------*/
void stop_picking()
{
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glFlush();
_uiHits = glRenderMode(GL_RENDER);
if ( _uiHits != 0 )
{
process_hits( _uiHits, selectBuf, 0 );
_uiRecalcuateSelectionLookAt = 1;//set recalculate to true so cam focuses on objects
_uiEploreMode = 1; //explore mode to true so cam moves
}
else
{
std::cout << "No Object in selection range " << "\n";
deselect_all_objects( *_plCurrentSceneList );
_uiEploreMode = 0; // come out of explore mode on deselection
_uiFlySet = 1;
selection_menu( 0 );
}
_iMode = RENDER;
}
/*--------------------------------------------
Author: Max Ashton
Description: Uses the vertices object names to determine selected object.
----------------------------------------------*/
void process_hits( GLuint hits, GLuint buffer[], int sw )
{
GLuint uiNumberOfNames;
GLuint uiNames, *pName, uiMinZ,*pNames;
pName = ( GLuint* ) buffer;
uiMinZ = 0xffffffff;//-1
for ( GLuint i = 0; i < hits; i++ )
{
uiNames = *pName;
pName++;
if ( *pName < uiMinZ )
{
uiNumberOfNames = uiNames;
uiMinZ = *pName;
pNames = pName + 2;
}
pName += uiNames + 2;
}
if ( uiNumberOfNames > 0 )
{
printf ( "You selected Object: " );
pName = pNames;
for ( GLuint j = 0; j < uiNumberOfNames; j++,pName++ )
{
printf( "%d ", *pName );
select_object( *_plCurrentSceneList, *pName );
}
}
printf ("\n");
} | [
"max@half-a-pixel.co.uk"
] | max@half-a-pixel.co.uk |
d29fa0063aeab298dd09ad862e94967c1a81fb0e | d8d64c4dc1d1e4b5e6a72b575efe1b740823342e | /_includes/source_code/code/25-PDP/triangle/triangle_official.cpp | 5324bebc927dab3c3478ad0e1f17e5711012b930 | [] | no_license | pdp-archive/pdp-archive.github.io | 6c6eb2a08fe8d20c8fb393e3437e89e2c0e9d231 | 9f8002334de7817a998a65a070f899b40f50e294 | refs/heads/master | 2023-06-08T19:07:22.444091 | 2023-05-31T12:45:43 | 2023-05-31T12:45:43 | 169,656,266 | 26 | 19 | null | 2023-05-31T12:45:45 | 2019-02-07T23:00:27 | C++ | UTF-8 | C++ | false | false | 1,021 | cpp | #include<stdio.h>
#include<string.h>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
#define MAXN 1005
#define f first
#define s second
#define mp make_pair
#define INF 0x3f3f3f3f
#define pii pair<int,int>
#define BASE 256
#define MOD 7293847562347896LL
int N,dp[MAXN][MAXN],back[MAXN][MAXN];
void Read () {
scanf("%d",&N);
for (int i=1;i<=N;i++) {
for (int j=1;j<=i;j++) {
scanf("%d",&back[i][j]);
}
}
}
void Solve() {
dp[1][1]=back[1][1]; // base cases of dp
for (int i=2;i<=N;i++) {
for (int j=1;j<=i;j++) {
if (j!=i)
dp[i][j]=max(dp[i][j],dp[i-1][j]+back[i][j]);
if (j!=1)
dp[i][j]=max(dp[i][j],dp[i-1][j-1]+back[i][j]);
}
}
int ans=0;
for (int i=1;i<=N;i++)
ans=max(dp[N][i],ans);
printf("%d\n",ans);
}
int main () {
freopen("triangle.in","r",stdin);
freopen("triangle.out","w",stdout);
Read();
Solve();
return 0;
}
| [
"dim-los_13@hotmail.com"
] | dim-los_13@hotmail.com |
ce43a0218365d9a70da5af1ae52cec26e7e158c4 | 04c108db9807bf5a4d3ade65960f90d5fc236158 | /C/ConsoleApplication21프로젝트/ConsoleApplication21프로젝트/소스.cpp | e533264405b4bd6d52eb4abbeac25da1410eb55c | [] | no_license | lhj0621/idu-projects | 4b0280d4fb6c3f73bc005a3105e3a4546479c18d | e8113e69e4cf46b56ac9ce7d4f1d5d971b1d1df0 | refs/heads/develop | 2022-12-10T10:56:34.270885 | 2019-09-06T14:13:12 | 2019-09-06T14:13:12 | 189,450,463 | 0 | 1 | null | 2022-12-08T04:28:44 | 2019-05-30T16:53:12 | TSQL | UHC | C++ | false | false | 4,897 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <mmsystem.h> //음악재생
#pragma comment(lib, "winmm") //음악재생
#include "tbc.h"
#define MAX 100
#define PAUSE 112
typedef struct {
int x, y;
} POS;
void draw_screen();
void draw_char(int x, int y, char* s);
void move_snake(POS* snake, int len);
int check_snake(POS* snake, int len);
void main2();
int score = 0, totlen = 5;
int main()
{
sndPlaySound(L"abc.wav", SND_ASYNC | SND_LOOP); //시작시 노래
int choice;
for (;;)
{
score = 0, totlen = 5;
draw_char(5, 1, "*조작키*");
draw_char(5, 2, "이동: ←→↑↓ ");
draw_char(5, 4, "*게임방법*");
draw_char(5, 5, "머리가 몸통이나 벽에 닿으면 게임 오버.");
draw_char(5, 8, "■■■■■■■■■■■■■■■■■■■■");
draw_char(5, 9, "■1번을 입력하시면 게임을 시작합니다. ■");
draw_char(5, 10, "■2번을 입력하시면 게임을 종료합니다. ■");
draw_char(5, 11, "■■■■■■■■■■■■■■■■■■■■");
draw_char(11, 13, "입력하세요 :");
scanf("%d", &choice);
if (choice == 1)
{
main2();
clrscr();
}
else if (choice == 2)
{
return 0;
}
else
{
draw_char(11, 14, "다시입력하세요");
}
}
}
void main2()
{
POS snake[MAX], item;
int i, n = 0, dir = -1, len = 5, loop = 1;
int speed = 150;
// 랜덤 초기화.
srand(time(NULL));
// 배경 그리기.
draw_screen();
// 뱀 초기위치.
for (i = 0; i < len; i++)
{
snake[i].x = 15 - i;
snake[i].y = 10 - i;
draw_char(snake[i].x, snake[i].y, "□");
}
// 먹이 처음 위치
item.x = rand() % 28 + 1;
item.y = rand() % 18 + 1;
/*draw_char(1, 21, "Score : 0");
draw_char(1, 22, "뱀의 길이 : 5");
draw_char(1, 23, "재시작 버튼은 R키입니다.");
draw_char(1, 24, "일시정지 키는 P입니다.");*/
// 게임 루프.
while (loop)
{
// 벽이나 몸통에 닿았는지 체크.
if (check_snake(snake, len) == 0)
break;
// 먹이를 먹었는지 체크
if (snake[0].x == item.x && snake[0].y == item.y)
{
score += 10;
totlen += 1;
item.x = rand() % 28 + 1;
item.y = rand() % 18 + 1;
draw_char(1, 21, "Score : "); //화면의 특정위치에 출력하는 함수
printf("%d\n", score); //현제 스코어 점수가 출력됨
draw_char(1, 22, "뱀의 길이 : ");
printf("%d", totlen);
// 스피드 증가.
if (speed > 10) speed -= 5;
// 꼬리 증가.
if (len < MAX)
{
snake[len] = snake[len - 1];
len++;
}
}
// 아이템 출력.
draw_char(item.x, item.y, "★");
// 뱀 움직임 처리.
move_snake(snake, len);
// 스피드 조절.
Sleep(speed);
}
draw_char(0, 25, " Game Over\n");
system("pause");
}
// 화면의 특정 위치로 이동해 출력하는 함수.
void draw_char(int x, int y, char* s)
{
COORD Pos = { x * 2, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos);
printf("%s", s);
}
void draw_screen()
{
int i;
system("cls");
draw_char(0, 0, "▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩");
for (i = 1; i < 20; i++)
{
draw_char(0, i, "▩");
draw_char(30, i, "▩");
}
draw_char(0, 20, "▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩\n");
draw_char(1, 21, "Score : ");
printf("%d\n", score);
draw_char(1, 22, "뱀의 길이 : ");
printf("%d\n", totlen);
draw_char(1, 23, "재시작 버튼은 R키입니다.");
}
void move_snake(POS* snake, int len)
{
static int dir = -1; //프로그램이 끝날때까지 값이 누적된다
// 키입력 처리.
if (_kbhit())
{
int key;
do { key = _getch(); } while (key == 224);
switch (key)
{
case 72: dir = 0; break; // 위쪽 이동.
case 80: dir = 1; break; // 아래쪽 이동.
case 75: dir = 2; break; // 왼쪽 이동.
case 77: dir = 3; break; // 오른쪽 이동.
case 'r':
system("cls");
score = 0, totlen = 5;
main2();
//break;
}
}
// 뱀 몸통 처리
if (dir != -1)
{
int i;
draw_char(snake[len - 1].x, snake[len - 1].y, " ");
for (i = len - 1; i > 0; i--) snake[i] = snake[i - 1];
draw_char(snake[1].x, snake[1].y, "□");
}
// 뱀 머리 처리.
switch (dir)
{
case 0: snake[0].y--; break;
case 1: snake[0].y++; break;
case 2: snake[0].x--; break;
case 3: snake[0].x++; break;
}
draw_char(snake[0].x, snake[0].y, "@");
}
int check_snake(POS* snake, int len)
{
int i;
// 머리가 벽에 닿았는지 체크.
if (snake[0].x == 0 || snake[0].y == 0 || snake[0].x == 30 || snake[0].y == 20)
return 0;
// 머리가 몸통에 닿았는지 체크.
for (i = 1; i < len; i++)
{
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y)
return 0;
}
return 1;
} | [
"lhj0621@gmail.com"
] | lhj0621@gmail.com |
947a51ae85b973e3273227a017aa6cbe3f28039a | 0233477eeb6d785b816ee017cf670e2830bdd209 | /SDK/SoT_BP_Cutscene_BagOfGold_functions.cpp | cc4b845898b650ce8343139a2b3476058a47d999 | [] | no_license | compy-art/SoT-SDK | a568d346de3771734d72463fc9ad159c1e1ad41f | 6eb86840a2147c657dcd7cff9af58b382e72c82a | refs/heads/master | 2020-04-17T02:33:02.207435 | 2019-01-13T20:55:42 | 2019-01-13T20:55:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 749 | cpp | // Sea of Thieves (1.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_Cutscene_BagOfGold_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function BP_Cutscene_BagOfGold.BP_Cutscene_BagOfGold_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_Cutscene_BagOfGold_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Cutscene_BagOfGold.BP_Cutscene_BagOfGold_C.UserConstructionScript");
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
1abb64cec415638fdcb80c0d5cc654676761fa33 | 235a75b6fa2e3736ff8c05b89b5919f94938ec90 | /表情识别/test1/DlgDisplayFrames.h | be209fe1500fc2cdc966503b57e818e6e6f7fea7 | [] | no_license | HelloAolia/biaoqingshibie | 36c6487cb2803f28b5c4209e375dbce87373c375 | 9ad8106e92a3c9ab1e03ee449456d6c975185e23 | refs/heads/master | 2020-08-06T20:26:53.415077 | 2017-02-16T12:43:27 | 2017-02-16T12:43:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,265 | h | #if !defined(AFX_DLGDISPLAYFRAMES_H__535F1FCF_9B1A_4446_9D73_C60A8F8D761C__INCLUDED_)
#define AFX_DLGDISPLAYFRAMES_H__535F1FCF_9B1A_4446_9D73_C60A8F8D761C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// DlgDisplayFrames.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CDlgDisplayFrames dialog
class CDlgDisplayFrames : public CDialog
{
// Construction
public:
CDlgDisplayFrames(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CDlgDisplayFrames)
enum { IDD = IDD_DIALOG5 };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDlgDisplayFrames)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
public:
CString m_path;
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CDlgDisplayFrames)
afx_msg void OnPaint();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DLGDISPLAYFRAMES_H__535F1FCF_9B1A_4446_9D73_C60A8F8D761C__INCLUDED_)
| [
"ylasce@gmail.com"
] | ylasce@gmail.com |
8e727e0b693f24833d6e59ccebb36c14fed6ecf6 | 39320b80b4aa862c0d545e85bd2dd88f2585bdce | /src/server/game/Entities/Creature/Creature.cpp | b7178af1b96837e0a90e07a3ac5857de0f76bfcc | [] | no_license | ProjectStarGate/StarGate-Plus-EMU | ec8c8bb4fab9f6d3432d76b2afac1e1e7ec3249f | 8e75d2976ae863557992e69353a23af759346eae | refs/heads/master | 2021-01-15T12:25:53.949001 | 2011-12-21T06:04:07 | 2011-12-21T06:04:07 | 3,004,543 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 71,286 | cpp | /*
* Copyright (C) 2005-2011 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008-2011 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2010-2012 Project-StarGate-Emu
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "gamePCH.h"
#include "Common.h"
#include "DatabaseEnv.h"
#include "WorldPacket.h"
#include "World.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Creature.h"
#include "QuestDef.h"
#include "GossipDef.h"
#include "Player.h"
#include "PoolMgr.h"
#include "Opcodes.h"
#include "Log.h"
#include "LootMgr.h"
#include "MapManager.h"
#include "CreatureAI.h"
#include "CreatureAISelector.h"
#include "Formulas.h"
#include "WaypointMovementGenerator.h"
#include "InstanceScript.h"
#include "BattlegroundMgr.h"
#include "Util.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "OutdoorPvPMgr.h"
#include "GameEventMgr.h"
#include "CreatureGroups.h"
#include "Vehicle.h"
#include "SpellAuraEffects.h"
#include "Group.h"
// apply implementation of the singletons
TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const {
TrainerSpellMap::const_iterator itr = spellList.find(spell_id);
if (itr != spellList.end())
return &itr->second;
return NULL;
}
bool VendorItemData::RemoveItem(uint32 item_id) {
bool found = false;
for (VendorItemList::iterator i = m_items.begin(); i != m_items.end();) {
if ((*i)->item == item_id) {
i = m_items.erase(i++);
found = true;
} else
++i;
}
return found;
}
VendorItem const* VendorItemData::FindItemCostPair(uint32 item_id,
uint32 extendedCost) const {
for (VendorItemList::const_iterator i = m_items.begin(); i != m_items.end();
++i)
if ((*i)->item == item_id && (*i)->ExtendedCost == extendedCost)
return *i;
return NULL;
}
uint32 CreatureInfo::GetRandomValidModelId() const {
uint8 c = 0;
uint32 modelIDs[4];
if (Modelid1)
modelIDs[c++] = Modelid1;
if (Modelid2)
modelIDs[c++] = Modelid2;
if (Modelid3)
modelIDs[c++] = Modelid3;
if (Modelid4)
modelIDs[c++] = Modelid4;
return ((c > 0) ? modelIDs[urand(0, c - 1)] : 0);
}
uint32 CreatureInfo::GetFirstValidModelId() const {
if (Modelid1)
return Modelid1;
if (Modelid2)
return Modelid2;
if (Modelid3)
return Modelid3;
if (Modelid4)
return Modelid4;
return 0;
}
bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) {
if (Unit* victim = Unit::GetUnit(m_owner, m_victim)) {
while (!m_assistants.empty()) {
Creature* assistant = Unit::GetCreature(m_owner,
*m_assistants.begin());
m_assistants.pop_front();
if (assistant && assistant->CanAssistTo(&m_owner, victim)) {
assistant->SetNoCallAssistance(true);
assistant->CombatStart(victim);
if (assistant->IsAIEnabled)
assistant->AI()->AttackStart(victim);
}
}
}
return true;
}
CreatureBaseStats const* CreatureBaseStats::GetBaseStats(uint8 level,
uint8 unitClass) {
return sObjectMgr->GetCreatureBaseStats(level, unitClass);
}
bool ForcedDespawnDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) {
m_owner.ForcedDespawn();
return true;
}
Creature::Creature() :
Unit(), lootForPickPocketed(false), lootForBody(false), m_groupLootTimer(
0), lootingGroupLowGUID(0), m_PlayerDamageReq(0), m_lootMoney(
0), m_lootRecipient(0), m_lootRecipientGroup(0), m_corpseRemoveTime(
0), m_respawnTime(0), m_respawnDelay(300), m_corpseDelay(60), m_respawnradius(
0.0f), m_reactState(REACT_AGGRESSIVE), m_defaultMovementType(
IDLE_MOTION_TYPE), m_DBTableGuid(0), m_equipmentId(0), m_AlreadyCallAssistance(
false), m_AlreadySearchedAssistance(false), m_regenHealth(true), m_AI_locked(
false), m_isDeadByDefault(false), m_meleeDamageSchoolMask(
SPELL_SCHOOL_MASK_NORMAL), m_creatureInfo(NULL), m_creatureData(
NULL), m_formation(NULL) {
m_regenTimer = CREATURE_REGEN_INTERVAL;
m_valuesCount = UNIT_END;
for (uint8 i = 0; i < CREATURE_MAX_SPELLS; ++i)
m_spells[i] = 0;
m_CreatureSpellCooldowns.clear();
m_CreatureCategoryCooldowns.clear();
m_GlobalCooldown = 0;
DisableReputationGain = false;
//m_unit_movement_flags = MONSTER_MOVE_WALK;
m_SightDistance = sWorld->getFloatConfig(CONFIG_SIGHT_MONSTER);
m_CombatDistance = 0; //MELEE_RANGE;
ResetLootMode(); // restore default loot mode
TriggerJustRespawned = false;
}
Creature::~Creature() {
m_vendorItemCounts.clear();
delete i_AI;
i_AI = NULL;
//if (m_uint32Values)
// sLog->outError("Deconstruct Creature Entry = %u", GetEntry());
}
void Creature::AddToWorld() {
///- Register the creature for guid lookup
if (!IsInWorld()) {
if (m_zoneScript)
m_zoneScript->OnCreatureCreate(this, true);
sObjectAccessor->AddObject(this);
Unit::AddToWorld();
SearchFormation();
AIM_Initialize();
if (IsVehicle())
GetVehicleKit()->Install();
}
}
void Creature::RemoveFromWorld() {
if (IsInWorld()) {
if (m_zoneScript)
m_zoneScript->OnCreatureCreate(this, false);
if (m_formation)
formation_mgr->RemoveCreatureFromGroup(m_formation, this);
Unit::RemoveFromWorld();
sObjectAccessor->RemoveObject(this);
}
}
void Creature::DisappearAndDie() {
DestroyForNearbyPlayers();
if (isAlive())
setDeathState(JUST_DIED);
RemoveCorpse(false);
}
void Creature::SearchFormation() {
if (isSummon())
return;
uint32 lowguid = GetDBTableGUIDLow();
if (!lowguid)
return;
CreatureGroupInfoType::iterator frmdata = CreatureGroupMap.find(lowguid);
if (frmdata != CreatureGroupMap.end())
formation_mgr->AddCreatureToGroup(frmdata->second->leaderGUID, this);
}
void Creature::RemoveCorpse(bool setSpawnTime) {
if ((getDeathState() != CORPSE && !m_isDeadByDefault)
|| (getDeathState() != ALIVE && m_isDeadByDefault))
return;
m_corpseRemoveTime = time(NULL);
setDeathState(DEAD);
UpdateObjectVisibility();
loot.clear();
uint32 respawnDelay = m_respawnDelay;
if (IsAIEnabled)
AI()->CorpseRemoved(respawnDelay);
// Should get removed later, just keep "compatibility" with scripts
if (setSpawnTime)
m_respawnTime = time(NULL) + respawnDelay;
float x, y, z, o;
GetRespawnCoord(x, y, z, &o);
SetHomePosition(x, y, z, o);
GetMap()->CreatureRelocation(this, x, y, z, o);
}
/**
* change the entry of creature until respawn
*/
bool Creature::InitEntry(uint32 Entry, uint32 /*team*/,
const CreatureData *data) {
CreatureInfo const *normalInfo = ObjectMgr::GetCreatureTemplate(Entry);
if (!normalInfo) {
sLog->outErrorDb(
"Creature::InitEntry creature entry %u does not exist.", Entry);
return false;
}
// get difficulty 1 mode entry
CreatureInfo const *cinfo = normalInfo;
for (uint8 diff = uint8(GetMap()->GetSpawnMode()); diff > 0;) {
// we already have valid Map pointer for current creature!
if (normalInfo->DifficultyEntry[diff - 1]) {
cinfo = ObjectMgr::GetCreatureTemplate(
normalInfo->DifficultyEntry[diff - 1]);
if (cinfo)
break; // template found
// check and reported at startup, so just ignore (restore normalInfo)
cinfo = normalInfo;
}
// for instances heroic to normal, other cases attempt to retrieve previous difficulty
if (diff >= RAID_DIFFICULTY_10MAN_HEROIC && GetMap()->IsRaid())
diff -= 2; // to normal raid difficulty cases
else
--diff;
}
SetEntry(Entry); // normal entry always
m_creatureInfo = cinfo; // map mode related always
// equal to player Race field, but creature does not have race
SetByteValue(UNIT_FIELD_BYTES_0, 0, 0);
// known valid are: CLASS_WARRIOR, CLASS_PALADIN, CLASS_ROGUE, CLASS_MAGE
SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
// Cancel load if no model defined
if (!(cinfo->GetFirstValidModelId())) {
sLog->outErrorDb(
"Creature (Entry: %u) has no model defined in table `creature_template`, can't load. ",
Entry);
return false;
}
uint32 display_id = sObjectMgr->ChooseDisplayId(0, GetCreatureInfo(), data);
CreatureModelInfo const *minfo = sObjectMgr->GetCreatureModelRandomGender(
display_id);
if (!minfo) // Cancel load if no model defined
{
sLog->outErrorDb(
"Creature (Entry: %u) has no model defined in table `creature_template`, can't load. ",
Entry);
return false;
}
display_id = minfo->modelid; // it can be different (for another gender)
SetDisplayId(display_id);
SetNativeDisplayId(display_id);
SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
// Load creature equipment
if (!data || data->equipmentId == 0) // use default from the template
LoadEquipment(cinfo->equipmentId);
else if (data && data->equipmentId != -1) // override, -1 means no equipment
LoadEquipment(data->equipmentId);
SetName(normalInfo->Name); // at normal entry always
SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, minfo->bounding_radius);
SetFloatValue(UNIT_FIELD_COMBATREACH, minfo->combat_reach);
SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
SetSpeed(MOVE_WALK, cinfo->speed_walk);
SetSpeed(MOVE_RUN, cinfo->speed_run);
SetSpeed(MOVE_SWIM, 1.0f); // using 1.0 rate
SetSpeed(MOVE_FLIGHT, 1.0f); // using 1.0 rate
SetFloatValue(OBJECT_FIELD_SCALE_X, cinfo->scale);
// checked at loading
m_defaultMovementType = MovementGeneratorType(cinfo->MovementType);
if (!m_respawnradius && m_defaultMovementType == RANDOM_MOTION_TYPE)
m_defaultMovementType = IDLE_MOTION_TYPE;
for (uint8 i = 0; i < CREATURE_MAX_SPELLS; ++i)
m_spells[i] = GetCreatureInfo()->spells[i];
return true;
}
bool Creature::UpdateEntry(uint32 Entry, uint32 team,
const CreatureData *data) {
if (!InitEntry(Entry, team, data))
return false;
CreatureInfo const* cInfo = GetCreatureInfo();
m_regenHealth = cInfo->RegenHealth;
// creatures always have melee weapon ready if any
SetSheath(SHEATH_STATE_MELEE);
SelectLevel(GetCreatureInfo());
if (team == HORDE)
setFaction(cInfo->faction_H);
else
setFaction(cInfo->faction_A);
uint32 npcflag, unit_flags, dynamicflags;
ObjectMgr::ChooseCreatureFlags(cInfo, npcflag, unit_flags, dynamicflags,
data);
if (cInfo->flags_extra & CREATURE_FLAG_EXTRA_WORLDEVENT)
SetUInt32Value(UNIT_NPC_FLAGS,
npcflag | sGameEventMgr->GetNPCFlag(this));
else
SetUInt32Value(UNIT_NPC_FLAGS, npcflag);
SetAttackTime(BASE_ATTACK, cInfo->baseattacktime);
SetAttackTime(OFF_ATTACK, cInfo->baseattacktime);
SetAttackTime(RANGED_ATTACK, cInfo->rangeattacktime);
SetUInt32Value(UNIT_FIELD_FLAGS, unit_flags);
SetUInt32Value(UNIT_DYNAMIC_FLAGS, dynamicflags);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
SetMeleeDamageSchool(SpellSchools(cInfo->dmgschool));
CreatureBaseStats const* stats = sObjectMgr->GetCreatureBaseStats(
getLevel(), cInfo->unit_class);
float armor = (float) stats->GenerateArmor(cInfo); // TODO: Why is this treated as uint32 when it's a float?
SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, armor);
SetModifierValue(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE,
float(cInfo->resistance1));
SetModifierValue(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE,
float(cInfo->resistance2));
SetModifierValue(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE,
float(cInfo->resistance3));
SetModifierValue(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE,
float(cInfo->resistance4));
SetModifierValue(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE,
float(cInfo->resistance5));
SetModifierValue(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE,
float(cInfo->resistance6));
SetCanModifyStats(true);
UpdateAllStats();
// checked and error show at loading templates
if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction_A)) {
if (factionTemplate->factionFlags & FACTION_TEMPLATE_FLAG_PVP)
SetPvP(true);
else
SetPvP(false);
}
// trigger creature is always not selectable and can not be attacked
if (isTrigger())
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
InitializeReactState();
if (cInfo->flags_extra & CREATURE_FLAG_EXTRA_NO_TAUNT) {
ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true);
ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, true);
}
// TODO: In fact monster move flags should be set - not movement flags.
if (cInfo->InhabitType & INHABIT_AIR)
AddUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING);
if (cInfo->InhabitType & INHABIT_WATER)
AddUnitMovementFlag(MOVEMENTFLAG_SWIMMING);
return true;
}
void Creature::Update(uint32 diff) {
if (m_GlobalCooldown <= diff)
m_GlobalCooldown = 0;
else
m_GlobalCooldown -= diff;
if (IsAIEnabled && TriggerJustRespawned) {
TriggerJustRespawned = false;
AI()->JustRespawned();
}
switch (m_deathState) {
case JUST_ALIVED:
// Don't must be called, see Creature::setDeathState JUST_ALIVED -> ALIVE promoting.
sLog->outError(
"Creature (GUID: %u Entry: %u) in wrong state: JUST_ALIVED (4)",
GetGUIDLow(), GetEntry());
break;
case JUST_DIED:
// Don't must be called, see Creature::setDeathState JUST_DIED -> CORPSE promoting.
sLog->outError(
"Creature (GUID: %u Entry: %u) in wrong state: JUST_DEAD (1)",
GetGUIDLow(), GetEntry());
break;
case DEAD: {
time_t now = time(NULL);
if (m_respawnTime <= now) {
bool allowed = IsAIEnabled ? AI()->CanRespawn() : true; // First check if there are any scripts that object to us respawning
if (!allowed) // Will be rechecked on next Update call
break;
uint64 dbtableHighGuid =
MAKE_NEW_GUID(m_DBTableGuid, GetEntry(), HIGHGUID_UNIT);
time_t linkedRespawntime = sObjectMgr->GetLinkedRespawnTime(
dbtableHighGuid, GetMap()->GetInstanceId());
if (!linkedRespawntime) // Can respawn
Respawn();
else // the master is dead
{
uint64 targetGuid = sObjectMgr->GetLinkedRespawnGuid(GetGUID());
if (targetGuid == GetGUID()) // if linking self, never respawn (check delayed to next day)
SetRespawnTime(DAY);
else
m_respawnTime = (
now > linkedRespawntime ? now : linkedRespawntime)
+ urand(5, MINUTE); // else copy time from master and add a little
SaveRespawnTime(); // also save to DB immediately
}
}
break;
}
case CORPSE: {
if (m_isDeadByDefault)
break;
if (m_groupLootTimer && lootingGroupLowGUID) {
// for delayed spells
m_Events.Update(diff);
if (m_groupLootTimer <= diff) {
Group* group = sObjectMgr->GetGroupByGUID(lootingGroupLowGUID);
if (group)
group->EndRoll(&loot);
m_groupLootTimer = 0;
lootingGroupLowGUID = 0;
} else
m_groupLootTimer -= diff;
} else if (m_corpseRemoveTime <= time(NULL)) {
RemoveCorpse(false);
sLog->outStaticDebug("Removing corpse... %u ",
GetUInt32Value(OBJECT_FIELD_ENTRY));
} else {
// for delayed spells
m_Events.Update(diff);
}
break;
}
case ALIVE: {
if (m_isDeadByDefault) {
if (m_corpseRemoveTime <= time(NULL)) {
RemoveCorpse(false);
sLog->outStaticDebug("Removing alive corpse... %u ",
GetUInt32Value(OBJECT_FIELD_ENTRY));
}
}
Unit::Update(diff);
// creature can be dead after Unit::Update call
// CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
if (!isAlive())
break;
// if creature is charmed, switch to charmed AI
if (NeedChangeAI) {
UpdateCharmAI();
NeedChangeAI = false;
IsAIEnabled = true;
}
if (!IsInEvadeMode() && IsAIEnabled) {
// do not allow the AI to be changed during update
m_AI_locked = true;
i_AI->UpdateAI(diff);
m_AI_locked = false;
}
// creature can be dead after UpdateAI call
// CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly)
if (!isAlive())
break;
if (m_regenTimer > 0) {
if (diff >= m_regenTimer)
m_regenTimer = 0;
else
m_regenTimer -= diff;
}
if (m_regenTimer != 0)
break;
bool bInCombat =
isInCombat()
&& (!getVictim() || // if isInCombat() is true and this has no victim
!getVictim()->GetCharmerOrOwnerPlayerOrPlayerItself()
|| // or the victim/owner/charmer is not a player
!getVictim()->GetCharmerOrOwnerPlayerOrPlayerItself()->isGameMaster()); // or the victim/owner/charmer is not a GameMaster
/*if (m_regenTimer <= diff)
{*/
if (!IsInEvadeMode() && (!bInCombat || IsPolymorphed())) // regenerate health if not in combat or if polymorphed
RegenerateHealth();
if (getPowerType() == POWER_ENERGY) {
if (!IsVehicle()
|| GetVehicleKit()->GetVehicleInfo()->m_powerType
!= POWER_PYRITE)
Regenerate(POWER_ENERGY);
} else
RegenerateMana();
/*if (!bIsPolymorphed) // only increase the timer if not polymorphed
m_regenTimer += CREATURE_REGEN_INTERVAL - diff;
}
else
if (!bIsPolymorphed) // if polymorphed, skip the timer
m_regenTimer -= diff;*/
m_regenTimer = CREATURE_REGEN_INTERVAL;
break;
}
case DEAD_FALLING:
GetMotionMaster()->UpdateMotion(diff);
break;
default:
break;
}
sScriptMgr->OnCreatureUpdate(this, diff);
}
void Creature::RegenerateMana() {
uint32 curValue = GetPower(POWER_MANA);
uint32 maxValue = GetMaxPower(POWER_MANA);
if (curValue >= maxValue)
return;
uint32 addvalue = 0;
// Combat and any controlled creature
if (isInCombat() || GetCharmerOrOwnerGUID()) {
if (!IsUnderLastManaUseEffect()) {
float ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA);
float Spirit = GetStat(STAT_SPIRIT);
addvalue = uint32((Spirit / 5.0f + 17.0f) * ManaIncreaseRate);
}
} else
addvalue = maxValue / 3;
// Apply modifiers (if any).
AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(
SPELL_AURA_MOD_POWER_REGEN_PERCENT);
for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin();
i != ModPowerRegenPCTAuras.end(); ++i)
if ((*i)->GetMiscValue() == POWER_MANA)
AddPctN(addvalue, (*i)->GetAmount());
addvalue += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_POWER_REGEN,
POWER_MANA) * CREATURE_REGEN_INTERVAL / (5 * IN_MILLISECONDS);
ModifyPower(POWER_MANA, addvalue);
}
void Creature::RegenerateHealth() {
if (!isRegeneratingHealth())
return;
uint32 curValue = GetHealth();
uint32 maxValue = GetMaxHealth();
if (curValue >= maxValue)
return;
uint32 addvalue = 0;
// Not only pet, but any controlled creature
if (GetCharmerOrOwnerGUID()) {
float HealthIncreaseRate = sWorld->getRate(RATE_HEALTH);
float Spirit = GetStat(STAT_SPIRIT);
if (GetPower(POWER_MANA) > 0)
addvalue = uint32(Spirit * 0.25 * HealthIncreaseRate);
else
addvalue = uint32(Spirit * 0.80 * HealthIncreaseRate);
} else
addvalue = maxValue / 3;
// Apply modifiers (if any).
AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(
SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin();
i != ModPowerRegenPCTAuras.end(); ++i)
AddPctN(addvalue, (*i)->GetAmount());
addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_REGEN)
* CREATURE_REGEN_INTERVAL / (5 * IN_MILLISECONDS);
ModifyHealth(addvalue);
}
void Creature::DoFleeToGetAssistance() {
if (!getVictim())
return;
if (HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
return;
float radius = sWorld->getFloatConfig(
CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS);
if (radius > 0) {
Creature* pCreature = NULL;
CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
cell.SetNoCreate();
Trinity::NearestAssistCreatureInCreatureRangeCheck u_check(this,
getVictim(), radius);
Trinity::CreatureLastSearcher<
Trinity::NearestAssistCreatureInCreatureRangeCheck> searcher(
this, pCreature, u_check);
TypeContainerVisitor<
Trinity::CreatureLastSearcher<
Trinity::NearestAssistCreatureInCreatureRangeCheck>,
GridTypeMapContainer> grid_creature_searcher(searcher);
cell.Visit(p, grid_creature_searcher, *GetMap(), *this, radius);
SetNoSearchAssistance(true);
UpdateSpeed(MOVE_RUN, false);
if (!pCreature)
//SetFeared(true, getVictim()->GetGUID(), 0 , sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY));
//TODO: use 31365
SetControlled(true, UNIT_STAT_FLEEING);
else
GetMotionMaster()->MoveSeekAssistance(pCreature->GetPositionX(),
pCreature->GetPositionY(), pCreature->GetPositionZ());
}
}
bool Creature::AIM_Initialize(CreatureAI* ai) {
// make sure nothing can change the AI during AI update
if (m_AI_locked) {
sLog->outDebug(LOG_FILTER_TSCR,
"AIM_Initialize: failed to init, locked.");
return false;
}
UnitAI *oldAI = i_AI;
Motion_Initialize();
i_AI = ai ? ai : FactorySelector::selectAI(this);
delete oldAI;
IsAIEnabled = true;
i_AI->InitializeAI();
return true;
}
void Creature::Motion_Initialize() {
if (!m_formation)
i_motionMaster.Initialize();
else if (m_formation->getLeader() == this) {
m_formation->FormationReset(false);
i_motionMaster.Initialize();
} else if (m_formation->isFormed())
i_motionMaster.MoveIdle(MOTION_SLOT_IDLE); //wait the order of leader
else
i_motionMaster.Initialize();
}
bool Creature::Create(uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry,
uint32 vehId, uint32 team, float x, float y, float z, float ang,
const CreatureData *data) {
ASSERT(map);
SetMap(map);
SetPhaseMask(phaseMask, false);
CreatureInfo const *cinfo = ObjectMgr::GetCreatureTemplate(Entry);
if (!cinfo) {
sLog->outErrorDb(
"Creature::Create(): creature template (guidlow: %u, entry: %u) does not exist.",
guidlow, Entry);
return false;
}
Relocate(x, y, z, ang);
if (!IsPositionValid()) {
sLog->outError(
"Creature::Create(): given coordinates for creature (guidlow %d, entry %d) are not valid (X: %f, Y: %f, Z: %f, O: %f)",
guidlow, Entry, x, y, z, ang);
return false;
}
//oX = x; oY = y; dX = x; dY = y; m_moveTime = 0; m_startMove = 0;
if (!CreateFromProto(guidlow, Entry, vehId, team, data))
return false;
switch (GetCreatureInfo()->rank) {
case CREATURE_ELITE_RARE:
m_corpseDelay = sWorld->getIntConfig(CONFIG_CORPSE_DECAY_RARE);
break;
case CREATURE_ELITE_ELITE:
m_corpseDelay = sWorld->getIntConfig(CONFIG_CORPSE_DECAY_ELITE);
break;
case CREATURE_ELITE_RAREELITE:
m_corpseDelay = sWorld->getIntConfig(CONFIG_CORPSE_DECAY_RAREELITE);
break;
case CREATURE_ELITE_WORLDBOSS:
m_corpseDelay = sWorld->getIntConfig(CONFIG_CORPSE_DECAY_WORLDBOSS);
ApplySpellImmune(0,IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true);
break;
default:
m_corpseDelay = sWorld->getIntConfig(CONFIG_CORPSE_DECAY_NORMAL);
break;
}
LoadCreaturesAddon();
CreatureModelInfo const *minfo = sObjectMgr->GetCreatureModelRandomGender(
GetNativeDisplayId());
if (minfo && !isTotem()) // Cancel load if no model defined or if totem
{
uint32 display_id = minfo->modelid; // it can be different (for another gender)
SetDisplayId(display_id);
SetNativeDisplayId(display_id);
SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
}
if (GetCreatureInfo()->InhabitType & INHABIT_AIR) {
if (GetDefaultMovementType() == IDLE_MOTION_TYPE)
AddUnitMovementFlag(MOVEMENTFLAG_CAN_FLY);
else
SetFlying(true);
}
if (GetCreatureInfo()->InhabitType & INHABIT_WATER)
AddUnitMovementFlag(MOVEMENTFLAG_SWIMMING);
LastUsedScriptID = GetCreatureInfo()->ScriptID;
// TODO: Replace with spell, handle from DB
if (isSpiritHealer()) {
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST,
GHOST_VISIBILITY_GHOST);
m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST,
GHOST_VISIBILITY_GHOST);
} else if (isSpiritGuide()) {
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST,
GHOST_VISIBILITY_GHOST | GHOST_VISIBILITY_ALIVE);
m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST,
GHOST_VISIBILITY_GHOST | GHOST_VISIBILITY_ALIVE);
}
if (Entry == VISUAL_WAYPOINT)
SetVisible(false);
return true;
}
bool Creature::isCanTrainingOf(Player* pPlayer, bool msg) const {
if (!isTrainer())
return false;
TrainerSpellData const* trainer_spells = GetTrainerSpells();
if ((!trainer_spells || trainer_spells->spellList.empty())
&& GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS) {
sLog->outErrorDb(
"Creature %u (Entry: %u) have UNIT_NPC_FLAG_TRAINER but have empty trainer spell list.",
GetGUIDLow(), GetEntry());
return false;
}
switch (GetCreatureInfo()->trainer_type) {
case TRAINER_TYPE_CLASS:
if (pPlayer->getClass() != GetCreatureInfo()->trainer_class) {
if (msg) {
pPlayer->PlayerTalkClass->ClearMenus();
switch (GetCreatureInfo()->trainer_class) {
case CLASS_DRUID:
pPlayer->PlayerTalkClass->SendGossipMenu(4913, GetGUID());
break;
case CLASS_HUNTER:
pPlayer->PlayerTalkClass->SendGossipMenu(10090, GetGUID());
break;
case CLASS_MAGE:
pPlayer->PlayerTalkClass->SendGossipMenu(328, GetGUID());
break;
case CLASS_PALADIN:
pPlayer->PlayerTalkClass->SendGossipMenu(1635, GetGUID());
break;
case CLASS_PRIEST:
pPlayer->PlayerTalkClass->SendGossipMenu(4436, GetGUID());
break;
case CLASS_ROGUE:
pPlayer->PlayerTalkClass->SendGossipMenu(4797, GetGUID());
break;
case CLASS_SHAMAN:
pPlayer->PlayerTalkClass->SendGossipMenu(5003, GetGUID());
break;
case CLASS_WARLOCK:
pPlayer->PlayerTalkClass->SendGossipMenu(5836, GetGUID());
break;
case CLASS_WARRIOR:
pPlayer->PlayerTalkClass->SendGossipMenu(4985, GetGUID());
break;
}
}
return false;
}
break;
case TRAINER_TYPE_PETS:
if (pPlayer->getClass() != CLASS_HUNTER) {
pPlayer->PlayerTalkClass->ClearMenus();
pPlayer->PlayerTalkClass->SendGossipMenu(3620, GetGUID());
return false;
}
break;
case TRAINER_TYPE_MOUNTS:
if (GetCreatureInfo()->trainer_race
&& pPlayer->getRace() != GetCreatureInfo()->trainer_race) {
if (msg) {
pPlayer->PlayerTalkClass->ClearMenus();
switch (GetCreatureInfo()->trainer_class) {
case RACE_DWARF:
pPlayer->PlayerTalkClass->SendGossipMenu(5865, GetGUID());
break;
case RACE_GNOME:
pPlayer->PlayerTalkClass->SendGossipMenu(4881, GetGUID());
break;
case RACE_HUMAN:
pPlayer->PlayerTalkClass->SendGossipMenu(5861, GetGUID());
break;
case RACE_NIGHTELF:
pPlayer->PlayerTalkClass->SendGossipMenu(5862, GetGUID());
break;
case RACE_ORC:
pPlayer->PlayerTalkClass->SendGossipMenu(5863, GetGUID());
break;
case RACE_TAUREN:
pPlayer->PlayerTalkClass->SendGossipMenu(5864, GetGUID());
break;
case RACE_TROLL:
pPlayer->PlayerTalkClass->SendGossipMenu(5816, GetGUID());
break;
case RACE_UNDEAD_PLAYER:
pPlayer->PlayerTalkClass->SendGossipMenu(624, GetGUID());
break;
case RACE_BLOODELF:
pPlayer->PlayerTalkClass->SendGossipMenu(5862, GetGUID());
break;
case RACE_DRAENEI:
pPlayer->PlayerTalkClass->SendGossipMenu(5864, GetGUID());
break;
}
}
return false;
}
break;
case TRAINER_TYPE_TRADESKILLS:
if (GetCreatureInfo()->trainer_spell
&& !pPlayer->HasSpell(GetCreatureInfo()->trainer_spell)) {
if (msg) {
pPlayer->PlayerTalkClass->ClearMenus();
pPlayer->PlayerTalkClass->SendGossipMenu(11031, GetGUID());
}
return false;
}
break;
default:
return false; // checked and error output at creature_template loading
}
return true;
}
bool Creature::isCanInteractWithBattleMaster(Player* pPlayer, bool msg) const {
if (!isBattleMaster())
return false;
return true;
}
bool Creature::isCanTrainingAndResetTalentsOf(Player* pPlayer) const {
return pPlayer->getLevel() >= 10
&& GetCreatureInfo()->trainer_type == TRAINER_TYPE_CLASS
&& pPlayer->getClass() == GetCreatureInfo()->trainer_class;
}
void Creature::AI_SendMoveToPacket(float x, float y, float z, uint32 time,
uint32 /*MovementFlags*/, uint8 /*type*/) {
/* uint32 timeElap = getMSTime();
if ((timeElap - m_startMove) < m_moveTime)
{
oX = (dX - oX) * ((timeElap - m_startMove) / m_moveTime);
oY = (dY - oY) * ((timeElap - m_startMove) / m_moveTime);
}
else
{
oX = dX;
oY = dY;
}
dX = x;
dY = y;
m_orientation = atan2((oY - dY), (oX - dX));
m_startMove = getMSTime();
m_moveTime = time;*/
SendMonsterMove(x, y, z, time);
}
Player *Creature::GetLootRecipient() const {
if (!m_lootRecipient)
return NULL;
return ObjectAccessor::FindPlayer(m_lootRecipient);
}
Group *Creature::GetLootRecipientGroup() const {
if (!m_lootRecipientGroup)
return NULL;
return sObjectMgr->GetGroupByGUID(m_lootRecipientGroup);
}
void Creature::SetLootRecipient(Unit *unit) {
// set the player whose group should receive the right
// to loot the creature after it dies
// should be set to NULL after the loot disappears
if (!unit) {
m_lootRecipient = 0;
m_lootRecipientGroup = 0;
RemoveFlag(UNIT_DYNAMIC_FLAGS,
UNIT_DYNFLAG_LOOTABLE | UNIT_DYNFLAG_TAPPED);
return;
}
if (unit->GetTypeId() != TYPEID_PLAYER && !unit->IsVehicle())
return;
Player* player = unit->GetCharmerOrOwnerPlayerOrPlayerItself();
if (!player) // normal creature, no player involved
return;
m_lootRecipient = player->GetGUID();
if (Group *group = player->GetGroup())
m_lootRecipientGroup = group->GetLowGUID();
SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED);
}
// return true if this creature is tapped by the player or by a member of his group.
bool Creature::isTappedBy(Player *player) const {
if (player->GetGUID() == m_lootRecipient)
return true;
Group* playerGroup = player->GetGroup();
if (!playerGroup || playerGroup != GetLootRecipientGroup()) // if we dont have a group we arent the recipient
return false; // if creature doesnt have group bound it means it was solo killed by someone else
return true;
}
void Creature::SaveToDB() {
// this should only be used when the creature has already been loaded
// preferably after adding to map, because mapid may not be valid otherwise
CreatureData const *data = sObjectMgr->GetCreatureData(m_DBTableGuid);
if (!data) {
sLog->outError("Creature::SaveToDB failed, cannot get creature data!");
return;
}
SaveToDB(GetMapId(), data->spawnMask, GetPhaseMask());
}
void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask) {
// update in loaded data
if (!m_DBTableGuid)
m_DBTableGuid = GetGUIDLow();
CreatureData& data = sObjectMgr->NewOrExistCreatureData(m_DBTableGuid);
uint32 displayId = GetNativeDisplayId();
uint32 npcflag = GetUInt32Value(UNIT_NPC_FLAGS);
uint32 unit_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
uint32 dynamicflags = GetUInt32Value(UNIT_DYNAMIC_FLAGS);
// check if it's a custom model and if not, use 0 for displayId
CreatureInfo const *cinfo = GetCreatureInfo();
if (cinfo) {
if (displayId == cinfo->Modelid1 || displayId == cinfo->Modelid2
|| displayId == cinfo->Modelid3 || displayId == cinfo->Modelid4)
displayId = 0;
if (npcflag == cinfo->npcflag)
npcflag = 0;
if (unit_flags == cinfo->unit_flags)
unit_flags = 0;
if (dynamicflags == cinfo->dynamicflags)
dynamicflags = 0;
}
// data->guid = guid don't must be update at save
data.id = GetEntry();
data.mapid = mapid;
data.phaseMask = phaseMask;
data.displayid = displayId;
data.equipmentId = GetEquipmentId();
data.posX = GetPositionX();
data.posY = GetPositionY();
data.posZ = GetPositionZ();
data.orientation = GetOrientation();
data.spawntimesecs = m_respawnDelay;
// prevent add data integrity problems
data.spawndist =
GetDefaultMovementType() == IDLE_MOTION_TYPE ? 0 : m_respawnradius;
data.currentwaypoint = 0;
data.curhealth = GetHealth();
data.curmana = GetPower(POWER_MANA);
data.is_dead = m_isDeadByDefault;
// prevent add data integrity problems
data.movementType =
!m_respawnradius && GetDefaultMovementType() == RANDOM_MOTION_TYPE ?
IDLE_MOTION_TYPE : GetDefaultMovementType();
data.spawnMask = spawnMask;
data.npcflag = npcflag;
data.unit_flags = unit_flags;
data.dynamicflags = dynamicflags;
// updated in DB
SQLTransaction trans = WorldDatabase.BeginTransaction();
trans->PAppend("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
std::ostringstream ss;
ss << "INSERT INTO creature VALUES (" << m_DBTableGuid << ", " << GetEntry()
<< ", " << mapid << ", " << uint32(spawnMask) << ", " // cast to prevent save as symbol
<< uint16(GetPhaseMask()) << ", " // prevent out of range error
<< displayId << ", " << GetEquipmentId() << ", " << GetPositionX() << ", "
<< GetPositionY() << ", " << GetPositionZ() << ", "
<< GetOrientation() << ", " << m_respawnDelay << ", " //respawn time
<< (float) m_respawnradius << ", " //spawn distance (float)
<< (uint32) (0) << ", " //currentwaypoint
<< GetHealth() << ", " //curhealth
<< GetPower(POWER_MANA) << ", " //curmana
<< (m_isDeadByDefault ? 1 : 0) << ", " //is_dead
<< GetDefaultMovementType() << ", " //default movement generator type
<< npcflag << ", " << unit_flags << ", " << dynamicflags << ")";
trans->Append(ss.str().c_str());
WorldDatabase.CommitTransaction(trans);
}
void Creature::SelectLevel(const CreatureInfo *cinfo) {
uint32 rank = isPet() ? 0 : cinfo->rank;
// level
uint8 minlevel = std::min(cinfo->maxlevel, cinfo->minlevel);
uint8 maxlevel = std::max(cinfo->maxlevel, cinfo->minlevel);
uint8 level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel);
SetLevel(level);
CreatureBaseStats const* stats = sObjectMgr->GetCreatureBaseStats(level,
cinfo->unit_class);
// health
float healthmod = _GetHealthMod(rank);
uint32 basehp = stats->GenerateHealth(cinfo);
uint32 health = uint32(basehp * healthmod);
SetCreateHealth(health);
SetMaxHealth(health);
SetHealth(health);
ResetPlayerDamageReq();
// mana
uint32 mana = stats->GenerateMana(cinfo);
SetCreateMana(mana);
SetMaxPower(POWER_MANA, mana); //MAX Mana
SetPower(POWER_MANA, mana);
// TODO: set UNIT_FIELD_POWER*, for some creature class case (energy, etc)
SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, (float) health);
SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, (float) mana);
//damage
float damagemod = 1.0f; //_GetDamageMod(rank);
SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, cinfo->mindmg * damagemod);
SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, cinfo->maxdmg * damagemod);
SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, cinfo->minrangedmg * damagemod);
SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, cinfo->maxrangedmg * damagemod);
SetModifierValue(UNIT_MOD_ATTACK_POWER_POS, BASE_VALUE,
cinfo->attackpower * damagemod);
SetModifierValue(UNIT_MOD_ATTACK_POWER_NEG, BASE_VALUE, 0);
}
float Creature::_GetHealthMod(int32 Rank) {
switch (Rank) // define rates for each elite rank
{
case CREATURE_ELITE_NORMAL:
return sWorld->getRate(RATE_CREATURE_NORMAL_HP);
case CREATURE_ELITE_ELITE:
return sWorld->getRate(RATE_CREATURE_ELITE_ELITE_HP);
case CREATURE_ELITE_RAREELITE:
return sWorld->getRate(RATE_CREATURE_ELITE_RAREELITE_HP);
case CREATURE_ELITE_WORLDBOSS:
return sWorld->getRate(RATE_CREATURE_ELITE_WORLDBOSS_HP);
case CREATURE_ELITE_RARE:
return sWorld->getRate(RATE_CREATURE_ELITE_RARE_HP);
default:
return sWorld->getRate(RATE_CREATURE_ELITE_ELITE_HP);
}
}
float Creature::_GetDamageMod(int32 Rank) {
switch (Rank) // define rates for each elite rank
{
case CREATURE_ELITE_NORMAL:
return sWorld->getRate(RATE_CREATURE_NORMAL_DAMAGE);
case CREATURE_ELITE_ELITE:
return sWorld->getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
case CREATURE_ELITE_RAREELITE:
return sWorld->getRate(RATE_CREATURE_ELITE_RAREELITE_DAMAGE);
case CREATURE_ELITE_WORLDBOSS:
return sWorld->getRate(RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE);
case CREATURE_ELITE_RARE:
return sWorld->getRate(RATE_CREATURE_ELITE_RARE_DAMAGE);
default:
return sWorld->getRate(RATE_CREATURE_ELITE_ELITE_DAMAGE);
}
}
float Creature::GetSpellDamageMod(int32 Rank) {
switch (Rank) // define rates for each elite rank
{
case CREATURE_ELITE_NORMAL:
return sWorld->getRate(RATE_CREATURE_NORMAL_SPELLDAMAGE);
case CREATURE_ELITE_ELITE:
return sWorld->getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
case CREATURE_ELITE_RAREELITE:
return sWorld->getRate(RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE);
case CREATURE_ELITE_WORLDBOSS:
return sWorld->getRate(RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE);
case CREATURE_ELITE_RARE:
return sWorld->getRate(RATE_CREATURE_ELITE_RARE_SPELLDAMAGE);
default:
return sWorld->getRate(RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE);
}
}
bool Creature::CreateFromProto(uint32 guidlow, uint32 Entry, uint32 vehId,
uint32 team, const CreatureData *data) {
SetZoneScript();
if (m_zoneScript && data) {
Entry = m_zoneScript->GetCreatureEntry(guidlow, data);
if (!Entry)
return false;
}
CreatureInfo const *cinfo = ObjectMgr::GetCreatureTemplate(Entry);
if (!cinfo) {
sLog->outErrorDb(
"Creature::CreateFromProto(): creature template (guidlow: %u, entry: %u) does not exist.",
guidlow, Entry);
return false;
}
SetOriginalEntry(Entry);
if (!vehId)
vehId = cinfo->VehicleId;
if (vehId && !CreateVehicleKit(vehId))
vehId = 0;
Object::_Create(guidlow, Entry, vehId ? HIGHGUID_VEHICLE : HIGHGUID_UNIT);
if (!UpdateEntry(Entry, team, data))
return false;
return true;
}
bool Creature::LoadFromDB(uint32 guid, Map *map) {
CreatureData const* data = sObjectMgr->GetCreatureData(guid);
if (!data) {
sLog->outErrorDb(
"Creature (GUID: %u) not found in table `creature`, can't load. ",
guid);
return false;
}
m_DBTableGuid = guid;
if (map->GetInstanceId() == 0) {
if (map->GetCreature(MAKE_NEW_GUID(guid, data->id, HIGHGUID_UNIT)))
return false;
} else
guid = sObjectMgr->GenerateLowGuid(HIGHGUID_UNIT);
uint16 team = 0;
if (!Create(guid, map, data->phaseMask, data->id, 0, team, data->posX,
data->posY, data->posZ, data->orientation, data))
return false;
//We should set first home position, because then AI calls home movement
SetHomePosition(data->posX, data->posY, data->posZ, data->orientation);
m_respawnradius = data->spawndist;
m_respawnDelay = data->spawntimesecs;
m_isDeadByDefault = data->is_dead;
m_deathState = m_isDeadByDefault ? DEAD : ALIVE;
m_respawnTime = sObjectMgr->GetCreatureRespawnTime(m_DBTableGuid,
GetInstanceId());
if (m_respawnTime) // respawn on Update
{
m_deathState = DEAD;
if (canFly()) {
float tz = map->GetHeight(data->posX, data->posY, data->posZ,
false);
if (data->posZ - tz > 0.1)
Relocate(data->posX, data->posY, tz);
}
}
uint32 curhealth;
if (!m_regenHealth) {
curhealth = data->curhealth;
if (curhealth) {
curhealth = uint32(
curhealth * _GetHealthMod(GetCreatureInfo()->rank));
if (curhealth < 1)
curhealth = 1;
}
SetPower(POWER_MANA, data->curmana);
} else {
curhealth = GetMaxHealth();
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
}
SetHealth(m_deathState == ALIVE ? curhealth : 0);
// checked at creature_template loading
m_defaultMovementType = MovementGeneratorType(data->movementType);
m_creatureData = data;
return true;
}
void Creature::LoadEquipment(uint32 equip_entry, bool force) {
if (equip_entry == 0) {
if (force) {
for (uint8 i = 0; i < 3; ++i)
SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, 0);
m_equipmentId = 0;
}
return;
}
EquipmentInfo const *einfo = sObjectMgr->GetEquipmentInfo(equip_entry);
if (!einfo)
return;
m_equipmentId = equip_entry;
for (uint8 i = 0; i < 3; ++i)
SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i, einfo->equipentry[i]);
}
bool Creature::hasQuest(uint32 quest_id) const {
QuestRelationBounds qr = sObjectMgr->GetCreatureQuestRelationBounds(
GetEntry());
for (QuestRelations::const_iterator itr = qr.first; itr != qr.second;
++itr) {
if (itr->second == quest_id)
return true;
}
return false;
}
bool Creature::hasInvolvedQuest(uint32 quest_id) const {
QuestRelationBounds qir =
sObjectMgr->GetCreatureQuestInvolvedRelationBounds(GetEntry());
for (QuestRelations::const_iterator itr = qir.first; itr != qir.second;
++itr) {
if (itr->second == quest_id)
return true;
}
return false;
}
void Creature::DeleteFromDB() {
if (!m_DBTableGuid) {
sLog->outError(
"Trying to delete not saved creature! LowGUID: %u, Entry: %u",
GetGUIDLow(), GetEntry());
return;
}
sObjectMgr->RemoveCreatureRespawnTime(m_DBTableGuid, GetInstanceId());
sObjectMgr->DeleteCreatureData(m_DBTableGuid);
SQLTransaction trans = WorldDatabase.BeginTransaction();
trans->PAppend("DELETE FROM creature WHERE guid = '%u'", m_DBTableGuid);
trans->PAppend("DELETE FROM creature_addon WHERE guid = '%u'",
m_DBTableGuid);
trans->PAppend("DELETE FROM game_event_creature WHERE guid = '%u'",
m_DBTableGuid);
trans->PAppend("DELETE FROM game_event_model_equip WHERE guid = '%u'",
m_DBTableGuid);
WorldDatabase.CommitTransaction(trans);
}
bool Creature::IsInvisibleDueToDespawn() const
{
if (Unit::IsInvisibleDueToDespawn())
return true;
if (isAlive() || m_corpseRemoveTime > time(NULL))
return false;
return true;
}
bool Creature::isVisibleForInState(WorldObject const* seer) const {
if (!Unit::isVisibleForInState(seer))
return false;
if (isAlive() || (m_isDeadByDefault && m_deathState == CORPSE)
|| m_corpseRemoveTime > time(NULL))
return true;
return false;
}
bool Creature::canSeeAlways(WorldObject const* obj) const {
if (Unit::canSeeAlways(obj))
return true;
if (IsAIEnabled && AI()->CanSeeAlways(obj))
return true;
return false;
}
bool Creature::canStartAttack(Unit const* who, bool force) const {
if (isCivilian())
return false;
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE))
return false;
if (!canFly()
&& (GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE + m_CombatDistance))
//|| who->IsControlledByPlayer() && who->IsFlying()))
// we cannot check flying for other creatures, too much map/vmap calculation
// TODO: should switch to range attack
return false;
if (!force) {
if (!_IsTargetAcceptable(who))
return false;
if (who->isInCombat())
if (Unit *victim = who->getAttackerForHelper())
if (IsWithinDistInMap(
victim,
sWorld->getFloatConfig(
CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS)))
force = true;
if (!force
&& (IsNeutralToAll()
|| !IsWithinDistInMap(who,
GetAttackDistance(who) + m_CombatDistance)))
return false;
}
if (!canCreatureAttack(who, force))
return false;
return IsWithinLOSInMap(who);
}
float Creature::GetAttackDistance(Unit const* pl) const {
float aggroRate = sWorld->getRate(RATE_CREATURE_AGGRO);
if (aggroRate == 0)
return 0.0f;
uint32 playerlevel = pl->getLevelForTarget(this);
uint32 creaturelevel = getLevelForTarget(pl);
int32 leveldif = int32(playerlevel) - int32(creaturelevel);
// "The maximum Aggro Radius has a cap of 25 levels under. Example: A level 30 char has the same Aggro Radius of a level 5 char on a level 60 mob."
if (leveldif < -25)
leveldif = -25;
// "The aggro radius of a mob having the same level as the player is roughly 20 yards"
float RetDistance = 20;
// "Aggro Radius varies with level difference at a rate of roughly 1 yard/level"
// radius grow if playlevel < creaturelevel
RetDistance -= (float) leveldif;
if (creaturelevel + 5 <= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) {
// detect range auras
RetDistance += GetTotalAuraModifier(SPELL_AURA_MOD_DETECT_RANGE);
// detected range auras
RetDistance += pl->GetTotalAuraModifier(SPELL_AURA_MOD_DETECTED_RANGE);
}
// "Minimum Aggro Radius for a mob seems to be combat range (5 yards)"
if (RetDistance < 5)
if (!(pl->isCamouflaged()))
RetDistance = 5;
return (RetDistance * aggroRate);
}
void Creature::setDeathState(DeathState s) {
if ((s == JUST_DIED && !m_isDeadByDefault)
|| (s == JUST_ALIVED && m_isDeadByDefault)) {
m_corpseRemoveTime = time(NULL) + m_corpseDelay;
m_respawnTime = time(NULL) + m_respawnDelay + m_corpseDelay;
// always save boss respawn time at death to prevent crash cheating
if (sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY)
|| isWorldBoss())
SaveRespawnTime();
}
Unit::setDeathState(s);
if (s == JUST_DIED) {
SetUInt64Value(UNIT_FIELD_TARGET, 0); // remove target selection in any cases (can be set at aura remove in Unit::setDeathState)
SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE);
setActive(false);
if (!isPet() && GetCreatureInfo()->SkinLootId)
if (LootTemplates_Skinning.HaveLootFor(
GetCreatureInfo()->SkinLootId))
if (hasLootRecipient())
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
if (HasSearchedAssistance()) {
SetNoSearchAssistance(false);
UpdateSpeed(MOVE_RUN, false);
}
//Dismiss group if is leader
if (m_formation && m_formation->getLeader() == this)
m_formation->FormationReset(true);
if (ZoneScript* zoneScript = GetZoneScript())
zoneScript->OnCreatureDeath(this);
if ((canFly() || IsFlying()) && FallGround())
return;
Unit::setDeathState(CORPSE);
} else if (s == JUST_ALIVED) {
//if (isPet())
// setActive(true);
SetFullHealth();
SetLootRecipient(NULL);
ResetPlayerDamageReq();
CreatureInfo const *cinfo = GetCreatureInfo();
AddUnitMovementFlag(MOVEMENTFLAG_WALKING);
if (GetCreatureInfo()->InhabitType & INHABIT_AIR)
AddUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING);
if (GetCreatureInfo()->InhabitType & INHABIT_WATER)
AddUnitMovementFlag(MOVEMENTFLAG_SWIMMING);
SetUInt32Value(UNIT_NPC_FLAGS, cinfo->npcflag);
ClearUnitState(UNIT_STAT_ALL_STATE);
SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool));
LoadCreaturesAddon(true);
Motion_Initialize();
if (GetCreatureData() && GetPhaseMask() != GetCreatureData()->phaseMask)
SetPhaseMask(GetCreatureData()->phaseMask, false);
if (m_vehicleKit)
m_vehicleKit->Reset();
Unit::setDeathState(ALIVE);
}
}
bool Creature::FallGround() {
// Let's abort after we called this function one time
if (getDeathState() == DEAD_FALLING)
return false;
float x, y, z;
GetPosition(x, y, z);
// use larger distance for vmap height search than in most other cases
float ground_Z = GetMap()->GetHeight(x, y, z, true, MAX_FALL_DISTANCE);
if (fabs(ground_Z - z) < 0.1f)
return false;
// Hack ... ground_Z should not be invalid
// If Vmap is fixed remove this
if (ground_Z == -200000.0f)
return false;
// End hack
GetMotionMaster()->MoveFall(ground_Z, EVENT_FALL_GROUND);
Unit::setDeathState(DEAD_FALLING);
return true;
}
void Creature::Respawn(bool force) {
DestroyForNearbyPlayers();
if (force) {
if (isAlive())
setDeathState(JUST_DIED);
else if (getDeathState() != CORPSE)
setDeathState(CORPSE);
}
RemoveCorpse(false);
if (getDeathState() == DEAD) {
if (m_DBTableGuid)
sObjectMgr->RemoveCreatureRespawnTime(m_DBTableGuid,
GetInstanceId());
sLog->outStaticDebug("Respawning...");
m_respawnTime = 0;
lootForPickPocketed = false;
lootForBody = false;
if (m_originalEntry != GetEntry())
UpdateEntry(m_originalEntry);
CreatureInfo const *cinfo = GetCreatureInfo();
SelectLevel(cinfo);
if (m_isDeadByDefault) {
setDeathState(JUST_DIED);
i_motionMaster.Clear();
ClearUnitState(UNIT_STAT_ALL_STATE);
LoadCreaturesAddon(true);
} else
setDeathState(JUST_ALIVED);
CreatureModelInfo const *minfo =
sObjectMgr->GetCreatureModelRandomGender(GetNativeDisplayId());
if (minfo) // Cancel load if no model defined
{
uint32 display_id = minfo->modelid; // it can be different (for another gender)
SetDisplayId(display_id);
SetNativeDisplayId(display_id);
SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender);
}
GetMotionMaster()->InitDefault();
//Call AI respawn virtual function
if (IsAIEnabled)
TriggerJustRespawned = true; //delay event to next tick so all creatures are created on the map before processing
uint32 poolid =
GetDBTableGUIDLow() ?
sPoolMgr->IsPartOfAPool<Creature>(GetDBTableGUIDLow()) :
0;
if (poolid)
sPoolMgr->UpdatePool<Creature>(poolid, GetDBTableGUIDLow());
//Re-initialize reactstate that could be altered by movementgenerators
InitializeReactState();
}
UpdateObjectVisibility();
}
void Creature::ForcedDespawn(uint32 timeMSToDespawn) {
if (timeMSToDespawn) {
ForcedDespawnDelayEvent *pEvent = new ForcedDespawnDelayEvent(*this);
m_Events.AddEvent(pEvent, m_Events.CalculateTime(timeMSToDespawn));
return;
}
if (isAlive())
setDeathState(JUST_DIED);
RemoveCorpse(false);
}
void Creature::DespawnOrUnsummon(uint32 msTimeToDespawn /*= 0*/) {
if (TempSummon* summon = this->ToTempSummon())
summon->UnSummon();
else
ForcedDespawn(msTimeToDespawn);
}
bool Creature::IsImmunedToSpell(SpellEntry const* spellInfo) {
if (!spellInfo)
return false;
if (GetCreatureInfo()->MechanicImmuneMask
& (1 << (spellInfo->Mechanic - 1)))
return true;
return Unit::IsImmunedToSpell(spellInfo);
}
bool Creature::IsImmunedToSpellEffect(SpellEntry const* spellInfo,
uint32 index) const {
if (GetCreatureInfo()->MechanicImmuneMask
& (1 << (spellInfo->EffectMechanic[index] - 1)))
return true;
if (GetCreatureInfo()->type == CREATURE_TYPE_MECHANICAL
&& spellInfo->Effect[index] == SPELL_EFFECT_HEAL)
return true;
return Unit::IsImmunedToSpellEffect(spellInfo, index);
}
SpellEntry const *Creature::reachWithSpellAttack(Unit *pVictim) {
if (!pVictim)
return NULL;
for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) {
if (!m_spells[i])
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i]);
if (!spellInfo) {
sLog->outError("WORLD: unknown spell id %i", m_spells[i]);
continue;
}
bool bcontinue = true;
for (uint32 j = 0; j < MAX_SPELL_EFFECTS; j++) {
if ((spellInfo->Effect[j] == SPELL_EFFECT_SCHOOL_DAMAGE)
|| (spellInfo->Effect[j] == SPELL_EFFECT_INSTAKILL)
|| (spellInfo->Effect[j]
== SPELL_EFFECT_ENVIRONMENTAL_DAMAGE)
|| (spellInfo->Effect[j] == SPELL_EFFECT_HEALTH_LEECH)) {
bcontinue = false;
break;
}
}
if (bcontinue)
continue;
if (spellInfo->manaCost > GetPower(POWER_MANA))
continue;
SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(
spellInfo->rangeIndex);
float range = GetSpellMaxRangeForHostile(srange);
float minrange = GetSpellMinRangeForHostile(srange);
float dist = GetDistance(pVictim);
//if (!isInFront(pVictim, range) && spellInfo->AttributesEx)
// continue;
if (dist > range || dist < minrange)
continue;
if (spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE
&& HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
continue;
if (spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY
&& HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
continue;
return spellInfo;
}
return NULL;
}
SpellEntry const *Creature::reachWithSpellCure(Unit *pVictim) {
if (!pVictim)
return NULL;
for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) {
if (!m_spells[i])
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_spells[i]);
if (!spellInfo) {
sLog->outError("WORLD: unknown spell id %i", m_spells[i]);
continue;
}
bool bcontinue = true;
for (uint32 j = 0; j < MAX_SPELL_EFFECTS; j++) {
if ((spellInfo->Effect[j] == SPELL_EFFECT_HEAL)) {
bcontinue = false;
break;
}
}
if (bcontinue)
continue;
if (spellInfo->manaCost > GetPower(POWER_MANA))
continue;
SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(
spellInfo->rangeIndex);
float range = GetSpellMaxRangeForFriend(srange);
float minrange = GetSpellMinRangeForFriend(srange);
float dist = GetDistance(pVictim);
//if (!isInFront(pVictim, range) && spellInfo->AttributesEx)
// continue;
if (dist > range || dist < minrange)
continue;
if (spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE
&& HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
continue;
if (spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY
&& HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
continue;
return spellInfo;
}
return NULL;
}
// select nearest hostile unit within the given distance (regardless of threat list).
Unit* Creature::SelectNearestTarget(float dist) const {
CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
cell.SetNoCreate();
Unit *target = NULL;
{
if (dist == 0.0f)
dist = MAX_VISIBILITY_DISTANCE;
Trinity::NearestHostileUnitCheck u_check(this, dist);
Trinity::UnitLastSearcher<Trinity::NearestHostileUnitCheck> searcher(
this, target, u_check);
TypeContainerVisitor<
Trinity::UnitLastSearcher<Trinity::NearestHostileUnitCheck>,
WorldTypeMapContainer> world_unit_searcher(searcher);
TypeContainerVisitor<
Trinity::UnitLastSearcher<Trinity::NearestHostileUnitCheck>,
GridTypeMapContainer> grid_unit_searcher(searcher);
cell.Visit(p, world_unit_searcher, *GetMap(), *this, dist);
cell.Visit(p, grid_unit_searcher, *GetMap(), *this, dist);
}
return target;
}
// select nearest hostile unit within the given attack distance (i.e. distance is ignored if > than ATTACK_DISTANCE), regardless of threat list.
Unit* Creature::SelectNearestTargetInAttackDistance(float dist) const {
CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
cell.SetNoCreate();
Unit *target = NULL;
if (dist > ATTACK_DISTANCE)
sLog->outError(
"Creature (GUID: %u Entry: %u) SelectNearestTargetInAttackDistance called with dist > ATTACK_DISTANCE. Extra distance ignored.",
GetGUIDLow(), GetEntry());
{
Trinity::NearestHostileUnitInAttackDistanceCheck u_check(this, dist);
Trinity::UnitLastSearcher<
Trinity::NearestHostileUnitInAttackDistanceCheck> searcher(this,
target, u_check);
TypeContainerVisitor<
Trinity::UnitLastSearcher<
Trinity::NearestHostileUnitInAttackDistanceCheck>,
WorldTypeMapContainer> world_unit_searcher(searcher);
TypeContainerVisitor<
Trinity::UnitLastSearcher<
Trinity::NearestHostileUnitInAttackDistanceCheck>,
GridTypeMapContainer> grid_unit_searcher(searcher);
cell.Visit(p, world_unit_searcher, *GetMap(), *this, ATTACK_DISTANCE);
cell.Visit(p, grid_unit_searcher, *GetMap(), *this, ATTACK_DISTANCE);
}
return target;
}
void Creature::SendAIReaction(AiReaction reactionType) {
WorldPacket data(SMSG_AI_REACTION, 12);
data << uint64(GetGUID());
data << uint32(reactionType);
((WorldObject*) this)->SendMessageToSet(&data, true);
sLog->outDebug(LOG_FILTER_TSCR, "WORLD: Sent SMSG_AI_REACTION, type %u.",
reactionType);
}
void Creature::CallAssistance() {
if (!m_AlreadyCallAssistance && getVictim() && !isPet() && !isCharmed()) {
SetNoCallAssistance(true);
float radius = sWorld->getFloatConfig(
CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS);
if (radius > 0) {
std::list<Creature*> assistList;
{
CellPair p(
Trinity::ComputeCellPair(GetPositionX(),
GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
cell.SetNoCreate();
Trinity::AnyAssistCreatureInRangeCheck u_check(this,
getVictim(), radius);
Trinity::CreatureListSearcher<
Trinity::AnyAssistCreatureInRangeCheck> searcher(this,
assistList, u_check);
TypeContainerVisitor<
Trinity::CreatureListSearcher<
Trinity::AnyAssistCreatureInRangeCheck>,
GridTypeMapContainer> grid_creature_searcher(searcher);
cell.Visit(p, grid_creature_searcher, *GetMap(), *this, radius);
}
if (!assistList.empty()) {
AssistDelayEvent *e = new AssistDelayEvent(
getVictim()->GetGUID(), *this);
while (!assistList.empty()) {
// Pushing guids because in delay can happen some creature gets despawned => invalid pointer
e->AddAssistant((*assistList.begin())->GetGUID());
assistList.pop_front();
}
m_Events.AddEvent(
e,
m_Events.CalculateTime(
sWorld->getIntConfig(
CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY)));
}
}
}
}
void Creature::CallForHelp(float fRadius) {
if (fRadius <= 0.0f || !getVictim() || isPet() || isCharmed())
return;
CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
cell.SetNoCreate();
Trinity::CallOfHelpCreatureInRangeDo u_do(this, getVictim(), fRadius);
Trinity::CreatureWorker<Trinity::CallOfHelpCreatureInRangeDo> worker(this,
u_do);
TypeContainerVisitor<
Trinity::CreatureWorker<Trinity::CallOfHelpCreatureInRangeDo>,
GridTypeMapContainer> grid_creature_searcher(worker);
cell.Visit(p, grid_creature_searcher, *GetMap(), *this, fRadius);
}
bool Creature::CanAssistTo(const Unit* u, const Unit* enemy,
bool checkfaction /*= true*/) const {
// is it true?
if (!HasReactState(REACT_AGGRESSIVE))
return false;
// we don't need help from zombies :)
if (!isAlive())
return false;
// we don't need help from non-combatant ;)
if (isCivilian())
return false;
if (HasFlag(
UNIT_FIELD_FLAGS,
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE
| UNIT_FLAG_PASSIVE))
return false;
// skip fighting creature
if (isInCombat())
return false;
// only free creature
if (GetCharmerOrOwnerGUID())
return false;
// only from same creature faction
if (checkfaction) {
if (getFaction() != u->getFaction())
return false;
} else {
if (!IsFriendlyTo(u))
return false;
}
// skip non hostile to caster enemy creatures
if (!IsHostileTo(enemy))
return false;
return true;
}
// use this function to avoid having hostile creatures attack
// friendlies and other mobs they shouldn't attack
bool Creature::_IsTargetAcceptable(const Unit *target) const {
ASSERT(target);
// if the target cannot be attacked, the target is not acceptable
if (IsFriendlyTo(target) || !target->isAttackableByAOE()
|| (m_vehicle
&& (IsOnVehicle(target)
|| m_vehicle->GetBase()->IsOnVehicle(target))))
return false;
if (target->HasUnitState(UNIT_STAT_DIED)) {
// guards can detect fake death
if (isGuard()
&& target->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH))
return true;
else
return false;
}
const Unit *myVictim = getAttackerForHelper();
const Unit *targetVictim = target->getAttackerForHelper();
// if I'm already fighting target, or I'm hostile towards the target, the target is acceptable
if (myVictim == target || targetVictim == this || IsHostileTo(target))
return true;
// if the target's victim is friendly, and the target is neutral, the target is acceptable
if (targetVictim && IsFriendlyTo(targetVictim))
return true;
// if the target's victim is not friendly, or the target is friendly, the target is not acceptable
return false;
}
void Creature::SaveRespawnTime() {
if (isSummon() || !m_DBTableGuid
|| (m_creatureData && !m_creatureData->dbData))
return;
sObjectMgr->SaveCreatureRespawnTime(m_DBTableGuid, GetInstanceId(),
m_respawnTime);
}
// this should not be called by petAI or
bool Creature::canCreatureAttack(Unit const *pVictim, bool force) const {
if (!pVictim->IsInMap(this))
return false;
if (!canAttack(pVictim, force))
return false;
if (!pVictim->isInAccessiblePlaceFor(this))
return false;
if (IsAIEnabled && !AI()->CanAIAttack(pVictim))
return false;
if (sMapStore.LookupEntry(GetMapId())->IsDungeon())
return true;
//Use AttackDistance in distance check if threat radius is lower. This prevents creature bounce in and out of combat every update tick.
float dist = std::max(GetAttackDistance(pVictim),
sWorld->getFloatConfig(CONFIG_THREAT_RADIUS)) + m_CombatDistance;
if (Unit *unit = GetCharmerOrOwner())
return pVictim->IsWithinDist(unit, dist);
else
return pVictim->IsInDist(&m_homePosition, dist);
}
CreatureDataAddon const* Creature::GetCreatureAddon() const {
if (m_DBTableGuid) {
if (CreatureDataAddon const* addon = ObjectMgr::GetCreatureAddon(m_DBTableGuid))
return addon;
}
// dependent from difficulty mode entry
return ObjectMgr::GetCreatureTemplateAddon(GetCreatureInfo()->Entry);
}
//creature_addon table
bool Creature::LoadCreaturesAddon(bool reload) {
CreatureDataAddon const *cainfo = GetCreatureAddon();
if (!cainfo)
return false;
if (cainfo->mount != 0)
Mount(cainfo->mount);
if (cainfo->bytes1 != 0) {
// 0 StandState
// 1 FreeTalentPoints Pet only, so always 0 for default creature
// 2 StandFlags
// 3 StandMiscFlags
SetByteValue(UNIT_FIELD_BYTES_1, 0, uint8(cainfo->bytes1 & 0xFF));
//SetByteValue(UNIT_FIELD_BYTES_1, 1, uint8((cainfo->bytes1 >> 8) & 0xFF));
SetByteValue(UNIT_FIELD_BYTES_1, 1, 0);
SetByteValue(UNIT_FIELD_BYTES_1, 2,
uint8((cainfo->bytes1 >> 16) & 0xFF));
SetByteValue(UNIT_FIELD_BYTES_1, 3,
uint8((cainfo->bytes1 >> 24) & 0xFF));
}
if (cainfo->bytes2 != 0) {
// 0 SheathState
// 1 Bytes2Flags
// 2 UnitRename Pet only, so always 0 for default creature
// 3 ShapeshiftForm Must be determined/set by shapeshift spell/aura
SetByteValue(UNIT_FIELD_BYTES_2, 0, uint8(cainfo->bytes2 & 0xFF));
//SetByteValue(UNIT_FIELD_BYTES_2, 1, uint8((cainfo->bytes2 >> 8) & 0xFF));
//SetByteValue(UNIT_FIELD_BYTES_2, 2, uint8((cainfo->bytes2 >> 16) & 0xFF));
SetByteValue(UNIT_FIELD_BYTES_2, 2, 0);
//SetByteValue(UNIT_FIELD_BYTES_2, 3, uint8((cainfo->bytes2 >> 24) & 0xFF));
SetByteValue(UNIT_FIELD_BYTES_2, 3, 0);
}
if (cainfo->emote != 0)
SetUInt32Value(UNIT_NPC_EMOTESTATE, cainfo->emote);
//Load Path
if (cainfo->path_id != 0)
m_path_id = cainfo->path_id;
if (cainfo->auras) {
for (CreatureDataAddonAura const* cAura = cainfo->auras;
cAura->spell_id; ++cAura) {
SpellEntry const *AdditionalSpellInfo = sSpellStore.LookupEntry(
cAura->spell_id);
if (!AdditionalSpellInfo) {
sLog->outErrorDb(
"Creature (GUID: %u Entry: %u) has wrong spell %u defined in `auras` field.",
GetGUIDLow(), GetEntry(), cAura->spell_id);
continue;
}
// skip already applied aura
if (HasAura(cAura->spell_id)) {
if (!reload)
sLog->outErrorDb(
"Creature (GUID: %u Entry: %u) has duplicate aura (spell %u) in `auras` field.",
GetGUIDLow(), GetEntry(), cAura->spell_id);
continue;
}
AddAura(AdditionalSpellInfo, cAura->effectMask, this);
sLog->outDebug(
LOG_FILTER_TSCR,
"Spell: %u with AuraEffectMask %u added to creature (GUID: %u Entry: %u)",
cAura->spell_id, cAura->effectMask, GetGUIDLow(),
GetEntry());
}
}
return true;
}
/// Send a message to LocalDefense channel for players opposition team in the zone
void Creature::SendZoneUnderAttackMessage(Player* attacker) {
uint32 enemy_team = attacker->GetTeam();
WorldPacket data(SMSG_ZONE_UNDER_ATTACK, 4);
data << (uint32) GetAreaId();
sWorld->SendGlobalMessage(&data, NULL,
(enemy_team == ALLIANCE ? HORDE : ALLIANCE));
}
void Creature::SetInCombatWithZone() {
if (!CanHaveThreatList()) {
sLog->outError(
"Creature entry %u call SetInCombatWithZone but creature cannot have threat list.",
GetEntry());
return;
}
Map* pMap = GetMap();
if (!pMap->IsDungeon()) {
sLog->outError(
"Creature entry %u call SetInCombatWithZone for map (id: %u) that isn't an instance.",
GetEntry(), pMap->GetId());
return;
}
Map::PlayerList const &PlList = pMap->GetPlayers();
if (PlList.isEmpty())
return;
for (Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end();
++i) {
if (Player* pPlayer = i->getSource()) {
if (pPlayer->isGameMaster())
continue;
if (pPlayer->isAlive()) {
this->SetInCombatWith(pPlayer);
pPlayer->SetInCombatWith(this);
AddThreat(pPlayer, 0.0f);
}
}
}
}
void Creature::_AddCreatureSpellCooldown(uint32 spell_id, time_t end_time) {
m_CreatureSpellCooldowns[spell_id] = end_time;
}
void Creature::_AddCreatureCategoryCooldown(uint32 category,
time_t apply_time) {
m_CreatureCategoryCooldowns[category] = apply_time;
}
void Creature::AddCreatureSpellCooldown(uint32 spellid) {
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellid);
if (!spellInfo)
return;
uint32 cooldown = GetSpellRecoveryTime(spellInfo);
if (Player *modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellid, SPELLMOD_COOLDOWN, cooldown);
if (cooldown)
_AddCreatureSpellCooldown(spellid,
time(NULL) + cooldown / IN_MILLISECONDS);
if (spellInfo->Category)
_AddCreatureCategoryCooldown(spellInfo->Category, time(NULL));
m_GlobalCooldown = spellInfo->StartRecoveryTime;
}
bool Creature::HasCategoryCooldown(uint32 spell_id) const {
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
if (!spellInfo)
return false;
// check global cooldown if spell affected by it
if (spellInfo->StartRecoveryCategory > 0 && m_GlobalCooldown > 0)
return true;
CreatureSpellCooldowns::const_iterator itr =
m_CreatureCategoryCooldowns.find(spellInfo->Category);
return (itr != m_CreatureCategoryCooldowns.end()
&& time_t(
itr->second
+ (spellInfo->CategoryRecoveryTime / IN_MILLISECONDS))
> time(NULL));
}
bool Creature::HasSpellCooldown(uint32 spell_id) const {
CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(
spell_id);
return (itr != m_CreatureSpellCooldowns.end() && itr->second > time(NULL))
|| HasCategoryCooldown(spell_id);
}
bool Creature::HasSpell(uint32 spellID) const {
uint8 i;
for (i = 0; i < CREATURE_MAX_SPELLS; ++i)
if (spellID == m_spells[i])
break;
return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells
}
time_t Creature::GetRespawnTimeEx() const {
time_t now = time(NULL);
if (m_respawnTime > now)
return m_respawnTime;
else
return now;
}
void Creature::GetRespawnCoord(float &x, float &y, float &z, float* ori,
float* dist) const {
if (m_DBTableGuid) {
if (CreatureData const* data = sObjectMgr->GetCreatureData(GetDBTableGUIDLow())) {
x = data->posX;
y = data->posY;
z = data->posZ;
if (ori)
*ori = data->orientation;
if (dist)
*dist = data->spawndist;
return;
}
}
x = GetPositionX();
y = GetPositionY();
z = GetPositionZ();
if (ori)
*ori = GetOrientation();
if (dist)
*dist = 0;
}
void Creature::AllLootRemovedFromCorpse() {
if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE)) {
time_t now = time(NULL);
if (m_corpseRemoveTime <= now)
return;
float decayRate;
CreatureInfo const *cinfo = GetCreatureInfo();
decayRate = sWorld->getRate(RATE_CORPSE_DECAY_LOOTED);
uint32 diff = uint32((m_corpseRemoveTime - now) * decayRate);
m_respawnTime -= diff;
// corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update
if (cinfo && cinfo->SkinLootId)
m_corpseRemoveTime = time(NULL);
else
m_corpseRemoveTime -= diff;
}
}
uint8 Creature::getLevelForTarget(WorldObject const* target) const {
if (!isWorldBoss() || !target->ToUnit())
return Unit::getLevelForTarget(target);
uint16 level = target->ToUnit()->getLevel()
+ sWorld->getIntConfig(CONFIG_WORLD_BOSS_LEVEL_DIFF);
if (level < 1)
return 1;
if (level > 255)
return 255;
return uint8(level);
}
std::string Creature::GetAIName() const {
return ObjectMgr::GetCreatureTemplate(GetEntry())->AIName;
}
std::string Creature::GetScriptName() const {
return sObjectMgr->GetScriptName(GetScriptId());
}
uint32 Creature::GetScriptId() const {
return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
}
VendorItemData const* Creature::GetVendorItems() const {
return sObjectMgr->GetNpcVendorItemList(GetEntry());
}
uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem) {
if (!vItem->maxcount)
return vItem->maxcount;
VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
for (; itr != m_vendorItemCounts.end(); ++itr)
if (itr->itemId == vItem->item)
break;
if (itr == m_vendorItemCounts.end())
return vItem->maxcount;
VendorItemCount* vCount = &*itr;
time_t ptime = time(NULL);
if (time_t(vCount->lastIncrementTime + vItem->incrtime) <= ptime) {
ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
uint32 diff = uint32(
(ptime - vCount->lastIncrementTime) / vItem->incrtime);
if ((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount) {
m_vendorItemCounts.erase(itr);
return vItem->maxcount;
}
vCount->count += diff * pProto->BuyCount;
vCount->lastIncrementTime = ptime;
}
return vCount->count;
}
uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem,
uint32 used_count) {
if (!vItem->maxcount)
return 0;
VendorItemCounts::iterator itr = m_vendorItemCounts.begin();
for (; itr != m_vendorItemCounts.end(); ++itr)
if (itr->itemId == vItem->item)
break;
if (itr == m_vendorItemCounts.end()) {
uint32 new_count =
vItem->maxcount > used_count ? vItem->maxcount - used_count : 0;
m_vendorItemCounts.push_back(VendorItemCount(vItem->item, new_count));
return new_count;
}
VendorItemCount* vCount = &*itr;
time_t ptime = time(NULL);
if (time_t(vCount->lastIncrementTime + vItem->incrtime) <= ptime) {
ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(vItem->item);
uint32 diff = uint32(
(ptime - vCount->lastIncrementTime) / vItem->incrtime);
if ((vCount->count + diff * pProto->BuyCount) < vItem->maxcount)
vCount->count += diff * pProto->BuyCount;
else
vCount->count = vItem->maxcount;
}
vCount->count = vCount->count > used_count ? vCount->count - used_count : 0;
vCount->lastIncrementTime = ptime;
return vCount->count;
}
TrainerSpellData const* Creature::GetTrainerSpells() const {
return sObjectMgr->GetNpcTrainerSpells(GetEntry());
}
// overwrite WorldObject function for proper name localization
const char* Creature::GetNameForLocaleIdx(LocaleConstant loc_idx) const {
if (loc_idx != DEFAULT_LOCALE) {
uint8 uloc_idx = uint8(loc_idx);
CreatureLocale const *cl = sObjectMgr->GetCreatureLocale(GetEntry());
if (cl) {
if (cl->Name.size() > uloc_idx && !cl->Name[uloc_idx].empty())
return cl->Name[uloc_idx].c_str();
}
}
return GetName();
}
void Creature::FarTeleportTo(Map* map, float X, float Y, float Z, float O) {
InterruptNonMeleeSpells(true);
CombatStop();
ClearComboPointHolders();
DeleteThreatList();
GetMotionMaster()->Clear(false);
DestroyForNearbyPlayers();
RemoveFromWorld();
ResetMap();
SetMap(map);
AddToWorld();
SetPosition(X, Y, Z, O, true);
}
bool Creature::IsDungeonBoss() const {
CreatureInfo const *cinfo = ObjectMgr::GetCreatureTemplate(GetEntry());
return cinfo && (cinfo->flags_extra & CREATURE_FLAG_EXTRA_DUNGEON_BOSS);
}
| [
"sharkipaust@web.de"
] | sharkipaust@web.de |
319bdab173eafc36b5843fde4edc2bded24390b3 | 1b3c5596447124a90f09887d977550923d9b84f2 | /code/operations/operation-delete.cpp | 5b02fc30c1724e5bc1f78fcba94a8419b5990f12 | [
"ISC"
] | permissive | ankurjain41282/gobby | eec8e467e9af4361b13b33cbe9aca1b1aed318c6 | c89ee9fca2a1d8bbb3eb7d3ce8b40bfbc800bfab | refs/heads/master | 2021-01-21T06:11:13.747020 | 2015-05-10T21:15:04 | 2015-05-10T21:15:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,341 | cpp | /* Gobby - GTK-based collaborative text editor
* Copyright (C) 2008-2014 Armin Burgmeier <armin@arbur.net>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "operations/operation-delete.hpp"
#include "util/i18n.hpp"
Gobby::OperationDelete::OperationDelete(Operations& operations,
InfBrowser* browser,
const InfBrowserIter* iter):
Operation(operations), m_browser(browser), m_iter(*iter),
m_name(inf_browser_get_node_name(browser, iter)), m_request(NULL)
{
g_object_ref(browser);
}
Gobby::OperationDelete::~OperationDelete()
{
if(m_request != NULL)
{
g_signal_handlers_disconnect_by_func(
G_OBJECT(m_request),
(gpointer)G_CALLBACK(on_request_finished_static),
this);
g_object_unref(m_request);
get_status_bar().remove_message(m_message_handle);
}
g_object_unref(m_browser);
}
void Gobby::OperationDelete::start()
{
InfRequest* request = inf_browser_remove_node(
m_browser,
&m_iter,
on_request_finished_static,
this
);
// Object might be gone at this point, so check stack variable
if(request != NULL)
{
m_request = request;
// Note infc_browser_remove_node does not return a
// new reference.
g_object_ref(m_request);
m_message_handle = get_status_bar().add_info_message(
Glib::ustring::compose(
_("Removing node \"%1\"..."), m_name));
}
}
void Gobby::OperationDelete::on_request_finished(const GError* error)
{
if(error)
{
get_status_bar().add_error_message(
Glib::ustring::compose(
_("Failed to delete node \"%1\""),
m_name),
error->message);
fail();
}
else
{
finish();
}
}
| [
"armin@arbur.net"
] | armin@arbur.net |
124dcb75b4b85c9f29a4d242de5acaf871ca90e4 | efd3314b262f6f0af22be805b46458b17122e71f | /Documentos/Parcial3/CC1038417027/constructor.cpp | d2db76b10d6d8b6a8972f00cbfa9ad00d5dc460d | [] | no_license | elime920/CursoFCII-2020-1 | f77f3ff500da64a6837dc9dc4b1da5444c60fbd4 | 33b5ec132460a9f207b52e6305d3a60bf5538ba1 | refs/heads/master | 2021-01-02T19:45:12.135931 | 2020-06-01T19:21:31 | 2020-06-01T19:21:31 | 239,771,525 | 0 | 1 | null | 2020-02-11T13:42:28 | 2020-02-11T13:42:28 | null | UTF-8 | C++ | false | false | 2,187 | cpp | #include <iostream>
//#ifndef "metodo_de_diferencias_finitas.h"
#include "metodo_de_diferencias_finitas.h"
#include <math.h>
#include <vector>
#include <iomanip>
#include <fstream>
#include <cstdlib>
using namespace std;
void imprimir(const vector<double> &,const vector<double> &);
metodo::metodo(int n, double a, double b, double al, double be,functype *f)
{
N = n;
inicioX=a;
finalX=b;
inicioY=al;
finalY=be;
h = (finalX - inicioX)/(N+1);
func = (functype*) malloc((size_t) sizeof(functype) * 3);
func[0]=f[0];
func[1]=f[1];
func[2]=f[2];
}
void metodo::paso()
{
vector <double> x(N+2);
vector <double> u(N+1);
vector <double> z(N+1);
vector <double> w(N+2);
ofstream archivo_sal;
archivo_sal.open("valores.txt");
if (archivo_sal.fail())
{
cout<<"Es imposible abrir el archivo"<<endl;
exit(1);
}
x[0]=inicioX;
for (int i=1;i<=N;i++)
{
if (i==1)
{
u[0]=0.0;
z[0]=0.0;
u[N]=0.0;
double l1,a1,b1,d1;
x[i]= inicioX + h;
a1= 2 + pow(h,2)*func[1](&x[i]);
b1= -1 + (h/2)* func[0](&x[i]);
d1= -pow(h,2)*func[2](&x[i]) + (1 + (h/2)*func[0](&x[i]))*inicioY;
l1=a1;
u[i]=b1/a1;
z[i]=d1/l1;
}
else if(i==N)
{
double ln,an,cn,dn;
x[i]= finalX - h ;
an= 2 + pow(h,2)*func[1](&x[i]);
cn= -1 -(h/2)*func[0](&x[i]);
dn= -pow(h,2)*func[2](&x[i]) + (1 + (h/2)*func[0](&x[i]))*finalY;
ln=an - cn*u[i-1];
z[i]=(dn - cn*z[i-1])/ln;
}
else
{
double li,ai,bi,ci,di;
x[i]= inicioX + i*h;
ai= 2 + pow(h,2)*func[1](&x[i]);
bi= -1 + (h/2)*func[0](&x[i]);
ci= -1 - (h/2)*func[0](&x[i]);
di= -pow(h,2)*func[2](&x[i]);
li=ai -ci*u[i-1];
u[i]=bi/li;
z[i]=(di - ci*z[i-1])/li;
}
}
w[0]=inicioY;
w[N+1]=finalY;
w[N]=z[N];
double b=N-1;
for(int i=1;i<N;i++)
{
w[b]=z[b] - u[b]*w[b+1];
archivo_sal<<x[b]<<" "<<w[b]<<endl;
b=b-1;
}
archivo_sal.close();
}
void imprimir(const vector<double> &arreglo1, const vector<double> &arreglo2)
{
size_t i;
for (i=0;i<arreglo1.size();i++)
{
cout<<setw(12)<<arreglo1[i]<<setw(12)<<arreglo2[i]<<endl;
}
}
metodo::~metodo(){
free(func);
}
| [
"crewdark@crewdark.crewdark"
] | crewdark@crewdark.crewdark |
afc678dc7551c9c6db9c5254f593ed354e6bbeb6 | ae1c6ad39b94b34b2312e7cc599321616016d767 | /HighlightTextEditor/jni/highlight/include/themereader.h | 6e63ea01fdeb833bfe270ea6d1cbd1d79c1cc92d | [] | no_license | vbea/AideProjects | cd4481943229fd585841863bd7f66f98543e54d9 | 0d6dfc4bb1e8aea7b60483b0cbc23190f8e0f26d | refs/heads/master | 2023-01-30T09:11:11.278783 | 2023-01-14T10:28:47 | 2023-01-14T10:28:47 | 200,463,935 | 24 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 4,221 | h | /***************************************************************************
themereader.h - description
-------------------
begin : Son Nov 10 2002
copyright : (C) 2002-2010 by Andre Simon
email : andre.simon1@gmx.de
***************************************************************************/
/*
This file is part of Highlight.
Highlight 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.
Highlight 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 Highlight. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef THEMEREADER_H
#define THEMEREADER_H
#include <string>
#include <Diluculum/LuaFunction.hpp>
#include <Diluculum/LuaVariable.hpp>
#include "elementstyle.h"
#include "stylecolour.h"
using namespace std;
namespace highlight
{
/** maps keyword class names and the corresponding formatting information*/
typedef map <string, ElementStyle> KeywordStyles;
/** iterator for keyword styles*/
typedef KeywordStyles::const_iterator KSIterator;
/** \brief Contains information about document formatting properties.
* @author Andre Simon
*/
class ThemeReader
{
private:
ElementStyle comment, slcomment, str, dstr,
escapeChar, number, directive, line, operators, interpolation;
ElementStyle defaultElem;
ElementStyle canvas;
string errorMsg;
string desc;
string themeInjections;
//vector <string> injections;
vector<Diluculum::LuaFunction*> pluginChunks;
bool fileOK;
KeywordStyles keywordStyles;
void initStyle(ElementStyle& style, const Diluculum::LuaVariable& var);
public:
/** Constructor */
ThemeReader();
~ThemeReader();
/** load style definition
\param styleDefinitionFile Style definition path
\return True if successfull */
bool load ( const string & styleDefinitionFile, OutputType outputType=HTML );
void addUserChunk(const Diluculum::LuaFunction& chunk) {
pluginChunks.push_back(new Diluculum::LuaFunction(chunk));
}
/** \return class names defined in the theme file */
vector <string> getClassNames() const;
/** \return keyword styles */
KeywordStyles getKeywordStyles() const;
/** \return Font size */
string getErrorMessage() const;
string getDescription() const {
return desc;
}
string getInjections() const;
/** \return Background colour*/
Colour getBgColour() const;
/** \return Style of default (unrecognized) strings */
ElementStyle getDefaultStyle() const;
/** \return Comment style*/
ElementStyle getCommentStyle() const;
/** \return Single line comment style*/
ElementStyle getSingleLineCommentStyle() const;
/** \return String style*/
ElementStyle getStringStyle() const;
/** \return Directive line string style*/
ElementStyle getPreProcStringStyle() const;
/** \return Escape character style*/
ElementStyle getEscapeCharStyle() const;
/** \return String interpolation style*/
ElementStyle getInterpolationStyle() const;
/** \return Number style*/
ElementStyle getNumberStyle() const;
/** \return Directive style*/
ElementStyle getPreProcessorStyle() const;
/** \return Type style*/
ElementStyle getTypeStyle() const;
/** \return Line number style*/
ElementStyle getLineStyle() const;
/** \return Operator style*/
ElementStyle getOperatorStyle() const;
/** \param className Name of keyword class (eg kwa, kwb, .., kwd)
\return keyword style of the given className
*/
ElementStyle getKeywordStyle ( const string &className ) ;
/** \return True if language definition was found */
bool found() const ;
};
}
#endif
| [
"vbea@foxmail.com"
] | vbea@foxmail.com |
bfad731c3b59b11d37d62add41bb0c3e82f0b587 | 4c457c5d8238f756b7ceedc66fba65b58831cea3 | /BAEKJOON_2083_RugbyClub/2083_RubyClub.cpp | 88add7a454a66ef18ce11a620660225ac7852a6c | [] | no_license | pikacsc/CodingTestPrac | f2a030d23881b8a8d086562ab2502849916819fd | 2e85c4cfd2795ab1e42d1976fa9132cabef7bfa3 | refs/heads/master | 2023-04-07T21:49:48.635654 | 2021-04-25T03:20:17 | 2021-04-25T03:20:17 | 268,752,494 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,333 | cpp | /*
https://www.acmicpc.net/problem/2083
문제
올 골드 럭비 클럽의 회원들은 성인부 또는 청소년부로 분류된다.
나이가 17세보다 많거나, 몸무게가 80kg 이상이면 성인부이다. 그 밖에는 모두 청소년부이다. 클럽 회원들을 올바르게 분류하라.
입력
각 줄은 이름과 두 자연수로 이루어진다. 두 자연수는 순서대로 나이와 몸무게를 나타낸다. 입력의 마지막 줄은 # 0 0 이다. 이 입력은 처리하지 않는다.
이름은 알파벳 대/소문자로만 이루어져 있고, 길이는 10을 넘지 않는다.
출력
입력 받은 각 회원에 대해 이름과 분류를 출력한다. 성인부 회원이면 'Senior', 청소년부 회원이면 'Junior'를 출력한다.
예제 입력 1
Joe 16 34
Bill 18 65
Billy 17 65
Sam 17 85
# 0 0
예제 출력 1
Joe Junior
Bill Senior
Billy Junior
Sam Senior
*/
#include <iostream>
char buffer[11];
int age;
int weight;
int main()
{
while (1)
{
std::cin >> buffer;
if (buffer[0] != '#')
std::cout << buffer;
buffer[0] = 0;
std::cin >> age;
std::cin >> weight;
if (age != 0 && weight != 0)
{
if (age > 17 || weight >= 80)
std::cout << " Senior" << std::endl;
else
std::cout << " Junior" << std::endl;
}
else
{
break;
}
}
return 0;
} | [
"ccc11203@gmail.com"
] | ccc11203@gmail.com |
e26b2524f35f8898b91177ba114c594c894a0838 | 2f8bf3203a41ab06398e95a9a640dd31ca8d917c | /src/crypter.cpp | e656f5926d07b8230ce124c1f6c78002f76fc099 | [
"MIT"
] | permissive | atdweb/winnercoin | eee6982f7c7fa37c6c3de3becb35ecbe8c54de58 | 5104a6efe968339cc497710b3bac650f81657076 | refs/heads/master | 2020-05-15T08:11:31.605013 | 2014-05-04T00:36:44 | 2014-05-04T00:36:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,567 | cpp | // Copyright (c) 2009-2012 The Winnercoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <vector>
#include <string>
#include "headers.h"
#ifdef WIN32
#include <windows.h>
#endif
#include "crypter.h"
#include "main.h"
#include "util.h"
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
// Try to keep the keydata out of swap (and be a bit over-careful to keep the IV that we don't even use out of swap)
// Note that this does nothing about suspend-to-disk (which will put all our key data on disk)
// Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process.
mlock(&chKey[0], sizeof chKey);
mlock(&chIV[0], sizeof chIV);
int i = 0;
if (nDerivationMethod == 0)
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
if (i != WALLET_CRYPTO_KEY_SIZE)
{
memset(&chKey, 0, sizeof chKey);
memset(&chIV, 0, sizeof chIV);
return false;
}
fKeySet = true;
return true;
}
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
{
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
return false;
// Try to keep the keydata out of swap
// Note that this does nothing about suspend-to-disk (which will put all our key data on disk)
// Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process.
mlock(&chKey[0], sizeof chKey);
mlock(&chIV[0], sizeof chIV);
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
fKeySet = true;
return true;
}
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext)
{
if (!fKeySet)
return false;
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = vchPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<unsigned char> (nCLen);
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
vchCiphertext.resize(nCLen + nFLen);
return true;
}
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
int nPLen = nLen, nFLen = 0;
vchPlaintext = CKeyingMaterial(nPLen);
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
vchPlaintext.resize(nPLen + nFLen);
return true;
}
bool EncryptSecret(CKeyingMaterial& vMasterKey, const CSecret &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt((CKeyingMaterial)vchPlaintext, vchCiphertext);
}
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CSecret& vchPlaintext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
}
| [
"atdwebing@gmail.com"
] | atdwebing@gmail.com |
e573ecc040bf05fe66e5fe0ea6abf67abee0f450 | 0bc727e09b828b51b218707f18a70058d2751adf | /libs/obcl/src/lexer/trie.cc | 56042b173d90807d7080e2f9b4b37e5e470de120 | [] | no_license | obs145628/milk | 78420eb42f97c71ca3e920def12ba2daafc8813e | 4bde854e09dff6038753f6005356cc7db427133f | refs/heads/master | 2020-09-22T08:16:11.765313 | 2020-01-25T07:39:33 | 2020-01-25T07:39:33 | 225,117,440 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | cc | #include <cassert>
#include <lexer/trie.hh>
namespace obcl {
Trie::Trie()
: _ready(false), _root(std::make_unique<RawTrie>()), _ptr(_root.get()) {
_root->val = STATE_INVALID;
_root->son = nullptr;
_root->sibl = nullptr;
}
void Trie::add_word(const char *w, token_type_t id) {
auto node = _root.get();
for (; *w != '\0'; ++w) {
char c = *w;
if (!node->son) {
node->son = std::make_unique<RawTrie>();
node = node->son.get();
node->c = c;
node->val = STATE_INVALID;
node->son = nullptr;
node->sibl = nullptr;
continue;
}
node = node->son.get();
while (node->sibl) {
if (node->c == c)
break;
node = node->sibl.get();
}
if (node->c == c) {
continue;
}
node->sibl = std::make_unique<RawTrie>();
node = node->sibl.get();
node->c = c;
node->val = STATE_INVALID;
node->son = nullptr;
node->sibl = nullptr;
}
node->val = id;
}
void Trie::ready() {
assert(!_ready);
_ready = true;
}
void Trie::reset() {
assert(_ready);
_ptr = _root.get();
}
void Trie::next(char c) {
assert(_ready);
if (!_ptr)
return;
const RawTrie *next = _ptr->son.get();
while (next) {
if (next->c == c)
break;
next = next->sibl.get();
}
_ptr = next;
}
bool Trie::possible_word() const {
assert(_ready);
return _ptr != nullptr;
}
token_type_t Trie::get_current_state() {
assert(_ready);
return _ptr ? _ptr->val : STATE_INVALID;
}
bool Trie::can_start_with(char c) const {
const RawTrie *node = _root->son.get();
while (node) {
if (node->c == c)
return true;
node = node->sibl.get();
}
return false;
}
} // namespace obcl
| [
"obs145628@gmail.com"
] | obs145628@gmail.com |
a124f7dee153673b184fa9b1481b5fb2b3f65625 | 301ad0331d5daf970207f183a8f4d4848484de71 | /thriftTest/gen-cpp/FileReceiver_server.skeleton.cpp | 52d629c5ad34ce6ea8d8c8c391966e6524f427ab | [] | no_license | Fortunato28/SDCITA | e80608c3e4236452fb963a8d1a91bada2ddf5f0b | cba722a81bd8d0cc42fb6a535b42a2d2077bb2e9 | refs/heads/master | 2020-04-13T13:58:20.851488 | 2018-12-27T05:18:46 | 2018-12-27T05:18:46 | 163,247,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,759 | cpp | // This autogenerated skeleton file illustrates how to build a server.
// You should copy it to another filename to avoid overwriting it.
#include "FileReceiver.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace std;
class FileReceiverHandler : virtual public FileReceiverIf {
public:
FileReceiverHandler()
{
// Your initialization goes here
}
void ping()
{
// Your implementation goes here
printf("ping\n");
}
void GetFile(FileChunk& _return, const std::string& fileName)
{
// Open file in binary mod
ifstream file (fileName, std::ios_base::ate | std::ios_base::binary);
if(!file)
{
cout << "File can`t be opened." << endl;
return;
}
std::vector<char> buf;
std::fstream::pos_type fileSize = file.tellg(); // Get number of bytes in file
file.seekg(0, std::ios_base::beg); // Set pointer to the begining of file
buf.resize(fileSize);
file.read(&buf[0], fileSize); // Read file in buffer
file.close();
std::string buffer(buf.begin(), buf.end());
_return.__set_fileName(fileName);
_return.__set_fileFormat("bash script");
_return.__set_data(buffer);
_return.__set_hash("Vot tebe hash");
_return.__set_isExecutable(true);
printf("GetFile\n");
}
void GetTask(Task& _return)
{
// Your implementation goes here
printf("GetTask\n");
}
bool SendResult(const FileChunk& result)
{
// Your implementation goes here
printf("SendResult\n");
}
};
int main(int argc, char **argv) {
int port = 9090;
::apache::thrift::stdcxx::shared_ptr<FileReceiverHandler> handler(new FileReceiverHandler());
::apache::thrift::stdcxx::shared_ptr<TProcessor> processor(new FileReceiverProcessor(handler));
::apache::thrift::stdcxx::shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
::apache::thrift::stdcxx::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
::apache::thrift::stdcxx::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
server.serve();
return 0;
}
| [
"fort.sav.28@gmail.com"
] | fort.sav.28@gmail.com |
62b80d51394d6e40e91a548cb99015fc2293c56b | ef66dadf885506c94897f7c6727c35a6b5d9b7d3 | /art-extension/compiler/optimizing/extensions/passes/pure_invokes_analysis.h | 67bfa513016436724bcffc5c32b6656d8dcd1227 | [
"Apache-2.0",
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | pramulkant/https-github.com-android-art-intel-marshmallow | aef8d075498f3c19712403c271b55ea457e053ec | 87e8c22f248164780b92aaa0cdea14bf6cda3859 | refs/heads/master | 2021-01-12T05:00:35.783906 | 2016-11-07T08:34:41 | 2016-11-07T08:34:41 | 77,827,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,162 | h | /*
* Copyright (C) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ART_COMPILER_OPTIMIZING_PURE_INVOKES_ANALYSIS_H_
#define ART_COMPILER_OPTIMIZING_PURE_INVOKES_ANALYSIS_H_
#include "driver/dex_compilation_unit.h"
#include "graph_x86.h"
#include "ext_utility.h"
#include "nodes.h"
#include "optimization_x86.h"
#include <unordered_set>
#include <vector>
namespace art {
typedef std::vector<HInvokeStaticOrDirect*> ResolvedInvokes;
class HPureInvokesAnalysis : public HOptimization_X86 {
public:
HPureInvokesAnalysis(HGraph* graph,
OptimizingCompilerStats* stats = nullptr)
: HOptimization_X86(graph, true, kPureInvokesHoistingPassName, stats) {}
void Run() OVERRIDE;
private:
/**
* @brief Finds candidates for pure invokes hoisting.
* @details This method makes primary part of work. It emilinates pure
* invokes for which we have proved that it is legal, and also
* accumulates those that can potentially be hoisted to the vector.
* @param hoisting_candidates The vector where candidates for hoisting are accumulated.
* @return true, if we found at least one candidate for hoisting.
*/
bool ProcessPureInvokes(ResolvedInvokes& hoisting_candidates);
bool CalledNotPureMethodInChain(HInstruction* insn,
std::unordered_set<HInstruction*>& objects_with_not_pure_invokes);
bool HoistPureInvokes(ResolvedInvokes& hoisting_candidates);
/**
* @brief Checks whether the result of the instuction can be null.
* @param insn The instuction to check.
* @return true, if we proved that insn cannot return null.
*/
bool CanReturnNull(HInstruction* insn);
/**
* @brief Checks whether the call is an invoke of pure method.
* @param call The call to check.
* @return true, if call invokes a pure method.
*/
bool IsPureMethodInvoke(HInvokeStaticOrDirect* call);
/**
* @brief Pessimistically checks whether the invoke can return null.
* @param call The invoke.
* @return false, if we proved that the call never returns null.
* true, otherwise.
*/
bool IsInvokeThatCanReturnNull(HInvokeStaticOrDirect* call);
static constexpr const char* kPureInvokesHoistingPassName = "pure_invokes_analysis";
// Method reference -> known answer for this method.
SafeMap<const MethodReference, bool, MethodReferenceComparator> pure_invokes_;
SafeMap<const MethodReference, bool, MethodReferenceComparator> null_invokes_;
DISALLOW_COPY_AND_ASSIGN(HPureInvokesAnalysis);
};
} // namespace art
#endif // ART_COMPILER_OPTIMIZING_PURE_INVOKES_ANALYSIS_H_
| [
"aleksey.v.ignatenko@intel.com"
] | aleksey.v.ignatenko@intel.com |
f86416d20c42b06957d0df5a3b7b35fe026f0ae0 | 6de9cd8f17bf1fdb59dc9405266453d613782952 | /naredba.hpp | 59332a85773a31db80c21f88fed259bfcf16f93b | [] | no_license | MrDejan995/KK-16-Lua-Interpreter | 1279b9d68d17a01be5ef3eea6fb9bc8d60b47d9c | 089d5eb8e8734e02a9f5abe493a7af5c37549e57 | refs/heads/master | 2021-07-04T13:01:38.670931 | 2017-09-27T21:32:39 | 2017-09-27T21:32:39 | 105,071,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,941 | hpp | #ifndef NAREDBA_HPP
#define NAREDBA_HPP
#include <string>
#include <map>
#include <vector>
#include "izraz.hpp"
extern std::map<std::string, double> Promenljive;
class Naredba {
public:
virtual ~Naredba() {}
virtual void interpretacija() = 0;
};
class Dodela : public Naredba {
public:
Dodela(std::string imePromenljive, Izraz* izraz)
: _ime(imePromenljive), _izraz(izraz)
{}
~Dodela() {
delete _izraz;
}
void interpretacija();
private:
std::string _ime;
Izraz* _izraz;
};
class Blok : public Naredba {
public:
Blok(std::vector<Naredba*> naredbe)
: _naredbe(naredbe)
{}
~Blok() {
for (auto & n : _naredbe)
delete n;
}
void interpretacija();
private:
std::vector<Naredba*> _naredbe;
};
class Ispis : public Naredba {
public:
Ispis(Izraz* i)
: _izraz(i)
{}
~Ispis() {
delete _izraz;
}
void interpretacija();
private:
Izraz* _izraz;
};
class NaredbaIzraz : public Naredba {
public:
NaredbaIzraz(Izraz* i)
: _i(i)
{}
~NaredbaIzraz() {
delete _i;
}
void interpretacija();
private:
Izraz* _i;
};
class IfThenElse : public Naredba {
public:
IfThenElse(Izraz* uslov, Blok* thenNaredba, Blok* elseNaredba)
: _uslov(uslov), _thenNaredba(thenNaredba), _elseNaredba(elseNaredba)
{}
~IfThenElse() {
delete _uslov;
delete _thenNaredba;
delete _elseNaredba;
}
void interpretacija();
private:
Izraz* _uslov;
Blok* _thenNaredba;
Blok* _elseNaredba;
};
class While : public Naredba {
public:
While(Izraz* uslov, Blok* telo)
: _uslov(uslov), _telo(telo)
{}
~While() {
delete _uslov;
delete _telo;
}
void interpretacija();
private:
Izraz* _uslov;
Blok* _telo;
};
class PraznaNaredba : public Naredba {
public:
void interpretacija();
};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
2d4ae11a9cc37449930189af4bb9c61b4dd9b1c7 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/inetsrv/query/cifrmcom/rptcrpt.cxx | a5a79a58ded3b0aaa00ae75eec6e132406ce3c17 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,112 | cxx | //---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1997.
//
// File: rptcrpt.cxx
//
// Contents: CFwCorruptionEvent Class
//
// History: 14-Jan-97 mohamedn Created
//
//--------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
#include <cievtmsg.h>
#include <alocdbg.hxx>
#include <rptcrpt.hxx>
#include <fwevent.hxx>
//+-------------------------------------------------------------------------
//
// Method: CFwCorruptionEvent::CFwCorruptionEvent
//
// Purpose: encapsulates packaging an eventlog item and a stack trace
// to be posted in the eventlog via CDmFwEventItem class.
//
// Arguments: [pwszVolumeName] - Volume name from pStorage->GetVolumeName()
// [pwszComponent] - string to be displayed in eventlog
// [adviseStatus ] - a reference to ICiCAdviseStatus interface
//
// History: 14-Jan-97 MohamedN Created
//
//--------------------------------------------------------------------------
CFwCorruptionEvent::CFwCorruptionEvent( WCHAR const * pwszVolumeName,
WCHAR const * pwszComponent,
ICiCAdviseStatus & adviseStatus )
{
TRY
{
CDmFwEventItem item( EVENTLOG_INFORMATION_TYPE,
MSG_CI_CORRUPT_INDEX_COMPONENT,
3 );
item.AddArg ( pwszComponent );
item.AddArg ( pwszVolumeName);
char szStackTrace[4096];
GetStackTrace( szStackTrace,sizeof(szStackTrace));
item.AddArg( szStackTrace );
item.ReportEvent(adviseStatus);
}
CATCH ( CException, e )
{
ciDebugOut(( DEB_ERROR, "Error 0x%X in ReportCorruption::ReportCorruption(3)\n",
e.GetErrorCode() ));
}
END_CATCH
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
2a9b401b15fc2c72463ee197a2b236a31a94ee06 | b51aba43593259c337e7013efdd9a50aab635cd3 | /src/llmq/quorums_dkgsession.h | d6871e25b9b89c20e04907b2aea4e92fb94406e6 | [
"MIT"
] | permissive | Krekeler/documentchain | 731ae7e43e71ce567f3d18ff6b727b575957d839 | 196b03bcd5c523de3db79c1336a88cd3c6a2650b | refs/heads/master | 2023-01-10T08:46:33.277025 | 2022-12-28T20:53:24 | 2022-12-28T20:53:24 | 140,447,396 | 19 | 6 | MIT | 2020-04-18T15:04:21 | 2018-07-10T14:48:54 | C++ | UTF-8 | C++ | false | false | 11,691 | h | // Copyright (c) 2018-2021 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_LLMQ_QUORUMS_DKGSESSION_H
#define BITCOIN_LLMQ_QUORUMS_DKGSESSION_H
#include <consensus/params.h>
#include <net.h>
#include <batchedlogger.h>
#include <bls/bls_ies.h>
#include <bls/bls_worker.h>
#include <evo/deterministicmns.h>
#include <llmq/quorums_utils.h>
class UniValue;
namespace llmq
{
class CFinalCommitment;
class CDKGSession;
class CDKGSessionManager;
class CDKGPendingMessages;
class CDKGLogger : public CBatchedLogger
{
public:
CDKGLogger(const CDKGSession& _quorumDkg, const std::string& _func);
CDKGLogger(const std::string& _llmqTypeName, const uint256& _quorumHash, int _height, bool _areWeMember, const std::string& _func);
};
class CDKGContribution
{
public:
Consensus::LLMQType llmqType;
uint256 quorumHash;
uint256 proTxHash;
BLSVerificationVectorPtr vvec;
std::shared_ptr<CBLSIESMultiRecipientObjects<CBLSSecretKey>> contributions;
CBLSSignature sig;
public:
template<typename Stream>
inline void SerializeWithoutSig(Stream& s) const
{
s << llmqType;
s << quorumHash;
s << proTxHash;
s << *vvec;
s << *contributions;
}
template<typename Stream>
inline void Serialize(Stream& s) const
{
SerializeWithoutSig(s);
s << sig;
}
template<typename Stream>
inline void Unserialize(Stream& s)
{
BLSVerificationVector tmp1;
CBLSIESMultiRecipientObjects<CBLSSecretKey> tmp2;
s >> llmqType;
s >> quorumHash;
s >> proTxHash;
s >> tmp1;
s >> tmp2;
s >> sig;
vvec = std::make_shared<BLSVerificationVector>(std::move(tmp1));
contributions = std::make_shared<CBLSIESMultiRecipientObjects<CBLSSecretKey>>(std::move(tmp2));
}
uint256 GetSignHash() const
{
CHashWriter hw(SER_GETHASH, 0);
SerializeWithoutSig(hw);
hw << CBLSSignature();
return hw.GetHash();
}
};
class CDKGComplaint
{
public:
Consensus::LLMQType llmqType{Consensus::LLMQ_NONE};
uint256 quorumHash;
uint256 proTxHash;
std::vector<bool> badMembers;
std::vector<bool> complainForMembers;
CBLSSignature sig;
public:
CDKGComplaint() = default;
explicit CDKGComplaint(const Consensus::LLMQParams& params);
ADD_SERIALIZE_METHODS
template<typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
READWRITE(llmqType);
READWRITE(quorumHash);
READWRITE(proTxHash);
READWRITE(DYNBITSET(badMembers));
READWRITE(DYNBITSET(complainForMembers));
READWRITE(sig);
}
uint256 GetSignHash() const
{
CDKGComplaint tmp(*this);
tmp.sig = CBLSSignature();
return ::SerializeHash(tmp);
}
};
class CDKGJustification
{
public:
Consensus::LLMQType llmqType;
uint256 quorumHash;
uint256 proTxHash;
std::vector<std::pair<uint32_t, CBLSSecretKey>> contributions;
CBLSSignature sig;
public:
ADD_SERIALIZE_METHODS
template<typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
READWRITE(llmqType);
READWRITE(quorumHash);
READWRITE(proTxHash);
READWRITE(contributions);
READWRITE(sig);
}
uint256 GetSignHash() const
{
CDKGJustification tmp(*this);
tmp.sig = CBLSSignature();
return ::SerializeHash(tmp);
}
};
// each member commits to a single set of valid members with this message
// then each node aggregate all received premature commitments
// into a single CFinalCommitment, which is only valid if
// enough (>=minSize) premature commitments were aggregated
class CDKGPrematureCommitment
{
public:
Consensus::LLMQType llmqType{Consensus::LLMQ_NONE};
uint256 quorumHash;
uint256 proTxHash;
std::vector<bool> validMembers;
CBLSPublicKey quorumPublicKey;
uint256 quorumVvecHash;
CBLSSignature quorumSig; // threshold sig share of quorumHash+validMembers+pubKeyHash+vvecHash
CBLSSignature sig; // single member sig of quorumHash+validMembers+pubKeyHash+vvecHash
public:
CDKGPrematureCommitment() = default;
explicit CDKGPrematureCommitment(const Consensus::LLMQParams& params);
int CountValidMembers() const
{
return (int)std::count(validMembers.begin(), validMembers.end(), true);
}
public:
ADD_SERIALIZE_METHODS
template<typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
READWRITE(llmqType);
READWRITE(quorumHash);
READWRITE(proTxHash);
READWRITE(DYNBITSET(validMembers));
READWRITE(quorumPublicKey);
READWRITE(quorumVvecHash);
READWRITE(quorumSig);
READWRITE(sig);
}
uint256 GetSignHash() const
{
return CLLMQUtils::BuildCommitmentHash(llmqType, quorumHash, validMembers, quorumPublicKey, quorumVvecHash);
}
};
class CDKGMember
{
public:
CDKGMember(CDeterministicMNCPtr _dmn, size_t _idx);
CDeterministicMNCPtr dmn;
size_t idx;
CBLSId id;
std::set<uint256> contributions;
std::set<uint256> complaints;
std::set<uint256> justifications;
std::set<uint256> prematureCommitments;
std::set<uint256> badMemberVotes;
std::set<uint256> complaintsFromOthers;
bool bad{false};
bool badConnection{false};
bool weComplain{false};
bool someoneComplain{false};
};
/**
* The DKG session is a single instance of the DKG process. It is owned and called by CDKGSessionHandler, which passes
* received DKG messages to the session. The session is not persistent and will loose it's state (the whole object is
* discarded) when it finishes (after the mining phase) or is aborted.
*
* When incoming contributions are received and the verification vector is valid, it is passed to CDKGSessionManager
* which will store it in the evo DB. Secret key contributions which are meant for the local member are also passed
* to CDKGSessionManager to store them in the evo DB. If verification of the SK contribution initially fails, it is
* not passed to CDKGSessionManager. If the justification phase later gives a valid SK contribution from the same
* member, it is then passed to CDKGSessionManager and after this handled the same way.
*
* The contributions stored by CDKGSessionManager are then later loaded by the quorum instances and used for signing
* sessions, but only if the local node is a member of the quorum.
*/
class CDKGSession
{
friend class CDKGSessionHandler;
friend class CDKGSessionManager;
friend class CDKGLogger;
private:
const Consensus::LLMQParams& params;
CBLSWorker& blsWorker;
CBLSWorkerCache cache;
CDKGSessionManager& dkgManager;
const CBlockIndex* pindexQuorum{nullptr};
private:
std::vector<std::unique_ptr<CDKGMember>> members;
std::map<uint256, size_t> membersMap;
std::set<uint256> relayMembers;
BLSVerificationVectorPtr vvecContribution;
BLSSecretKeyVector skContributions;
BLSIdVector memberIds;
std::vector<BLSVerificationVectorPtr> receivedVvecs;
// these are not necessarily verified yet. Only trust in what was written to the DB
BLSSecretKeyVector receivedSkContributions;
/// Contains the received unverified/encrypted DKG contributions
std::vector<std::shared_ptr<CBLSIESMultiRecipientObjects<CBLSSecretKey>>> vecEncryptedContributions;
uint256 myProTxHash;
CBLSId myId;
size_t myIdx{(size_t)-1};
// all indexed by msg hash
// we expect to only receive a single vvec and contribution per member, but we must also be able to relay
// conflicting messages as otherwise an attacker might be able to broadcast conflicting (valid+invalid) messages
// and thus split the quorum. Such members are later removed from the quorum.
mutable CCriticalSection invCs;
std::map<uint256, CDKGContribution> contributions;
std::map<uint256, CDKGComplaint> complaints;
std::map<uint256, CDKGJustification> justifications;
std::map<uint256, CDKGPrematureCommitment> prematureCommitments;
mutable CCriticalSection cs_pending;
std::vector<size_t> pendingContributionVerifications;
// filled by ReceivePrematureCommitment and used by FinalizeCommitments
std::set<uint256> validCommitments;
public:
CDKGSession(const Consensus::LLMQParams& _params, CBLSWorker& _blsWorker, CDKGSessionManager& _dkgManager) :
params(_params), blsWorker(_blsWorker), cache(_blsWorker), dkgManager(_dkgManager) {}
bool Init(const CBlockIndex* pindexQuorum, const std::vector<CDeterministicMNCPtr>& mns, const uint256& _myProTxHash);
size_t GetMyMemberIndex() const { return myIdx; }
/**
* The following sets of methods are for the first 4 phases handled in the session. The flow of message calls
* is identical for all phases:
* 1. Execute local action (e.g. create/send own contributions)
* 2. PreVerify incoming messages for this phase. Preverification means that everything from the message is checked
* that does not require too much resources for verification. This specifically excludes all CPU intensive BLS
* operations.
* 3. CDKGSessionHandler will collect pre verified messages in batches and perform batched BLS signature verification
* on these.
* 4. ReceiveMessage is called for each pre verified message with a valid signature. ReceiveMessage is also
* responsible for further verification of validity (e.g. validate vvecs and SK contributions).
*/
// Phase 1: contribution
void Contribute(CDKGPendingMessages& pendingMessages);
void SendContributions(CDKGPendingMessages& pendingMessages);
bool PreVerifyMessage(const CDKGContribution& qc, bool& retBan) const;
void ReceiveMessage(const CDKGContribution& qc, bool& retBan);
void VerifyPendingContributions();
// Phase 2: complaint
void VerifyAndComplain(CDKGPendingMessages& pendingMessages);
void VerifyConnectionAndMinProtoVersions();
void SendComplaint(CDKGPendingMessages& pendingMessages);
bool PreVerifyMessage(const CDKGComplaint& qc, bool& retBan) const;
void ReceiveMessage(const CDKGComplaint& qc, bool& retBan);
// Phase 3: justification
void VerifyAndJustify(CDKGPendingMessages& pendingMessages);
void SendJustification(CDKGPendingMessages& pendingMessages, const std::set<uint256>& forMembers);
bool PreVerifyMessage(const CDKGJustification& qj, bool& retBan) const;
void ReceiveMessage(const CDKGJustification& qj, bool& retBan);
// Phase 4: commit
void VerifyAndCommit(CDKGPendingMessages& pendingMessages);
void SendCommitment(CDKGPendingMessages& pendingMessages);
bool PreVerifyMessage(const CDKGPrematureCommitment& qc, bool& retBan) const;
void ReceiveMessage(const CDKGPrematureCommitment& qc, bool& retBan);
// Phase 5: aggregate/finalize
std::vector<CFinalCommitment> FinalizeCommitments();
bool AreWeMember() const { return !myProTxHash.IsNull(); }
void MarkBadMember(size_t idx);
void RelayInvToParticipants(const CInv& inv) const;
public:
CDKGMember* GetMember(const uint256& proTxHash) const;
private:
bool ShouldSimulateError(const std::string& type);
};
void SetSimulatedDKGErrorRate(const std::string& type, double rate);
} // namespace llmq
#endif // BITCOIN_LLMQ_QUORUMS_DKGSESSION_H
| [
"mail@krekeler.de"
] | mail@krekeler.de |
9ea6fe6ea563b66e6a7d29c0acd9efa48936f6b7 | b310d3cf58a826237507c3574e7d8b55103302ff | /src/framework/Font.h | 62e454d130b872dacaf40ab131e7549e5b0a14d3 | [] | no_license | rdemoparty/stardust | e88cb76979460dcc418990167a642ae89422ea90 | cc03b7d2eb667f49cc5c2ae66d9c043efdfc3d14 | refs/heads/master | 2021-01-17T07:46:00.396255 | 2014-12-23T10:45:45 | 2014-12-23T10:45:45 | 24,285,985 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | h | #pragma once
#include <GLheaders.h>
#include <stb_truetype.h>
#include <string>
#include <glm/vec4.hpp>
namespace Acidrain {
class Font {
public:
Font(std::string fontFile, float fontSize = 32.0f);
~Font();
void print(float x, float y, const char* text, const glm::vec4& color);
private:
GLuint atlasId;
float fontSize;
stbtt_bakedchar cdata[96];
};
} // namespace Acidrain | [
"benishor@gmail.com"
] | benishor@gmail.com |
05f7aecf6f0090d9528e5566344b2fee2023b59b | ff62e0a836b7e0c1627d24f5e01f1782922d0c1c | /fluorender/FluoRender/Cluster/exmax.h | 2b0a4d44cec9adb8f47878b1227d5d62cef3ef4b | [
"MIT"
] | permissive | mcuma/fluorender | 9c86185d0b7cb145e34c363457a6b05eb681051a | 23ce813aa47924242168124d8c39e30d38a45ed8 | refs/heads/master | 2020-04-03T12:58:57.920207 | 2018-10-31T22:23:29 | 2018-10-31T22:23:29 | 155,270,480 | 0 | 0 | null | 2018-10-29T19:40:21 | 2018-10-29T19:40:21 | null | UTF-8 | C++ | false | false | 2,944 | h | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2014 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef FL_Exmax_h
#define FL_Exmax_h
#include "ClusterMethod.h"
#include <FLIVR/Matrix.h>
namespace FL
{
class ClusterExmax : public ClusterMethod
{
public:
ClusterExmax();
~ClusterExmax();
void SetClnum(unsigned int num)
{ m_clnum = num; }
void SetMaxiter(size_t num)
{ m_max_iter = num; }
bool Execute();
float GetProb();
void SetWeakResult(bool result = true)
{ m_weak_result = result; }
//for test
void GenerateNewColors(void* label,
size_t nx, size_t ny, size_t nz);
void GenerateNewColors2(void* label,
size_t nx, size_t ny, size_t nz);
private:
//cluster number
unsigned int m_clnum;
//try to match the cluster
bool m_weak_result;
//measure for convergence
float m_eps;
//maximum iteration number
size_t m_max_iter;
//parameters to estimate
typedef struct
{
double tau;
FLIVR::Point mean;
FLIVR::Mat3 covar;
} Params;
//all paramters to estimate
std::vector<Params> m_params;
std::vector<Params> m_params_prv;
//likelihood
double m_likelihood;
double m_likelihood_prv;
//membership probabilities
std::vector<std::vector<double>> m_mem_prob;//0-idx: comps; 1-idx: points
std::vector<std::vector<double>> m_mem_prob_prv;//for comparison
std::vector<double> m_count;//count for changes
//histogram
typedef struct
{
double value;//starting value of the range
size_t count;
} EmBin;
std::vector<EmBin> m_histogram;
size_t m_bins;
private:
void Initialize();
void Expectation();
double Gaussian(FLIVR::Point &p, FLIVR::Point &m, FLIVR::Mat3 &s);
void Maximization();
bool Converge();
void GenResult();
void GenHistogram(size_t bins);
void GenUncertainty(double delta, bool output = false);
};
}
#endif//FL_Exmax_h | [
"basisunus@yahoo.com"
] | basisunus@yahoo.com |
d6d189a9bd1f168d8ca3f66ee1771e2315c01f92 | 2a88b58673d0314ed00e37ab7329ab0bbddd3bdc | /blazetest/src/mathtest/tdvecdmatmult/V7bM7x13b.cpp | 9790391d7194ff07bc77ff97c08def4ce371117e | [
"BSD-3-Clause"
] | permissive | shiver/blaze-lib | 3083de9600a66a586e73166e105585a954e324ea | 824925ed21faf82bb6edc48da89d3c84b8246cbf | refs/heads/master | 2020-09-05T23:00:34.583144 | 2016-08-24T03:55:17 | 2016-08-24T03:55:17 | 66,765,250 | 2 | 1 | NOASSERTION | 2020-04-06T05:02:41 | 2016-08-28T11:43:51 | C++ | UTF-8 | C++ | false | false | 3,703 | cpp | //=================================================================================================
/*!
// \file src/mathtest/tdvecdmatmult/V7bM7x13b.cpp
// \brief Source file for the V7bM7x13b dense vector/dense matrix multiplication math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticMatrix.h>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/tdvecdmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'V7bM7x13b'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::StaticVector<TypeB,7UL> V7b;
typedef blaze::StaticMatrix<TypeB,7UL,13UL> M7x13b;
// Creator type definitions
typedef blazetest::Creator<V7b> CV7b;
typedef blazetest::Creator<M7x13b> CM7x13b;
// Running the tests
RUN_TDVECDMATMULT_OPERATION_TEST( CV7b(), CM7x13b() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
a5c1c66b00dc8049085e1fa279a1f02367539785 | a25f5cca8caf95687d39e846fd7f2b15562bc6a7 | /2021_01/2021_01_23/011_Deep_Constructor.cpp | a02ff02307f1a13048795e338528b094c3d6e33c | [] | no_license | ITlearning/ROKA_CPP | 241dd0debab9eb03ca36bf2087b8d45d34760906 | f268eaa92d290c4f3bb0392bbf5ae5b7fd1742af | refs/heads/main | 2023-03-20T08:19:41.951503 | 2021-03-06T08:02:06 | 2021-03-06T08:02:06 | 324,778,256 | 1 | 0 | null | 2021-01-31T15:04:23 | 2020-12-27T14:24:20 | C++ | UTF-8 | C++ | false | false | 1,260 | cpp | // 깊은 복사 생성자를 가진 정상적인 Person 클래스
#include <iostream>
#include <cstring>
using namespace std;
class Person {
char* name;
int id;
public:
Person(int id, const char* name); // 생성자
Person(const Person& person); // 복사 생성자
~Person();
void changeName(const char* name);
void show() { cout << id << ',' << name << endl; }
};
Person::Person(int id, const char* name) {
this->id = id;
int len = strlen(name);
this->name = new char [len+1];
strcpy(this->name, name);
}
Person::Person(const Person& person) {
this->id = person.id;
int len = strlen(person.name);
this->name = new char [len+1];
strcpy(this->name, person.name);
cout << "복사 생성자 실행, 원본 객체의 이름 " << this->name << endl;
}
Person::~Person() {
if(name) {
delete [] name;
}
}
void Person::changeName(const char* name) {
if(strlen(name) > strlen(this->name))
return;
strcpy(this->name, name);
}
int main() {
Person father(1, "Kitae");
Person daughter(father);
cout << "daughter 객체 생성 직후 ----" << endl;
father.show();
daughter.show();
daughter.changeName("Grace");
cout << "daughter 이름을 Grace로 변경한 후 ----" << endl;
father.show();
daughter.show();
return 0;
} | [
"yo7504@naver.com"
] | yo7504@naver.com |
71d67d0854a9dee1607422a942ad7f22d795ecc8 | 31a0b0749c30ff37c3a72592387f9d8195de4bd6 | /cpp/src/ray/runtime/abstract_ray_runtime.h | ef4468466694021a113fcd93a16a487922b39725 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | longshotsyndicate/ray | 15100bad514b602a3fa39bfe205288e7bec75d90 | 3341fae573868338b665bcea8a1c4ee86b702751 | refs/heads/master | 2023-01-28T15:16:00.401509 | 2022-02-18T05:35:47 | 2022-02-18T05:35:47 | 163,961,795 | 1 | 1 | Apache-2.0 | 2023-01-14T08:01:02 | 2019-01-03T11:03:35 | Python | UTF-8 | C++ | false | false | 4,135 | h | // Copyright 2020-2021 The Ray Authors.
//
// 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.
#pragma once
#include <ray/api/ray_runtime.h>
#include <msgpack.hpp>
#include <mutex>
#include "../config_internal.h"
#include "../util/process_helper.h"
#include "./object/object_store.h"
#include "./task/task_executor.h"
#include "./task/task_submitter.h"
#include "ray/common/id.h"
#include "ray/core_worker/context.h"
#include "ray/core_worker/core_worker.h"
namespace ray {
namespace internal {
using ray::core::WorkerContext;
class RayIntentionalSystemExitException : public RayException {
public:
RayIntentionalSystemExitException(const std::string &msg) : RayException(msg){};
};
class AbstractRayRuntime : public RayRuntime {
public:
virtual ~AbstractRayRuntime(){};
void Put(std::shared_ptr<msgpack::sbuffer> data, ObjectID *object_id);
void Put(std::shared_ptr<msgpack::sbuffer> data, const ObjectID &object_id);
void Put(ray::rpc::ErrorType type, const ObjectID &object_id);
std::string Put(std::shared_ptr<msgpack::sbuffer> data);
std::shared_ptr<msgpack::sbuffer> Get(const std::string &id);
std::vector<std::shared_ptr<msgpack::sbuffer>> Get(const std::vector<std::string> &ids);
std::vector<bool> Wait(const std::vector<std::string> &ids, int num_objects,
int timeout_ms);
std::string Call(const RemoteFunctionHolder &remote_function_holder,
std::vector<ray::internal::TaskArg> &args,
const CallOptions &task_options);
std::string CreateActor(const RemoteFunctionHolder &remote_function_holder,
std::vector<ray::internal::TaskArg> &args,
const ActorCreationOptions &create_options);
std::string CallActor(const RemoteFunctionHolder &remote_function_holder,
const std::string &actor,
std::vector<ray::internal::TaskArg> &args,
const CallOptions &call_options);
void AddLocalReference(const std::string &id);
void RemoveLocalReference(const std::string &id);
std::string GetActorId(const std::string &actor_name);
void KillActor(const std::string &str_actor_id, bool no_restart);
void ExitActor();
ray::PlacementGroup CreatePlacementGroup(
const ray::PlacementGroupCreationOptions &create_options);
void RemovePlacementGroup(const std::string &group_id);
bool WaitPlacementGroupReady(const std::string &group_id, int timeout_seconds);
const TaskID &GetCurrentTaskId();
const JobID &GetCurrentJobID();
virtual const WorkerContext &GetWorkerContext();
static std::shared_ptr<AbstractRayRuntime> GetInstance();
static std::shared_ptr<AbstractRayRuntime> DoInit();
static void DoShutdown();
const std::unique_ptr<ray::gcs::GlobalStateAccessor> &GetGlobalStateAccessor();
bool WasCurrentActorRestarted();
virtual ActorID GetCurrentActorID() { return ActorID::Nil(); }
virtual std::vector<PlacementGroup> GetAllPlacementGroups();
virtual PlacementGroup GetPlacementGroupById(const std::string &id);
virtual PlacementGroup GetPlacementGroup(const std::string &name);
protected:
std::unique_ptr<TaskSubmitter> task_submitter_;
std::unique_ptr<TaskExecutor> task_executor_;
std::unique_ptr<ObjectStore> object_store_;
std::unique_ptr<ray::gcs::GlobalStateAccessor> global_state_accessor_;
private:
static std::shared_ptr<AbstractRayRuntime> abstract_ray_runtime_;
void Execute(const TaskSpecification &task_spec);
PlacementGroup GeneratePlacementGroup(const std::string &str);
};
} // namespace internal
} // namespace ray
| [
"noreply@github.com"
] | noreply@github.com |
99c5ab007bea00f5f2b751b0b01a5581e5bf616a | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_2071_collectd-5.6.2.cpp | 05a8814392e6f747556faed0b3e865e627c572d0 | [] | 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 | 291 | cpp | static int dispatch_speed(CURL *curl, CURLINFO info, value_list_t *vl) {
CURLcode code;
value_t v;
code = curl_easy_getinfo(curl, info, &v.gauge);
if (code != CURLE_OK)
return -1;
v.gauge *= 8;
vl->values = &v;
vl->values_len = 1;
return plugin_dispatch_values(vl);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
a60783307e45650dd80788eadf78e060e770b59b | 06954096d7b4d0732379f6354f8a355af6070831 | /src/game/server/swarm/asw_marine_speech.cpp | 3830f4449f731594c17b4b4fc96f433de3956d1e | [] | no_license | Nightgunner5/Jastian-Summer | 9ee590bdac8d5cf281f844d1be3f1f5709ae4b91 | 22749cf0839bbb559bd13ec7e6a5af4458b8bdb7 | refs/heads/master | 2016-09-06T15:55:32.938564 | 2011-04-16T17:57:12 | 2011-04-16T17:57:12 | 1,446,629 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 36,747 | cpp | #include "cbase.h"
#include "asw_marine_speech.h"
#include "asw_marine.h"
#include "asw_marine_resource.h"
#include "asw_gamerules.h"
#include "engine/IEngineSound.h"
#include "SoundEmitterSystem/isoundemittersystembase.h"
#include "soundchars.h"
#include "ndebugoverlay.h"
#include "asw_game_resource.h"
#include "te_effect_dispatch.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern ISoundEmitterSystemBase *soundemitterbase;
// chatter probabilites (1/x)
#define BASE_CHATTER_SELECTION_CHANCE 5.0f
#define CHATTER_INTERVAL 3.0f
#define ASW_INTERVAL_CHATTER_INCOMING 30.0f
#define ASW_INTERVAL_CHATTER_NO_AMMO 30.0f
#define ASW_INTERVAL_FF 12.0f
#define ASW_CALM_CHATTER_TIME 10.0f
// chance of doing a direction hold position shout (from 0 to 1)
#define ASW_DIRECTIONAL_HOLDING_CHATTER 0.5f
ConVar asw_debug_marine_chatter("asw_debug_marine_chatter", "0", 0, "Show debug info about when marine chatter is triggered");
#define ACTOR_SARGE (1 << 0)
#define ACTOR_WILDCAT (1 << 1)
#define ACTOR_FAITH (1 << 2)
#define ACTOR_CRASH (1 << 3)
#define ACTOR_JAEGER (1 << 4)
#define ACTOR_WOLFE (1 << 5)
#define ACTOR_BASTILLE (1 << 6)
#define ACTOR_VEGAS (1 << 7)
#define ACTOR_FLYNN (1 << 8)
#define ACTOR_ALL (ACTOR_SARGE | ACTOR_JAEGER | ACTOR_WILDCAT | ACTOR_WOLFE | ACTOR_FAITH | ACTOR_BASTILLE | ACTOR_CRASH | ACTOR_FLYNN)
int CASW_MarineSpeech::s_CurrentConversation = CONV_NONE;
int CASW_MarineSpeech::s_CurrentConversationChatterStage = -1;
int CASW_MarineSpeech::s_iCurrentConvLine = -1;
CHandle<CASW_Marine> CASW_MarineSpeech::s_hActor1 = NULL;
CHandle<CASW_Marine> CASW_MarineSpeech::s_hActor2 = NULL;
CHandle<CASW_Marine> CASW_MarineSpeech::s_hCurrentActor = NULL;
static int s_Actor1Indices[ASW_NUM_CONVERSATIONS]={
0, // CONV_NONE,
ACTOR_CRASH | ACTOR_VEGAS, // CONV_SYNUP,
ACTOR_CRASH, // CONV_CRASH_COMPLAIN,
ACTOR_FAITH | ACTOR_BASTILLE, // CONV_MEDIC_COMPLAIN,
ACTOR_BASTILLE, // CONV_HEALING_CRASH
ACTOR_VEGAS, // CONV_TEQUILA,
ACTOR_CRASH, // CONV_CRASH_IDLE,
ACTOR_FAITH | ACTOR_BASTILLE, // CONV_SERIOUS_INJURY,
ACTOR_JAEGER, // CONV_STILL_BREATHING,
ACTOR_SARGE, // CONV_SARGE_IDLE,
ACTOR_CRASH, // CONV_BIG_ALIEN,
ACTOR_WILDCAT | ACTOR_WOLFE, // CONV_AUTOGUN
ACTOR_WOLFE, // CONV_WOLFE_BEST,
ACTOR_SARGE, // CONV_SARGE_JAEGER_CONV1, (jaeger starts)
ACTOR_JAEGER, // CONV_SARGE_JAEGER_CONV2, (sarge starts)
ACTOR_WILDCAT, // CONV_WILDCAT_KILL,
ACTOR_WOLFE, // CONV_WOLFE_KILL
ACTOR_SARGE, //CONV_COMPLIMENT_JAEGER, // 17
ACTOR_JAEGER, //CONV_COMPLIMENT_SARGE, // 18
ACTOR_WILDCAT, //CONV_COMPLIMENT_WOLFE, // 19
ACTOR_WOLFE, //CONV_COMPLIMENT_WILDCAT, // 20
};
static int s_Actor2Indices[ASW_NUM_CONVERSATIONS]={
0, // CONV_NONE,
ACTOR_FAITH | ACTOR_BASTILLE, // CONV_SYNUP,
ACTOR_BASTILLE, // CONV_CRASH_COMPLAIN,
ACTOR_ALL, // CONV_MEDIC_COMPLAIN,
ACTOR_CRASH, // CONV_HEALING_CRASH
ACTOR_ALL &~ ACTOR_FLYNN, // CONV_TEQUILA,
ACTOR_SARGE | ACTOR_JAEGER | ACTOR_BASTILLE, // CONV_CRASH_IDLE,
ACTOR_ALL, // CONV_SERIOUS_INJURY,
ACTOR_ALL &~ (ACTOR_SARGE | ACTOR_FLYNN | ACTOR_WOLFE), // CONV_STILL_BREATHING,
ACTOR_SARGE | ACTOR_CRASH, // CONV_SARGE_IDLE,
ACTOR_SARGE, // CONV_BIG_ALIEN,
ACTOR_SARGE | ACTOR_JAEGER, // CONV_AUTOGUN
ACTOR_WILDCAT, // CONV_WOLFE_BEST,
ACTOR_JAEGER, // CONV_SARGE_JAEGER_CONV1, (sarge is 2nd)
ACTOR_SARGE, // CONV_SARGE_JAEGER_CONV2, (jaeger is 2nd)
ACTOR_WOLFE, // CONV_WILDCAT_KILL,
ACTOR_WILDCAT, // CONV_WOLFE_KILL
ACTOR_JAEGER, //CONV_COMPLIMENT_JAEGER, // 17
ACTOR_SARGE, //CONV_COMPLIMENT_SARGE, // 18
ACTOR_WOLFE, //CONV_COMPLIMENT_WOLFE, // 19
ACTOR_WILDCAT, //CONV_COMPLIMENT_WILDCAT, // 20
};
static int s_ConvChatterLine1[ASW_NUM_CONVERSATIONS]={
-1, // CONV_NONE,
CHATTER_SYNUP_SPOTTED, // CONV_SYNUP,
CHATTER_CRASH_COMPLAIN, // CONV_CRASH_COMPLAIN,
CHATTER_MEDIC_COMPLAIN, // CONV_MEDIC_COMPLAIN,
CHATTER_HEALING_CRASH, // CONV_HEALING_CRASH
CHATTER_TEQUILA_START, // CONV_TEQUILA,
CHATTER_CRASH_IDLE, // CONV_CRASH_IDLE,
CHATTER_SERIOUS_INJURY, // CONV_SERIOUS_INJURY,
CHATTER_STILL_BREATHING, // CONV_STILL_BREATHING,
CHATTER_SARGE_IDLE, // CONV_SARGE_IDLE,
CHATTER_BIG_ALIEN_DEAD, // CONV_BIG_ALIEN,
CHATTER_AUTOGUN, // CONV_AUTOGUN
CHATTER_WOLFE_BEST, // CONV_WOLFE_BEST,
CHATTER_SARGE_JAEGER_CONV_1, // CONV_SARGE_JAEGER_CONV1, (jaeger starts)
CHATTER_SARGE_JAEGER_CONV_2, // CONV_SARGE_JAEGER_CONV2, (sarge starts)
CHATTER_WILDCAT_KILL, // CONV_WILDCAT_KILL,
CHATTER_WOLFE_KILL, // CONV_WOLFE_KILL
CHATTER_COMPLIMENTS_JAEGER, //CONV_COMPLIMENT_JAEGER, // 17
CHATTER_COMPLIMENTS_SARGE, //CONV_COMPLIMENT_SARGE, // 18
CHATTER_COMPLIMENTS_WOLFE, //CONV_COMPLIMENT_WOLFE, // 19
CHATTER_COMPLIMENTS_WILDCAT, //CONV_COMPLIMENT_WILDCAT, // 20
};
static int s_ConvChatterLine2[ASW_NUM_CONVERSATIONS]={
-1, // CONV_NONE,
CHATTER_SYNUP_REPLY, // CONV_SYNUP,
CHATTER_CRASH_COMPLAIN_REPLY, // CONV_CRASH_COMPLAIN,
CHATTER_MEDIC_COMPLAIN_REPLY, // CONV_MEDIC_COMPLAIN,
CHATTER_HEALING_CRASH_REPLY, // CONV_HEALING_CRASH
CHATTER_TEQUILA_REPLY, // CONV_TEQUILA,
CHATTER_CRASH_IDLE_REPLY, // CONV_CRASH_IDLE,
CHATTER_SERIOUS_INJURY_REPLY, // CONV_SERIOUS_INJURY,
CHATTER_STILL_BREATHING_REPLY, // CONV_STILL_BREATHING,
CHATTER_SARGE_IDLE_REPLY, // CONV_SARGE_IDLE,
CHATTER_BIG_ALIEN_REPLY, // CONV_BIG_ALIEN,
CHATTER_AUTOGUN_REPLY, // CONV_AUTOGUN
CHATTER_WOLFE_BEST_REPLY, // CONV_WOLFE_BEST,
CHATTER_SARGE_JAEGER_CONV_1_REPLY, // CONV_SARGE_JAEGER_CONV1, (jaeger starts)
CHATTER_SARGE_JAEGER_CONV_2_REPLY, // CONV_SARGE_JAEGER_CONV2, (sarge starts)
CHATTER_WILDCAT_KILL_REPLY_AHEAD, // CONV_WILDCAT_KILL, NOTE: OR BEHIND...
CHATTER_WOLFE_KILL_REPLY_AHEAD, // CONV_WOLFE_KILL
-1, //CONV_COMPLIMENT_JAEGER, // 17
-1, //CONV_COMPLIMENT_SARGE, // 18
-1, //CONV_COMPLIMENT_WOLFE, // 19
-1, //CONV_COMPLIMENT_WILDCAT, // 20
};
static int s_ConvNumStages[ASW_NUM_CONVERSATIONS]={
0, // CONV_NONE,
2, // CONV_SYNUP,
3, // CONV_CRASH_COMPLAIN,
2, // CONV_MEDIC_COMPLAIN,
3, // CONV_HEALING_CRASH
3, // CONV_TEQUILA,
2, // CONV_CRASH_IDLE,
3, // CONV_SERIOUS_INJURY,
3, // CONV_STILL_BREATHING,
3, // CONV_SARGE_IDLE,
3, // CONV_BIG_ALIEN, // todo:should be 4?
3, // CONV_AUTOGUN
3, // CONV_WOLFE_BEST,
3, // CONV_SARGE_JAEGER_CONV1, (jaeger starts)
3, // CONV_SARGE_JAEGER_CONV2, (sarge starts)
3, // CONV_WILDCAT_KILL, NOTE: OR BEHIND...
3, // CONV_WOLFE_KILL
1, //CONV_COMPLIMENT_JAEGER, // 17
1, //CONV_COMPLIMENT_SARGE, // 18
1, //CONV_COMPLIMENT_WOLFE, // 19
1, //CONV_COMPLIMENT_WILDCAT, // 20
};
/*
CHATTER_TEQUILA_REPLY_SARGE, // Vegas only
CHATTER_TEQUILA_REPLY_JAEGER, // Vegas only
CHATTER_TEQUILA_REPLY_WILDCAT, // Vegas only
CHATTER_TEQUILA_REPLY_WOLFE, // Vegas only
CHATTER_TEQUILA_REPLY_FAITH, // Vegas only
CHATTER_TEQUILA_REPLY_BASTILLE, // Vegas only
CHATTER_SERIOUS_INJURY_FOLLOW_UP, // faith/bastille only
CHATTER_FIRST_BLOOD_START, // vegas only
CHATTER_FIRST_BLOOD_WIN, // vegas only
CHATTER_WILDCAT_KILL_REPLY_BEHIND,
CHATTER_WOLFE_KILL_REPLY_BEHIND,
*/
bool CASW_MarineSpeech::StartConversation(int iConversation, CASW_Marine *pMarine, CASW_Marine *pSecondMarine)
{
if (!pMarine || !pMarine->GetMarineProfile() || iConversation < 0 || iConversation > CONV_COMPLIMENT_WILDCAT
|| pMarine->GetHealth() <= 0 || pMarine->IsInfested() || pMarine->IsOnFire())
return false;
if ( !ASWGameResource() )
return false;
CASW_Game_Resource *pGameResource = ASWGameResource();
// check this marine can start this conversation
if (! ((1 << pMarine->GetMarineProfile()->m_ProfileIndex) & s_Actor1Indices[iConversation]) )
return false;
CASW_Marine *pChosen = NULL;
if (pSecondMarine != NULL && pSecondMarine->GetMarineProfile()!=NULL)
{
// if the other actor was specified, check they can do the conversation
if (! ((1 << pSecondMarine->GetMarineProfile()->m_ProfileIndex) & s_Actor2Indices[iConversation]) )
return false;
if (pSecondMarine->IsInfested() || pMarine->IsOnFire())
return false;
pChosen = pSecondMarine;
}
else
{
// try and find another actor to chat with
int iNearby = 0;
for (int i=0;i<pGameResource->GetMaxMarineResources();i++)
{
CASW_Marine_Resource *pMR = pGameResource->GetMarineResource(i);
CASW_Marine *pOtherMarine = pMR ? pMR->GetMarineEntity() : NULL;
if (pOtherMarine && pOtherMarine != pMarine && (pOtherMarine->GetAbsOrigin().DistTo(pMarine->GetAbsOrigin()) < 600)
&& pOtherMarine->GetHealth() > 0 && !pOtherMarine->IsInfested() && !pOtherMarine->IsOnFire() && pOtherMarine->GetMarineProfile()
&& ((1 << pOtherMarine->GetMarineProfile()->m_ProfileIndex) & s_Actor2Indices[iConversation]) )
iNearby++;
}
if (iNearby > 0)
{
int iChosen = random->RandomInt(0, iNearby-1);
for (int i=0;i<pGameResource->GetMaxMarineResources();i++)
{
CASW_Marine_Resource *pMR = pGameResource->GetMarineResource(i);
CASW_Marine *pOtherMarine = pMR ? pMR->GetMarineEntity() : NULL;
if (pOtherMarine && pOtherMarine != pMarine && (pOtherMarine->GetAbsOrigin().DistTo(pMarine->GetAbsOrigin()) < 600)
&& pOtherMarine->GetHealth() > 0 && !pOtherMarine->IsInfested() && !pOtherMarine->IsOnFire() && pOtherMarine->GetMarineProfile()
&& ((1 << pOtherMarine->GetMarineProfile()->m_ProfileIndex) & s_Actor2Indices[iConversation]) )
{
if (iChosen <= 0)
{
pChosen = pOtherMarine;
break;
}
iChosen--;
}
}
}
}
if (!pChosen && iConversation != CONV_SYNUP) // synup doesn't need 2 people to start the conv
return false;
if (asw_debug_marine_chatter.GetBool())
Msg("%f: Starting conv %d successfully, between marines %s and %s\n", gpGlobals->curtime, iConversation, pMarine->GetMarineProfile()->m_ShortName,
pChosen ? pChosen->GetMarineProfile()->m_ShortName : "no-one");
s_CurrentConversation = iConversation;
s_CurrentConversationChatterStage = 0;
s_hCurrentActor = pMarine;
s_hActor1 = pMarine;
s_hActor2 = pChosen;
s_iCurrentConvLine = s_ConvChatterLine1[iConversation];
pMarine->GetMarineSpeech()->QueueChatter(s_iCurrentConvLine, gpGlobals->curtime, gpGlobals->curtime + 5.0f);
return true;
}
void CASW_MarineSpeech::StopConversation()
{
if (asw_debug_marine_chatter.GetBool())
Msg("Stopping conversation");
s_CurrentConversation = CONV_NONE;
s_CurrentConversationChatterStage = 0;
s_hCurrentActor = NULL;
s_hActor1 = NULL;
s_hActor2 = NULL;
}
CASW_MarineSpeech::CASW_MarineSpeech(CASW_Marine *pMarine)
{
m_pMarine = pMarine;
m_fPersonalChatterTime = 0;
m_SpeechQueue.Purge();
m_fFriendlyFireTime = 0;
}
CASW_MarineSpeech::~CASW_MarineSpeech()
{
}
bool CASW_MarineSpeech::TranslateChatter(int &iChatterType, CASW_Marine_Profile *pProfile)
{
if (!pProfile)
return false;
// special holding position translations
if (iChatterType == CHATTER_HOLDING_POSITION)
{
if (random->RandomFloat() < ASW_DIRECTIONAL_HOLDING_CHATTER)
FindDirectionalHoldingChatter(iChatterType);
}
// random chance of playing some chatters
else if (iChatterType == CHATTER_SELECTION)
{
// check for using injured version
if (m_pMarine->IsWounded())
iChatterType = CHATTER_SELECTION_INJURED;
}
return true;
}
bool CASW_MarineSpeech::ForceChatter(int iChatterType, int iTimerType)
{
if (!m_pMarine || !m_pMarine->GetMarineResource() || (m_pMarine->GetHealth()<=0 && iChatterType != CHATTER_DIE))
return false;
CASW_Marine_Profile *pProfile = m_pMarine->GetMarineResource()->GetProfile();
if (!pProfile)
return false;
if (!TranslateChatter(iChatterType, pProfile))
return false;
// check for discarding chatter if it only has a random chance of playing and we don't hit
if (random->RandomFloat() > pProfile->m_fChatterChance[iChatterType])
return true;
// if marine doesn't have this line, then don't try playing it
const char *szChatter = pProfile->m_Chatter[iChatterType];
if (szChatter[0] == '\0')
return false;
InternalPlayChatter(m_pMarine, szChatter, iTimerType, iChatterType);
return true;
}
bool CASW_MarineSpeech::Chatter(int iChatterType, int iSubChatter, CBasePlayer *pOnlyForPlayer)
{
#ifdef JASTIANSUMMER_DLL
if ( m_pMarine->GetEntityNameAsCStr() && !Q_stricmp( m_pMarine->GetEntityNameAsCStr(), "#asw_name_sarge" ) )
return false; // Player does not talk.
#endif
if (iChatterType < 0 || iChatterType >= NUM_CHATTER_LINES)
{
AssertMsg1( false, "Faulty chatter type %d\n", iChatterType );
return false;
}
if (!m_pMarine || !m_pMarine->GetMarineResource() || (m_pMarine->GetHealth()<=0 && iChatterType != CHATTER_DIE))
{
AssertMsg( false, "Absent marine tried to chatter\n" );
return false;
}
CASW_Marine_Profile *pProfile = m_pMarine->GetMarineResource()->GetProfile();
if (!pProfile)
{
AssertMsg1( false, "Marine %s is missing a profile\n", m_pMarine->GetDebugName() );
return false;
}
if (gpGlobals->curtime < GetTeamChatterTime())
return false;
if (!TranslateChatter(iChatterType, pProfile))
return false;
// check for discarding chatter if some marines are in the middle of a conversation
if (s_CurrentConversation != CONV_NONE)
{
CASW_Marine *pCurrentActor = (s_CurrentConversationChatterStage == 1) ? s_hActor2.Get() : s_hActor1.Get();
int iCurrentConvLine = s_iCurrentConvLine;
// if this isn't the right speaker saying the right line...
if (iChatterType != iCurrentConvLine || m_pMarine != pCurrentActor)
return false;
}
// check for discarding chatter if it only has a random chance of playing and we don't hit
if (random->RandomFloat() > pProfile->m_fChatterChance[iChatterType])
return true;
if (iChatterType == CHATTER_FIRING_AT_ALIEN)
{
if (gpGlobals->curtime < GetIncomingChatterTime())
return false;
SetIncomingChatterTime(gpGlobals->curtime + ASW_INTERVAL_CHATTER_INCOMING);
}
// if marine doesn't have this line, then don't try playing it
const char *szChatter = pProfile->m_Chatter[iChatterType];
if (szChatter[0] == '\0')
return false;
InternalPlayChatter(m_pMarine, szChatter, ASW_CHATTER_TIMER_TEAM, iChatterType, iSubChatter, pOnlyForPlayer);
return true;
}
bool CASW_MarineSpeech::PersonalChatter(int iChatterType)
{
if (iChatterType < 0 || iChatterType >= NUM_CHATTER_LINES)
return false;
if (!m_pMarine || !m_pMarine->GetMarineResource() || (m_pMarine->GetHealth()<=0 && iChatterType != CHATTER_DIE))
return false;
CASW_Marine_Profile *pProfile = m_pMarine->GetMarineResource()->GetProfile();
if (!pProfile)
return false;
if (gpGlobals->curtime < GetPersonalChatterTime())
return false;
if (!TranslateChatter(iChatterType, pProfile))
return false;
// check for discarding chatter if it only has a random chance of playing and we don't hit
if (random->RandomFloat() > pProfile->m_fChatterChance[iChatterType])
return true;
// if marine doesn't have this line, then don't try playing it
const char *szChatter = pProfile->m_Chatter[iChatterType];
if (szChatter[0] == '\0')
return false;
InternalPlayChatter(m_pMarine, szChatter, ASW_CHATTER_TIMER_PERSONAL, iChatterType);
return true;
}
void CASW_MarineSpeech::InternalPlayChatter(CASW_Marine* pMarine, const char* szSoundName, int iSetTimer, int iChatterType, int iSubChatter, CBasePlayer *pOnlyForPlayer)
{
if (!pMarine || !ASWGameRules() || iSubChatter >= NUM_SUB_CHATTERS)
return;
if (ASWGameRules()->GetGameState() > ASW_GS_INGAME)
return;
// only allow certain chatters when marine is on fire
if (pMarine->IsOnFire())
{
if (iChatterType != CHATTER_FRIENDLY_FIRE &&
iChatterType != CHATTER_MEDIC &&
iChatterType != CHATTER_INFESTED &&
iChatterType != CHATTER_PAIN_SMALL &&
iChatterType != CHATTER_PAIN_LARGE &&
iChatterType != CHATTER_DIE &&
iChatterType != CHATTER_ON_FIRE)
return;
}
if (asw_debug_marine_chatter.GetBool())
Msg("%s playing chatter %s %d\n", pMarine->GetMarineProfile()->m_ShortName, szSoundName, iChatterType);
// select a sub chatter
int iMaxChatter = pMarine->GetMarineProfile()->m_iChatterCount[iChatterType];
if (iMaxChatter <= 0)
{
Msg("Warning, couldn't play chatter of type %d as no sub chatters of that type for this marine\n", iChatterType);
return;
}
if (iSubChatter < 0)
iSubChatter = random->RandomInt(0, iMaxChatter - 1);
// asw temp comment
CPASAttenuationFilter filter( pMarine );
//CSoundParameters params;
//char chatterbuffer[128];
//Q_snprintf(chatterbuffer, sizeof(chatterbuffer), "%s%d", szSoundName, iSubChatter);
//if ( pMarine->GetParametersForSound( chatterbuffer, params, NULL ) )
{
//if (!params.soundname[0])
//return;
if (iSetTimer != ASW_CHATTER_TIMER_NONE)
{
// asw temp comment
//char *skipped = PSkipSoundChars( params.soundname );
//float duration = enginesound->GetSoundDuration( skipped );
//Msg("ingame duration for sound %s is %f\n", skipped, duration);
float duration = pMarine->GetMarineProfile()->m_fChatterDuration[iChatterType][iSubChatter];
if (iSetTimer == ASW_CHATTER_TIMER_TEAM)
{
// make sure no one else talks until this is done
SetTeamChatterTime(gpGlobals->curtime + duration);
SetPersonalChatterTime(gpGlobals->curtime + duration);
}
else // ASW_CHATTER_TIMER_PERSONAL
{
SetPersonalChatterTime(gpGlobals->curtime + duration);
}
}
//EmitSound_t ep( params );
//pMarine->EmitSound( filter, pMarine->entindex(), ep );
// user messages based speech
CEffectData data;
data.m_vOrigin = pMarine->GetAbsOrigin();
data.m_nEntIndex = pMarine->entindex();
data.m_nDamageType = iChatterType;
data.m_nMaterial = iSubChatter;
if (!pOnlyForPlayer)
{
CPASFilter filter( data.m_vOrigin );
filter.SetIgnorePredictionCull(true);
DispatchEffect( filter, 0.0, "ASWSpeech", data );
}
else
{
CSingleUserRecipientFilter filter( pOnlyForPlayer );
filter.SetIgnorePredictionCull(true);
DispatchEffect( filter, 0.0, "ASWSpeech", data );
}
}
}
void CASW_MarineSpeech::Precache()
{
if (!m_pMarine || !m_pMarine->GetMarineProfile())
{
//Msg("Error: Attempted to precache marine speech when either marine is null or marine has no marine resource.");
return;
}
CASW_Marine_Profile *profile= m_pMarine->GetMarineProfile();
// asw temp comment of speech
profile->PrecacheSpeech(m_pMarine);
}
float CASW_MarineSpeech::GetTeamChatterTime()
{
if (!ASWGameRules())
return 0;
return ASWGameRules()->GetChatterTime();
}
float CASW_MarineSpeech::GetIncomingChatterTime()
{
if (!ASWGameRules())
return 0;
return ASWGameRules()->GetIncomingChatterTime();
}
void CASW_MarineSpeech::SetTeamChatterTime(float f)
{
if ( asw_debug_marine_chatter.GetBool() )
Msg( "%f:SetTeamChatterTime %f\n", gpGlobals->curtime, f );
if (ASWGameRules())
ASWGameRules()->SetChatterTime(f);
}
void CASW_MarineSpeech::SetIncomingChatterTime(float f)
{
if ( asw_debug_marine_chatter.GetBool() )
Msg( "%f:SetIncomingChatterTime %f\n", gpGlobals->curtime, f );
if (ASWGameRules())
ASWGameRules()->SetIncomingChatterTime(f);
}
void CASW_MarineSpeech::SetPersonalChatterTime(float f)
{
if ( asw_debug_marine_chatter.GetBool() )
Msg( "%f:SetPersonalChatterTime %f\n", gpGlobals->curtime, f );
m_fPersonalChatterTime = f;
}
bool CASW_MarineSpeech::FindDirectionalHoldingChatter(int &iChatterType)
{
if ( !m_pMarine )
return false;
Vector vecFacing;
QAngle angHolding(0, m_pMarine->GetHoldingYaw(), 0);
AngleVectors(angHolding, &vecFacing);
// first check there's no other marines standing in front of us
CASW_Game_Resource *pGameResource = ASWGameResource();
if (!pGameResource)
return false;
int m = pGameResource->GetMaxMarineResources();
for (int i=0;i<m;i++)
{
CASW_Marine_Resource *pMR = pGameResource->GetMarineResource(i);
if (!pMR || !pMR->GetMarineEntity())
continue;
CASW_Marine *pOtherMarine = pMR->GetMarineEntity();
Vector diff = pOtherMarine->GetAbsOrigin() - m_pMarine->GetAbsOrigin();
if (diff.Length() > 1000) // if they're too far away, don't count them as blocking our covering area
continue;
// check they're in front
diff.z = 0;
diff.NormalizeInPlace();
if (diff.Dot(vecFacing) < 0.3f)
continue;
// this marine is in front, so we can't do a directional shout
return false;
}
// do a few traces to roughly check we're not facing a wall
trace_t tr;
if (asw_debug_marine_chatter.GetBool())
NDebugOverlay::Line( m_pMarine->WorldSpaceCenter(), m_pMarine->WorldSpaceCenter() + vecFacing * 300.0f, 255, 0, 0, false, 5.0f );
UTIL_TraceLine(m_pMarine->WorldSpaceCenter(), m_pMarine->WorldSpaceCenter() + vecFacing * 300.0f, MASK_SOLID, m_pMarine, COLLISION_GROUP_NONE, &tr);
if (tr.fraction < 1.0f)
return false;
angHolding[YAW] += 30;
AngleVectors(angHolding, &vecFacing);
if (asw_debug_marine_chatter.GetBool())
NDebugOverlay::Line( m_pMarine->WorldSpaceCenter(), m_pMarine->WorldSpaceCenter() + vecFacing * 200.0f, 255, 0, 0, false, 5.0f );
UTIL_TraceLine(m_pMarine->WorldSpaceCenter(), m_pMarine->WorldSpaceCenter() + vecFacing * 200.0f, MASK_SOLID, m_pMarine, COLLISION_GROUP_NONE, &tr);
if (tr.fraction < 1.0f)
return false;
angHolding[YAW] -= 60;
AngleVectors(angHolding, &vecFacing);
if (asw_debug_marine_chatter.GetBool())
NDebugOverlay::Line( m_pMarine->WorldSpaceCenter(), m_pMarine->WorldSpaceCenter() + vecFacing * 200.0f, 255, 0, 0, false, 5.0f );
UTIL_TraceLine(m_pMarine->WorldSpaceCenter(), m_pMarine->WorldSpaceCenter() + vecFacing * 200.0f, MASK_SOLID, m_pMarine, COLLISION_GROUP_NONE, &tr);
if (tr.fraction < 1.0f)
return false;
// okay, we're good to do a directional, let's see which one to do
float fYaw = anglemod(m_pMarine->GetHoldingYaw());
if (fYaw < 40 || fYaw > 320)
iChatterType = CHATTER_HOLDING_EAST;
else if (fYaw > 50 && fYaw < 130)
iChatterType = CHATTER_HOLDING_NORTH;
else if (fYaw > 140 && fYaw < 220)
iChatterType = CHATTER_HOLDING_WEST;
else if (fYaw > 230 && fYaw < 310)
iChatterType = CHATTER_HOLDING_SOUTH;
else
return false; // wasn't facing close enough to a cardinal
return true;
}
void CASW_MarineSpeech::QueueChatter(int iChatterType, float fPlayTime, float fMaxPlayTime, CBasePlayer *pOnlyForPlayer)
{
if (!m_pMarine || m_pMarine->GetHealth() <= 0)
return;
// check this speech isn't already in the queue
int iCount = m_SpeechQueue.Count();
for (int i=iCount-1;i>=0;i--)
{
if (m_SpeechQueue[i].iChatterType == iChatterType)
return;
}
if (iChatterType == CHATTER_HOLDING_POSITION) // if marine is holding
{
int iCount = m_SpeechQueue.Count();
for (int i=iCount-1;i>=0;i--)
{
if (m_SpeechQueue[i].iChatterType == CHATTER_USE) // then remove any 'confirming move order' type speech queued up
m_SpeechQueue.Remove(i);
}
}
else if (iChatterType == CHATTER_USE) // if marine is confirming move order
{
int iCount = m_SpeechQueue.Count();
for (int i=iCount-1;i>=0;i--)
{
if (m_SpeechQueue[i].iChatterType == CHATTER_HOLDING_POSITION) // then remove any holding position speech queued up
m_SpeechQueue.Remove(i);
}
}
// don't FF fire too frequently
if (iChatterType == CHATTER_FRIENDLY_FIRE)
{
if (gpGlobals->curtime < m_fFriendlyFireTime)
return;
m_fFriendlyFireTime = gpGlobals->curtime + ASW_INTERVAL_FF;
}
if (asw_debug_marine_chatter.GetBool())
Msg("%f: queuing speech %d at time %f\n", gpGlobals->curtime, iChatterType, fPlayTime);
CASW_Queued_Speech entry;
entry.iChatterType = iChatterType;
entry.fPlayTime = fPlayTime;
entry.fMaxPlayTime = fMaxPlayTime;
entry.hOnlyForPlayer = pOnlyForPlayer;
m_SpeechQueue.AddToTail(entry);
}
void CASW_MarineSpeech::Update()
{
if (!m_pMarine)
return;
int iCount = m_SpeechQueue.Count();
// loop backwards because we might remove one
for (int i=iCount-1;i>=0;i--)
{
if (gpGlobals->curtime >= m_SpeechQueue[i].fPlayTime)
{
// try to play the queued speech
if (asw_debug_marine_chatter.GetBool())
Msg("%f: trying to play queued speech %d\n", gpGlobals->curtime, m_SpeechQueue[i].iChatterType);
bool bPlay = true;
if ((m_SpeechQueue[i].iChatterType == CHATTER_HOLDING_POSITION
|| m_SpeechQueue[i].iChatterType == CHATTER_USE)
&& m_pMarine->IsInhabited())
{
bPlay = false;
}
if (!bPlay)
{
if (asw_debug_marine_chatter.GetBool())
Msg(" removing queued speech; inappropriate to play it now (marine probably inhabited and this is an AI line)\n");
m_SpeechQueue.Remove(i);
continue;
}
if (Chatter(m_SpeechQueue[i].iChatterType, -1, m_SpeechQueue[i].hOnlyForPlayer.Get()))
{
if (s_CurrentConversation != CONV_NONE)
{
CASW_Marine *pCurrentActor = (s_CurrentConversationChatterStage == 1) ? s_hActor2.Get() : s_hActor1.Get();
int iCurrentConvLine = s_iCurrentConvLine;
// if we just finished the currently queued conversation line...
if (m_SpeechQueue[i].iChatterType == iCurrentConvLine && m_pMarine == pCurrentActor)
{
s_CurrentConversationChatterStage++;
int iNumStages = s_ConvNumStages[s_CurrentConversation];
/*
CHATTER_WILDCAT_KILL_REPLY_BEHIND,
CHATTER_WOLFE_KILL_REPLY_BEHIND,
*/
// check all the actors are alive still, etc and we're not at the end of the conversation
if (s_CurrentConversationChatterStage >= iNumStages
|| !s_hActor1.Get() || s_hActor1.Get()->GetHealth()<=0
|| !s_hActor2.Get() || s_hActor2.Get()->GetHealth()<=0)
{
StopConversation();
}
else
{
// queue up the next line
pCurrentActor = (s_CurrentConversationChatterStage == 1) ? s_hActor2.Get() : s_hActor1.Get();
iCurrentConvLine = (s_CurrentConversationChatterStage == 0) ? s_ConvChatterLine1[s_CurrentConversation] : s_ConvChatterLine2[s_CurrentConversation];
// make wolfe/wildcat pick the right line in their conv
if (s_CurrentConversation == CONV_WILDCAT_KILL)
{
if (asw_debug_marine_chatter.GetBool())
Msg("CONV_WILDCAT_KILL, stage %d\n", s_CurrentConversationChatterStage);
if (s_CurrentConversationChatterStage == 1) // wolfe replying, does he have more or less kills
{
if (GetWildcatAhead())
iCurrentConvLine = CHATTER_WILDCAT_KILL_REPLY_BEHIND;
else
iCurrentConvLine = CHATTER_WILDCAT_KILL_REPLY_AHEAD;
}
else if (s_CurrentConversationChatterStage == 2) // wildcat following up
{
if (GetWildcatAhead())
iCurrentConvLine = CHATTER_WILDCAT_KILL_REPLY_AHEAD;
else
iCurrentConvLine = CHATTER_WILDCAT_KILL_REPLY_BEHIND;
}
}
else if (s_CurrentConversation == CONV_WOLFE_KILL)
{
if (asw_debug_marine_chatter.GetBool())
Msg("CONV_WILDCAT_KILL, stage %d\n", s_CurrentConversationChatterStage);
if (s_CurrentConversationChatterStage == 1) // wildcat replying, does he have more or less kills
{
if (GetWildcatAhead())
iCurrentConvLine = CHATTER_WOLFE_KILL_REPLY_AHEAD;
else
iCurrentConvLine = CHATTER_WOLFE_KILL_REPLY_BEHIND;
}
else if (s_CurrentConversationChatterStage == 2) // wolfe following up
{
if (GetWildcatAhead())
iCurrentConvLine = CHATTER_WOLFE_KILL_REPLY_BEHIND;
else
iCurrentConvLine = CHATTER_WOLFE_KILL_REPLY_AHEAD;
}
}
if (s_CurrentConversationChatterStage == 2)
{
if (s_CurrentConversation == CONV_TEQUILA && s_hActor2.Get()->GetMarineProfile())
{
int iProfileIndex = s_hActor2.Get()->GetMarineProfile()->m_ProfileIndex;
// change the line to one appropriate for who we're talking to
if (iProfileIndex == 0) iCurrentConvLine = CHATTER_TEQUILA_REPLY_SARGE;
else if (iProfileIndex == 4) iCurrentConvLine = CHATTER_TEQUILA_REPLY_JAEGER;
else if (iProfileIndex == 1) iCurrentConvLine = CHATTER_TEQUILA_REPLY_WILDCAT;
else if (iProfileIndex == 5) iCurrentConvLine = CHATTER_TEQUILA_REPLY_WOLFE;
else if (iProfileIndex == 2) iCurrentConvLine = CHATTER_TEQUILA_REPLY_FAITH;
else if (iProfileIndex == 6) iCurrentConvLine = CHATTER_TEQUILA_REPLY_BASTILLE;
else iCurrentConvLine = -1;
}
else if (s_CurrentConversation == CONV_SERIOUS_INJURY)
{
iCurrentConvLine = CHATTER_SERIOUS_INJURY_FOLLOW_UP;
}
}
if (iCurrentConvLine == -1 || s_hActor2.Get()==NULL)
StopConversation();
else
{
if (asw_debug_marine_chatter.GetBool())
Msg("Queuing up the next line in this conversation %d\n", iCurrentConvLine);
s_iCurrentConvLine = iCurrentConvLine;
pCurrentActor->GetMarineSpeech()->QueueChatter(iCurrentConvLine, GetTeamChatterTime() + 0.05f, GetTeamChatterTime() + 60.0f);
}
}
}
}
if (asw_debug_marine_chatter.GetBool())
Msg(" and removing the speech (%d) since it played ok (or failed the chance to play)\n", m_SpeechQueue[i].iChatterType);
m_SpeechQueue.Remove(i);
}
else
{
if (asw_debug_marine_chatter.GetBool())
Msg(" didn't play ok, trying to requeue\n");
m_SpeechQueue[i].fPlayTime = GetTeamChatterTime() + 0.05f; // try and queue it up for when we next have a gap
if (m_SpeechQueue[i].fPlayTime > m_SpeechQueue[i].fMaxPlayTime) // if it's too late, then abort
{
if (asw_debug_marine_chatter.GetBool())
Msg(" but out of time!\n");
m_SpeechQueue.Remove(i);
}
}
}
}
}
bool CASW_MarineSpeech::GetWildcatAhead()
{
int iWildcatKills = 0;
int iWolfeKills = 0;
if ( !ASWGameResource() )
return false;
CASW_Game_Resource *pGameResource = ASWGameResource();
for (int i=0;i<pGameResource->GetMaxMarineResources();i++)
{
CASW_Marine_Resource *pMR = pGameResource->GetMarineResource(i);
if (pMR && pMR->GetProfile() && pMR->GetProfile()->m_VoiceType == ASW_VOICE_WILDCAT)
iWildcatKills = pMR->m_iAliensKilled;
else if (pMR && pMR->GetProfile() && pMR->GetProfile()->m_VoiceType == ASW_VOICE_WOLFE)
iWolfeKills = pMR->m_iAliensKilled;
}
return iWildcatKills > iWolfeKills;
}
struct MarineFlavorSpeech
{
unsigned char uchChatterType;
unsigned char uchSubChatter;
};
const int g_nNumFlavorSpeech = 25;
MarineFlavorSpeech g_MarineFlavorSpeech[ g_nNumFlavorSpeech ][ ASW_VOICE_TYPE_TOTAL ] =
{
{
{ 44, 1 }, // Sarge
{ 1,0 }, // Jaeger
{ 3,1 }, // Wildcat
{ 0,0 }, // Wolf
{ 0,1 }, // Faith
{ 2,2 }, // Bastille
{ 0,1 }, // Crash
{ 0,0 }, // Flynn
{ 0,1 }, // Vegas
},
{
{ 123, 0 }, // Sarge
{ 3,5 }, // Jaeger
{ 3,2 }, // Wildcat
{ 1,0 }, // Wolf
{ 1,3 }, // Faith
{ 2,3 }, // Bastille
{ 1,1 }, // Crash
{ 1,1 }, // Flynn
{ 1,2 }, // Vegas
},
{
{ 123, 2 }, // Sarge
{ 3,10 }, // Jaeger
{ 3,4 }, // Wildcat
{ 1,3 }, // Wolf
{ 2,2 }, // Faith
{ 3,0 }, // Bastille
{ 2,0 }, // Crash
{ 3,0 }, // Flynn
{ 2,1 }, // Vegas
},
{
{ 104, 0 }, // Sarge
{ 3,12 }, // Jaeger
{ 3,5 }, // Wildcat
{ 2,0 }, // Wolf
{ 2,0 }, // Faith
{ 3,8 }, // Bastille
{ 3,3 }, // Crash
{ 3,2 }, // Flynn
{ 3,0 }, // Vegas
},
{
{ 104, 1 }, // Sarge
{ 3,13 }, // Jaeger
{ 3,6 }, // Wildcat
{ 3,1 }, // Wolf
{ 3,4 }, // Faith
{ 3,10 }, // Bastille
{ 3,4 }, // Crash
{ 123,0 }, // Flynn
{ 3,2 }, // Vegas
},
{
{ 114, 1 }, // Sarge
{ 3,9 }, // Jaeger
{ 0,0 }, // Wildcat
{ 3,0 }, // Wolf
{ 3,7 }, // Faith
{ 3,11 }, // Bastille
{ 27,2 }, // Crash
{ 3,5 }, // Flynn
{ 3,8 }, // Vegas
},
{
{ 2, 2 }, // Sarge
{ 3,7 }, // Jaeger
{ 1,2 }, // Wildcat
{ 3,2 }, // Wolf
{ 3,3 }, // Faith
{ 3,13 }, // Bastille
{ 54,3 }, // Crash
{ 3,3 }, // Flynn
{ 3,5 }, // Vegas
},
{
{ 3, 5 }, // Sarge
{ 3,6 }, // Jaeger
{ 45,1 }, // Wildcat
{ 3,3 }, // Wolf
{ 3,8 }, // Faith
{ 3,0 }, // Bastille
{ 72,4 }, // Crash
{ 3,1 }, // Flynn
{ 6,3 }, // Vegas
},
{
{ 3, 7 }, // Sarge
{ 3,2 }, // Jaeger
{ 54,1 }, // Wildcat
{ 3,6 }, // Wolf
{ 3,9 }, // Faith
{ 3,15 }, // Bastille
{ 73,1 }, // Crash
{ 5,3 }, // Flynn
{ 45,1 }, // Vegas
},
{
{ 3, 8 }, // Sarge
{ 5,2 }, // Jaeger
{ 61,0 }, // Wildcat
{ 3,4 }, // Wolf
{ 54,2 }, // Faith
{ 3,5 }, // Bastille
{ 75,4 }, // Crash
{ 75,0 }, // Flynn
{ 47,2 }, // Vegas
},
{
{ 3, 12 }, // Sarge
{ 54,3 }, // Jaeger
{ 3,3 }, // Wildcat
{ 3,5 }, // Wolf
{ 54,3 }, // Faith
{ 45,2 }, // Bastille
{ 75,4 }, // Crash
{ 61,0 }, // Flynn
{ 54,2 }, // Vegas
},
{
{ 3, 2 }, // Sarge
{ 54,4 }, // Jaeger
{ 108,1 }, // Wildcat
{ 3,6 }, // Wolf
{ 71,2 }, // Faith
{ 54,1 }, // Bastille
{ 61,2 }, // Crash
{ 123,0 }, // Flynn
{ 54,0 }, // Vegas
},
{
{ 3, 9 }, // Sarge
{ 108,0 }, // Jaeger
{ 63,0 }, // Wildcat
{ 66,2 }, // Wolf
{ 84,1 }, // Faith
{ 69,13 }, // Bastille
{ 82,0 }, // Crash
{ 85,0 }, // Flynn
{ 54,3 }, // Vegas
},
{
{ 47, 1 }, // Sarge
{ 101,0 }, // Jaeger
{ 4,0 }, // Wildcat
{ 123,3 }, // Wolf
{ 0,1 }, // Faith
{ 69,18 }, // Bastille
{ 96,0 }, // Crash
{ 0,0 }, // Flynn
{ 72,0 }, // Vegas
},
{
{ 52, 2 }, // Sarge
{ 1,0 }, // Jaeger
{ 3,1 }, // Wildcat
{ 110,8 }, // Wolf
{ 1,3 }, // Faith
{ 69,10 }, // Bastille
{ 2,1 }, // Crash
{ 85, }, // Flynn
{ 73,7 }, // Vegas
},
{
{ 3, 13 }, // Sarge
{ 3,5 }, // Jaeger
{ 3,2 }, // Wildcat
{ 85,0 }, // Wolf
{ 2,2 }, // Faith
{ 71,0 }, // Bastille
{ 3,5 }, // Crash
{ 1,1 }, // Flynn
{ 75,4 }, // Vegas
},
{
{ 3, 14 }, // Sarge
{ 3,10 }, // Jaeger
{ 3,4 }, // Wildcat
{ 0,0 }, // Wolf
{ 2,0 }, // Faith
{ 61,0 }, // Bastille
{ 0,1 }, // Crash
{ 3,0 }, // Flynn
{ 61,0 }, // Vegas
},
{
{ 3, 14 }, // Sarge
{ 3,12 }, // Jaeger
{ 3,5 }, // Wildcat
{ 1,0 }, // Wolf
{ 3,4 }, // Faith
{ 123,11 }, // Bastille
{ 1,3 }, // Crash
{ 3,2 }, // Flynn
{ 61,1 }, // Vegas
},
{
{ 3, 16 }, // Sarge
{ 3,13 }, // Jaeger
{ 3,6 }, // Wildcat
{ 1,3 }, // Wolf
{ 3,7 }, // Faith
{ 123,7 }, // Bastille
{ 2,0 }, // Crash
{ 1,1 }, // Flynn
{ 61,2 }, // Vegas
},
{
{ 3, 17 }, // Sarge
{ 3,9 }, // Jaeger
{ 0,0 }, // Wildcat
{ 2,0 }, // Wolf
{ 3,3 }, // Faith
{ 83,0 }, // Bastille
{ 3,3 }, // Crash
{ 3,5 }, // Flynn
{ 63,0 }, // Vegas
},
{
{ 61, 1 }, // Sarge
{ 3,7 }, // Jaeger
{ 1,2 }, // Wildcat
{ 3,1 }, // Wolf
{ 3,8 }, // Faith
{ 84,1 }, // Bastille
{ 3,4 }, // Crash
{ 3,3 }, // Flynn
{ 112,1 }, // Vegas
},
{
{ 61, 2 }, // Sarge
{ 3,6 }, // Jaeger
{ 45,1 }, // Wildcat
{ 3,0 }, // Wolf
{ 3,0 }, // Faith
{ 87,0 }, // Bastille
{ 27,2 }, // Crash
{ 3,1 }, // Flynn
{ 112,0 }, // Vegas
},
{
{ 1, 1 }, // Sarge
{ 3,2 }, // Jaeger
{ 54,1 }, // Wildcat
{ 3,2 }, // Wolf
{ 3,9 }, // Faith
{ 98,1 }, // Bastille
{ 54,3 }, // Crash
{ 5,3 }, // Flynn
{ 88,0 }, // Vegas
},
{
{ 1, 3 }, // Sarge
{ 5,2 }, // Jaeger
{ 61,0 }, // Wildcat
{ 3,4 }, // Wolf
{ 54,2 }, // Faith
{ 99,0 }, // Bastille
{ 72,4 }, // Crash
{ 75,0 }, // Flynn
{ 99,0 }, // Vegas
},
{
{ 38, 2 }, // Sarge
{ 54,3 }, // Jaeger
{ 3,3 }, // Wildcat
{ 3,5 }, // Wolf
{ 54,3 }, // Faith
{ 2,2 }, // Bastille
{ 73,1 }, // Crash
{ 61,0 }, // Flynn
{ 102,0 }, // Vegas
},
};
bool CASW_MarineSpeech::ClientRequestChatter(int iChatterType, int iSubChatter)
{
CASW_Marine_Profile *pProfile = m_pMarine->GetMarineResource()->GetProfile();
if ( !pProfile )
{
return false;
}
if ( iChatterType == -1 )
{
int nRandomSpeech = RandomInt( 0, g_nNumFlavorSpeech - 1 );
iChatterType = g_MarineFlavorSpeech[ nRandomSpeech ][ pProfile->GetVoiceType() ].uchChatterType;
iSubChatter = g_MarineFlavorSpeech[ nRandomSpeech ][ pProfile->GetVoiceType() ].uchSubChatter;
}
// todo: disallow some chatter types (misleading or annoying ones like onfire, infested, etc)
if (iChatterType < 0 || iChatterType >= NUM_CHATTER_LINES)
{
AssertMsg1( false, "Faulty chatter type %d\n", iChatterType );
return false;
}
if (!m_pMarine || !m_pMarine->GetMarineResource() || (m_pMarine->GetHealth()<=0 && iChatterType != CHATTER_DIE))
{
AssertMsg( false, "Absent marine tried to chatter\n" );
return false;
}
if (gpGlobals->curtime < GetTeamChatterTime())
{
return false;
}
//if (!TranslateChatter(iChatterType, pProfile))
//return false;
// if marine doesn't have this line, then don't try playing it
const char *szChatter = pProfile->m_Chatter[iChatterType];
if (szChatter[0] == '\0')
{
return false;
}
InternalPlayChatter(m_pMarine, szChatter, ASW_CHATTER_TIMER_TEAM, iChatterType, iSubChatter);
return true;
}
bool CASW_MarineSpeech::AllowCalmConversations(int iConversation)
{
if (ASWGameRules() && ASWGameRules()->m_fLastFireTime > gpGlobals->curtime - ASW_CALM_CHATTER_TIME)
return false;
return true;
} | [
"nightgunner5@llamaslayers.net"
] | nightgunner5@llamaslayers.net |
955d80406c7d12b2208d73f3a33863dca938558b | d0ba116cf6870503c20d541a40a5f203563dd14a | /problemA.cpp | bb440e266660cbac87351aab5b564375c3541fab | [] | no_license | owaisNazir22/CodeForces678 | 76bfc3e88b578119ba5ca9948c1d9723eac7e740 | 21e82c37ee577b950ec055250b9f08fc0ff4bc80 | refs/heads/master | 2023-01-04T10:42:16.263917 | 2020-10-26T14:47:20 | 2020-10-26T14:47:20 | 307,404,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 390 | cpp | #include <bits/stdc++.h>
using namespace std;
int main () {
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector <int> v (n);
for (int i = 0; i < n; i++) cin >> v [i];
int sum = 0;
for (int i = 0; i < n; i++) sum += v [i];
if (sum == m) cout << "YES" << endl;
else cout << "NO" << endl;
}
} | [
"owaisnazir22@gmail.com"
] | owaisnazir22@gmail.com |
573a7379641057bbba8bfd7d1ff17179f4a0eeb4 | 25ee3becee33b6b2e77f325fb35cda90e563530b | /leetcode/141.cpp | 69075891093e2967a4d3899e993d0a00aaac68cc | [] | no_license | roy4801/solved_problems | fe973d8eb13ac4ebbb3bc8504a10fb1259da8d7a | b0de694516823a3ee8af88932452f40c287e9d10 | refs/heads/master | 2023-08-16T21:43:11.108043 | 2023-08-16T14:25:12 | 2023-08-16T14:25:12 | 127,760,119 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,509 | cpp | /*
* Leetcode Easy 141. Linked List Cycle
* author: roy4801
* AC(C++)
*/
#include <bits/stdc++.h>
using namespace std;
#include "helper.h"
typedef pair<int, int> P;
typedef long long int LL;
#define PB push_back
#define MP make_pair
#define X first
#define Y second
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
set<ListNode*> s;
bool intuition(ListNode *head)
{
ListNode *cur = head;
while(cur)
{
if(s.count(cur))
{
return true;
}
s.insert(cur);
cur = cur->next;
}
return false;
}
bool floyd(ListNode *head)
{
ListNode *a = head, *b = head;
while(b && b->next)
{
a = a->next;
b = b->next->next;
if(a == b)
return true;
}
return false;
}
bool hasCycle(ListNode *head)
{
return floyd(head);
}
};
int main()
{
// vector<int> v = {3,2,0,-4};
// int pos = 1;
vector<int> v = {1,2};
int pos = 0;
// vector<int> v = {1};
// int pos = -1;
//
ListNode *h = build_sll(v), *last = h, *c = h;
while(last->next)
last = last->next;
while(pos > 0 && c->next)
{
c = c->next;
pos--;
}
//
cout << Solution{}.hasCycle(h) << '\n';
} | [
"a82611141@gmail.com"
] | a82611141@gmail.com |
ec37693b1633242282ce9eacb4a3031fe5ee347c | 5dd577121662880d9c88bd8d3d4eccbf2678178e | /src/utils/math_utils.cpp | 76ce43667db949d1eb925cafec5e7e13356bbdc3 | [
"MIT"
] | permissive | artbataev/end2end | 7125e7040f027efbd82dc2eab0566d42beb219e0 | b30eadaf9c66c33f56f9adf73b3c15508bd69131 | refs/heads/master | 2021-03-27T13:30:06.334005 | 2020-10-30T21:09:21 | 2020-10-30T21:09:21 | 123,341,247 | 37 | 5 | MIT | 2020-10-22T19:58:42 | 2018-02-28T20:54:21 | Python | UTF-8 | C++ | false | false | 65 | cpp | // Copyright 2019 Vladimir Bataev
#include "utils/math_utils.h"
| [
"artbataev@gmail.com"
] | artbataev@gmail.com |
cb1d2f0ee3e3118338759ce5c3c564ccb9baf742 | 42402cf1029724cd03095840af66cc55759e0def | /contracts/vm_api/system.cpp | e84f38d4616fd9ec97efe41b94c78285c90e264b | [
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | learnforpractice/eos | 17ca01946d19ba3c19da9174ae6e814c4c358e95 | 24649e9325d1f3b4c89c0f21d91d74d9c41f27d2 | refs/heads/master | 2022-08-31T12:55:43.092397 | 2019-12-19T15:37:30 | 2019-12-19T15:37:30 | 101,472,470 | 0 | 0 | null | 2017-08-26T08:10:13 | 2017-08-26T08:10:13 | null | UTF-8 | C++ | false | false | 1,015 | cpp | /**
* @file
* @copyright defined in eos/LICENSE
*/
#include <eosiolib/system.h>
#include "vm_api.h"
extern "C" {
void eosio_abort() {
get_vm_api()->eosio_abort();
}
void eosio_assert( uint32_t test, const char* msg ) {
EOSIO_ASSERT( test, msg );
}
void eosio_assert_message( uint32_t test, const char* msg, uint32_t msg_len ) {
get_vm_api()->eosio_assert_message( test, msg, msg_len );
}
void eosio_assert_code( uint32_t test, uint64_t code ) {
get_vm_api()->eosio_assert_code( test, code );
}
void eosio_exit( int32_t code ) {
get_vm_api()->eosio_exit( code );
}
uint64_t current_time() {
return get_vm_api()->current_time();
}
uint32_t now() {
return (uint32_t)( current_time() / 1000000 );
}
void set_last_error(const char* error, size_t size) {
get_vm_api()->set_last_error(error, size);
}
size_t get_last_error(char* error, size_t size) {
return get_vm_api()->get_last_error(error, size);
}
void clear_last_error() {
get_vm_api()->clear_last_error();
}
}
| [
"learnforpractice@gmail.com"
] | learnforpractice@gmail.com |
4418edc10a62f9d50fb76f19d73cc76e4cb153c5 | 6e9bca274c22aa51e1bcb0b765769c6e9e3da7da | /times.cpp | cdbd6b4ebc81f8bd535f5c75e76629aa1a8ac1b8 | [] | no_license | TalesMachado137/PDS2_TP | 034913b293782263d31c12b0c8886dcf35e5ee11 | a0afd75523f2996ce801fb20cb057f4f320a3033 | refs/heads/master | 2020-09-24T11:57:49.855979 | 2019-12-04T03:25:52 | 2019-12-04T03:25:52 | 225,755,269 | 0 | 0 | null | 2019-12-04T03:25:54 | 2019-12-04T01:51:10 | C++ | UTF-8 | C++ | false | false | 3,195 | cpp | #include "times.h"
times:: times (std::vector<Jogador*> Jogadores, tecnico* Profexor, std::string nome, bool usuario){
this-> _escudo=nome;
this->_Elenco= Jogadores;
this->_time_usuario=usuario;
this->Gols=0;
this-> _Tecnico=Profexor;
}
times::~times () {}
std::string times:: get_escudo(){
return(this->_escudo);
}
void times:: get_elenco() { //Imprime o time e seus jogadores, alem do estilo adotado pelo tecnico
int i;
std::cout<<"Nome:"<<get_escudo()<<std::endl;
std::cout<<"Elenco:"<<std::endl;
std::cout<<std::endl;
for(i=0;i<int (_Elenco.size());i++){
std::cout<<_Elenco[i]->get_nome()<<" "<<std::endl;
std::cout<<"Posicao:"<<" "<<_Elenco[i]->get_posicao()<<std::endl;
if(_Elenco[i]->get_estrela()==true)
std::cout<<"*Jogador Decisivo*"<<std::endl;
std::cout<<std::endl;
std::cout<< "Ataque:"<<_Elenco[i]->get_ForcaAtaque()<<" "<<"Defesa:"<<_Elenco[i]->get_ForcaDefesa()<<std::endl;
std::cout<<std::endl;
}
std::cout<<"Treinador:"<<_Tecnico->get_nome()<< " ";
std::cout<<" Estilo do treinador:"<<_Tecnico->get_tipo()<<std::endl;
}
float times::atacando() {//retorna for�a de ataque do time, que � a media dos atributos dos jogadores com alguns incrementos como: estilo do treinador, destaques individuais(estrela)
int i;
int k=0;
int ataque=0;
bool Boost;
for(i=0;i<int(_Elenco.size());i++){
if(_Elenco[i]->get_posicao()=="Goleiro") {
k++;
} else {
ataque+=_Elenco[i]->get_ForcaAtaque();
Boost=_Elenco[i]->get_estrela();
if (Boost==true&&_Elenco[i]->get_posicao()=="Ofensivo") {
ataque+=10;
} }
}
ataque/=(_Elenco.size()-k );
ataque+=_Tecnico->get_ForcaAtaque();
return(ataque);
}
float times:: defendendo () {//retorna for�a de defesa do time, que � a media dos atributos dos jogadores com alguns incrementos como: estilo do treinador, destaques individuais(estrela)
int i;
int defesa=0;
bool Boost;
for(i=0;i<int(_Elenco.size());i++){
defesa+=_Elenco[i]->get_ForcaDefesa();
Boost=_Elenco[i]->get_estrela();
if (Boost==true&&(_Elenco[i]->get_posicao()=="Defensor"||_Elenco[i]->get_posicao()=="Goleiro") ) {
defesa+=10;
}
}
defesa/=_Elenco.size();
defesa+=_Tecnico->get_ForcaDefesa();
return(defesa);
}
bool times:: get_user(){ // fun��o que retorna um variavel booleana, se for true indica que o time em quest�o esta sendo usado pelo usuario, caso contrario � false
return(_time_usuario);
}
void times::set_user(bool w) { // fun��o que retorna um variavel booleana, se for true indica que o time em quest�o esta sendo usado pelo usuario, caso contrario � false
this->_time_usuario=w;
cout<< "Sua equipe: " + this->get_escudo();
cout << "\n";
}
void times::Fez_gol(int n){
this->Gols+=n;
}
void times:: Zerar_gol(){
this->Gols=0;
}
int times:: get_Gols(){
return (this->Gols);
}
void times:: Change_manager() {
std::string novo_tipo;
std::string nome=this->_Tecnico->get_nome();
novo_tipo=this->_Tecnico->ValidaTecnico();
this->_Tecnico= new tecnico (novo_tipo,nome);
}
| [
"noreply@github.com"
] | noreply@github.com |
32a4b509d5f1d3adb11062aed5ac3e03076c1b92 | 8fcec27c2cdad7e2b01f4b4623ef0ac26545133e | /butano/src/bn_inside_window.cpp.h | d3e16e03a02a43b249219378cf4d00479541ebd2 | [
"Zlib"
] | permissive | colorstheforce/butano | 47ed5fd549afa463637c8c4a3a4219fbc9ce5b34 | b068ab5fc88b0c8b0e8e09d7c28215cf718877b3 | refs/heads/master | 2023-01-24T20:09:46.790260 | 2020-12-06T20:51:13 | 2020-12-06T20:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | h | /*
* Copyright (c) 2020 Gustavo Valiente gustavo.valiente@protonmail.com
* zlib License, see LICENSE file.
*/
#include "bn_inside_window.h"
#include "bn_display_manager.h"
namespace bn
{
bool inside_window::visible() const
{
return display_manager::inside_window_enabled(id());
}
void inside_window::set_visible(bool visible)
{
return display_manager::set_inside_window_enabled(id(), visible);
}
}
| [
"gustavo.valiente@protonmail.com"
] | gustavo.valiente@protonmail.com |
76af5ad2ae5fe774fc7b20bd74c87118b66bc68c | 7495e64fdc16caa575e8b2822ea42df59b664e5a | /trunk/src/protocol/transfer/getblockinitrequest.cc | d8f682603b99cbe29040ff99a48a07c30f85c4a8 | [] | no_license | patrickpclee/codfs | dda6a8668c4e157118c7f7773676d88a2d4b0ffe | f3765f148adaecc1c45b132d2453cc74f7a2712f | refs/heads/master | 2021-01-01T20:06:15.538155 | 2015-03-31T09:45:55 | 2015-03-31T09:45:55 | 26,440,466 | 11 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,472 | cc | #include "getblockinitrequest.hh"
#include "../../common/debug.hh"
#include "../../protocol/message.pb.h"
#include "../../common/enums.hh"
#ifdef COMPILE_FOR_OSD
#include "../../osd/osd.hh"
extern Osd* osd;
#endif
GetBlockInitRequestMsg::GetBlockInitRequestMsg(Communicator* communicator) :
Message(communicator) {
}
GetBlockInitRequestMsg::GetBlockInitRequestMsg(Communicator* communicator,
uint32_t osdSockfd, uint64_t segmentId, uint32_t blockId,
vector<offset_length_t> symbols, DataMsgType dataMsgType, bool isParity) :
Message(communicator) {
_sockfd = osdSockfd;
_segmentId = segmentId;
_blockId = blockId;
_symbols = symbols;
_dataMsgType = dataMsgType;
_isParity = isParity;
}
void GetBlockInitRequestMsg::prepareProtocolMsg() {
string serializedString;
ncvfs::GetBlockInitRequestPro getBlockInitRequestPro;
getBlockInitRequestPro.set_segmentid(_segmentId);
getBlockInitRequestPro.set_blockid(_blockId);
getBlockInitRequestPro.set_datamsgtype((ncvfs::DataMsgPro_DataMsgType)_dataMsgType);
getBlockInitRequestPro.set_isparity(_isParity);
vector<offset_length_t>::iterator it;
for (it = _symbols.begin(); it < _symbols.end(); ++it) {
ncvfs::OffsetLengthPro* offsetLengthPro =
getBlockInitRequestPro.add_offsetlength();
offsetLengthPro->set_offset((*it).first);
offsetLengthPro->set_length((*it).second);
}
if (!getBlockInitRequestPro.SerializeToString(&serializedString)) {
cerr << "Failed to write string." << endl;
return;
}
setProtocolSize(serializedString.length());
setProtocolType(GET_BLOCK_INIT_REQUEST);
setProtocolMsg(serializedString);
}
void GetBlockInitRequestMsg::parse(char* buf) {
memcpy(&_msgHeader, buf, sizeof(struct MsgHeader));
ncvfs::GetBlockInitRequestPro getBlockInitRequestPro;
getBlockInitRequestPro.ParseFromArray(buf + sizeof(struct MsgHeader),
_msgHeader.protocolMsgSize);
_segmentId = getBlockInitRequestPro.segmentid();
_blockId = getBlockInitRequestPro.blockid();
_dataMsgType = (DataMsgType)getBlockInitRequestPro.datamsgtype();
_isParity = getBlockInitRequestPro.isparity();
for (int i = 0; i < getBlockInitRequestPro.offsetlength_size(); ++i) {
offset_length_t tempOffsetLength;
uint32_t offset = getBlockInitRequestPro.offsetlength(i).offset();
uint32_t length = getBlockInitRequestPro.offsetlength(i).length();
tempOffsetLength = make_pair (offset, length);
_symbols.push_back(tempOffsetLength);
}
}
void GetBlockInitRequestMsg::doHandle() {
#ifdef COMPILE_FOR_OSD
osd->getBlockRequestProcessor (_msgHeader.requestId, _sockfd, _segmentId, _blockId, _symbols, _dataMsgType, _isParity);
#endif
}
void GetBlockInitRequestMsg::printProtocol() {
debug(
"[GET_BLOCK_INIT_REQUEST] Segment ID = %" PRIu64 ", Block ID = %" PRIu32 ", dataMsgType = %d\n",
_segmentId, _blockId, _dataMsgType);
}
/*
void GetBlockInitRequestMsg::setRecoveryBlockData (BlockData blockData) {
_recoveryBlockData = blockData;
}
BlockData GetBlockInitRequestMsg::getRecoveryBlockData () {
return _recoveryBlockData;
}
void GetBlockInitRequestMsg::setBlockSize(uint32_t blockSize) {
_blockSize = blockSize;
}
uint32_t GetBlockInitRequestMsg::getBlockSize() {
return _blockSize;
}
void GetBlockInitRequestMsg::setChunkCount(uint32_t chunkCount) {
_chunkCount = chunkCount;
}
uint32_t GetBlockInitRequestMsg::getChunkCount() {
return _chunkCount;
}
*/
| [
"cwchan@cse.cuhk.edu.hk"
] | cwchan@cse.cuhk.edu.hk |
cdb8e814060137fb8c898204c814c35f9ceac5fe | 67f32c6fb3d638c7810fb5825cb09627da54f205 | /uva/10911.cpp | b13af6f58b0ad78c372aa5c41df141f3c8193e77 | [] | no_license | usmarcv/competitive-programming | 8d063acaaf890781c75aa6b28405391834890352 | cce08a6a312831fb4a7b2b62c0e384d0dbd3204b | refs/heads/master | 2022-08-20T21:25:15.726362 | 2022-07-26T14:09:16 | 2022-07-26T14:09:16 | 178,268,586 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,065 | cpp | #include <bits/stdc++.h>
#define endl '\n'
#define __ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
int n, target;
double dist[20][20], memo[1 << 16];
double matching (int bitmask){
if(memo[bitmask] > -0.5) return memo[bitmask];
if(bitmask == target) return memo[bitmask] = 0;
double ans = 2000000000.0;
int p1, p2;
for(p1 = 0; p1 < 2 * n; p1++)
if(!(bitmask & (1 << p1))) break;
for(p2 = p1 + 1; p2 < 2 * n; p2++)
if(!(bitmask & (1 << p2)))
ans = min(ans, dist[p1][p2] + matching(bitmask | (1 << p1) | (1 << p2)));
return memo[bitmask] = ans;
}
int main(){__
int i, j, caseNo = 1, x[20], y[20];
while(scanf("%d",&n), n){
for(i = 0; i < 2 * n; i++)
scanf("%*s %d %d", &x[i], &y[i]);
for(i = 0; i < 2 * n; i++)
for(i = 0; i < 2 * n - 1; i++)
for(j = i + 1; j < 2 * n; j++)
dist[i][j] = dist[j][i] = hypot(x[i] - x[j], y[i] - y[j]);
for(i = 0; i < (1 << 16); i++) memo[i] = -1.0;
target = (1 << (2 * n)) - 1;
printf("Case %d: %.2lf\n",caseNo++, matching(0));
}
return 0;
}
| [
"usmarc.v@gmail.com"
] | usmarc.v@gmail.com |
46e49357c96d9df30cbec84c4c241135d04904df | 080d949bbd6aa4e05a5ede553f94d3c7a13544a2 | /Project1/Project1.cpp | c0f89a853b08f8696b46dc475a6dd8bd9d1be24a | [] | no_license | tanxiaosysu/Lectures_DataStructures | 58a44e21008c17fdde3e464c7c7a5fd39f24df3a | 8c145df4359f7a74753f685e1a593307eccbb7d7 | refs/heads/master | 2021-01-01T05:51:52.742620 | 2014-11-19T12:12:17 | 2014-11-19T12:12:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,908 | cpp | #include <iostream>
#include <set>
#include <stack>
using namespace std;
class stackt {
public:
stack<int> a;
int number;
bool operator<(const stackt &other) const {
return (a.top() < other.a.top());
}
};
int n;
set<stackt> s;
int numofstack = 0;
int wanttoout,noout,noin;
int inlist[2000];
void popp(set<stackt>::iterator &it) {
stackt b;
b = *it;
b.a.pop();
if (!b.a.empty()) s.insert(b);
s.erase(it);
}
void check() {
bool suc;
set<stackt>::iterator iter;
do {
suc = false;
for (iter = s.begin(); iter != s.end(); iter++) {
if (iter->a.top() == wanttoout) {
//stacktoout();
cout << wanttoout << " from stack "<< iter->number << " to out." << endl;
set<stackt>::iterator it;
it = iter;
iter++;
popp(it);
it = s.end();
wanttoout++;
noout--;
suc = true;
if (iter == s.end()) break;
} else if (iter->a.top() > wanttoout) break;
}
} while (suc == true);
}
void pushp(set<stackt>::iterator it, int x) {
stackt b;
b = *it;
b.a.push(x);
s.insert(b);
s.erase(it);
}
void intostack(int x) {
set<stackt>::iterator iter;
bool suc = false;
for (iter = s.begin(); iter != s.end(); iter++) {
if (x < iter->a.top()) {
set<stackt>::iterator it;
cout << x << " from in to stack " << iter->number << "." << endl;
it = iter;
iter++;
pushp(it, x);
suc = true;
// print x from in to stack, no new stack;
if (iter == s.end()) break;
}
}
if (suc == false) {
numofstack++;
stackt b;
b.number = numofstack;
b.a.push(x);
s.insert(b);
cout << x << " from in to stack.Create a new stack(No." << b.number << ")." << endl;
// print x from in to stack, create new stack;
}
noin--;
}
int main() {
cout << "Please input:\n"
<< "Every input has 2 lines\n"
<< "The first line is the length of the train.(length >= 2)\n"
<< "The second line is the number of train carriage.(seperated by space)\n";
cin >> n;
int i;
for (i = 1; i <= n; i++) cin >> inlist[i];
wanttoout = 1;
noout = n;
noin = n;
while (noout > 0) {
check();
if (noout == 0) {
cout << "Program over." << endl;
cout << "Use " << numofstack << " stack(s)." << endl;
break;
}
if (noin > 0 && inlist[noin] == wanttoout) {
cout << wanttoout << " from in to out.No new stack." << endl;
wanttoout++;
noout--;
noin--;
} else {
intostack(inlist[noin]);
}
}
return 0;
}
| [
"tanx7@mail2.sysu.edu.cn"
] | tanx7@mail2.sysu.edu.cn |
ce98c2bea6536f0a561e3ba672beaa309cc9200b | b2f4389f2006c128a0a06003b8e1c965368e2f93 | /Simulation/OLD/striatum_RK2.cpp | f4b35679e3e58647e2fff4eef3e25bf66bce1448 | [] | no_license | ModelDBRepository/137502 | 54eb9cc63fea8e105c30c804cbf24e963fda3462 | 7aaa0ebad38823a3e12719609877167c6c96aa18 | refs/heads/master | 2020-05-29T18:29:22.566126 | 2019-05-31T05:08:08 | 2019-05-31T05:08:08 | 189,301,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,936 | cpp | // striatum model solved using mid-point method (aka 2nd order Runge-Kutta)
#include <mex.h>
#include <matrix.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
// ===============================================================
// RANDOM NUMBER GENERATOR
#define SHR3 (jz=jsr, jsr^=(jsr<<13), jsr^=(jsr>>17), jsr^=(jsr<<5),jz+jsr)
#define UNI (.5 + (signed) SHR3 * .2328306e-9)
#define RNOR (hz=SHR3, iz=hz&127, (abs(hz)<kn[iz])? hz*wn[iz] : nfix())
#define REXP (jz=SHR3, iz=jz&255, ( jz <ke[iz])? jz*we[iz] : efix())
static unsigned int iz,jz,jsr=123456789,kn[128],ke[256];
static int hz; static float wn[128],fn[128], we[256],fe[256];
float nfix(void) { /*provides RNOR if #define cannot */
const float r = 3.442620f; static float x, y;
for(;;){ x=hz*wn[iz];
if(iz==0){ do{x=-log(UNI)*0.2904764; y=-log(UNI);} while(y+y<x*x);
return (hz>0)? r+x : -r-x;
}
if( fn[iz]+UNI*(fn[iz-1]-fn[iz]) < exp(-.5*x*x) ) return x;
hz=SHR3; iz=hz&127;if(abs(hz)<kn[iz]) return (hz*wn[iz]);
}
}
float efix(void) { /*provides REXP if #define cannot */
float x;
for(;;){
if(iz==0) return (7.69711-log(UNI));
x=jz*we[iz];
if( fe[iz]+UNI*(fe[iz-1]-fe[iz]) < exp(-x) ) return (x);
jz=SHR3; iz=(jz&255);
if(jz<ke[iz]) return (jz*we[iz]);
}
}
// == This procedure sets the seed and creates the tables ==
void zigset(unsigned int jsrseed) {
const double m1 = 2147483648.0, m2 = 4294967296.;
double dn=3.442619855899,tn=dn,vn=9.91256303526217e-3, q;
double de=7.697117470131487, te=de, ve=3.949659822581572e-3;
int i; jsr=jsrseed;
/* Tables for RNOR: */
q=vn/exp(-.5*dn*dn);
kn[0]=(dn/q)*m1; kn[1]=0;
wn[0]=q/m1; wn[127]=dn/m1;
fn[0]=1.; fn[127]=exp(-.5*dn*dn);
for(i=126;i>=1;i--) {
dn=sqrt(-2.*log(vn/dn+exp(-.5*dn*dn)));
kn[i+1]=(dn/tn)*m1; tn=dn;
fn[i]=exp(-.5*dn*dn); wn[i]=dn/m1;
}
/* Tables for REXP */
q = ve/exp(-de);
ke[0]=(de/q)*m2; ke[1]=0;
we[0]=q/m2; we[255]=de/m2;
fe[0]=1.; fe[255]=exp(-de);
for(i=254;i>=1;i--) {
de=-log(ve/de+exp(-de));
ke[i+1]= (de/te)*m2; te=de;
fe[i]=exp(-de); we[i]=de/m2;
}
}
int mxGetScalarInt32(const mxArray* a, int defaultValue = -2147483648)
{
if (mxIsEmpty(a))
{
if (defaultValue == -2147483648) throw "missing input";
return defaultValue;
}
if (!mxIsInt32(a)) throw "not int32";
if (mxGetNumberOfDimensions(a) != 2) throw "expected scalar";
if (mxGetM(a) != 1 || mxGetN(a) != 1) throw "expected scalar";
return mxGetScalar(a);
//if (fabs(val) > pow(2,30)) throw "value out of range";
//if (floor(val) != val) throw "value not an integer";
//return val;
}
double mxGetScalarDouble(const mxArray* a, double defaultValue = -2147483648.1)
{
if (mxIsEmpty(a))
{
if (defaultValue == -2147483648.1) throw "missing input";
return defaultValue;
}
if (!mxIsDouble(a)) throw "not Double";
if (mxGetNumberOfDimensions(a) != 2) throw "expected scalar";
if (mxGetM(a) != 1 || mxGetN(a) != 1) throw "expected scalar";
return mxGetScalar(a);
}
struct MatrixInt32
{
int* data;
int M, N;
};
MatrixInt32 mxGetMatrixInt32(const mxArray* a, int M = -1, int N = -1)
{
MatrixInt32 ret;
if (!mxIsInt32(a)) throw "not int32";
if (mxGetNumberOfDimensions(a) != 2) throw "expected 2D matrix";
if (mxIsComplex(a)) throw "expected real matrix";
if (mxIsEmpty(a)) ret.data = NULL;
else ret.data = (int*)mxGetData(a);
ret.M = mxGetM(a);
ret.N = mxGetN(a);
if (M != -1 && M != ret.M) throw "interger matrix has wrong dimension (M)";
if (N != -1 && N != ret.N) throw "interger matrix has wrong dimension (N)";
return ret;
}
struct MatrixDouble
{
double* data;
int M, N;
};
MatrixDouble mxGetMatrixDouble(const mxArray* a, int M = -1, int N = -1)
{
MatrixDouble ret;
if (!mxIsDouble(a)) throw "not double";
if (mxGetNumberOfDimensions(a) != 2) throw "expected 2D matrix";
if (mxIsComplex(a)) throw "expected real matrix";
if (mxIsEmpty(a)) ret.data = NULL;
else ret.data = (double*)mxGetData(a);
ret.M = mxGetM(a);
ret.N = mxGetN(a);
if (M != -1 && M != ret.M) throw "double matrix has wrong dimension (M)";
if (N != -1 && N != ret.N) throw "double matrix has wrong dimension (N)";
return ret;
}
// ===============================================================
// Main simulation function
void execute(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
// ===============================================================
// The Inputs
// ---------------------------------------------------------------
if (nrhs != 72) throw "not enough inputs";
// ---------------------------------------------------------------
// Get the inputs
double tstart = mxGetScalarDouble(prhs[0]);
double tfinal = mxGetScalarDouble(prhs[1]);
double dt = mxGetScalarDouble(prhs[2]);
// double dt_fs = mxGetScalarDouble(prhs[3]);
int tend = (int)(tfinal / dt);
MatrixDouble MSparams = mxGetMatrixDouble(prhs[3]);
MatrixDouble FSparams = mxGetMatrixDouble(prhs[4]);
double Eglu = mxGetScalarDouble(prhs[5]);
double Egaba = mxGetScalarDouble(prhs[6]);
double ts_glu_AMPA = mxGetScalarDouble(prhs[7]);
double ts_glu_NMDA = mxGetScalarDouble(prhs[8]);
double ts_gaba = mxGetScalarDouble(prhs[9]);
double tau_fsgap = mxGetScalarDouble(prhs[10]);
int MSspikebuffer = mxGetScalarInt32(prhs[11]);
int FSspikebuffer = mxGetScalarInt32(prhs[12]);
MatrixDouble initVms = mxGetMatrixDouble(prhs[13]);
MatrixDouble initUms = mxGetMatrixDouble(prhs[14], initVms.M, initVms.N);
MatrixDouble initVfs = mxGetMatrixDouble(prhs[15]);
MatrixDouble initUfs = mxGetMatrixDouble(prhs[16], initVfs.M, initVfs.N);
MatrixDouble initVfsgap = mxGetMatrixDouble(prhs[17]);
// get the dimensions of the MS and FS networks
const int *dims_ms = mxGetDimensions(prhs[13]);
int ndim_ms = mxGetNumberOfDimensions(prhs[13]);
int N_MS = initVms.M;
const int *dims_fs = mxGetDimensions(prhs[15]);
int ndim_fs = mxGetNumberOfDimensions(prhs[15]);
int N_FS = initVfs.M;
const int *dims_fsgap = mxGetDimensions(prhs[17]);
int ndim_fsgap = mxGetNumberOfDimensions(prhs[17]);
int N_fsgap = initVfsgap.M*initVfsgap.N;
MatrixDouble initSEQ_MSglu = mxGetMatrixDouble(prhs[18], N_MS);
MatrixDouble initSEQ_FSglu = mxGetMatrixDouble(prhs[19], N_FS);
MatrixDouble initSEQ_MSGABA = mxGetMatrixDouble(prhs[20], N_MS);
MatrixDouble initSEQ_FSGABA = mxGetMatrixDouble(prhs[21], N_FS);
MatrixDouble initCTX = mxGetMatrixDouble(prhs[22]);
// *** NEED TO REMOVE THIS AND FIND ANOTHER WAY TO SET UP MATRICES FURTHER DOWN ***
const int *initSEQ_MSGABA_dims = mxGetDimensions(prhs[20]);
int initSEQ_MSGABA_ndim = mxGetNumberOfDimensions(prhs[20]);
const int *initSEQ_FSGABA_dims = mxGetDimensions(prhs[21]);
int initSEQ_FSGABA_ndim = mxGetNumberOfDimensions(prhs[21]);
// *** Not used currently, but will need bounds check put on dimensions ***
MatrixDouble Ims = mxGetMatrixDouble(prhs[23]);
MatrixDouble Ifs = mxGetMatrixDouble(prhs[24]);
MatrixInt32 Cctms = mxGetMatrixInt32(prhs[25], N_MS, 1); // need to set bound on to N_MS, no + 1
MatrixInt32 Cctms_b = mxGetMatrixInt32(prhs[26], N_MS+1, 1);
MatrixInt32 Cctms_d = mxGetMatrixInt32(prhs[27], N_MS, 1);
MatrixDouble Cctms_w = mxGetMatrixDouble(prhs[28], N_MS, 1);
// double a_ms = mxGetScalarDouble(prhs[29]);
MatrixInt32 Cmsms = mxGetMatrixInt32(prhs[29]);
MatrixInt32 Cmsms_b = mxGetMatrixInt32(prhs[30], N_MS+1, 1);
MatrixInt32 Cmsms_d = mxGetMatrixInt32(prhs[31], Cmsms.M, Cmsms.N);
MatrixDouble Cmsms_w = mxGetMatrixDouble(prhs[32], Cmsms.M, Cmsms.N);
MatrixInt32 Cfsms = mxGetMatrixInt32(prhs[33]);
MatrixInt32 Cfsms_b = mxGetMatrixInt32(prhs[34], N_FS+1, 1);
MatrixInt32 Cfsms_d = mxGetMatrixInt32(prhs[35], Cfsms.M, Cfsms.N);
MatrixDouble Cfsms_w = mxGetMatrixDouble(prhs[36], Cfsms.M, Cfsms.N);
const int *dims_Cfsms_b = mxGetDimensions(prhs[34]);
MatrixInt32 Cctfs = mxGetMatrixInt32(prhs[37], N_FS, 1);
MatrixInt32 Cctfs_b = mxGetMatrixInt32(prhs[38], N_FS+1, 1);
MatrixInt32 Cctfs_d = mxGetMatrixInt32(prhs[39], N_FS, 1);
MatrixDouble Cctfs_w = mxGetMatrixDouble(prhs[40], N_FS, 1);
const int *dims_Cctfs_b = mxGetDimensions(prhs[38]);
// double a_fs = mxGetScalarDouble(prhs[42]);
MatrixInt32 Cfsfs = mxGetMatrixInt32(prhs[41]);
MatrixInt32 Cfsfs_b = mxGetMatrixInt32(prhs[42], N_FS+1, 1);
MatrixInt32 Cfsfs_d = mxGetMatrixInt32(prhs[43], Cfsfs.M, Cfsfs.N);
MatrixDouble Cfsfs_w = mxGetMatrixDouble(prhs[44], Cfsfs.M, Cfsfs.N);
const int *dims_Cfsfs_b = mxGetDimensions(prhs[42]);
MatrixInt32 Cgapfs = mxGetMatrixInt32(prhs[45]);
MatrixInt32 Cgapfs_b = mxGetMatrixInt32(prhs[46], N_FS+1, 1);
MatrixDouble Cgapfs_w = mxGetMatrixDouble(prhs[47], Cgapfs.M, Cgapfs.N);
MatrixInt32 Pgapfs = mxGetMatrixInt32(prhs[48]);
MatrixDouble CTX_state = mxGetMatrixDouble(prhs[49]);
MatrixInt32 CHAN1_MS = mxGetMatrixInt32(prhs[50]);
MatrixInt32 CHAN1_FS = mxGetMatrixInt32(prhs[51]);
MatrixInt32 CHAN2_MS = mxGetMatrixInt32(prhs[52]);
MatrixInt32 CHAN2_FS = mxGetMatrixInt32(prhs[53]);
const int *dims_CHAN1_MS = mxGetDimensions(prhs[50]);
int N_CHAN1_MS = dims_CHAN1_MS[0];
const int *dims_CHAN1_FS = mxGetDimensions(prhs[51]);
int N_CHAN1_FS = dims_CHAN1_FS[0];
MatrixInt32 N_MSSEG = mxGetMatrixInt32(prhs[54], N_MS, 1);
MatrixDouble r_MSSEG = mxGetMatrixDouble(prhs[55], N_MS, 1);
MatrixDouble alpha_MSSEG = mxGetMatrixDouble(prhs[56], N_MS, 1);
MatrixInt32 N_FSSEG = mxGetMatrixInt32(prhs[57], N_FS, 1);
MatrixDouble r_FSSEG = mxGetMatrixDouble(prhs[58], N_FS, 1);
MatrixDouble alpha_FSSEG = mxGetMatrixDouble(prhs[59], N_FS, 1);
double glu_ratio = mxGetScalarDouble(prhs[60]);
double DA = mxGetScalarDouble(prhs[61]);
MatrixInt32 RecordChan_MS = mxGetMatrixInt32(prhs[62]);
const int dims_RecordChan_MS_out [2] = {tend, RecordChan_MS.M};
MatrixDouble PULSE = mxGetMatrixDouble(prhs[63]);
double Nctx_ms = mxGetScalarDouble(prhs[64]);
double Nctx_fs = mxGetScalarDouble(prhs[65]);
double ts_spks = mxGetScalarDouble(prhs[66]);
MatrixInt32 Pt = mxGetMatrixInt32(prhs[67]);
MatrixInt32 Pch = mxGetMatrixInt32(prhs[68], Pt.M, Pt.N);
MatrixDouble Phz = mxGetMatrixDouble(prhs[69], Pt.M, Pt.N);
int RANDSEED = mxGetScalarInt32(prhs[70]);
const char* filename = mxArrayToString(prhs[71]);
// ===============================================================
// set the random numer seeds
zigset(RANDSEED);
// ===============================================================
// Set up easy access to the MS and FS parameters
#define _MS(__m,__n) (MSparams.data[__n * MSparams.M + __m])
#define _FS(__m,__n) (FSparams.data[__n * FSparams.M + __m])
// ===============================================================
// get some dimensions
if (!filename) throw "no filename supplied for log file";
// open log file
FILE* fid = fopen(filename, "w");
if (!fid) throw "failed open log file";
fprintf(fid, "*************************************************** \n");
fprintf(fid, "*************** STARTING SIMULATION *************** \n");
fprintf(fid, "*************************************************** \n");
fprintf(fid, "tstart = %f msec \n", tstart);
fprintf(fid, "tfinal = %f msec \n", tfinal);
fprintf(fid, "dt = %f msec \n", dt);
fprintf(fid, "tend = %i iterations \n", tend);
fprintf(fid, " \n");
fprintf(fid, "N_MS = %i \n", N_MS);
fprintf(fid, "Example MS parameters are C = %f, vr = %f, vt = %f, a = %f, b = %f, c = %f, d = %f, vp = %f, k = %f, EDA = %f, alpha = %f, beta1 = %f, beta2 = %f, gDA = %f \n", _MS(0,0), _MS(0,1), _MS(0,2), _MS(0,3), _MS(0,4), _MS(0,5), _MS(0,6), _MS(0,7), _MS(0,8), _MS(0,9), _MS(0,10), _MS(0,11), _MS(0,12), _MS(0,13), _MS(0,14));
fprintf(fid, " \n");
fprintf(fid, "N_FS = %i \n", N_FS);
fprintf(fid, "Example FS parameters are C = %f, vr = %f, vt = %f, k = %f, a = %f, b = %f, c = %f, d = %f, vpeak = %f, vb = %f, eta = %f, epsilon = %f \n", _FS(0,0), _MS(0,1), _FS(0,2), _FS(0,3), _FS(0,4), _FS(0,5), _FS(0,6), _FS(0,7), _FS(0,8), _FS(0,9), _FS(0,10), _FS(0,11));
fprintf(fid, " \n");
fprintf(fid, "Eglu = %f \n", Eglu);
fprintf(fid, "Egaba = %f \n", Egaba);
fprintf(fid, "ts_glu_AMPA = %f \n", ts_glu_AMPA);
fprintf(fid, "ts_glu_NMDA = %f \n", ts_glu_NMDA);
fprintf(fid, "ts_gaba = %f \n", ts_gaba);
fprintf(fid, "tau_fsgap = %f \n", tau_fsgap);
fprintf(fid, " \n");
fprintf(fid, "gAMPA_MS = %f \n", Cctms_w.data[0]);
fprintf(fid, "gNMDA_MS = %f \n", glu_ratio * Cctms_w.data[0]);
fprintf(fid, "gGLUTAMATE_FS = %f \n", Cctfs_w.data[0]);
fprintf(fid, " \n");
fprintf(fid, "MSspikebuffer = %i \n", MSspikebuffer);
fprintf(fid, "FSspikebuffer = %i \n", FSspikebuffer);
fprintf(fid, " \n");
fprintf(fid, "*************************************************** \n");
fclose(fid);
// ===============================================================
// Set and init some parameters
double T; // Simulation Time
// int extasteps = (int)(dt_ms / dt_fs); // Number of extra iterations needed to solve the FS neurons
float VMS,UMS,VFS,UFS,U; // temp variables for the ms and fs neurons
float Vms1,Ums1,Vfs1,Ufs1,tmp; // temp variables for mid-point
float hdt = dt*0.5; // half time-step for midpoint method
// parameters for the MS neurons
int MSspikecount = 0;
int SEQind_ms = 0;
int SpikeEventCycle_MSGABA = 0;
int maxSEQdelay_MSGABA = initSEQ_MSGABA.N - 1;
int SpikeQueSize_MS = N_MS * (maxSEQdelay_MSGABA+1);
double Mg_ms[N_MS]; // Mg block for the MS NMDA channels
double lambda1_ms;
double lambda2_ms;
// parameters for the FS neurons
int FSspikecount = 0;
int SEQind_fs;
int SpikeEventCycle_FSGABA = 0;
int maxSEQdelay_FSGABA = initSEQ_FSGABA_dims[1] - 1;
int SpikeQueSize_FS = N_FS * (maxSEQdelay_FSGABA+1);
double lambda1_fs;
double lambda2_fs;
// parameters for the MS neuron spike-event generator
float p_MSSEG; // adjust for time in msec, not seconds!
int spk_ms[N_MS];
float U_MSSEG;
int R_MSSEG;
double gluExp_ms_AMPA = exp(-dt / ts_glu_AMPA);
double gluExp_ms_NMDA = exp(-dt / ts_glu_NMDA);
double gabaExp_ms = exp(-dt / ts_gaba);
float EMg = 1; // magnesium ion concentration in mM
double SpksExp = exp(-dt / ts_spks);
// parameters for the FS neuron spike-event generator
float p_FSSEG; // adjust for time in msec, not seconds!
int spk_fs[N_FS];
float U_FSSEG;
int R_FSSEG;
double gluExp_fs = exp(-dt / ts_glu_AMPA);
double gabaExp_fs = exp(-dt / ts_gaba);
// ===============================================================
// The Outputs
double *tout; // Time stamps
double *Vmsout; // example MS membrane potential
double *Vfsout; // Example FS membran potential
double *STms; // MS neuron spike times
double *STfs; // FS neuron spike times
// output states so we can continue simulations
double *Vms; // MS membrane potentials
double *Ums; // MS U values
double *Vfs; // FS membrane potentials
double *Ufs; // FS U values
double *Vfsgap; // Membrane potentials of the FS gap junctions
double *Gglu_ms_AMPA; // *** Place holder for current glutamate input conductance to the MS neurons ***
double *Gglu_ms_NMDA; // *** Place holder for current glutamate input conductance to the MS neurons ***
double *Ggaba_ms; // Current input GABA conductance to the MS neurons
double *SEQ_MSGABA; // Incomming GABAergic spike buffer for the FS neurons
double *Gglu_fs; // *** Place holder for current glutamate input conductance to the MS neurons ***
double *Ggaba_fs; // Current input GABA conductance to the MS neurons
double *SEQ_FSGABA; // Incomming GABAergic spike buffer for the FS neurons
double *RecordChan_MS_out; // output from the recording electrode
//create the output arrays
plhs[0] = mxCreateDoubleMatrix(tend, 1, mxREAL);
tout = mxGetPr(plhs[0]);
plhs[1] = mxCreateDoubleMatrix(tend, 1, mxREAL);
Vmsout = mxGetPr(plhs[1]);
plhs[2] = mxCreateDoubleMatrix(tend, 1, mxREAL);
Vfsout = mxGetPr(plhs[2]);
plhs[3] = mxCreateDoubleMatrix(MSspikebuffer, 2, mxREAL);
STms = mxGetPr(plhs[3]);
plhs[4] = mxCreateDoubleMatrix(FSspikebuffer, 2, mxREAL);
STfs = mxGetPr(plhs[4]);
plhs[5] = mxCreateNumericArray(ndim_ms,dims_ms,mxDOUBLE_CLASS,mxREAL);
Vms = mxGetPr(plhs[5]);
plhs[6] = mxCreateNumericArray(ndim_ms,dims_ms,mxDOUBLE_CLASS,mxREAL);
Ums = mxGetPr(plhs[6]);
plhs[7] = mxCreateNumericArray(ndim_fs,dims_fs,mxDOUBLE_CLASS,mxREAL);
Vfs = mxGetPr(plhs[7]);
plhs[8] = mxCreateNumericArray(ndim_fs,dims_fs,mxDOUBLE_CLASS,mxREAL);
Ufs = mxGetPr(plhs[8]);
plhs[9] = mxCreateNumericArray(ndim_fsgap,dims_fsgap,mxDOUBLE_CLASS,mxREAL);
Vfsgap = mxGetPr(plhs[9]);
plhs[10] = mxCreateNumericArray(ndim_ms,dims_ms,mxDOUBLE_CLASS,mxREAL);
Gglu_ms_AMPA = mxGetPr(plhs[10]);
plhs[11] = mxCreateNumericArray(ndim_ms,dims_ms,mxDOUBLE_CLASS,mxREAL);
Gglu_ms_NMDA = mxGetPr(plhs[11]);
plhs[12] = mxCreateNumericArray(ndim_ms,dims_ms,mxDOUBLE_CLASS,mxREAL);
Ggaba_ms = mxGetPr(plhs[12]);
plhs[13] = mxCreateNumericArray(initSEQ_MSGABA_ndim,initSEQ_MSGABA_dims,mxDOUBLE_CLASS,mxREAL);
SEQ_MSGABA = mxGetPr(plhs[13]);
plhs[14] = mxCreateNumericArray(ndim_fs,dims_fs,mxDOUBLE_CLASS,mxREAL);
Gglu_fs = mxGetPr(plhs[14]);
plhs[15] = mxCreateNumericArray(ndim_fs,dims_fs,mxDOUBLE_CLASS,mxREAL);
Ggaba_fs = mxGetPr(plhs[15]);
plhs[16] = mxCreateNumericArray(initSEQ_FSGABA_ndim,initSEQ_FSGABA_dims,mxDOUBLE_CLASS,mxREAL);
SEQ_FSGABA = mxGetPr(plhs[16]);
plhs[17] = mxCreateNumericArray(2, dims_RecordChan_MS_out,mxDOUBLE_CLASS,mxREAL);
RecordChan_MS_out = mxGetPr(plhs[17]);
// ===============================================================
// Set up easy access to the cortical state and recording channels
const int *CTX_state_dims = mxGetDimensions(prhs[58]);
#define _CTX_state(__m,__n) (CTX_state[__n*CTX_state_dims[0]+__m])
const int *RecordChan_MS_out_dims = mxGetDimensions(plhs[17]);
#define _RecordChan_MS_out(__m,__n) (RecordChan_MS_out[__n*RecordChan_MS_out_dims[0]+__m])
// ===============================================================
// init the variables
for (int i = 0; i < N_MS; i++){
Vms[i] = initVms.data[i];
Ums[i] = initUms.data[i];
}
for (int i = 0; i < N_FS; i++){
Vfs[i] = initVfs.data[i];
Ufs[i] = initUfs.data[i];
}
for (int i = 0; i < N_fsgap; i++){
Vfsgap[i] = initVfsgap.data[i];
}
float IAMPA_ms[N_MS];
float INMDA_ms[N_MS];
float IDA_ms[N_MS];
float IGABA_ms[N_MS];
float Isyn_ms[N_MS];
float tmpIDA_ms;
for (int i = 0; i < N_MS; i++){
IAMPA_ms[i] = 0;
INMDA_ms[i] = 0;
IDA_ms[i] = 0;
IGABA_ms[i] = 0;
Isyn_ms[i] = 0;
tmpIDA_ms = 0;
}
float IAMPA_fs[N_FS];
float IGABA_fs[N_FS];
float IDA_fs[N_FS];
float Isyn_fs[N_FS];
float Igapfs[N_FS];
for (int j = 0; j < N_FS; j++){
IAMPA_fs[j] = 0.0;
IGABA_fs[j] = 0.0;
IDA_fs[j] = 0.0;
Isyn_fs[j] = 0.0;
Igapfs[j] = 0.0;
}
int Vgap1,Vgap2;
// ===============================================================
// Active D1 and D2 receptors for the MS and FS neurons
lambda1_ms = DA; lambda2_ms = DA;
lambda1_fs = DA; lambda2_fs = DA;
// ===============================================================
// run the simulation
int SelectionCounter = 0;
for (int t = (int)tstart; t < tend; t++){
T = t * dt;
// reset the random seed
if (UNI < (0.01*dt)){
RANDSEED++;
zigset(RANDSEED);
}
// ================================================================
// Look for changes in the selection pulses
if (Pt.data[SelectionCounter] == t){
printf("Selection Pulse Detected %f \n", T);
if (Pch.data[SelectionCounter] == 1){
printf("Selection Pulse Channel %i \n", Pch.data[SelectionCounter]);
for (int i = 0; i < CHAN1_MS.M; i++){
r_MSSEG.data[CHAN1_MS.data[i]] = Phz.data[SelectionCounter];
}
for (int i = 0; i < CHAN1_FS.M; i++){
r_FSSEG.data[CHAN1_FS.data[i]] = Phz.data[SelectionCounter];
}
}
if (Pch.data[SelectionCounter] == 2){
printf("Selection Pulse Channel %i \n", Pch.data[SelectionCounter]);
for (int i = 0; i < CHAN2_MS.M; i++){
r_MSSEG.data[CHAN2_MS.data[i]] = Phz.data[SelectionCounter];
}
for (int i = 0; i < CHAN2_FS.M; i++){
r_FSSEG.data[CHAN2_FS.data[i]] = Phz.data[SelectionCounter];
}
}
SelectionCounter++;
}
// ===============================================================
// Update the MS neurons
for (int i = 0; i < N_MS; i++){
// ---------------------------------------------------------------
// Update the MS spike-event que
spk_ms[i] = 0; // reset the spike que
int T_MSSEG = 0;
p_MSSEG = r_MSSEG.data[i] * dt * 0.001;
U_MSSEG = UNI;
R_MSSEG = (U_MSSEG <= p_MSSEG); // the reference spike train
for (int ist = 0; ist < N_MSSEG.data[i]; ist++){
if (UNI <= alpha_MSSEG.data[i]){
T_MSSEG = R_MSSEG;
}
else {
T_MSSEG = (UNI <= p_MSSEG);
}
spk_ms[i] = spk_ms[i] + T_MSSEG;
}
// ---------------------------------------------------------------
//Update the MS neurons cortical input
Gglu_ms_AMPA[i] = Gglu_ms_AMPA[i] + ((Cctms_w.data[i]) * spk_ms[i] / ts_glu_AMPA);
Gglu_ms_AMPA[i] = Gglu_ms_AMPA[i] * gluExp_ms_AMPA;
Gglu_ms_NMDA[i] = Gglu_ms_NMDA[i] + (glu_ratio * Cctms_w.data[i] * spk_ms[i] / ts_glu_NMDA);
Gglu_ms_NMDA[i] = Gglu_ms_NMDA[i] * gluExp_ms_NMDA;
// ---------------------------------------------------------------
// Mg block of the MS NMDA channels
Mg_ms[i] = 1 / ( 1 + (EMg / 3.57) * exp(-Vms[i] * 0.062) );
// ---------------------------------------------------------------
// get PSPs from the other MS and FS neurons
Ggaba_ms[i] += SEQ_MSGABA[SpikeEventCycle_MSGABA*N_MS + i]; // Adds current GABAergic PSPs to the conductance bin
Ggaba_ms[i] = Ggaba_ms[i] * gabaExp_ms;
SEQ_MSGABA[SpikeEventCycle_MSGABA*N_MS + i] = 0; // reset the PSP buffer
// ---------------------------------------------------------------
// update the membrane
VMS = Vms[i]; // save the previous state
UMS = Ums[i]; // save the previous state
IGABA_ms[i] = (Ggaba_ms[i] * (Egaba - VMS));
IAMPA_ms[i] = (Gglu_ms_AMPA[i] * (Eglu - VMS)) * (1 + _MS(i,12) * lambda1_ms);
INMDA_ms[i] = Mg_ms[i] * (Gglu_ms_NMDA[i] * (Eglu - VMS)) * (1 + _MS(i,11) * lambda2_ms);
IDA_ms[i] = lambda1_ms * _MS(i,13) * (Vms[i] - _MS(i,9));
Isyn_ms[i] = IAMPA_ms[i] + INMDA_ms[i] + IGABA_ms[i] + IDA_ms[i];
//Vms[i] = VMS + dt * ( ( _MS(i,8) * (1 - _MS(i,10)*lambda2_ms) * (VMS - _MS(i,1)) * (VMS - _MS(i,2)) - Ums[i]) + Isyn_ms[i] ) / _MS(i,0);
//Ums[i] = Ums[i] + dt * _MS(i,3) * (_MS(i,4) * (VMS - _MS(i,1)) - Ums[i]);
Vms1 = VMS + hdt * ( ( _MS(i,8) * (1 - _MS(i,10)*lambda2_ms) * (VMS - _MS(i,1)) * (VMS - _MS(i,2)) - UMS) + Isyn_ms[i] ) / _MS(i,0);
Ums1 = UMS + hdt * _MS(i,3) * (_MS(i,4) * (VMS - _MS(i,1)) - UMS);
Vms[i] = VMS + dt * (( _MS(i,8) * (1 - _MS(i,10)*lambda2_ms) * (Vms1 - _MS(i,1)) * (Vms1 - _MS(i,2)) - Ums1) + Isyn_ms[i] ) / _MS(i,0);
Ums[i] = UMS + dt * _MS(i,3) * (_MS(i,4) * (Vms1 - _MS(i,1)) - Ums1);
if (Vms[i] >= _MS(i,7)){ // Check for spike events
VMS = _MS(i,7);
Vms[i] = _MS(i,5);
Ums[i] = Ums[i] + _MS(i,6);
// ---------------------------------------------------------------
// save the cell number and spike time
if (MSspikecount < MSspikebuffer){
STms[MSspikecount] = i;
STms[MSspikecount+MSspikebuffer] = T;
MSspikecount++;
}
else if (MSspikecount >= MSspikebuffer){
printf("Warning, exceeded MS spike buffer size \n");
printf("%i %i \n", MSspikecount, MSspikebuffer);
t = tend;
}
// ---------------------------------------------------------------
// Update the Spike event que for the target cells
for (int targcellind = Cmsms_b.data[i]; targcellind <= Cmsms_b.data[i+1]-1; targcellind++){ // for each of the target cells
// get the index in the spike que for the target cell, given its delay
SEQind_ms = Cmsms.data[targcellind] + ((SpikeEventCycle_MSGABA-1) + Cmsms_d.data[targcellind])*N_MS;
if (SEQind_ms >= SpikeQueSize_MS){ // if SEind is larger than the spike que, wrap around
SEQind_ms = SEQind_ms - SpikeQueSize_MS;
}
// add the spike event to the spike que for the target cell
SEQ_MSGABA[SEQind_ms] = SEQ_MSGABA[SEQind_ms] + (Cmsms_w.data[targcellind] / ts_gaba); // update the Spike event que
}
}
}
// update the FS gap junctions
for (int k = 0; k < N_fsgap; k++){
Vgap1 = Pgapfs.data[k];
Vgap2 = Pgapfs.data[k + N_fsgap];
Vfsgap[k] = Vfsgap[k] + dt * ((Vfs[Vgap1] - Vfsgap[k]) + (Vfs[Vgap2] - Vfsgap[k])) / tau_fsgap;
}
// ---------------------------------------------------------------
// for each FS neuron
// ---------------------------------------------------------------
for (int j = 0; j < N_FS; j++){
float testIgapfs = Igapfs[j];
spk_fs[j] = 0; // reset the spike que
int T_FSSEG = 0;
p_FSSEG = r_FSSEG.data[j] * dt * 0.001;
U_FSSEG = UNI;
R_FSSEG = (U_FSSEG <= p_FSSEG); // the reference spike train
for (int ist = 0; ist < N_FSSEG.data[j]; ist++){
if (UNI <= alpha_FSSEG.data[j]){
T_FSSEG = R_FSSEG;
}
else {
T_FSSEG = (UNI <= p_FSSEG);
}
spk_fs[j] = spk_fs[j] + T_FSSEG;
}
// ---------------------------------------------------------------
//Update the FS neurons cortical input
Gglu_fs[j] = Gglu_fs[j] + (Cctfs_w.data[j] * spk_fs[j] / ts_glu_AMPA);
Gglu_fs[j] = Gglu_fs[j] * gluExp_fs;
// ---------------------------------------------------------------
// get GABAergic input from the other FS neurons
Ggaba_fs[j] += SEQ_FSGABA[SpikeEventCycle_FSGABA*N_FS + j]; // Adds current GABAergic PSPs to the conductance bin
Ggaba_fs[j] = Ggaba_fs[j] * gabaExp_fs;
if (SEQ_FSGABA[SpikeEventCycle_FSGABA*N_FS + j] > 1000){
printf("Too many spikes! %i %i \n", SEQ_FSGABA[SpikeEventCycle_FSGABA*N_FS + j], t);
throw "Too many spikes";
}
SEQ_FSGABA[SpikeEventCycle_FSGABA*N_FS + j] = 0; // reset the PSP buffer
// ---------------------------------------------------------------
// calculate the current from the gap junctions
Igapfs[j] = 0.0;
for (int source = Cgapfs_b.data[j]; source < Cgapfs_b.data[j+1]; source++){
Igapfs[j] = Igapfs[j] + Cgapfs_w.data[source] * (Vfsgap[Cgapfs.data[source]] - Vfs[j]);
if (isinf(Igapfs[j])){
printf("\n \n **** Warning, Igapfs is a inf. Vfsgap %f Cgapfs %i source %i **** \n \n", Vfsgap[Cgapfs.data[source]], Cgapfs.data[source], source);
throw "Igapfs is a Inf";
}
}
// ---------------------------------------------------------------
//Update the FS neurons
VFS = Vfs[j]; // save the previous state
UFS = Ufs[j]; // save the previous state
// DA modulation of the GABA currents
IAMPA_fs[j] = (Gglu_fs[j] * (Eglu - Vfs[j]));
IGABA_fs[j] = (Ggaba_fs[j] * (Egaba - Vfs[j])) * (1 - _FS(j, 11)*lambda2_fs);
Isyn_fs[j] = IAMPA_fs[j] + IGABA_fs[j];
if (isnan(Isyn_fs[j])){
printf("Warning, Isyn_fs is a NaN %f, IAMPA = %f, IGABA = %f IDA_fs = %f\n", Isyn_fs[j], IAMPA_fs[j], IGABA_fs[j], IDA_fs[j]);
printf("Warning, Vfs is a NaN \n");
throw "Vfs is a NaN";
}
if (isnan(Igapfs[j])){
printf("Warning, Igapfs is a NaN \n");
throw "Igapfs is a NaN";
}
if (isinf(Igapfs[j])){
printf("Warning, Igapfs is a inf \n");
throw "Igapfs is a Inf";
}
// Vfs[j] = VFS + dt * (_FS(j, 3) * ((VFS - _FS(j, 1) * (1-_FS(j, 10)*lambda1_fs)) * (VFS - _FS(j, 2))) - Ufs[j] + Igapfs[j] + Isyn_fs[j] ) / _FS(j, 0);
// midpoint estimate of V
Vfs1 = VFS + hdt * (_FS(j, 3) * ((VFS - _FS(j, 1) * (1-_FS(j, 10)*lambda1_fs)) * (VFS - _FS(j, 2))) - UFS + Igapfs[j] + Isyn_fs[j] ) / _FS(j, 0);
// midpoint estimate of U
if (VFS < _FS(j, 9)){
//Ufs[j] = UFS + dt * -_FS(j, 4)*UFS;
Ufs1 = UFS + hdt * -_FS(j, 4)*UFS;
}
else if (VFS >= _FS(j, 9)){
tmp = (VFS - _FS(j, 9));
//Ufs[j] = UFS + dt * _FS(j, 4) * (_FS(j, 5) * pow((VFS - _FS(j, 9)), 3) - UFS);
Ufs1 = UFS + hdt * _FS(j, 4) * (_FS(j, 5) * tmp*tmp*tmp - UFS);
}
// second-step update of V
Vfs[j] = VFS + dt * (_FS(j, 3) * ((Vfs1 - _FS(j, 1) * (1-_FS(j, 10)*lambda1_fs)) * (Vfs1 - _FS(j, 2))) - Ufs1 + Igapfs[j] + Isyn_fs[j] ) / _FS(j, 0);
// second-step update of U
if (VFS < _FS(j, 9)){
//Ufs[j] = UFS + dt * -_FS(j, 4)*UFS;
Ufs[j] = UFS + dt * -_FS(j, 4)*Ufs1;
}
else if (VFS >= _FS(j, 9)){
tmp = (Vfs1 - _FS(j, 9));
//Ufs[j] = UFS + dt * _FS(j, 4) * (_FS(j, 5) * pow((VFS - _FS(j, 9)), 3) - UFS);
Ufs[j] = UFS + dt * _FS(j, 4) * (_FS(j, 5) * tmp*tmp*tmp - Ufs1);
}
if (isnan(Vfs[j])){
printf("Warning, Isyn_fs = %f, and Igapfs = %f \n", Isyn_fs[j], Igapfs[j]);
printf("Warning, Vfs is a NaN \n");
throw "Vfs is a NaN";
}
// ---------------------------------------------------------------
// Check for spike events
if (Vfs[j] >= _FS(j, 8)){
VFS = _FS(j, 8);
Vfs[j] = _FS(j, 6);
Ufs[j] = Ufs[j] + _FS(j, 7);
// ---------------------------------------------------------------
// save the cell number and spike time
if (FSspikecount < FSspikebuffer){
STfs[FSspikecount] = j;
STfs[FSspikecount+FSspikebuffer] = T;
FSspikecount++;
}
// check for overrun of the spike buffer
else if (FSspikecount >= FSspikebuffer){
printf("Warning, exceeded FS spike buffer size \n");
throw "exceeded FS spike buffer size";
}
// ---------------------------------------------------------------
// Update the MS spike event que
for (int targcellind = Cfsms_b.data[j]; targcellind <= Cfsms_b.data[j+1]-1; targcellind++){ // for each of the target cells
// get the index in the spike que for the target cell, given its delay
SEQind_ms = Cfsms.data[targcellind] + ((SpikeEventCycle_MSGABA-1) + Cfsms_d.data[targcellind])*N_MS;
if (SEQind_ms >= SpikeQueSize_MS){ // if SEind is larger than the spike que, wrap around
SEQind_ms = SEQind_ms - SpikeQueSize_MS;
}
// add the spike event to the spike que for the target cell
SEQ_MSGABA[SEQind_ms] = SEQ_MSGABA[SEQind_ms] + (Cfsms_w.data[targcellind] / ts_gaba); // update the Spike event que
}
// ---------------------------------------------------------------
// Update the FS spike event que
for (int targcellind = Cfsfs_b.data[j]; targcellind <= Cfsfs_b.data[j+1]-1; targcellind++){ // for each of the target cells
// get the index in the spike que for the target cell, given its delay
SEQind_fs = Cfsfs.data[targcellind] + ((SpikeEventCycle_FSGABA-1) + Cfsfs_d.data[targcellind])*N_FS;
// if SEind is larger than the spike que, wrap around
if (SEQind_fs >= SpikeQueSize_FS){
SEQind_fs = SEQind_fs - SpikeQueSize_FS;
}
if ((Cfsfs_w.data[targcellind]) > 100){
printf("Warning, FS weight too big! %i %f \n", targcellind, Cfsfs_w.data[targcellind]);
throw "FS weight too big!";
}
// add the spike event to the spike que for the target cell
SEQ_FSGABA[SEQind_fs] = SEQ_FSGABA[SEQind_fs] + (Cfsfs_w.data[targcellind] / ts_gaba);
}
}
} // for each FS neurons
// ===============================================================
// update the MS PSP cycle position
if (SpikeEventCycle_MSGABA < maxSEQdelay_MSGABA){
SpikeEventCycle_MSGABA++;
}
else {
SpikeEventCycle_MSGABA = 0;
}
// update the FS PSP cycle position
if (SpikeEventCycle_FSGABA < maxSEQdelay_FSGABA){
SpikeEventCycle_FSGABA++;
}
else {
SpikeEventCycle_FSGABA = 0;
}
// ===============================================================
// save some example neuron behaviour
tout[t] = T;
Vmsout[t] = Vms[0];
Vfsout[t] = Vfs[0];
for (int RecInd = 0; RecInd < RecordChan_MS.M; RecInd++){
_RecordChan_MS_out(t, RecInd) = Isyn_ms[RecordChan_MS.data[RecInd]];
}
_RecordChan_MS_out(t, 0) = Vms[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 1) = Ums[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 2) = spk_ms[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 3) = Gglu_ms_AMPA[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 4) = Gglu_ms_NMDA[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 5) = IAMPA_ms[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 6) = INMDA_ms[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 7) = Ggaba_ms[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 8) = IGABA_ms[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 9) = IDA_ms[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 10) = Isyn_ms[RecordChan_MS.data[1]];
_RecordChan_MS_out(t, 11) = Vms[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 12) = Ums[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 13) = spk_ms[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 14) = Gglu_ms_AMPA[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 15) = Gglu_ms_NMDA[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 16) = IAMPA_ms[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 17) = INMDA_ms[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 18) = Ggaba_ms[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 19) = IGABA_ms[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 20) = IDA_ms[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 21) = Isyn_ms[RecordChan_MS.data[10]];
_RecordChan_MS_out(t, 22) = Vms[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 23) = Ums[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 24) = spk_ms[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 25) = Gglu_ms_AMPA[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 26) = Gglu_ms_NMDA[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 27) = IAMPA_ms[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 28) = INMDA_ms[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 29) = Ggaba_ms[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 30) = IGABA_ms[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 31) = IDA_ms[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 32) = Isyn_ms[RecordChan_MS.data[15]];
_RecordChan_MS_out(t, 33) = Vms[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 34) = Ums[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 35) = spk_ms[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 36) = Gglu_ms_AMPA[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 37) = Gglu_ms_NMDA[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 38) = IAMPA_ms[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 39) = INMDA_ms[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 40) = Ggaba_ms[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 41) = IGABA_ms[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 42) = IDA_ms[RecordChan_MS.data[20]];
_RecordChan_MS_out(t, 43) = Isyn_ms[RecordChan_MS.data[20]];
} // end of the simulation loop
} // end of the main simulation function
// ========================================================================
// Code to catch exceptions before they crash DCE!!!
// ========================================================================
#include <exception>
using namespace std;
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
try {
// dodgy code
execute(nlhs, plhs, nrhs, prhs);
}
catch(std::exception& e) {
printf(e.what());
return;
}
catch(const char* e) {
printf(e);
return;
}
catch(...) {
// report and close gracefully
printf("an unexpected exception occurred\n");
return;
}
}
| [
"tom.morse@yale.edu"
] | tom.morse@yale.edu |
6fb3ab9f009cbc48ad5f8faac5238e7e0cb8113f | 2523d516ce49af7f082685b8a34c7dd8e99a40b1 | /Day 26/linked list.cpp | 30ba70ae51db321db5ecc523f18a2f7406728fd3 | [] | no_license | jtomar24/100-days-of-code | 3b3ee0f5421a7dc9b1ceb606b05fffc4feb3c1ac | 3f6843507dc635d272aae52ca825ed090cf51f85 | refs/heads/main | 2023-07-08T12:11:19.332444 | 2021-08-15T16:26:17 | 2021-08-15T16:26:17 | 372,228,583 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | #include <bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
};
void printLinkedList(Node* n)
{
while(n!=0)
{
cout<<n->data<<" ";
n=n->next;
}
}
int main() {
//CREATING 3 NODES
Node* head=NULL;
Node* second=NULL;
Node* third=NULL;
//ALLOCATING NODES IN HEAP
head=new Node();
second=new Node();
third=new Node();
//ASSIGNING THE data
head->data=1;
head->next=second;
second->data=2;
second->next=third;
third->data=3;
third->next=NULL;
printLinkedList(head);
return 0;
}
//output :1 2 3
| [
"noreply@github.com"
] | noreply@github.com |
466d7797c1c472a6ad9918a2b5c2f16893877645 | dfe1f796a54143e5eb8661f3328ad29dbfa072d6 | /psx/_dump_/34/_dump_c_src_/diabpsx/psxsrc/prof.cpp | 948927c5c11c1bd75aa74bff65d4598cd2ecc875 | [
"Unlicense"
] | permissive | diasurgical/scalpel | 0f73ad9be0750ce08eb747edc27aeff7931800cd | 8c631dff3236a70e6952b1f564d0dca8d2f4730f | refs/heads/master | 2021-06-10T18:07:03.533074 | 2020-04-16T04:08:35 | 2020-04-16T04:08:35 | 138,939,330 | 15 | 7 | Unlicense | 2019-08-27T08:45:36 | 2018-06-27T22:30:04 | C | UTF-8 | C++ | false | false | 1,220 | cpp | // C:\diabpsx\PSXSRC\PROF.CPP
#include "types.h"
// address: 0x8008D648
// line start: 87
// line end: 94
void PROF_Open__Fv() {
}
// address: 0x8008D688
// line start: 99
// line end: 100
bool PROF_State__Fv() {
}
// address: 0x8008D694
// line start: 104
// line end: 105
void PROF_On__Fv() {
}
// address: 0x8008D6A4
// line start: 109
// line end: 110
void PROF_Off__Fv() {
}
// address: 0x8008D6B0
// line start: 114
// line end: 115
void PROF_CpuEnd__Fv() {
}
// address: 0x8008D6E0
// line start: 119
// line end: 120
void PROF_CpuStart__Fv() {
}
// address: 0x8008D704
// line start: 124
// line end: 125
void PROF_DrawStart__Fv() {
}
// address: 0x8008D728
// line start: 129
// line end: 130
void PROF_DrawEnd__Fv() {
}
// address: 0x8008D758
// line start: 134
// line end: 174
void PROF_Draw__FPUl(unsigned long *Ot) {
{
{
// register: 2
// size: 0x18
register struct POLY_F4 *F4;
// register: 22
register int XCent;
{
// register: 23
register int f;
{
// register: 2
// size: 0x14
register struct POLY_F3 *F3;
}
}
}
}
}
// address: 0x8008D94C
// line start: 179
// line end: 180
void PROF_Restart__Fv() {
}
| [
"rnd0x00@gmail.com"
] | rnd0x00@gmail.com |
fdf5f322807704f7f2e8a57c98b140be6039fd4e | 9c5d00397522025a79d4773e5d97a09a9bca65f8 | /Common/Packet/MSGCMD/PacketMSGCMD_CHGACCE.cpp | 7f490c6c0fabe263aea09e8f61aed6920ee691fe | [] | no_license | uraraworks/SBOP2 | b818c2a0515110c21f02fcd99fb1a26553cb8e10 | 11a77d846782df6ba74dd45803477cf19fb32934 | refs/heads/master | 2023-07-05T07:52:52.013477 | 2021-08-17T08:33:24 | 2021-08-17T08:33:24 | 275,423,701 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,087 | cpp | /* Copyright(C)URARA-works 2007 */
/* ========================================================================= */
/* ファイル名 :PacketMSGCMD_CHGACCE.cpp */
/* 内容 :コマンド(メッセージコマンド系:アクセサリ変更) 実装ファイル */
/* 作成 :年がら年中春うらら(URARA-works) */
/* 作成開始日 :2007/05/04 */
/* ========================================================================= */
#include "StdAfx.h"
#include "Command.h"
#include "PacketMSGCMD_CHGACCE.h"
/* ========================================================================= */
/* 関数名 :CPacketMSGCMD_CHGACCE::CPacketMSGCMD_CHGACCE */
/* 内容 :コンストラクタ */
/* 日付 :2007/05/04 */
/* ========================================================================= */
CPacketMSGCMD_CHGACCE::CPacketMSGCMD_CHGACCE()
{
m_dwCharID = 0;
m_nType = 0;
}
/* ========================================================================= */
/* 関数名 :CPacketMSGCMD_CHGACCE::~CPacketMSGCMD_CHGACCE */
/* 内容 :デストラクタ */
/* 日付 :2007/05/04 */
/* ========================================================================= */
CPacketMSGCMD_CHGACCE::~CPacketMSGCMD_CHGACCE()
{
}
/* ========================================================================= */
/* 関数名 :CPacketMSGCMD_CHGACCE::Make */
/* 内容 :パケットを作成 */
/* 日付 :2007/05/04 */
/* ========================================================================= */
void CPacketMSGCMD_CHGACCE::Make(
DWORD dwCharID, /* [in] キャラID */
int nType) /* [in] 種別 */
{
PBYTE pData, pDataTmp;
DWORD dwSize;
PPACKETBASE pPacketBase;
dwSize = sizeof (PACKETBASE) +
sizeof (dwCharID) +
sizeof (nType);
pData = new BYTE[dwSize];
ZeroMemory (pData, dwSize);
pPacketBase = (PPACKETBASE)pData;
pPacketBase->byCmdMain = SBOCOMMANDID_MAIN_MSGCMD;
pPacketBase->byCmdSub = SBOCOMMANDID_SUB_MSGCMD_CHGACCE;
pDataTmp = (PBYTE)(pPacketBase + 1);
CopyMemoryRenew (pDataTmp, &dwCharID, sizeof (dwCharID), pDataTmp); /* キャラID */
CopyMemoryRenew (pDataTmp, &nType, sizeof (nType), pDataTmp); /* 種別 */
RenewPacket (pData, dwSize);
}
/* ========================================================================= */
/* 関数名 :CPacketMSGCMD_CHGACCE::Set */
/* 内容 :パケットを設定 */
/* 日付 :2007/05/04 */
/* ========================================================================= */
PBYTE CPacketMSGCMD_CHGACCE::Set(PBYTE pPacket)
{
PBYTE pRet, pDataTmp;
pRet = pPacket;
pDataTmp = CPacketBase::Set (pPacket);
CopyMemoryRenew (&m_dwCharID, pDataTmp, sizeof (m_dwCharID), pDataTmp); /* キャラID */
CopyMemoryRenew (&m_nType, pDataTmp, sizeof (m_nType), pDataTmp); /* 種別 */
pRet = pDataTmp;
return pRet;
}
/* Copyright(C)URARA-works 2007 */
| [
"RXP10430@868715c2-6dae-4c12-b071-75cd31844a78"
] | RXP10430@868715c2-6dae-4c12-b071-75cd31844a78 |
b625b21c17a0667f5fe4b69c08d2619f3a7098a9 | 1aad97e21199629787575238c4aee672915e4f24 | /src/main.cpp | f046adc7fca7c931209b703ba105c4911f46aed8 | [] | no_license | Freff/AlgoTrader | 5aa1702753c4177c0e3c9b6a42dfed42db875597 | 02903130bbe02b06f5471a91429f091df1d8a7ca | refs/heads/master | 2021-09-03T08:24:49.173481 | 2018-01-07T14:12:32 | 2018-01-07T14:12:32 | 108,639,862 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,413 | cpp | //============================================================================
// Name : AlgoTrader.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <memory>
#include "algorithm/BasicInvestor.hpp"
#include "finance/Wallet.hpp"
#include "stocks/StockRegistry.hpp"
#include "algorithm/IAlgorithmRegistry.hpp"
#include "algorithm/AlgorithmRegistry.hpp"
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <curlpp/Exception.hpp>
#include <curlpp/Infos.hpp>
#include <json.hpp>
#include <sstream>
#include <fstream>
using json = nlohmann::json;
//Date Time Open High Low Close Volume
int main()
{
// std::shared_ptr<IWallet> wallet = std::make_shared<Wallet>(1000.0);
// std::shared_ptr<IStockRegistry> sr = std::make_shared<StockRegistry>();
// sr->load("IBM", "res/IBM_unadjusted.txt");
//
// std::shared_ptr<IAlgorithmRegistry> ar = std::make_shared<AlgorithmRegistry>();
// ar->addAlgorithm("basic", std::make_shared<BasicInvestor>(wallet));
//
// auto a = ar->getAlgorithm("basic");
// a->run();
std::ifstream inFile("secret-api-key.txt");
std::string secret;
if(inFile.good())
{
std::getline(inFile, secret);
}
inFile.close();
std::string url = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&outputsize=compact&interval=1min&apikey=" + secret;
try
{
curlpp::Cleanup cleaner;
curlpp::Easy request;
std::stringstream result;
using namespace curlpp::Options;
request.setOpt(cURLpp::Options::Verbose(true));
request.setOpt(cURLpp::Options::Url(url));
request.setOpt(cURLpp::Options::WriteStream(&result));
request.perform();
std::string effURL;
curlpp::infos::EffectiveUrl::get(request, effURL);
std::cout << result.str();
auto parsedResult = json::parse(result.str());
for (auto& element : parsedResult) {
//std::cout << element << std::endl;
}
}
catch ( curlpp::LogicError & e ) {
std::cout << e.what() << std::endl;
}
catch ( curlpp::RuntimeError & e ) {
std::cout << e.what() << std::endl;
}
}
| [
"chris.bean91@gmail.com"
] | chris.bean91@gmail.com |
57f0a81bdad49e86547afaa954309f588aa81b16 | 8c6047251fab46c71030b8fc4fac995c3269639f | /modules/wechat_qrcode/src/decodermgr.cpp | 2b410ac3c475caa89a1e1cd881f6621266775a88 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-Warranty",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | DevenLu/opencv_contrib | 01210c07b292f2290861df1e51b27cc5fb9295c9 | 273246d8572cf005c7648e60c6cef78240edfb3e | refs/heads/master | 2023-02-12T21:40:03.347386 | 2021-01-15T08:15:00 | 2021-01-15T08:15:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,881 | cpp | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Tencent is pleased to support the open source community by making WeChat QRCode available.
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
#include "decodermgr.hpp"
#include "precomp.hpp"
using zxing::ArrayRef;
using zxing::BinaryBitmap;
using zxing::DecodeHints;
using zxing::ErrorHandler;
using zxing::LuminanceSource;
using zxing::Ref;
using zxing::Result;
using zxing::UnicomBlock;
namespace cv {
namespace wechat_qrcode {
int DecoderMgr::decodeImage(cv::Mat src, bool use_nn_detector, string& result) {
int width = src.cols;
int height = src.rows;
if (width <= 20 || height <= 20)
return -1; // image data is not enough for providing reliable results
std::vector<uint8_t> scaled_img_data(src.data, src.data + width * height);
zxing::ArrayRef<uint8_t> scaled_img_zx =
zxing::ArrayRef<uint8_t>(new zxing::Array<uint8_t>(scaled_img_data));
zxing::Ref<zxing::Result> zx_result;
decode_hints_.setUseNNDetector(use_nn_detector);
Ref<ImgSource> source;
qbarUicomBlock_ = new UnicomBlock(width, height);
// Four Binarizers
ErrorHandler err_handler;
int tryBinarizeTime = 4;
for (int tb = 0; tb < tryBinarizeTime; tb++) {
err_handler.Reset();
if (source == NULL || height * width > source->getMaxSize()) {
source = ImgSource::create(scaled_img_zx.data(), width, height, 1, 1, err_handler);
if (err_handler.ErrCode()) {
continue;
}
} else {
source->reset(scaled_img_zx.data(), width, height, 1, 1, err_handler);
if (err_handler.ErrCode()) {
continue;
}
}
int ret = TryDecode(source, zx_result);
if (!ret) {
result = zx_result->getText()->getText();
return ret;
}
// try different binarizers
binarizer_mgr_.SwitchBinarizer();
}
return -1;
}
int DecoderMgr::TryDecode(Ref<LuminanceSource> source, Ref<Result>& result) {
int res = -1;
string cell_result;
// get binarizer
zxing::Ref<zxing::Binarizer> binarizer = binarizer_mgr_.Binarize(source);
zxing::Ref<zxing::BinaryBitmap> binary_bitmap(new BinaryBitmap(binarizer));
binary_bitmap->m_poUnicomBlock = qbarUicomBlock_;
result = Decode(binary_bitmap, decode_hints_);
res = (result == NULL) ? 1 : 0;
if (res == 0) {
result->setBinaryMethod(int(binarizer_mgr_.GetCurBinarizer()));
}
return res;
}
Ref<Result> DecoderMgr::Decode(Ref<BinaryBitmap> image, DecodeHints hints) {
return reader_->decode(image, hints);
}
} // namespace wechat_qrcode
} // namespace cv | [
"zhigangdai@hotmail.com"
] | zhigangdai@hotmail.com |
d2f81af1b42c7c23d953f49f122570deb0de8540 | 0d4ddc3725b13280c930685bb59937a916a63bac | /CS1805-U201814615 于祯奇/工程文件及源代码/CreateCNF.cpp | 6920320ff90bf7ec378a570489713dccaa97c217 | [] | no_license | Yu-zq1010/C-And-Data-Structure-Course-Design_BC_202003 | 883e7a60942bbfe39893b434c0504075136a71e6 | 6ced272fda4fb5428c5e2190bc8c42b74da0fa00 | refs/heads/master | 2022-07-26T06:19:18.575993 | 2020-05-07T12:29:15 | 2020-05-07T12:29:15 | 262,038,899 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,976 | cpp | #include"head.h"
status CreateAdjacencyList(char* filename, CNF& F)
{
char s[4]; int i = 0, j = 0, k = 0;/*计数器*/ int a = 0, n[50] = { 0 }, * Cla = NULL; FILE* fp = NULL;
if ((fp = fopen(filename, "r")) == NULL)//如果filename文件打开失败
{
return ERROR;
}
for (; s[0] != 'p'; fscanf(fp, "%c", &s[0]));//逐个读取文件中的元素,直到遇到以p为开始的正文
fscanf(fp, "%s", s);
if (s[0] == 'c' && s[1] == 'n' && s[2] == 'f')//若是cnf文件
{
fscanf(fp, "%d", &F.LitNum);
fscanf(fp, "%d", &F.ClaNum);
if (!(F.Letters = (LitList)calloc(2 * F.LitNum + 1, sizeof(Litnode))))//动态分配数组
{
exit(OVERFLOW);
}
for (i = 0; i < F.ClaNum; i++)//循环输入第i个子句
{
j = 0;//初始化计数器
fscanf(fp, "%d", &a);
while (a != 0)//逐个录入每个子句的文字
{
n[j] = a;
j++;//统计每个子句的文字个数
fscanf(fp, "%d", &a);
}
if (!(Cla = (int*)calloc(j + 1, sizeof(int))))//动态分配数组
{
exit(OVERFLOW);
}
Cla[0] = j;//将标志位设置为子句长度,大于0表明则该子句存在
for (k = 0; k < j; k++)//将保存好的数放在动态数组中
{
Cla[k + 1] = n[k];
}
for (k = 1; k < j + 1; k++)//构建每个文字的邻接表
{
ClaNode* L;//创建新的结点,方便插入
if (!(L = (ClaNode*)malloc(sizeof(ClaNode))))
{
exit(OVERFLOW);
}
L->clause = Cla;
L->ClaNum = Cla[0];
if (Cla[k] > 0 && NotSameNum(Cla, k))//若该文字为正文字
{
L->NextCla = F.Letters[Cla[k]].FirstCla;
F.Letters[Cla[k]].FirstCla = L;
}
else if (Cla[k] < 0 && NotSameNum(Cla, k))//若为负文字
{
L->NextCla = F.Letters[F.LitNum - Cla[k]].FirstCla;
F.Letters[F.LitNum - Cla[k]].FirstCla = L;
}
}
}
for (i = 1; i <= 2 * F.LitNum; i++)
{
F.Letters[i].value = Undefine;
}
return OK;
}
else
{
return ERROR;//不是cnf文件,创建失败
}
} | [
"yuzhenqi19991010@gmail.com"
] | yuzhenqi19991010@gmail.com |
10d8e511796e8c712b9cf18611c99f2b84f401e2 | 6043c1d986bcda428aba1d0fa7a3b170a4d4b0b6 | /practice5.cpp | 146dc3771b133ce836f106ebe8a225ba8996b8df | [] | no_license | raima20/C_Programming | 1d796c08ac22a1515ee10d68c8e781148821c5d7 | f66358f1f23b607d07c8e10661da8c2fdfa80c8d | refs/heads/master | 2023-06-21T22:12:15.161961 | 2021-07-19T15:55:55 | 2021-07-19T15:55:55 | 387,517,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | cpp | #include<stdio.h>
int main()
{
int a[100],i,n,sum=0;
printf("Enter the number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("a[%d]:",i);
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
sum=sum+a[i];
printf("%d",sum);
return 0;
}
| [
"sarkar.raima155@gmail.com"
] | sarkar.raima155@gmail.com |
6c3b7ea9f142006542d0b2694453dbe7c72554af | 9eb5f9e81206311648505e43d36733cfee82dc75 | /sbl/math/crt.hpp | b5c2827a46ecf4cafad801bd09d21cb7f6b3b593 | [
"Apache-2.0"
] | permissive | Mizuchi/SBL | 7c696bab1614b261d6a629e201dbb0dd057a19f1 | e5bbb8c83ed809af398de2b7c5cc78a28f7ab798 | refs/heads/master | 2016-09-03T07:10:20.447759 | 2013-09-24T12:15:30 | 2013-09-24T12:15:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | hpp | #ifndef _sbl_chinart
#define _sbl_chinart
#include<functional>
#include<numeric>
#include"gcd.hpp"
#include"modular.hpp"
namespace sbl {
/// @return a solution to a Chinese Remainder Theorem problem.
/// @pre gcd(m[i], m[j]) == 1
/// @post return % a[i] == m[i]
template <
class Return,
class IterBegA,
class IterEndA,
class IterBegM,
class IterEndM
> Return crt(
IterBegA begA,
IterEndA endA,
IterBegM begM,
IterEndM endM
) {
// arg: [2, 3, 2]; [3, 5, 7]
// ret: 23
assert(std::distance(begA, endA) == std::distance(begM, endM));
Return result(0);
Return p = 1;
p = std::accumulate(begM, endM, p, std::multiplies<Return>());
while (begA != endA) {
assert(begM != endM);
Return t = p / *begM;
Return x, y;
gcd<Return, Return>(t, *begM, &x, &y);
// result += t * x * A[i]
result = add_mod(result, mul_mod(t, mul_mod(x, *begA, p), p), p);
++begA;
++begM;
}
return result;
}
} // namespace sbl
#endif
| [
"ytj000@gmail.com"
] | ytj000@gmail.com |
352aab1d33475ba28e7da1eea1b4d54e8a3c8339 | aa1715249d62f07bbe9ad96a7dc60398298b2993 | /RSA_primes/bserver.cpp | 9224271c8dab851c61e6994ff864c6e813582a11 | [] | no_license | BlackEtude/Computer-security | e934dbc7705ba20246f96e2f837f03d75155a930 | 8921a05d6c08e8a3660a2248fec917968b447c21 | refs/heads/master | 2021-03-22T04:02:10.152178 | 2018-10-27T07:18:37 | 2018-10-27T07:18:37 | 107,356,695 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,408 | cpp | //
// Created by pandemic on 05.12.17.
//
#include "bserver.h"
bserver::bserver() {
num = BN_new();
ctx = BN_CTX_new();
}
void bserver::setup(char* path) {
generate_password();
// Generate key pairs
// generate_safe_keys(50, path);
generate_safe_keys(100, path);
// generate_safe_keys(4096, path);
// generate_safe_keys(8192, path);
// generate_safe_keys(16384, path);
// Generate worse key pairs
// generate_weak_keys(50, path);
generate_weak_keys(100, path);
// generate_weak_keys(4096, path);
// generate_weak_keys(8192, path);
// generate_weak_keys(16384, path);
}
void bserver::generate_password() {
auto *p = generate_random_bytes(LENGTH);
auto *password = code_base64(p, LENGTH);
std::cout << "Generated pass: " << password << std::endl;
auto *s = generate_random_bytes(LENGTH);
auto *salt = code_base64(s, LENGTH);
unsigned char out[HASH_LEN];
memset(out, 0, sizeof out);
if(PKCS5_PBKDF2_HMAC(password, LENGTH, reinterpret_cast<const unsigned char *>(salt), LENGTH, ITERS, EVP_sha256(), HASH_LEN, out) != 1) {
std::cout << "Failure" << std::endl;
}
auto *key = code_base64(out, HASH_LEN);
std::ofstream out_pass("server_pass");
std::ofstream out_salt("server_salt");
out_pass << key;
out_salt << salt;
}
unsigned char* bserver::generate_random_bytes(int size) {
auto *buff = (unsigned char*)(malloc(size + 1));
if (!RAND_bytes(buff, size)) {
return NULL;
}
return buff;
}
char* bserver::code_base64(unsigned char *buff, int size) {
char *bytes = NULL;
BIO *b64, *out;
BUF_MEM *bptr;
// Create a base64 filter/sink
if ((b64 = BIO_new(BIO_f_base64())) == NULL) {
return NULL;
}
// Create a memory source
if ((out = BIO_new(BIO_s_mem())) == NULL) {
return NULL;
}
// Chain them
out = BIO_push(b64, out);
BIO_set_flags(out, BIO_FLAGS_BASE64_NO_NL);
// Write the bytes
BIO_write(out, buff, size);
BIO_flush(out);
// Now remove the base64 filter
out = BIO_pop(b64);
// Write the null terminating character
BIO_write(out, "\0", 1);
BIO_get_mem_ptr(out, &bptr);
// Allocate memory for the output and copy it to the new location
bytes = (char*)malloc(bptr->length);
strncpy(bytes, bptr->data, bptr->length);
// Cleanup
BIO_set_close(out, BIO_CLOSE);
BIO_free_all(out);
// free(buff);
return bytes;
}
void bserver::generate_safe_keys(int key_length, char *path_to_save) {
// Measure elapsed time
auto start = std::chrono::high_resolution_clock::now();
// Obliczamy wartość n = pq
// Obliczamy wartość funkcji Eulera dla n: φ ( n ) = ( p − 1 ) ( q − 1 ) {\displaystyle \varphi (n)=(p-1)(q-1)} \varphi (n)=(p-1)(q-1)
// Wybieramy liczbę e (1 < e < φ(n)) względnie pierwszą z φ(n)
// Znajdujemy liczbę d, gdzie jej różnica z odwrotnością liczby e jest podzielna przez φ(n) :
//
// d ≡ e−1 (mod φ(n))
//TODO
BIGNUM *prime1 = BN_new();
BIGNUM *prime2 = BN_new();
BIGNUM *d_safe = BN_new();
BIGNUM *e_safe = BN_new();
BIGNUM *n_safe = BN_new();
BIGNUM *euler = BN_new();
BN_generate_prime_ex(prime1, key_length/2, 1, NULL, NULL, NULL);
BN_generate_prime_ex(prime2, key_length/2, 1, NULL, NULL, NULL);
BN_mul(n_safe, prime1, prime2, ctx);
BIGNUM *one = BN_new();
BIGNUM *temp1 = BN_new();
BIGNUM *temp2 = BN_new();
BN_set_word(one, 1);
BN_sub(temp1, prime1, one);
BN_sub(temp2, prime2, one);
BN_mul(euler, temp1, temp2, ctx);
BIGNUM *gcd = BN_new();
BN_one(one);
do {
BN_rand_range(e_safe, euler);
BN_gcd(gcd, e_safe, euler, ctx);
}
while(BN_cmp(gcd, one) != 0);
BN_mod_inverse(d_safe, e_safe, euler, ctx);
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Generate " << key_length << " keys time: ";
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << "ms" << std::endl;
std::cout << "Prime1: " << BN_bn2dec(prime1) << " is safe: " << check_if_strong_prime(prime1) << std::endl;
std::cout << "Prime2: " << BN_bn2dec(prime2) << " is safe: " << check_if_strong_prime(prime2) << std::endl;
BN_free(prime1);
BN_free(prime2);
BN_free(euler);
BN_free(one);
BN_free(temp1);
BN_free(temp2);
BN_free(gcd);
char p[30];
FILE *file;
std::string s = std::to_string(key_length);
char const *length = s.c_str();
// Save public key
memset(p, 0, sizeof p);
strcat(p, path_to_save);
strcat(p, "public");
strcat(p, length);
file = fopen(p , "w+");
BN_print_fp(file, n_safe);
fprintf(file, "\n");
BN_print_fp(file, e_safe);
fclose(file);
// Save private key
memset(p, 0, sizeof p);
strcat(p, path_to_save);
strcat(p, "private");
strcat(p, length);
file = fopen(p , "w+");
BN_print_fp(file, n_safe);
fprintf(file, "\n");
BN_print_fp(file, d_safe);
fclose(file);
std::cout << "Key " << key_length << " generated" << std::endl << std::endl;
BN_free(n_safe);
BN_free(d_safe);
BN_free(e_safe);
}
void bserver::generate_weak_keys(int key_length, char *path_to_save) {
// Measure elapsed time
auto start = std::chrono::high_resolution_clock::now();
// Obliczamy wartość n = pq
// Obliczamy wartość funkcji Eulera dla n: φ ( n ) = ( p − 1 ) ( q − 1 )
// Wybieramy liczbę e (1 < e < φ(n)) względnie pierwszą z φ(n)
// Znajdujemy liczbę d, gdzie jej różnica z odwrotnością liczby e jest podzielna przez φ(n) :
//
// d ≡ e−1 (mod φ(n))
//TODO
BIGNUM *prime1 = BN_new();
BIGNUM *prime2 = BN_new();
BIGNUM *d_weak = BN_new();
BIGNUM *e_weak = BN_new();
BIGNUM *n_weak = BN_new();
BIGNUM *euler = BN_new();
BIGNUM *max = BN_new();
BIGNUM *max_4 = BN_new();
BIGNUM *zero = BN_new();
BIGNUM *div = BN_new();
BN_set_word(zero, 0);
do {
std::cout << "Generate primes" << std::endl;
BN_generate_prime_ex(prime1, key_length / 2, 0, NULL, NULL, NULL);
BN_generate_prime_ex(prime2, key_length / 2, 0, NULL, NULL, NULL);
BN_mul(n_weak, prime1, prime2, ctx);
max = find_max_factorial(prime1);
BN_mul(max_4, max, max, ctx);
BN_mul(max_4, max_4, max, ctx);
BN_mul(max_4, max_4, max, ctx);
BN_div(div, NULL, max_4, n_weak, ctx);
}
while(BN_cmp(div, zero) > 0);
std::cout << "Prime1: " << BN_bn2dec(prime1) << " is safe: " << check_if_strong_prime(prime1) << std::endl;
std::cout << "Prime2: " << BN_bn2dec(prime2) << " is safe: " << check_if_strong_prime(prime2) << std::endl;
std::cout << BN_bn2dec(n_weak) << " <== N" << std::endl;
std::cout << BN_bn2dec(max_4) << " <== Max^4" << std::endl;
BIGNUM *one = BN_new();
BIGNUM *temp1 = BN_new();
BIGNUM *temp2 = BN_new();
BN_set_word(one, 1);
BN_sub(temp1, prime1, one);
BN_sub(temp2, prime2, one);
BN_mul(euler, temp1, temp2, ctx);
BIGNUM *gcd = BN_new();
BN_one(one);
do {
BN_rand_range(e_weak, euler);
BN_gcd(gcd, e_weak, euler, ctx);
}
while(BN_cmp(gcd, one) != 0);
BN_mod_inverse(d_weak, e_weak, euler, ctx);
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Generate " << key_length << " keys time: ";
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << "ms" << std::endl;
//free
BN_free(gcd);
BN_free(one);
BN_free(temp1);
BN_free(temp2);
BN_free(euler);
BN_free(max);
BN_free(max_4);
BN_free(div);
BN_free(zero);
char p[30];
FILE *file;
std::string s = std::to_string(key_length);
char const *length = s.c_str();
// Save public key
memset(p, 0, sizeof p);
strcat(p, path_to_save);
strcat(p, "public");
strcat(p, length);
file = fopen(p , "w+");
BN_print_fp(file, n_weak);
fprintf(file, "\n");
BN_print_fp(file, e_weak);
fclose(file);
// Save private key
memset(p, 0, sizeof p);
strcat(p, path_to_save);
strcat(p, "private");
strcat(p, length);
file = fopen(p , "w+");
BN_print_fp(file, n_weak);
fprintf(file, "\n");
BN_print_fp(file, d_weak);
fclose(file);
std::cout << "Key " << key_length << " generated" << std::endl << std::endl;
BN_free(n_weak);
BN_free(e_weak);
BN_free(d_weak);
}
void bserver::communicate_with_client(char *password, int port, char *key_path) {
// If pass is not correct -> end
if(!is_server_password_valid(password)) {
std::cout << "Given password is not correct. Aborting..." << std::endl;
return;
}
std::cout << "Given password is correct" << std::endl << std::endl;
// Load proper private key (N, d)
read_key_from_file(key_path);
// Start server
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the given port
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("server_listen");
exit(EXIT_FAILURE);
}
while(true) {
if ((new_socket = accept(server_fd, (struct sockaddr *) &address, (socklen_t *) &addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// Get message from client
read(new_socket, buffer, BUFFER_SIZE);
BIGNUM *m = BN_new();
BN_hex2bn(&m, buffer);
std::cout << "Message received from client" << std::endl;
// If x is not in Zn group -> abort
if (!is_msg_in_group(m)) {
std::cout << "Message x is not in Zn. Aborting..." << std::endl << std::endl;
return;
}
std::cout << "Message x is in Zn." << std::endl;
// Send signed message to client
std::cout << "Signing..." << std::endl;
char *signed_msg = sign_msg(m);
send(new_socket, signed_msg, strlen(signed_msg), 0);
std::cout << "Signed msg sent to client" << std::endl << std::endl;
BN_free(m);
}
}
bool bserver::is_server_password_valid(char *user_pass) {
std::string pass;
std::ifstream myfile("server_pass");
if (myfile.is_open()) {
while (std::getline(myfile, pass));
myfile.close();
}
std::string salt;
std::ifstream myfile2("server_salt");
if (myfile2.is_open()) {
while(std::getline(myfile2, salt));
myfile2.close();
}
unsigned char out[HASH_LEN];
memset(out, 0, sizeof out);
// Hash user's pass
if(PKCS5_PBKDF2_HMAC(user_pass, LENGTH, reinterpret_cast<const unsigned char *>(salt.c_str()), LENGTH, ITERS, EVP_sha256(), HASH_LEN, out) != 1) {
std::cout << "Failure" << std::endl;
}
auto *key = code_base64(out, HASH_LEN);
if(key == pass) {
return true;
}
return false;
}
void bserver::read_key_from_file(char *path) {
std::cout << "Loading key from: " << path << std::endl;
std::string item_name;
std::ifstream nameFileout;
nameFileout.open(path);
std::string line;
//TODO free 'temp' ?
auto *temp = new std::string[2];
int i = 0;
while(std::getline(nameFileout, line)) {
temp[i] = line;
i++;
}
const char *c = temp[0].c_str();
BN_hex2bn(&N, c);
c = temp[1].c_str();
BN_hex2bn(&d, c);
}
bool bserver::is_msg_in_group(BIGNUM *num) {
// If num is in group -> gcd(num,N) == 1
BIGNUM *gcd = BN_new();
BIGNUM *one = BN_new();
BN_gcd(gcd, num, N, ctx);
int ret = BN_cmp(one, gcd);
BN_free(gcd);
BN_free(one);
return ret != 0;
}
char* bserver::sign_msg(BIGNUM *msg_to_sign) {
// s'= (m')^d (mod N)
// Measure time
auto start = std::chrono::high_resolution_clock::now();
BIGNUM *result = BN_new();
BN_mod_exp(result, msg_to_sign, d, N, ctx);
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Signing time: ";
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << "ms" << std::endl;
char *ret = BN_bn2hex(result);
BN_free(result);
return ret;
}
bool bserver::check_if_strong_prime(BIGNUM *prime) {
//condition: prime = 2*q+1
BIGNUM *one = BN_new();
BN_set_word(one, 1);
BN_sub(prime, prime, one);
BN_add(one, one, one);
BN_div(prime, NULL, prime, one, ctx);
int ret = BN_is_prime_fasttest_ex(prime, BN_prime_checks, ctx, 1, NULL);
BN_free(one);
if(ret == 0)
return false;
return true;
}
BIGNUM* bserver::find_max_factorial(BIGNUM *number) {
BIGNUM *z = BN_new();
BIGNUM *one = BN_new();
BIGNUM *rem = BN_new();
BN_set_word(one, 1);
BN_set_word(z, 2);
std::vector<BIGNUM*> factorials;
BN_sub(number, number, one);
BIGNUM *power = BN_new();
BN_mul(power, z, z, ctx);
// z^2 <= number
while(BN_cmp(number, power) >= 0) {
BN_div(NULL, rem, number, z, ctx);
if(BN_is_zero(rem)) {
factorials.push_back(BN_dup(z));
BN_div(number, NULL, number, z, ctx);
}
else {
BN_add(z, z, one);
}
BN_mul(power, z, z, ctx);
}
if(BN_cmp(number, one) == 1) {
factorials.push_back(number);
}
// Find max factorial
BIGNUM *max = BN_new();
BN_set_word(one, 1);
BN_set_word(max, 1);
for(int i = 0; i < factorials.size(); i++) {
if(BN_cmp(factorials.at(i), max) == 1) {
max = BN_dup(factorials.at(i));
}
}
//free
// for(int i = 0; i < factorials.size(); i++)
// BN_free(factorials.at(i));
BN_free(rem);
BN_free(z);
BN_free(power);
BN_free(one);
return max;
}
bserver::~bserver() {
RSA_free(r);
BN_free(num);
BN_free(N);
BN_free(d);
BN_CTX_free(ctx);
}
int main(int argc, char*argv[]) {
if(argc < 3) {
std::cout << "Missing arguments. Aborting..." << std::endl;
return -1;
}
bserver *server = new bserver();
if(strcmp(argv[1], "setup") == 0) {
std::cout << "Setup mode started" << std::endl;
server->setup(argv[2]);
return 0;
}
if(argc < 5) {
std::cout << "Missing arguments" << std::endl;
return -1;
}
if(strcmp(argv[1], "sign") == 0) {
std::cout << "Sign mode started\n" << std::endl;
server->communicate_with_client(argv[2], atoi(argv[3]), argv[4]);
}
else {
std::cout << "Wrong mode selected. Choose 'setup' or 'sign'" << std::endl;
}
return 0;
} | [
"229726@student.pwr.edu.pl"
] | 229726@student.pwr.edu.pl |
944a3c9445076cddcc985ba22cdb0b337a11ba5a | 9e3408b7924e45aa851ade278c46a77b3a85614e | /CHIBI-Engine/Externals/boost/mpl/arg.hpp | 8e69c589abd7da5c21a448230ee43b9f7e8fce73 | [] | no_license | stynosen/CHIBI-Engine | 542a8670bbcd932c0fd10a6a04be3af2eb3991f4 | 6a1b41e94df2e807e9ce999ce955bf19bb48c8ec | refs/heads/master | 2021-01-25T06:37:16.554974 | 2014-01-08T21:49:00 | 2014-01-08T21:49:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,317 | hpp |
#if !defined(BOOST_PP_IS_ITERATING)
///// header body
#ifndef BOOST_MPL_ARG_HPP_INCLUDED
#define BOOST_MPL_ARG_HPP_INCLUDED
// Copyright Peter Dimov 2001-2002
// Copyright Aleksey Gurtovoy 2001-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: arg.hpp 49239 2008-10-10 09:10:26Z agurtovoy $
// $Date: 2008-10-10 11:10:26 +0200 (vr, 10 okt 2008) $
// $Revision: 49239 $
#if !defined(BOOST_MPL_PREPROCESSING_MODE)
# include <boost/mpl/arg_fwd.hpp>
# include <boost/mpl/aux_/na.hpp>
# include <boost/mpl/aux_/na_assert.hpp>
# include <boost/mpl/aux_/arity_spec.hpp>
# include <boost/mpl/aux_/arg_typedef.hpp>
#endif
#include <boost/mpl/aux_/config/static_constant.hpp>
#include <boost/mpl/aux_/config/use_preprocessed.hpp>
#if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \
&& !defined(BOOST_MPL_PREPROCESSING_MODE)
# define BOOST_MPL_PREPROCESSED_HEADER arg.hpp
# include <boost/mpl/aux_/include_preprocessed.hpp>
#else
# include <boost/mpl/limits/arity.hpp>
# include <boost/mpl/aux_/preprocessor/default_params.hpp>
# include <boost/mpl/aux_/preprocessor/params.hpp>
# include <boost/mpl/aux_/config/lambda.hpp>
# include <boost/mpl/aux_/config/dtp.hpp>
# include <boost/mpl/aux_/nttp_decl.hpp>
# include <boost/preprocessor/iterate.hpp>
# include <boost/preprocessor/inc.hpp>
# include <boost/preprocessor/cat.hpp>
BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN
// local macro, #undef-ined at the end of the header
#if !defined(BOOST_MPL_CFG_NO_DEFAULT_PARAMETERS_IN_NESTED_TEMPLATES)
# define AUX778076_ARG_N_DEFAULT_PARAMS(param,value) \
BOOST_MPL_PP_DEFAULT_PARAMS( \
BOOST_MPL_LIMIT_METAFUNCTION_ARITY \
, param \
, value \
) \
/**/
#else
# define AUX778076_ARG_N_DEFAULT_PARAMS(param,value) \
BOOST_MPL_PP_PARAMS( \
BOOST_MPL_LIMIT_METAFUNCTION_ARITY \
, param \
) \
/**/
#endif
#define BOOST_PP_ITERATION_PARAMS_1 \
(3,(0, BOOST_MPL_LIMIT_METAFUNCTION_ARITY, <boost/mpl/arg.hpp>))
#include BOOST_PP_ITERATE()
# undef AUX778076_ARG_N_DEFAULT_PARAMS
BOOST_MPL_AUX_NONTYPE_ARITY_SPEC(1,int,arg)
BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE
#endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // BOOST_MPL_ARG_HPP_INCLUDED
///// iteration
#else
#define i_ BOOST_PP_FRAME_ITERATION(1)
#if i_ > 0
template<> struct arg<i_>
{
BOOST_STATIC_CONSTANT(int, value = i_);
typedef arg<BOOST_PP_INC(i_)> next;
BOOST_MPL_AUX_ARG_TYPEDEF(na, tag)
BOOST_MPL_AUX_ARG_TYPEDEF(na, type)
template<
AUX778076_ARG_N_DEFAULT_PARAMS(typename U, na)
>
struct apply
{
typedef BOOST_PP_CAT(U,i_) type;
BOOST_MPL_AUX_ASSERT_NOT_NA(type);
};
};
#else
template<> struct arg<-1>
{
BOOST_STATIC_CONSTANT(int, value = -1);
BOOST_MPL_AUX_ARG_TYPEDEF(na, tag)
BOOST_MPL_AUX_ARG_TYPEDEF(na, type)
template<
AUX778076_ARG_N_DEFAULT_PARAMS(typename U, na)
>
struct apply
{
typedef U1 type;
BOOST_MPL_AUX_ASSERT_NOT_NA(type);
};
};
#endif // i_ > 0
#undef i_
#endif // BOOST_PP_IS_ITERATING
| [
"stijndoyen@hotmail.com"
] | stijndoyen@hotmail.com |
f8e4e1556c937fa352388507a1600d168a5b4777 | 6f874ccb136d411c8ec7f4faf806a108ffc76837 | /code/Windows-classic-samples/Samples/Win7Samples/dataaccess/oledb/omniprov/source/irowsetscroll.h | 077e4ebab9a5ee265bf80294fd557200991c342f | [
"MIT"
] | permissive | JetAr/ZDoc | c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435 | e81a3adc354ec33345e9a3303f381dcb1b02c19d | refs/heads/master | 2022-07-26T23:06:12.021611 | 2021-07-11T13:45:57 | 2021-07-11T13:45:57 | 33,112,803 | 8 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 15,371 | h | // Start of IRowsetScroll.h
// File: IRowsetScroll.h
//
// This file contains the information for the IRowsetScrollImpl class.
//
// IRowsetScrollImpl inherits from IRowsetLocateImpl and IRowsetScroll and does the following:
//
// 1. IRowsetScrollImpl :: GetApproximatePosition - Gets the Approximate position of a row corresponding to a specified bookmark
// 2. IRowsetScrollImpl :: GetRowsAtRatio - Fetches rows starting from a fractional position in the rowset
// 3. IRowsetScrollImpl :: Compare - Compares two bookmark
// 4. IRowsetScrollImpl :: GetRowsAt - Fetches rows starting with the row specified by an offset from a bookmark
// 5. IRowsetScrollImpl :: GetRowsByBookmark - Fetches rows that match the specified bookmark
// 6. IRowsetScrollImpl :: Hash - Returns hash values for the specified bookmarks
//
// Class IRowsetScrollImpl
#ifndef _IROWSETSCROLLIMPL_7F4B3871_6B9C_11d3_AC94_00C04F8DB3D5_H
#define _IROWSETSCROLLIMPL_7F4B3871_6B9C_11d3_AC94_00C04F8DB3D5_H
#include "RNCP.h" // The ConnectionPoint and IRowsetNotify Proxy class
template <class T,class RowsetInterface=IRowsetScroll>
class ATL_NO_VTABLE IRowsetScrollImpl : public IRowsetImpl<T, RowsetInterface>
{
public:
STDMETHOD (GetApproximatePosition)(
/* [in] */ HCHAPTER hReserved,
/* [in] */ DBBKMARK cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [out] */ DBCOUNTITEM __RPC_FAR *pulPosition,
/* [out] */ DBCOUNTITEM __RPC_FAR *pcRows)
{
ATLTRACE2(atlTraceDBProvider, 0, "IRowsetScrollImpl::GetApproximatePosition\n");
HRESULT hr;
T* pT = (T*)this;
T::ObjectLock cab((T*) pT);
if(DB_NULL_HCHAPTER != hReserved)
return DB_E_NOTSUPPORTED;
// DANK: RowsetViewer was getting an error as it would use this function to get the
// approximate number of rows. I modified to do the arg checking earlier before the
// bookmark validation
if(pulPosition == NULL && pcRows == NULL)
return S_OK;
if(cbBookmark == 0)
{
if (*pcRows != NULL)
*pcRows = pT->m_rgRowHandles.GetCount();
return S_OK;
}
// SQLOLEDB does not have this implemented MDAC 2.1 SP2...
// Validate the bookmarks only if a bookmark is specified
// If No-op
hr = ValidateBookmark(cbBookmark, pBookmark);
if(hr != S_OK)
return hr;
// This deals with all the ros inside the rowset after a GetNextRows( )...
// Hence, operations are confined to m_rgRowHandles
// There is no change to the state of the cursor just return the number of rows between m_iRowset and the current bookmark...
// *pcRows should always be greater than *pulPosition !!
// Now if cbBookmark != 0 and pBookmark is valid-> check pBookmark and find the ulPosition and pcRows
if(pBookmark != NULL)
{
DBROWOFFSET iRowsetTemp = pT->m_iRowset; // Cache the current rowset
if ((cbBookmark == 1) && (*pBookmark == DBBMK_FIRST))
iRowsetTemp = 1;
if ((cbBookmark == 1) && (*pBookmark == DBBMK_LAST))
// iRowsetTemp = pT->m_rgRowData.GetSize();
iRowsetTemp = pT->m_DBFile.m_Rows.GetCount();
// m_iRowset - From current cursor get current Bookmark
// Check if iRowsetTemp exists in the current current
// Need to economize this if many rows exist in the cursor....
if (NULL == m_rgRowHandles.Lookup(iRowsetTemp))
return DB_E_BADBOOKMARK;
//ULONG dwCurBkmrk = pT->m_rgRowData[iRowsetTemp].m_dwBookmark;
ULONG dwCurBkmrk = pT->m_DBFile.m_Rows[iRowsetTemp-1]->m_bmk;
if( (*(ULONG*)pBookmark < dwCurBkmrk) )
return DB_E_BADBOOKMARK;
DBBKMARK ulNumRows = *(ULONG*)pBookmark - dwCurBkmrk;
*pulPosition = iRowsetTemp;
*pcRows = ulNumRows;
}
else return DB_E_BADBOOKMARK;
return S_OK;
}
STDMETHOD (GetRowsAtRatio)(
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ DBCOUNTITEM ulNumerator,
/* [in] */ DBCOUNTITEM ulDenominator,
/* [in] */ DBROWCOUNT cRows,
/* [out] */ DBCOUNTITEM __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows)
{
ATLTRACE2(atlTraceDBProvider, 0, "IRowsetScrollImpl::GetRowsAtRatio\n");
T* pT = (T*)this;
T::ObjectLock cab((T*) pT);
HRESULT hr = S_OK;
// Validation
if(DB_NULL_HCHAPTER != hReserved2)
return DB_E_NOTSUPPORTED;
if(NULL == pcRowsObtained || NULL == prghRows)
return E_INVALIDARG;
// Check Fetching Backwards
if (cRows < 0 && !pT->m_bCanFetchBack)
return DB_E_CANTFETCHBACKWARDS;
if(ulDenominator == 0 || (ulNumerator > ulDenominator) )
return DB_E_BADRATIO;
// Setting up the Start Position
DBROWOFFSET iRowsetTemp = pT->m_iRowset; // Cache the current rowset
if(ulNumerator == 0 && cRows >0) // Start Point - First Row
pT->m_iRowset = 0;
else if ( (ulNumerator == 0 && cRows < 0) || (ulNumerator == ulDenominator && cRows > 0)) // DB_S_ENDOFROWSET
hr = DB_S_ENDOFROWSET;
else if (ulNumerator == ulDenominator && cRows < 0) // Last Row
//pT->m_iRowset = pT->m_rgRowData.GetSize() - 1;
pT->m_iRowset = pT->m_DBFile.m_Rows.GetCount() - 1;
else // All other conditions
//pT->m_iRowset = (ulNumerator /ulDenominator) * pT->m_rgRowData.GetSize();
pT->m_iRowset = (ulNumerator /ulDenominator) * pT->m_DBFile.m_Rows.GetCount();
// Not sure about HOLDROWS optimizations - DB_E_ROWSNOTRELEASED
// Call IRowsetImpl::GetNextRows to actually get the rows.
if(hr == S_OK)
hr = pT->GetNextRows(hReserved2, 0, cRows, pcRowsObtained, prghRows);
pT->m_iRowset = iRowsetTemp; // Return back to orignal cursor position
// Send notification message
if(FAILED(pT->Fire_OnRowChangeMy(this, cRows, *prghRows, DBREASON_ROW_ACTIVATE, DBEVENTPHASE_DIDEVENT, TRUE)))
ATLTRACE2(atlTraceDBProvider, 0, "Failed to Fire DBREASON_ROW_ACTIVATE in DBEVENTPHASE_DIDEVENT phase\n");
return hr;
}
// IROWSETLOCATE Methods
STDMETHOD (Compare)(HCHAPTER hReserved, DBBKMARK cbBookmark1,
const BYTE * pBookmark1, DBBKMARK cbBookmark2, const BYTE * pBookmark2,
DBCOMPARE * pComparison)
{
ATLTRACE("IRowsetLocateImpl::Compare");
T* pT = (T*)this;
T::ObjectLock cab((T*) pT);
if(DB_NULL_HCHAPTER != hReserved)
return DB_E_NOTSUPPORTED;
HRESULT hr = ValidateBookmark(cbBookmark1, pBookmark1);
if (hr != S_OK)
return hr;
hr = ValidateBookmark(cbBookmark2, pBookmark2);
if (hr != S_OK)
return hr;
// Return the value based on the bookmark values
if (*pBookmark1 == *pBookmark2)
*pComparison = DBCOMPARE_EQ;
if (*pBookmark1 < *pBookmark2)
*pComparison = DBCOMPARE_LT;
if (*pBookmark1 > *pBookmark2)
*pComparison = DBCOMPARE_GT;
return S_OK;
}
STDMETHOD (GetRowsAt)(HWATCHREGION hReserved1, HCHAPTER hReserved2,
DBBKMARK cbBookmark, const BYTE * pBookmark, DBROWOFFSET lRowsOffset,
DBROWCOUNT cRows, DBCOUNTITEM * pcRowsObtained, HROW ** prghRows)
{
ATLTRACE("IRowsetScrollImpl::GetRowsAt\n");
T* pT = (T*)this;
T::ObjectLock cab((T*) pT);
if(DB_NULL_HCHAPTER != hReserved2)
return DB_E_NOTSUPPORTED;
// Check bookmark
HRESULT hr = ValidateBookmark(cbBookmark, pBookmark);
if (hr != S_OK)
return hr;
// Check the other pointers
if (pcRowsObtained == NULL || prghRows == NULL)
return E_INVALIDARG;
// Set the current row position to the bookmark. Handle any
// normal values
// We need to handle the offset as the start position is defined
// as the bookmark + offset. If the offset is negative, and we
// do not have m_bCanScrollBack then return an error. The
// GetNextRows function handles the case where cRows is negative
// and we don't have m_bCanFetchBack set.
if (lRowsOffset < 0 && !pT->m_bCanScrollBack)
return DB_E_CANTSCROLLBACKWARDS;
if (cRows < 0 && !pT->m_bCanFetchBack)
return DB_E_CANTFETCHBACKWARDS;
DBROWOFFSET iRowsetTemp = pT->m_iRowset; // Cache the current rowset
pT->m_iRowset = *pBookmark;
if ((cbBookmark == 1) && (*pBookmark == DBBMK_FIRST))
pT->m_iRowset = 1;
if ((cbBookmark == 1) && (*pBookmark == DBBMK_LAST))
// pT->m_iRowset = pT->m_rgRowData.GetSize();
pT->m_iRowset = pT->m_DBFile.m_Rows.GetCount();
// Set the start position to m_iRowset + lRowsOffset
pT->m_iRowset += lRowsOffset;
if (lRowsOffset >= 0)
(cRows >= 0) ? pT->m_iRowset -= 1 : pT->m_iRowset +=0;
else
(cRows >= 0) ? pT->m_iRowset -= 1 : pT->m_iRowset +=0;
// (lRowsOffset >= 0) ? m_iRowset -= 1 : m_iRowset += 1;
// TODO: this is not very generic - perhaps there is something we can do here
if (pT->m_iRowset < 0 || pT->m_iRowset > (DBROWOFFSET)pT->m_DBFile.m_Rows.GetCount())
{
pT->m_iRowset = iRowsetTemp;
return DB_E_BADSTARTPOSITION; // For 1.x Provider
}
// Call IRowsetImpl::GetNextRows to actually get the rows.
hr = pT->GetNextRows(hReserved2, 0, cRows, pcRowsObtained, prghRows);
pT->m_iRowset = iRowsetTemp;
// Send notification message
if(FAILED(pT->Fire_OnRowChangeMy(this, cRows, *prghRows, DBREASON_ROW_ACTIVATE, DBEVENTPHASE_DIDEVENT, TRUE)))
ATLTRACE2(atlTraceDBProvider, 0, "Failed to Fire DBREASON_ROW_ACTIVATE in DBEVENTPHASE_DIDEVENT phase\n");
return hr;
}
STDMETHOD (GetRowsByBookmark)(HCHAPTER hReserved, DBCOUNTITEM cRows,
const DBBKMARK rgcbBookmarks[], const BYTE * rgpBookmarks[],
HROW rghRows[], DBROWSTATUS rgRowStatus[])
{
HRESULT hr = S_OK;
ATLTRACE("IRowsetLocateImpl::GetRowsByBookmark");
T* pT = (T*)this;
if (rgcbBookmarks == NULL || rgpBookmarks == NULL || rghRows == NULL)
return E_INVALIDARG;
if (cRows == 0)
return S_OK; // No rows fetched in this case.
bool bErrors = false;
for (DBCOUNTITEM l=0; l<cRows; l++)
{
// Validate each bookmark before fetching the row. Note, it is
// an error for the bookmark to be one of the standard values
hr = ValidateBookmark(rgcbBookmarks[l], rgpBookmarks[l]);
if (hr != S_OK)
{
bErrors = TRUE;
if (rgRowStatus != NULL)
{
rgRowStatus[l] = DBROWSTATUS_E_INVALID;
continue;
}
}
// Fetch the row, we now that it is a valid row after validation.
DBCOUNTITEM ulRowsObtained = 0;
if (pT->CreateRow((long)*rgpBookmarks[l], ulRowsObtained, &rghRows[l]) != S_OK)
{
bErrors = TRUE;
}
else
{
if (rgRowStatus != NULL)
rgRowStatus[l] = DBROWSTATUS_S_OK;
}
}
if (bErrors)
return DB_S_ERRORSOCCURRED;
if (FAILED(pT->Fire_OnRowChangeMy(this, cRows, rghRows, DBREASON_ROW_ACTIVATE, DBEVENTPHASE_DIDEVENT, TRUE)))
ATLTRACE2(atlTraceDBProvider, 0, "Failed to Fire DBREASON_ROW_ACTIVATE in DBEVENTPHASE_DIDEVENT phase\n");
return hr;
}
STDMETHOD (Hash)(HCHAPTER hReserved, DBCOUNTITEM cBookmarks,
const DBBKMARK rgcbBookmarks[], const BYTE * rgpBookmarks[],
DBHASHVALUE rgHashedValues[], DBROWSTATUS rgBookmarkStatus[])
{
ATLTRACE("IRowsetScrollImpl::Hash\n");
T* pT = (T*)this;
T::ObjectLock cab((T*) pT);
// Validation
//ROWSET_NOTIFICATION_REENTRANCY_CHECK
if(DB_NULL_HCHAPTER != hReserved)
return DB_E_NOTSUPPORTED;
if (cBookmarks <= 0)
return S_OK;
if((rgHashedValues == NULL) || (cBookmarks != 0 && (rgcbBookmarks == NULL || rgpBookmarks==NULL)) )
return E_INVALIDARG;
// Logic for hashing
DBCOUNTITEM cerrors =0;
if(rgBookmarkStatus)
{
// Loop through the array hashing them and recording their status
for(DBCOUNTITEM i=0; i<cBookmarks; i++)
{
if(SUCCEEDED(HashBmk(rgcbBookmarks[i],rgpBookmarks[i],&(rgHashedValues[i]))) )
rgBookmarkStatus[i] = DBROWSTATUS_S_OK;
else
{
cerrors++;
rgBookmarkStatus[i] = DBROWSTATUS_E_INVALID;
}
}
}
else
{
// Loop through the array hashing them
for(DBCOUNTITEM i=0; i<cBookmarks; i++)
{
if(FAILED(HashBmk(rgcbBookmarks[i],rgpBookmarks[i],&(rgHashedValues[i]))) )
cerrors++;
}
}
if (cerrors == 0) return S_OK;
if (cerrors < cBookmarks)
return DB_S_ERRORSOCCURRED;
else return DB_E_ERRORSOCCURRED;
}
// Implementation
protected:
HRESULT HashBmk(DBBKMARK cbBmk,const BYTE *pbBmk,DBHASHVALUE *pdwHashedValue,ULONG ulTableSize=0xffffffff)
{
if (cbBmk != sizeof(ULONG) || pbBmk == NULL)
return E_INVALIDARG;
ATLASSERT(pdwHashedValue);
*pdwHashedValue = (*(UNALIGNED ULONG*)pbBmk) % ulTableSize;
return S_OK;
}
HRESULT ValidateBookmark(DBBKMARK cbBookmark, const BYTE* pBookmark)
{
T* pT = (T*)this;
T::ObjectLock cab((T*) pT);
if (cbBookmark == 0 || pBookmark == NULL)
return E_INVALIDARG;
if(*pBookmark == DBBMK_INVALID)
return DB_E_BADBOOKMARK;
// All of our bookmarks are DWORDs, if they are anything other than
// sizeof(DWORD) then we have an invalid bookmark
if ((cbBookmark != sizeof(DWORD)) && (cbBookmark != 1))
{
ATLTRACE("Bookmarks are invalid length, should be DWORDs");
return DB_E_BADBOOKMARK;
}
// If the contents of our bookmarks are less than 0 or greater than
// rowcount, then they are invalid
size_t nRows = pT->m_DBFile.m_Rows.GetCount();
if ((*pBookmark <= 0 || *pBookmark > nRows)
&& *pBookmark != DBBMK_FIRST && *pBookmark != DBBMK_LAST)
{
ATLTRACE("Bookmark has invalid range");
return DB_E_BADBOOKMARK;
}
return S_OK;
}
};
#endif
// End of IRowsetScroll.h
| [
"126.org@gmail.com"
] | 126.org@gmail.com |
148bc5c5eb84a9898ee2afb81c9c195df663dd3d | 622cf89f7dca202c3f912cf02d9ab86c65d2befc | /303. Range Sum Query - Immutable.cpp | f06409ec0c3feb7a14087475b4a63f9c9fe95e5e | [] | no_license | Mufidy/MyLeetCodeSolution | 9ff3fd7a7bdbacedf8eadbaf73c06df19c4d7622 | 933952b40c3ded5b66635a31b8db825921237340 | refs/heads/master | 2021-01-20T20:28:30.152793 | 2016-06-18T12:16:07 | 2016-06-18T12:16:07 | 60,612,831 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 889 | cpp | /*
Given an integer array nums, find the sum of the elements between indices i and j (i ¡Ü j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
*/
#include <iostream>
#include <vector>
using namespace std;
class NumArray
{
public:
vector<int> sum;
NumArray(vector<int> &nums)
{
int tmp = 0;
for (int i = 0; i < nums.size(); i++)
{
tmp += nums.at(i);
sum.push_back(tmp);
}
}
int sumRange(int i, int j)
{
if (i == 0)
{
return sum.at(j);
}
else
{
return sum.at(j) - sum.at(i-1);
}
}
};
int main()
{
vector <int> nums = { -2, 0, 3, -5, 2, -1 };
NumArray na(nums);
cout << na.sumRange(0, 2) << endl;
cout << na.sumRange(2, 5) << endl;
cout << na.sumRange(1, 2) << endl;
} | [
"776549916@qq.com"
] | 776549916@qq.com |
47b08b7de86c4a44bc826b8ca833a834893cf09c | e0264425151ec739030174f54195f1eaf518d397 | /cpp/examples/ipc/dep/shm_fifo.common.h | 0fa86807e013cb7b27e8f118ea1e9772122ec23f | [
"Unlicense"
] | permissive | blakewoolbright/fps_platform | b72f6c4dd41ce716f1ccf4a52f4bb73bf8da2aa9 | cd81f799432cfc3700c2dfda4e01fc6c154d53f9 | refs/heads/master | 2021-03-27T19:15:29.024142 | 2020-04-13T16:46:20 | 2020-04-13T16:46:20 | 47,855,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 934 | h | #ifndef FPS__EXAMPLES__SHM_FIFO_COMMON__H
#define FPS__EXAMPLES__SHM_FIFO_COMMON__H
#include <stdint.h>
#include <string>
namespace fps {
namespace examples {
namespace shm_fifo {
//---------------------------------------------------------------------------------------
struct Message
{
char content_[ 64 ] ;
Message()
{
set( 0 ) ;
}
Message( const Message & rhs )
{ std::memcpy( content_, rhs.content_, sizeof( content_ ) ) ;
}
inline
void
set( uint64_t value )
{ ::sprintf( content_, "\n%.63lu", value ) ;
}
inline
uint64_t
get() const
{
uint32_t rv = ::strtoul( content_, NULL, 10 ) ;
return rv ;
}
} ;
//---------------------------------------------------------------------------------------
static const uint32_t Capacity = 1024 ;
static const char Name[] = "fps.shm_fifo_example.data" ;
}}}
#endif
| [
"blake.woolbright@gmail.com"
] | blake.woolbright@gmail.com |
256a20c83e7e7bff424509e1d214eef19b4711ff | d1c7f1e8e42495cc93beba1804122a9d8b14d9a5 | /lru_cache_impl.hpp | 56e55ee13518e58610a8e0083a38774738301699 | [
"MIT"
] | permissive | thatoddmailbox/duck_hero | 325cd15b49f39b62a1c7b8100f241087077511c5 | d96e379491b165dc0bb868ab2a0e4ef6f2365986 | refs/heads/master | 2023-03-31T00:09:48.915826 | 2021-03-25T01:50:05 | 2021-03-25T01:50:05 | 139,845,192 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,324 | hpp | namespace duckhero
{
template<typename K, typename V>
LRUCache<K, V>::LRUCache(int in_cache_size, void (*in_evict_callback)(V *))
{
cache_size = in_cache_size;
_evict_callback = in_evict_callback;
}
template<typename K, typename V>
LRUCache<K, V>::~LRUCache()
{
if (_evict_callback)
{
for (K key : _last_access)
{
_evict_callback(&_data[key]);
}
}
}
template<typename K, typename V>
void LRUCache<K, V>::Evict()
{
while (_last_access.size() > cache_size)
{
K key_to_remove = _last_access.front();
if (_evict_callback)
{
_evict_callback(&_data[key_to_remove]);
}
typename std::map<K, V>::iterator it = _data.find(key_to_remove);
_data.erase(it);
_last_access.pop_front();
}
}
template<typename K, typename V>
bool LRUCache<K, V>::Exists(K key)
{
typename std::map<K, V>::iterator it = _data.find(key);
return (it != _data.end());
}
template<typename K, typename V>
V LRUCache<K, V>::Get(K key)
{
// move this key to the back of the list
_last_access.splice(_last_access.end(), _last_access, std::find(_last_access.begin(), _last_access.end(), key));
return _data[key];
}
template<typename K, typename V>
void LRUCache<K, V>::Put(K key, V value)
{
_last_access.insert(_last_access.end(), key);
Evict();
_data[key] = value;
}
} | [
"astuder@notetoscreen.com"
] | astuder@notetoscreen.com |
a23b6459ae681e91715abcc40ac0842ecd996c38 | e3c7f0cb6a34c4a413d23a7d03ae3023194833ed | /external_tests/exp_functions_et.h | 12c373575f7366c8c5b238a7adee87561b180bde | [] | no_license | MichalSara99/sse_vectorised_functions_tests | 8e068dbfbf4f6408464cf0f1a06722598b46f54e | 1c056fe2160b81177d27af9d5c6781f1a477d2b7 | refs/heads/master | 2023-04-10T06:04:57.507969 | 2021-04-30T13:32:05 | 2021-04-30T13:32:05 | 310,437,953 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,277 | h | #pragma once
#if !defined(_EXP_FUNCTIONS_ET)
#define _EXP_FUNCTIONS_ET
#include <chrono>
#include <iomanip>
#include <iostream>
#include <new>
#include <random>
#include <sse_math_x86_lib.h>
#include "macros/sse_macros.h"
using namespace sse_basics;
void testBasicExpSSEDouble()
{
int const n = 16 + 1;
std::size_t const align = 16;
double *x = sse_utility::aligned_alloc<double>(n, align);
double *res1 = sse_utility::aligned_alloc<double>(n, align);
double *res2 = sse_utility::aligned_alloc<double>(n, align);
// test some basic known values:
const double pi = sse_constants::pi<double>();
x[0] = 0.0;
x[1] = pi / 2.0;
x[2] = pi;
x[3] = 3.0 * pi / 2.0;
x[4] = 5.0 * pi / 4.0;
x[5] = 2.0 * pi;
x[6] = 4.0 * pi;
x[7] = 3.0 * pi;
x[8] = 6.0 * pi / 3.0;
x[9] = -2.0 * pi;
x[10] = -pi / 4.0;
x[11] = 7.0 * pi / 4.0;
x[12] = 0.5;
x[13] = pi / 3.0;
x[14] = 23.5;
x[15] = 4.0 * pi / 3.0;
x[16] = 10.5;
auto start_asm = std::chrono::system_clock::now();
bool rc1 = exp_sse(x, n, res1);
auto end_asm = std::chrono::system_clock::now();
auto elapsed_asm = std::chrono::duration<double>(end_asm - start_asm).count();
auto start_cpp = std::chrono::system_clock::now();
for (int i = 0; i < n; ++i)
{
res2[i] = exp(x[i]);
}
auto end_cpp = std::chrono::system_clock::now();
auto elapsed_cpp = std::chrono::duration<double>(end_cpp - start_cpp).count();
SSE_ASSERT(rc1 == 1, "Failure in packed cosine SSE occured");
std::cout << " C++ Assembly (SSE) Difference\n";
std::cout << "=========================================================\n\n";
for (int i = 0; i < n; ++i)
{
std::cout << i << " | " << res2[i];
std::cout << " | " << res1[i];
std::cout << " | " << (res1[i] - res2[i]) << "\n";
}
std::cout << "=========================================================\n\n";
std::cout << "\n"
<< "Elapsed (C++): " << elapsed_cpp;
std::cout << "\n"
<< "Elapsed (Assembly): " << elapsed_asm << "\n";
sse_utility::aligned_free(x);
sse_utility::aligned_free(res1);
sse_utility::aligned_free(res2);
}
void testBasicExpSSEFloat()
{
int const n = 16 + 1;
std::size_t const align = 16;
float *x = sse_utility::aligned_alloc<float>(n, align);
float *res1 = sse_utility::aligned_alloc<float>(n, align);
float *res2 = sse_utility::aligned_alloc<float>(n, align);
// test some basic known values:
const float pi = sse_constants::pi<float>();
x[0] = 0.0f;
x[1] = pi / 2.0f;
x[2] = pi;
x[3] = 3.0f * pi / 2.0f;
x[4] = 5.0f * pi / 4.0f;
x[5] = 2.0f * pi;
x[6] = 4.0f * pi;
x[7] = 3.0f * pi;
x[8] = 6.0f * pi / 3.0f;
x[9] = -2.0f * pi;
x[10] = -pi / 4.0f;
x[11] = 7.0f * pi / 4.0f;
x[12] = 0.5f;
x[13] = pi / 3.0f;
x[14] = 23.5f;
x[15] = 4.0f * pi / 3.0f;
x[16] = 10.2f;
auto start_asm = std::chrono::system_clock::now();
bool rc1 = exp_sse(x, n, res1);
auto end_asm = std::chrono::system_clock::now();
auto elapsed_asm = std::chrono::duration<double>(end_asm - start_asm).count();
auto start_cpp = std::chrono::system_clock::now();
for (int i = 0; i < n; ++i)
{
res2[i] = exp(x[i]);
}
auto end_cpp = std::chrono::system_clock::now();
auto elapsed_cpp = std::chrono::duration<double>(end_cpp - start_cpp).count();
SSE_ASSERT(rc1 == 1, "Failure in packed cosine SSE occured");
std::cout << " C++ Assembly (SSE) Difference\n";
std::cout << "=========================================================\n\n";
for (int i = 0; i < n; ++i)
{
std::cout << i << " | " << res2[i];
std::cout << " | " << res1[i];
std::cout << " | " << (res1[i] - res2[i]) << "\n";
}
std::cout << "=========================================================\n\n";
std::cout << "\n"
<< "Elapsed (C++): " << elapsed_cpp;
std::cout << "\n"
<< "Elapsed (Assembly): " << elapsed_asm << "\n";
sse_utility::aligned_free(x);
sse_utility::aligned_free(res1);
sse_utility::aligned_free(res2);
}
void testBasicFastExpSSEDouble()
{
int const n = 16 + 1;
std::size_t const align = 16;
double *x = sse_utility::aligned_alloc<double>(n, align);
double *res1 = sse_utility::aligned_alloc<double>(n, align);
double *res2 = sse_utility::aligned_alloc<double>(n, align);
// test some basic known values:
const double pi = sse_constants::pi<double>();
x[0] = 0.1;
x[1] = pi / 2.0;
x[2] = pi;
x[3] = 3.0 * pi / 2.0;
x[4] = 5.0 * pi / 4.0;
x[5] = 2.0 * pi;
x[6] = 4.0 * pi;
x[7] = 3.0 * pi;
x[8] = 6.0 * pi / 3.0;
x[9] = -2.0 * pi;
x[10] = -pi / 4.0;
x[11] = 7.0 * pi / 4.0;
x[12] = 0.5;
x[13] = pi / 3.0;
x[14] = 1.5;
x[15] = 4.0 * pi / 3.0;
x[16] = 25.0;
auto start_asm = std::chrono::system_clock::now();
bool rc1 = exp_fast_sse(x, n, res1);
auto end_asm = std::chrono::system_clock::now();
auto elapsed_asm = std::chrono::duration<double>(end_asm - start_asm).count();
auto start_cpp = std::chrono::system_clock::now();
for (int i = 0; i < n; ++i)
{
res2[i] = exp(x[i]);
}
auto end_cpp = std::chrono::system_clock::now();
auto elapsed_cpp = std::chrono::duration<double>(end_cpp - start_cpp).count();
SSE_ASSERT(rc1 == 1, "Failure in packed exp_fast SSE occured");
std::cout << " C++ Assembly (SSE) Difference\n";
std::cout << "=========================================================\n\n";
for (int i = 0; i < n; ++i)
{
std::cout << i << " | " << res2[i];
std::cout << " | " << res1[i];
std::cout << " | " << (res1[i] - res2[i]) << "\n";
}
std::cout << "=========================================================\n\n";
std::cout << "\n"
<< "Elapsed (C++): " << elapsed_cpp;
std::cout << "\n"
<< "Elapsed (Assembly): " << elapsed_asm << "\n";
sse_utility::aligned_free(x);
sse_utility::aligned_free(res1);
sse_utility::aligned_free(res2);
}
void testBasicFastExpSSEFloat()
{
int const n = 16 + 1;
std::size_t const align = 16;
float *x = sse_utility::aligned_alloc<float>(n, align);
float *res1 = sse_utility::aligned_alloc<float>(n, align);
float *res2 = sse_utility::aligned_alloc<float>(n, align);
// test some basic known values:
const float pi = sse_constants::pi<float>();
x[0] = 0.0f;
x[1] = pi / 2.0f;
x[2] = pi;
x[3] = 3.0f * pi / 2.0f;
x[4] = 5.0f * pi / 4.0f;
x[5] = 2.0f * pi;
x[6] = 4.0f * pi;
x[7] = 3.0f * pi;
x[8] = 6.0f * pi / 3.0f;
x[9] = -2.0f * pi;
x[10] = -pi / 4.0f;
x[11] = 7.0f * pi / 4.0f;
x[12] = 0.5f;
x[13] = pi / 3.0f;
x[14] = 23.5f;
x[15] = 4.0f * pi / 3.0f;
x[16] = 10.2f;
auto start_asm = std::chrono::system_clock::now();
bool rc1 = exp_fast_sse(x, n, res1);
auto end_asm = std::chrono::system_clock::now();
auto elapsed_asm = std::chrono::duration<double>(end_asm - start_asm).count();
auto start_cpp = std::chrono::system_clock::now();
for (int i = 0; i < n; ++i)
{
res2[i] = exp(x[i]);
}
auto end_cpp = std::chrono::system_clock::now();
auto elapsed_cpp = std::chrono::duration<double>(end_cpp - start_cpp).count();
SSE_ASSERT(rc1 == 1, "Failure in packed cosine SSE occured");
std::cout << " C++ Assembly (SSE) Difference\n";
std::cout << "=========================================================\n\n";
for (int i = 0; i < n; ++i)
{
std::cout << i << " | " << res2[i];
std::cout << " | " << res1[i];
std::cout << " | " << (res1[i] - res2[i]) << "\n";
}
std::cout << "=========================================================\n\n";
std::cout << "\n"
<< "Elapsed (C++): " << elapsed_cpp;
std::cout << "\n"
<< "Elapsed (Assembly): " << elapsed_asm << "\n";
sse_utility::aligned_free(x);
sse_utility::aligned_free(res1);
sse_utility::aligned_free(res2);
}
#endif ///_EXP_FUNCTIONS_ET
| [
"michal.sara99@gmail.com"
] | michal.sara99@gmail.com |
cb42082322ca3bc31f57588f52952c6d4b777059 | 9a6c7b1f2c42c825bfc6e6584aac15241883af0e | /src/init.cpp | e84f5bcdf17a2129778e1f60e6d16384119eb5f8 | [
"MIT"
] | permissive | schieran64/AMITY | 148809f1b6cd1b4597def6c57d52d169404ca3d9 | 46dc9fec6d6e2f5d64044a7a534c95cece13ee2c | refs/heads/master | 2020-12-31T05:10:13.640422 | 2016-05-03T20:49:31 | 2016-05-03T20:49:31 | 58,000,498 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,855 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "checkpoints.h"
#include "zerocoin/ZeroTest.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
std::string strWalletFileName;
bool fConfChange;
bool fEnforceCanonical;
unsigned int nNodeLifespan;
unsigned int nDerivationMethodIndex;
unsigned int nMinerSleep;
bool fUseFastIndex;
enum Checkpoints::CPMode CheckpointsMode;
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
void ExitTimeout(void* parg)
{
#ifdef WIN32
MilliSleep(5000);
ExitProcess(0);
#endif
}
void StartShutdown()
{
#ifdef QT_GUI
// ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
uiInterface.QueueShutdown();
#else
// Without UI, Shutdown() can simply be started in a new thread
NewThread(Shutdown, NULL);
#endif
}
void Shutdown(void* parg)
{
static CCriticalSection cs_Shutdown;
static bool fTaken;
// Make this thread recognisable as the shutdown thread
RenameThread("AMITY-shutoff");
bool fFirstThread = false;
{
TRY_LOCK(cs_Shutdown, lockShutdown);
if (lockShutdown)
{
fFirstThread = !fTaken;
fTaken = true;
}
}
static bool fExit;
if (fFirstThread)
{
fShutdown = true;
nTransactionsUpdated++;
// CTxDB().Close();
bitdb.Flush(false);
StopNode();
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
delete pwalletMain;
NewThread(ExitTimeout, NULL);
MilliSleep(50);
printf("AMITY exited\n\n");
fExit = true;
#ifndef QT_GUI
// ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
exit(0);
#endif
}
else
{
while (!fExit)
MilliSleep(500);
MilliSleep(100);
ExitThread(0);
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown(NULL);
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("AMITY version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" AMITYd [options] " + "\n" +
" AMITYd [options] <command> [params] " + _("Send command to -server or AMITYd") + "\n" +
" AMITYd [options] help " + _("List commands") + "\n" +
" AMITYd [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "AMITY:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
fRet = AppInit2();
}
catch (std::exception& e) {
PrintException(&e, "AppInit()");
} catch (...) {
PrintException(NULL, "AppInit()");
}
if (!fRet)
Shutdown(NULL);
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return 1;
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, _("AMITY"), CClientUIInterface::OK | CClientUIInterface::MODAL);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, _("AMITY"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
return true;
}
bool static Bind(const CService &addr, bool fError = true) {
if (IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (fError)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: AMITY.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: AMITYd.pid)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 29854 or testnet: 29855)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -irc " + _("Find peers using internet relay chat (default: 0)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
" -staking " + _("Stake your coins to support network and gain reward (default: 1)") + "\n" +
" -synctime " + _("Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)") + "\n" +
" -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
" -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 29853 or testnet: 29855)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
" -enforcecanonical " + _("Enforce transaction scripts to use canonical PUSH operators (default: 1)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2()
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
nNodeLifespan = GetArg("-addrlifespan", 7);
fUseFastIndex = GetBoolArg("-fastindex", true);
nMinerSleep = GetArg("-minersleep", 500);
CheckpointsMode = Checkpoints::STRICT;
std::string strCpMode = GetArg("-cppolicy", "strict");
if(strCpMode == "strict")
CheckpointsMode = Checkpoints::STRICT;
if(strCpMode == "advisory")
CheckpointsMode = Checkpoints::ADVISORY;
if(strCpMode == "permissive")
CheckpointsMode = Checkpoints::PERMISSIVE;
nDerivationMethodIndex = 0;
fTestNet = GetBoolArg("-testnet");
//fTestNet = true;
if (fTestNet) {
SoftSetBoolArg("-irc", true);
}
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
bitdb.SetDetach(GetBoolArg("-detachdb", false));
#if !defined(WIN32) && !defined(QT_GUI)
fDaemon = GetBoolArg("-daemon");
#else
fDaemon = false;
#endif
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps");
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
fConfChange = GetBoolArg("-confchange", false);
fEnforceCanonical = GetBoolArg("-enforcecanonical", true);
if (mapArgs.count("-mininput"))
{
if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
std::string strDataDir = GetDataDir().string();
std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
// strWalletFileName must be a plain filename without a directory
if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. AMITY is probably already running."), strDataDir.c_str()));
#if !defined(WIN32) && !defined(QT_GUI)
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0)
{
CreatePidFile(GetPidFile(), pid);
return true;
}
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("AMITY version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Used data directory %s\n", strDataDir.c_str());
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "AMITY server starting\n");
int64_t nStart;
// ********************************************************* Step 5: verify database integrity
uiInterface.InitMessage(_("Verifying database integrity..."));
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
return false;
}
if (filesystem::exists(GetDataDir() / strWalletFileName))
{
CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
uiInterface.ThreadSafeMessageBox(msg, _("AMITY"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
#if defined(USE_IPV6)
#if ! USE_IPV6
else
SetLimited(NET_IPV6);
#endif
#endif
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
#ifdef USE_UPNP
fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
#endif
bool fBound = false;
if (!fNoListen)
{
std::string strError;
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind);
}
} else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
#endif
if (!IsLimited(NET_IPV4))
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip"))
{
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
{
if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
{
InitError(_("Invalid amount for -reservebalance=<amount>"));
return false;
}
}
if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
{
if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load blockchain
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
}
if (GetBoolArg("-loadblockindextest"))
{
CTxDB txdb("r");
txdb.LoadBlockIndex();
PrintBlockTree();
return false;
}
uiInterface.InitMessage(_("Loading block index..."));
printf("Loading block index...\n");
nStart = GetTimeMillis();
if (!LoadBlockIndex())
return InitError(_("Error loading blkindex.dat"));
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRId64"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Testing Zerocoin
if (GetBoolArg("-zerotest", false))
{
printf("\n=== ZeroCoin tests start ===\n");
Test_RunAllTests();
printf("=== ZeroCoin tests end ===\n\n");
}
// ********************************************************* Step 8: load wallet
uiInterface.InitMessage(_("Loading wallet..."));
printf("Loading wallet...\n");
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFileName);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
uiInterface.ThreadSafeMessageBox(msg, _("AMITY"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of AMITY") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart AMITY to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
strErrors << _("Cannot initialize keypool") << "\n";
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRId64"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb(strWalletFileName);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
}
if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRId64"ms\n", GetTimeMillis() - nStart);
}
// ********************************************************* Step 9: import blocks
if (mapArgs.count("-loadblock"))
{
uiInterface.InitMessage(_("Importing blockchain data file."));
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
{
FILE *file = fopen(strFile.c_str(), "rb");
if (file)
LoadExternalBlockFile(file);
}
exit(0);
}
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
printf("Loading addresses...\n");
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRId64"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
if (!NewThread(StartNode, NULL))
InitError(_("Error: could not start node"));
if (fServer)
NewThread(ThreadRPCServer, NULL);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
printf("Done loading\n");
if (!strErrors.str().empty())
return InitError(strErrors.str());
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
#if !defined(QT_GUI)
// Loop until process is exit()ed from shutdown() function,
// called from ThreadRPCServer thread when a "stop" command is received.
while (1)
MilliSleep(5000);
#endif
return true;
}
| [
"AMITYDEV"
] | AMITYDEV |
1a5a33a0786e3940dbd527319a4454ae7b62db54 | b16e618b507fdeb9a0f672ef1a6a32a965b1eae6 | /FPSProject/Source/FPSProject/SecProjectile.cpp | 0e3edeeafccd8dae5255cadb95d2dc56ab99714c | [] | no_license | Blasterdude/imgd-4000-projects | c79a4b71befdca298d2ef36d1f24093d810a360e | 9d1340c48d9ed4e18ac8de60beb900427bf2a8f0 | refs/heads/master | 2020-04-01T15:28:10.876325 | 2018-10-16T19:07:34 | 2018-10-16T19:07:34 | 153,338,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,180 | cpp | // Thomas J. Meehan
#include "FPSProject.h"
#include "SecProjectile.h"
// Sets default values
ASecProjectile::ASecProjectile()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ASecProjectile::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ASecProjectile::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
//constructor
ASecProjectile::ASecProjectile(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
// Use a sphere as a simple collision representation
CollisionComp = ObjectInitializer.CreateDefaultSubobject<USphereComponent>(this, TEXT("SphereComp"));
CollisionComp->InitSphereRadius(15.0f);
RootComponent = CollisionComp;
CollisionComp->BodyInstance.SetCollisionProfileName("SecProjectile");
CollisionComp->OnComponentHit.AddDynamic(this, &ASecProjectile::OnHit);
// Use a ProjectileMovementComponent to govern this projectile's movement
ProjectileMovement = ObjectInitializer.CreateDefaultSubobject<UProjectileMovementComponent>(this, TEXT("ProjectileComp"));
ProjectileMovement->UpdatedComponent = CollisionComp;
ProjectileMovement->InitialSpeed = 2000.f;
ProjectileMovement->MaxSpeed = 2000.f;
ProjectileMovement->bRotationFollowsVelocity = true;
ProjectileMovement->bShouldBounce = true;
ProjectileMovement->Bounciness = 0.9f;
}
/** inits velocity of the projectile in the shoot direction */
void ASecProjectile::InitVelocity(const FVector& ShootDirection)
{
if (ProjectileMovement)
{
// set the projectile's velocity to the desired direction
ProjectileMovement->Velocity = ShootDirection * ProjectileMovement->InitialSpeed;
}
}
//deals with collision
void ASecProjectile::OnHit(AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
if ( OtherActor && (OtherActor != this) && OtherComp )
{
OtherComp->AddImpulseAtLocation(ProjectileMovement->Velocity * 100.0f, Hit.ImpactPoint);
}
}
| [
"tom.meehan8@gmail.com"
] | tom.meehan8@gmail.com |
1f6a8b0dd736343e3f842e3a853ea6c16215ebec | e6623dfd08cd7200834fbccf3003c777e09c6bee | /apps/dac_fft_group_fixed/projects/k2_dsp/src/transpose.cpp | e17ede26db4ce61315a871d4535f1711c0a5ed82 | [] | no_license | louisbob/Spider | ed9c013ce7c109c812366dd86c40f760e43e9c64 | 9f1b4fa9b3141c9ac35a327c55685c2dfaf2089e | refs/heads/master | 2020-12-28T22:01:21.831252 | 2015-05-26T11:41:30 | 2015-05-26T11:41:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,277 | cpp | /****************************************************************************
* Copyright or © or Copr. IETR/INSA (2013): Julien Heulot, Yaset Oliva, *
* Maxime Pelcat, Jean-François Nezan, Jean-Christophe Prevotet *
* *
* [jheulot,yoliva,mpelcat,jnezan,jprevote]@insa-rennes.fr *
* *
* This software is a computer program whose purpose is to execute *
* parallel applications. *
* *
* This software is governed by the CeCILL-C license under French law and *
* abiding by the rules of distribution of free software. You can use, *
* modify and/ or redistribute the software under the terms of the CeCILL-C *
* license as circulated by CEA, CNRS and INRIA at the following URL *
* "http://www.cecill.info". *
* *
* As a counterpart to the access to the source code and rights to copy, *
* modify and redistribute granted by the license, users are provided only *
* with a limited warranty and the software's author, the holder of the *
* economic rights, and the successive licensors have only limited *
* liability. *
* *
* In this respect, the user's attention is drawn to the risks associated *
* with loading, using, modifying and/or developing or reproducing the *
* software by the user in light of its specific status of free software, *
* that may mean that it is complicated to manipulate, and that also *
* therefore means that it is reserved for developers and experienced *
* professionals having in-depth computer knowledge. Users are therefore *
* encouraged to load and test the software's suitability as regards their *
* requirements in conditions enabling the security of their systems and/or *
* data to be ensured and, more generally, to use and operate it in the *
* same conditions as regards security. *
* *
* The fact that you are presently reading this means that you have had *
* knowledge of the CeCILL-C license and that you accept its terms. *
****************************************************************************/
#include <lrt.h>
#include <assert.h>
#include <stdio.h>
#include "actors.h"
extern "C"{
#include "edma.h"
}
void transpose(Param Nc, Param Nr, Cplx16* restrict in, Cplx16* restrict out){
#if VERBOSE
printf("Execute transpose\n");
#endif
int res = edma_cpy(
in, out,
/*ACnt: element size*/ 4,
/*BCnt: line size*/ 256,
/*CCnt: n lines in matrice*/ 256,
/*SrcBIdx: = ACnt */ 4,
/*DstBIdx: = CCnt*ACnt */ 4*256,
/*SrcCIdx: = ACnt*BCnt */ 4*256,
/*DstCIdx: = ACnt */ 4);
if(res)
printf("Edma cpy failed\n");
}
| [
"jheulot@insa-rennes.fr"
] | jheulot@insa-rennes.fr |
6030df31cc29ea48a5c3b0944a25e13eb29fec36 | 5423df24db9b2ef2ef88a44430a4005ca1a28680 | /GameAladdin/GameComponents/Timer.cpp | 0bcc3b6a98b437b673d10e0b8ab312cbdf376e74 | [] | no_license | huynhminhtan/game-aladdin-genesis | 44a10cc87cbee175f82a3c7ce17be871baccaae5 | 3fd67ad1841af721d5849ef5c5c20ed538cbc475 | refs/heads/main | 2021-03-27T15:39:51.073537 | 2018-01-07T02:33:36 | 2018-01-07T02:33:36 | 103,738,577 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | cpp | #include "Timer.h"
Timer* Timer::_instance = NULL;
Timer::Timer()
{
}
Timer::~Timer()
{
}
Timer * Timer::GetInstance()
{
if (!_instance)
_instance = new Timer();
return _instance;
}
void Timer::StartCounter()
{
if (!QueryPerformanceFrequency(&_clockRate))
{
return;
}
QueryPerformanceCounter(&_startTime);
}
float Timer::GetCouter()
{
QueryPerformanceCounter(&_endTime);
_delta.QuadPart = _endTime.QuadPart - _startTime.QuadPart;
return ((float)_delta.QuadPart / _clockRate.QuadPart);
}
| [
"minhtan.itdev@gmail.com"
] | minhtan.itdev@gmail.com |
91d342e55ad428381738fd3067163fedc9157d39 | 37b7262db2602aa772e7ec2c30835cc507c5a4d4 | /NumberWithUnits.cpp | 4b21259bba582829a2dadcc6c1a4a9e18eadb230 | [] | no_license | rivkastrilitz/NumberWithUnits_a | d3411716ea2b251fc0eda42096b7910380cdad3a | e53f2c4dfd9104590bf173eabf22caab2a0119db | refs/heads/master | 2023-04-08T05:01:51.311835 | 2021-04-21T12:46:55 | 2021-04-21T12:46:55 | 359,480,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,028 | cpp | #include "NumberWithUnits.hpp"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using namespace ariel;
namespace ariel{
NumberWithUnits::NumberWithUnits(double num,const string str){
this->number=num;
this->unit=str;
}
NumberWithUnits n(0,"9");
void ariel::NumberWithUnits::read_units(ifstream& units){
}
// onary
NumberWithUnits operator+ (const NumberWithUnits& n1){
return n1;
}
// return n1 after changes
NumberWithUnits operator += (const NumberWithUnits &n1 ,const NumberWithUnits& n2){
return n;
}
NumberWithUnits operator+ (const NumberWithUnits& n1,const NumberWithUnits& n2){
return n;
}
// onary
NumberWithUnits operator- (const NumberWithUnits& n1){
return NumberWithUnits (n1.number*-1,n1.unit);
}
// return n1 after changes
NumberWithUnits operator-= (const NumberWithUnits& n1,const NumberWithUnits& n2){
return n;
}
NumberWithUnits operator- (const NumberWithUnits& n1,const NumberWithUnits& n2){
return n;
}
NumberWithUnits operator *(const NumberWithUnits& n1,double d){
return NumberWithUnits (n1.number *d,n1.unit);
}
NumberWithUnits operator *(double d, NumberWithUnits& n1){
return NumberWithUnits (n1.number *d,n1.unit);
}
bool operator <(const NumberWithUnits& n1,const NumberWithUnits& n2){
return true;
}
bool operator <=(const NumberWithUnits& n1,const NumberWithUnits& n2){
return true;
}
bool operator >(const NumberWithUnits& n1,const NumberWithUnits& n2){
return true;
}
bool operator >=(const NumberWithUnits& n1,const NumberWithUnits& n2){
return true;
}
bool operator ==(const NumberWithUnits & n1,const NumberWithUnits& n2){
return true;
}
bool operator !=(const NumberWithUnits& n1,const NumberWithUnits& n2){
return true;
}
// // // // prefix and postfix
// ++x
NumberWithUnits operator++(NumberWithUnits& n1){
return NumberWithUnits (++n1.number,n1.unit);
}
// x++
NumberWithUnits operator++(NumberWithUnits& n1,int num){
return NumberWithUnits (n1.number++,n1.unit);
}
// --x
NumberWithUnits operator--(NumberWithUnits& n1){
return NumberWithUnits (--n1.number,n1.unit);
}
// x--
NumberWithUnits operator--(NumberWithUnits& n1,int num){
return NumberWithUnits (n1.number--,n1.unit);
}
// // // // // // input and output
std::ostream& operator << (std::ostream& out,const NumberWithUnits& n1){
out<<n1.number<<" ["<<n1.unit <<" ]"<<endl;
return out;
}
std::istream& operator >>(std::istream& in, NumberWithUnits& n1){
return in;
}
}
| [
"rivk1471@gmail.com"
] | rivk1471@gmail.com |
56d60e13f13e1e5a942918d20a95f233e8ca5682 | 3c8e0c8f1296ccc506b2a5f5ac3b709af71f22b6 | /trainings/2014_08_bobr/08. 14-08-17/e.cpp | ac533ffa6498c04d225fe19792df4e9be6278d6f | [] | no_license | jnikhilreddy/acm-conventions | f32c93317917ce9e8dfa944994b80771ecd5409b | 5e510637873a48a47581afa3398bbc892cc5e31c | refs/heads/master | 2021-05-30T12:28:23.012629 | 2015-12-10T14:33:17 | 2015-12-10T14:33:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,324 | cpp | #define VERBOSE
#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <bitset>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#ifdef _DEBUG
# include <conio.h>
#endif
#ifndef _DEBUG
# undef VERBOSE
#endif
#define eps 1e-8
#define inf (1000 * 1000 * 1000)
#define linf (4LL * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)
#define sqr(x) ((x) * (x))
#define eq(x, y) (((x) > (y) ? (x) - (y) : (y) - (x)) <= eps)
#define sz(x) int((x).size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define mp make_pair
using namespace std;
typedef unsigned uint;
typedef long long llong;
typedef unsigned long long ullong;
typedef long double ldouble;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
struct debug_t {
template <typename T>
debug_t& operator<<(const T& value) {
# ifdef VERBOSE
cout << value;
# endif
return *this;
}
} debug;
double a,b;
double r(double h) {
return a*pow(M_E,-sqr(h)) + b*sqrt(h);
}
int main() {
# ifdef _DEBUG
freopen("e.in", "r", stdin);
# else
freopen("e.in", "r", stdin);
freopen("e.out", "w", stdout);
# endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
double V; int n; cin >> V >> n;
double best_ind = 0, best_eps = 1e20;
for(int i = 0; i < n; i++) {
double h;
cin >> a >> b >> h;
double step = h / 1e6;
double h1 = 0, h2 = step;
double cur_v = 0;
while( h2 < h ) {
double r1 = r(h1), r2 = r(h2);
cur_v += step * M_PI * sqr((r2+r1)/2);
h1 += step; h2 += step;
}
double cur_eps = fabs(V - cur_v);
if( cur_eps < best_eps )
best_ind = i, best_eps = cur_eps;
}
cout << best_ind << "\n";
# ifdef _DEBUG
_getch();
# endif
return 0;
}
| [
"zakharov.k.l@yandex.ru"
] | zakharov.k.l@yandex.ru |
cfbb29e74718aff4927d990f9562d18505e60aba | 2bfddaf9c0ceb7bf46931f80ce84a829672b0343 | /tests/xtd.tunit.unit_tests/src/xtd/tunit/tests/assume_throws_failed_tests.cpp | 39e859dcb48445b3394702de7485d5f82707a111 | [
"MIT"
] | permissive | gammasoft71/xtd | c6790170d770e3f581b0f1b628c4a09fea913730 | ecd52f0519996b96025b196060280b602b41acac | refs/heads/master | 2023-08-19T09:48:09.581246 | 2023-08-16T20:52:11 | 2023-08-16T20:52:11 | 170,525,609 | 609 | 53 | MIT | 2023-05-06T03:49:33 | 2019-02-13T14:54:22 | C++ | UTF-8 | C++ | false | false | 914 | cpp | #include <xtd/tunit/assume.h>
#include <xtd/tunit/test_class_attribute.h>
#include <xtd/tunit/test_method_attribute.h>
#include "../../../assert_unit_tests/assert_unit_tests.h"
#include <vector>
namespace xtd::tunit::tests {
class test_class_(assume_throws_failed_tests) {
public:
void test_method_(test_case_failed) {
std::vector v = {1, 2, 3, 4};
xtd::tunit::assume::throws<std::out_of_range>([&] {v.at(2);});
}
};
}
void test_(assume_throws_failed_tests, test_output) {
auto [output, result] = run_test_("assume_throws_failed_tests.*");
assert_value_("Start 1 test from 1 test case\n"
" ABORTED assume_throws_failed_tests.test_case_failed\n"
" Test aborted\n"
"End 1 test from 1 test case ran.\n", output);
}
void test_(assume_throws_failed_tests, test_result) {
auto [output, result] = run_test_("assume_throws_failed_tests.*");
assert_value_(0, result);
}
| [
"gammasoft71@gmail.com"
] | gammasoft71@gmail.com |
0b0727cb39c2be6d83736d74f12c2506a96bed29 | 11cd4f066c28c0b23272b6724f741dd6231c5614 | /UVA 571 Jugs.cpp | 8d882bc107ebe5566ff85932a87cda463a291be8 | [] | no_license | Maruf089/Competitive-Programming | 155161c95a7a517cdbf7e59242c6e3fc25dd02b7 | 26ce0d2884842d4db787b5770c10d7959245086e | refs/heads/master | 2021-06-24T11:00:55.928489 | 2021-06-01T05:45:58 | 2021-06-01T05:45:58 | 222,057,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,918 | cpp | ///*بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيم*///
//#pragma GCC optimize("Ofast")
//#pragma GCC target("avx,avx2,fma")
//#pragma GCC optimization ("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define ln '\n'
#define inp(x) scanf("%lld",&x)
#define inp2(a,b) scanf("%lld %lld",&a,&b)
#define f0(i,b) for(int i=0;i<(b);i++)
#define f1(i,b) for(int i=1;i<=(b);i++)
#define MOD 1000000007
#define PI acos(-1)
#define ll long long int
typedef pair<int,int> pii;
typedef pair<ll, ll> pll;
#define pb push_back
#define F first
#define S second
#define sz size()
#define LCM(a,b) (a*(b/__gcd(a,b)))
//#define harmonic(n) 0.57721566490153286060651209+log(n)+1.0/(2*n)
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define all(v) v.begin(),v.end()
#define MEM(a, b) memset(a, b, sizeof(a))
#define fastio ios_base::sync_with_stdio(false)
///Inline functions
inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; }
//inline bool isLeapYearll year) { return (year%400==0) | (year%4==0 && year%100!=0); }
inline void normal(ll &a) { a %= MOD; (a < 0) && (a += MOD); }
inline ll modMul(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a*b)%MOD; }
inline ll modAdd(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a+b)%MOD; }
inline ll modSub(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); a -= b; normal(a); return a; }
inline ll modPow(ll b, ll p) { ll r = 1; while(p) { if(p&1) r = modMul(r, b); b = modMul(b, b); p >>= 1; } return r; }
inline ll modInverse(ll a) { return modPow(a, MOD-2); }
inline ll modDiv(ll a, ll b) { return modMul(a, modInverse(b)); }
inline bool isInside(pii p,ll n,ll m){ return (p.first>=0&&p.first<n&&p.second>=0&&p.second<m); }
inline bool isInside(pii p,ll n){ return (p.first>=0&&p.first<n&&p.second>=0&&p.second<n); }
inline bool isSquare(ll x){ ll s = sqrt(x); return (s*s==x); }
inline bool isFib(ll x) { return isSquare(5*x*x+4)|| isSquare(5*x*x-4); }
inline bool isPowerOfTwo(ll x){ return ((1LL<<(ll)log2(x))==x); }
/// DEBUG --------------------------------------------------------------------------------->>>>>>
///**
template < typename F, typename S >
ostream& operator << ( ostream& os, const pair< F, S > & p )
{
return os << "(" << p.first << ", " << p.second << ")";
}
template < typename T >
ostream &operator << ( ostream & os, const vector< T > &v )
{
os << "{";
for (auto it = v.begin(); it != v.end(); ++it)
{
if ( it != v.begin() )
os << ", ";
os << *it;
}
return os << "}";
}
template < typename T >
ostream &operator << ( ostream & os, const set< T > &v )
{
os << "[";
for (auto it = v.begin(); it != v.end(); ++it)
{
if ( it != v.begin())
os << ", ";
os << *it;
}
return os << "]";
}
template < typename F, typename S >
ostream &operator << ( ostream & os, const map< F, S > &v )
{
os << "[";
for (auto it = v.begin(); it != v.end(); ++it)
{
if ( it != v.begin() )
os << ", ";
os << it -> first << " = " << it -> second ;
}
return os << "]";
}
#define dbg(args...) do {cerr << #args << " : "; faltu(args); } while(0)
clock_t tStart = clock();
#define timeStamp dbg("Execution Time: ", (double)(clock() - tStart)/CLOCKS_PER_SEC)
void faltu ()
{
cerr << endl;
}
template <typename T>
void faltu( T a[], int n )
{
for (int i = 0; i < n; ++i)
cerr << a[i] << ' ';
cerr << endl;
}
template <typename T, typename ... hello>
void faltu( T arg, const hello &... rest)
{
cerr << arg << ' ';
faltu(rest...);
}
/// TEMPLATE ----------------------------------------------------------------------->>>>>>
struct func
{
//this is a sample overloading function for sorting stl
bool operator()(pii const &a, pii const &b)
{
if(a.F==b.F)
return (a.S<b.S);
return (a.F<b.F);
}
};
/*------------------------------Graph Moves----------------------------*/
//Rotation: S -> E -> N -> W
//const int fx[] = {0, +1, 0, -1};
//const int fy[] = {-1, 0, +1, 0};
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; // Kings Move
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; // Kings Move
//const int fx[]={-2, -2, -1, -1, 1, 1, 2, 2}; // Knights Move
//const int fy[]={-1, 1, -2, 2, -2, 2, -1, 1}; // Knights Move
/*---------------------------------------------------------------------*/
/// Bit Operations
/// count set bit C = (num * 0x200040008001ULL & 0x111111111111111ULL) % 0xf; /// 32 bit integer
/// inline bool checkBit(ll n, int i) { return n&(1LL<<i); }
/// inline ll setBit(ll n, int i) { return n|(1LL<<i); }
/// inline ll resetBit(ll n, int i) { return n&(~(1LL<<i)); }
/// ************************************** Code starts here ****************************************** */
const ll INF = 0x3f3f3f3f3f3f3f3f;
const long double EPS = 1e-9;
const int inf = 0x3f3f3f3f;
const int mx = (int)1e5+9;
ll n,m,a,b,t,i,j,d,cs=0,counT=0,k,ans=0,l=0,sum1=0,sum=0,Max,Min,num;
vector<ll>vc;
map<ll,ll>mp;
int main()
{
// freopen("in.txt","r",stdin);
fastio;
int ja,jb,aim,A,B;
while(cin >> ja >> jb >> aim)
{
if(ja==aim)
{
cout << "fill A\nSuccess\n";
continue;
}
if(jb==aim)
{
cout << "fill B\nSuccess\n";
continue;
}
a = b = 0 ;
while(B!=aim)
{
if(a==0)
{
cout << "fill A\n";
A = ja;
}
}
}
/// Comment the debugger section
}
| [
"noreply@github.com"
] | noreply@github.com |
5f6cb7da41eee480062586eae4728075b22a949c | 7c3a5a9147d319a3ae020fe8d0d487f1cc497e01 | /OpenGLApp/include/Window.h | b3aa260ba75a4e3c3cd85fa128963c9bb26dd0fe | [] | no_license | Nikitaenterprise/OpenGLApp | 510766af6296200b9b6fb0943acf671bd540ae44 | e2fb0c1370394f9a552de81c7be589a8b367ca88 | refs/heads/master | 2020-04-05T13:57:21.006085 | 2018-12-13T18:14:20 | 2018-12-13T18:14:20 | 156,917,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 926 | h | #pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class Window
{
public:
Window();
Window(GLuint windowWidth, GLuint windowHeight);
int initialise();
GLint getBufferWidth() { return bufferWidth; }
GLint getBufferHeight() { return bufferHeight; }
bool getShouldClose() { return glfwWindowShouldClose(mainWindow); }
bool *getKeys() { return keys; };
GLfloat getXChange();
GLfloat getYChange();
void swapBuffers() { glfwSwapBuffers(mainWindow); }
~Window();
private:
GLFWwindow *mainWindow;
GLuint width, height;
GLint bufferWidth, bufferHeight;
bool keys[1024];
GLfloat lastX, lastY;
GLfloat xChange, yChange;
bool mouseFirstMoved;
void createCallBack();
static void handleKey(GLFWwindow *window, int key, int code, int action, int mode);
static void handleMouse(GLFWwindow *window, double xPos, double yPos);
};
| [
"prof.frimen@mail.ru"
] | prof.frimen@mail.ru |
28add2c1dcc6e5de4306008da3d6d98d31e5d364 | 7589fb3b3f380974b0ca217f9b756911c1cc4e0d | /ouzel/animators/Sequence.hpp | 63f51d4e9767543061699f5f3acfda2944aee9e8 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | VitoTringolo/ouzel | 2af2c373c9aa56eff9c8ee7954acc905a2a8fe90 | df20fbb4687f8a8fd3b0d5c1b83d26271f8c7c3a | refs/heads/master | 2020-04-21T02:09:36.750445 | 2019-02-05T00:55:56 | 2019-02-05T00:55:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | hpp | // Copyright 2015-2018 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_SEQUENCE_HPP
#define OUZEL_SEQUENCE_HPP
#include <vector>
#include "animators/Animator.hpp"
namespace ouzel
{
namespace scene
{
class Sequence final: public Animator
{
public:
explicit Sequence(const std::vector<Animator*>& initAnimators);
explicit Sequence(const std::vector<std::unique_ptr<Animator>>& initAnimators);
void play() override;
protected:
void updateProgress() override;
private:
Animator* currentAnimator = nullptr;
};
} // namespace scene
} // namespace ouzel
#endif // OUZEL_SEQUENCE_HPP
| [
"elviss@elviss.lv"
] | elviss@elviss.lv |
2ef93ed5a2ce22db15169a9a4fc5d21536dc6461 | 3630a2ec288d62d74f9018720a1e804ffc039fdf | /Others/indeednow-finalb-open/a.cpp | 6bb73d4533e8edfd5d710df7e4165bbf557ff3a7 | [] | no_license | kant/AtCoder | 8f8970d46fb415983927b2626a34cf3a3c81e090 | b9910f20980243f1d40c18c8f16e258c3e6e968f | refs/heads/master | 2022-12-10T10:15:43.200914 | 2020-02-17T07:23:46 | 2020-02-17T07:23:46 | 292,367,026 | 0 | 0 | null | 2020-09-02T18:45:51 | 2020-09-02T18:45:50 | null | UTF-8 | C++ | false | false | 332 | cpp | #include <bits/stdc++.h>
using namespace std;
long long MOD = 1e9 + 7;
int main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
long long a, b, ans = 0;
cin >> a >> b;
for(long long i = a; i <= b; i++){
ans += i * (1 + i) / 2 * i;
ans %= MOD;
}
cout << ans << endl;
return 0;
} | [
"dendai0122@gmail.com"
] | dendai0122@gmail.com |
f12881a5cec3512ea90a52f79980f2c413293579 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_1531_git-2.4.2.cpp | f5c8b388bd7ae40c8f53118e8916acd7ad0843ea | [] | 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 | 2,336 | cpp | static int fsck_tag_buffer(struct tag *tag, const char *data,
unsigned long size, fsck_error error_func)
{
unsigned char sha1[20];
int ret = 0;
const char *buffer;
char *to_free = NULL, *eol;
struct strbuf sb = STRBUF_INIT;
if (data)
buffer = data;
else {
enum object_type type;
buffer = to_free =
read_sha1_file(tag->object.sha1, &type, &size);
if (!buffer)
return error_func(&tag->object, FSCK_ERROR,
"cannot read tag object");
if (type != OBJ_TAG) {
ret = error_func(&tag->object, FSCK_ERROR,
"expected tag got %s",
typename(type));
goto done;
}
}
if (require_end_of_header(buffer, size, &tag->object, error_func))
goto done;
if (!skip_prefix(buffer, "object ", &buffer)) {
ret = error_func(&tag->object, FSCK_ERROR, "invalid format - expected 'object' line");
goto done;
}
if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') {
ret = error_func(&tag->object, FSCK_ERROR, "invalid 'object' line format - bad sha1");
goto done;
}
buffer += 41;
if (!skip_prefix(buffer, "type ", &buffer)) {
ret = error_func(&tag->object, FSCK_ERROR, "invalid format - expected 'type' line");
goto done;
}
eol = strchr(buffer, '\n');
if (!eol) {
ret = error_func(&tag->object, FSCK_ERROR, "invalid format - unexpected end after 'type' line");
goto done;
}
if (type_from_string_gently(buffer, eol - buffer, 1) < 0)
ret = error_func(&tag->object, FSCK_ERROR, "invalid 'type' value");
if (ret)
goto done;
buffer = eol + 1;
if (!skip_prefix(buffer, "tag ", &buffer)) {
ret = error_func(&tag->object, FSCK_ERROR, "invalid format - expected 'tag' line");
goto done;
}
eol = strchr(buffer, '\n');
if (!eol) {
ret = error_func(&tag->object, FSCK_ERROR, "invalid format - unexpected end after 'type' line");
goto done;
}
strbuf_addf(&sb, "refs/tags/%.*s", (int)(eol - buffer), buffer);
if (check_refname_format(sb.buf, 0))
error_func(&tag->object, FSCK_WARN, "invalid 'tag' name: %.*s",
(int)(eol - buffer), buffer);
buffer = eol + 1;
if (!skip_prefix(buffer, "tagger ", &buffer))
/* early tags do not contain 'tagger' lines; warn only */
error_func(&tag->object, FSCK_WARN, "invalid format - expected 'tagger' line");
else
ret = fsck_ident(&buffer, &tag->object, error_func);
done:
strbuf_release(&sb);
free(to_free);
return ret;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
d31776cca83b63cd9c5d4feff6420440d049fa8a | 3e4d7e46e51f556d4bbe6de62b50d7cedae612d4 | /app/src/main/cpp/utils.hpp | 30471c91248e82f8e0ef1578285095e909686937 | [] | no_license | siwangqishiq/CubeDemo | f0d461a91699363cd392913f1caa582ba45cb303 | 6511c3250180f1040a2a0a738bceb4e3384705e1 | refs/heads/master | 2020-04-18T03:02:52.556809 | 2019-01-24T08:37:27 | 2019-01-24T08:37:27 | 167,185,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,529 | hpp | #ifndef __UTILS_H__
#define __UTILS_H__
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define PI 3.1415926f
#define normalize(x, y, z) \
{ \
float norm = 1.0f / sqrt(x*x+y*y+z*z); \
x *= norm; y *= norm; z *= norm; \
}
#define I(_i, _j) ((_j)+4*(_i))
//产生一个单位矩阵
void matrixSetIdentityM(float *m)
{
memset((void*)m, 0, 16*sizeof(float));
m[0] = m[5] = m[10] = m[15] = 1.0f;
}
//产生一个旋转矩阵
void matrixSetRotateM(float *m, float a, float x, float y, float z)
{
float s, c;
memset((void*)m, 0, 15*sizeof(float));
m[15] = 1.0f;
a *= PI/180.0f;
s = sin(a);
c = cos(a);
if (1.0f == x && 0.0f == y && 0.0f == z) {
m[5] = c; m[10] = c;
m[6] = s; m[9] = -s;
m[0] = 1;
} else if (0.0f == x && 1.0f == y && 0.0f == z) {
m[0] = c; m[10] = c;
m[8] = s; m[2] = -s;
m[5] = 1;
} else if (0.0f == x && 0.0f == y && 1.0f == z) {
m[0] = c; m[5] = c;
m[1] = s; m[4] = -s;
m[10] = 1;
} else {
normalize(x, y, z);
float nc = 1.0f - c;
float xy = x * y;
float yz = y * z;
float zx = z * x;
float xs = x * s;
float ys = y * s;
float zs = z * s;
m[ 0] = x*x*nc + c;
m[ 4] = xy*nc - zs;
m[ 8] = zx*nc + ys;
m[ 1] = xy*nc + zs;
m[ 5] = y*y*nc + c;
m[ 9] = yz*nc - xs;
m[ 2] = zx*nc - ys;
m[ 6] = yz*nc + xs;
m[10] = z*z*nc + c;
}
}
//矩阵相乘
void matrixMultiplyMM(float *m, float *lhs, float *rhs)
{
float t[16];
for (int i = 0; i < 4; i++) {
const float rhs_i0 = rhs[I(i, 0)];
float ri0 = lhs[ I(0,0) ] * rhs_i0;
float ri1 = lhs[ I(0,1) ] * rhs_i0;
float ri2 = lhs[ I(0,2) ] * rhs_i0;
float ri3 = lhs[ I(0,3) ] * rhs_i0;
for (int j = 1; j < 4; j++) {
const float rhs_ij = rhs[ I(i,j) ];
ri0 += lhs[ I(j,0) ] * rhs_ij;
ri1 += lhs[ I(j,1) ] * rhs_ij;
ri2 += lhs[ I(j,2) ] * rhs_ij;
ri3 += lhs[ I(j,3) ] * rhs_ij;
}
t[ I(i,0) ] = ri0;
t[ I(i,1) ] = ri1;
t[ I(i,2) ] = ri2;
t[ I(i,3) ] = ri3;
}
memcpy(m, t, sizeof(t));
}
//矩阵缩放
void matrixScaleM(float *m, float x, float y, float z)
{
for (int i = 0; i < 4; i++)
{
m[i] *= x; m[4+i] *=y; m[8+i] *= z;
}
}
//矩阵平移
void matrixTranslateM(float *m, float x, float y, float z)
{
for (int i = 0; i < 4; i++)
{
m[12+i] += m[i]*x + m[4+i]*y + m[8+i]*z;
}
}
//m矩阵绕指定轴旋转
void matrixRotateM(float *m, float a, float x, float y, float z)
{
float rot[16], res[16];
matrixSetRotateM(rot, a, x, y, z);
matrixMultiplyMM(res, m, rot);
memcpy(m, res, 16*sizeof(float));
}
//根据uvn坐标 生成相机变换矩阵
void matrixLookAtM(float *m,
float eyeX, float eyeY, float eyeZ,
float cenX, float cenY, float cenZ,
float upX, float upY, float upZ)
{
float fx = cenX - eyeX;
float fy = cenY - eyeY;
float fz = cenZ - eyeZ;
normalize(fx, fy, fz);
float sx = fy * upZ - fz * upY;
float sy = fz * upX - fx * upZ;
float sz = fx * upY - fy * upX;
normalize(sx, sy, sz);
float ux = sy * fz - sz * fy;
float uy = sz * fx - sx * fz;
float uz = sx * fy - sy * fx;
m[ 0] = sx;
m[ 1] = ux;
m[ 2] = -fx;
m[ 3] = 0.0f;
m[ 4] = sy;
m[ 5] = uy;
m[ 6] = -fy;
m[ 7] = 0.0f;
m[ 8] = sz;
m[ 9] = uz;
m[10] = -fz;
m[11] = 0.0f;
m[12] = 0.0f;
m[13] = 0.0f;
m[14] = 0.0f;
m[15] = 1.0f;
matrixTranslateM(m, -eyeX, -eyeY, -eyeZ);
}
//生成一个透视矩阵
void matrixFrustumM(float *m, float left, float right, float bottom, float top, float near, float far)
{
float r_width = 1.0f / (right - left);
float r_height = 1.0f / (top - bottom);
float r_depth = 1.0f / (near - far);
float x = 2.0f * (near * r_width);
float y = 2.0f * (near * r_height);
float A = 2.0f * ((right+left) * r_width);
float B = (top + bottom) * r_height;
float C = (far + near) * r_depth;
float D = 2.0f * (far * near * r_depth);
memset((void*)m, 0, 16*sizeof(float));
m[ 0] = x;
m[ 5] = y;
m[ 8] = A;
m[ 9] = B;
m[10] = C;
m[14] = D;
m[11] = -1.0f;
}
#endif | [
"yuyi.py@alibaba-inc.com"
] | yuyi.py@alibaba-inc.com |
597137a540df0fdbab6ba73c092917629bea81dd | ebf0efb9a55ccbe23f43334437e1b572979d6fce | /Project/VAO.cpp | ceac37b7e771611d2656217e176e8f1d423f2afa | [] | no_license | salmin609/opengl | 806afb8f23b4763455a7bbc1bfd20bc2075a307f | 5b6c5eaf93b8cfeeedd9a0d7d4140a3ff63fdfbe | refs/heads/main | 2023-05-31T02:40:38.084477 | 2021-06-21T08:40:27 | 2021-06-21T08:40:27 | 351,985,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,940 | cpp | #include "VAO.h"
#include "Graphic.h"
#include "Shader.h"
#include "Buffer.hpp"
VAO::VAO(Shader* shaderData) : shader(nullptr), buffer(nullptr)
{
shader = shaderData;
glGenVertexArrays(1, &vaoId);
}
void VAO::Init(std::vector<Vertex>& datas, bool onlyPos)
{
if(shader != nullptr)
{
shader->Use();
}
glBindVertexArray(vaoId);
buffer = new Buffer(GL_ARRAY_BUFFER, (unsigned)(datas.size() * sizeof(Vertex)), GL_STATIC_DRAW, (void*)datas.data());
buffer->Bind();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, position));
glEnableVertexAttribArray(0);
if (!onlyPos)
{
if (datas[0].normal != Vector3())
{
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, normal));
glEnableVertexAttribArray(1);
}
if (datas[0].texCoord != Vector2())
{
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, texCoord));
glEnableVertexAttribArray(2);
}
}
}
void VAO::Init(float* data, int size, int indexNum, const std::vector<int>& sizePerIndex)
{
if (shader != nullptr)
{
shader->Use();
}
glBindVertexArray(vaoId);
buffer = new Buffer(GL_ARRAY_BUFFER, size * sizeof(float), GL_STATIC_DRAW, (void*)data);
buffer->Bind();
const size_t sizeVecSize = sizePerIndex.size();
int stride = 0;
for (size_t i = 0; i < sizeVecSize; ++i)
{
stride += sizePerIndex[i];
}
size_t offset = 0;
for (int i = 0; i < indexNum; ++i)
{
const unsigned sizeOfIndex = sizePerIndex[i];
glVertexAttribPointer(i, sizeOfIndex, GL_FLOAT, GL_FALSE, stride * sizeof(float), (GLvoid*)offset);
glEnableVertexAttribArray(i);
offset += sizePerIndex[i] * sizeof(float);
}
}
void VAO::Bind()
{
if (shader != nullptr)
{
shader->Use();
}
glBindVertexArray(vaoId);
}
unsigned VAO::GetId()
{
return vaoId;
}
VAO::~VAO()
{
glDeleteVertexArrays(1, &vaoId);
if (buffer != nullptr)
{
delete buffer;
}
}
| [
"ryan95kr@gmail.com"
] | ryan95kr@gmail.com |
bf07cbcc6a185b974022fe4d91aab239b65b1d0a | 59a750a75ccd6f019307e9d981f17ac022d50934 | /Source/Tutorial.cpp | 936b76e1ed3e3c7594b4c0df2700ecb0b67fc7b9 | [] | no_license | KimuraRyuya/Neon | 4f99f7e2ec4070e8d83394915c192c823f6b92cc | f9c4a29ad4d67c47a0ea8756ba402611c9f0e56c | refs/heads/master | 2023-02-07T12:02:59.327249 | 2020-12-22T02:33:04 | 2020-12-22T02:33:04 | 322,459,385 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 15,568 | cpp | #include "Tutorial.h"
#include "SceneManager.h"
#include "ParticleSystem.h"
#include "CollisionJudge.h"
#include "../Library/MyLib.h"
#include "../Library/Camera.h"
#include <imgui.h>
#include "EditParameter.h"
void Tutorial::Initialize()
{
characterSystem = std::make_unique<CharacterSystem>();
characterSystem->SetEditParameter(editParameter);
characterSystem->Initialize();
combo = std::make_unique<Combo>();
combo->Initialize();
trackingScore = std::make_unique<TrackingScore>();
trackingScore->Initialize();
playerHpUi = std::make_unique<PlayerHpUi>();
playerHpUi->Initialize();
PlayerShotSystem::GetInstance()->Initialize();
bloomEffect = std::make_unique<Bloom>(pFrameWork.GetDevice(), pFrameWork.screenWidth, pFrameWork.screenHeight);
framebuffers[0] = std::make_unique<Descartes::FrameBuffer>(pFrameWork.GetDevice(), pFrameWork.screenWidth, pFrameWork.screenHeight, false/*enable_msaa*/, 8, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R24G8_TYPELESS);
framebuffers[1] = std::make_unique<Descartes::FrameBuffer>(pFrameWork.GetDevice(), pFrameWork.screenWidth, pFrameWork.screenHeight, false/*enable_msaa*/, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R24G8_TYPELESS);
framebuffers[2] = std::make_unique<Descartes::FrameBuffer>(pFrameWork.GetDevice(), pFrameWork.screenWidth, pFrameWork.screenHeight, false/*enable_msaa*/, 8, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R24G8_TYPELESS);
framebuffers[3] = std::make_unique<Descartes::FrameBuffer>(pFrameWork.GetDevice(), pFrameWork.screenWidth, pFrameWork.screenHeight, false/*enable_msaa*/, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R24G8_TYPELESS);
tonemap_effect = std::make_unique<ToneMap>(pFrameWork.GetDevice());
textTex = std::make_unique<Billboard>(L"Data/Texture/Tutorial.png");
textTex->DissolveTextureLoad(L"Data/Texture/menunoise.png");
textTex->EmissiveTextureLoad(L"Data/Texture/dissolve_edgecolor1.png");
buttonTex = std::make_unique<Billboard>(L"Data/Texture/Button.png");
buttonTex->DissolveTextureLoad(L"Data/Texture/menunoise.png");
buttonTex->EmissiveTextureLoad(L"Data/Texture/dissolve_edgecolor1.png");
textPos = { 20.0f, 0.5f, -6.0f };
displyNum = 0.0f;
buttonTrg = false;
buttonAnimFrame = 0.0f;
isCameraMove = false;
cameraMoveTime = 0.0f;
state = State::Move;
characterSystem->SetEditParameter(editParameter);
}
void Tutorial::Reset()
{
characterSystem->Reset();
combo->Reset();
trackingScore->Reset();
playerHpUi->Reset();
PlayerShotSystem::GetInstance()->Reset();
textPos = { 20.0f, 0.5f, -6.0f };
displyNum = 0.0f;
buttonTrg = false;
buttonAnimFrame = 0.0f;
isCameraMove = false;
cameraMoveTime = 0.0f;
state = State::Move;
}
SceneState Tutorial::Update(std::shared_ptr<BG> bg, float elapsedTime)
{
if (isCameraMove)
{
trackingScore->SetTrackingPos(characterSystem->GetPlayerAddress()->GetPos());
trackingScore->Update(elapsedTime);
PlayerShotSystem::GetInstance()->Update(elapsedTime);
CollisionJudge::PlayerShotVSStage(PlayerShotSystem::GetInstance(), bg, characterSystem.get());
DirectX::XMFLOAT3 ori = DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f);
DirectX::XMVECTOR _origin = DirectX::XMLoadFloat3(&ori);
DirectX::XMVECTOR _cameraT = DirectX::XMLoadFloat3(&cameraTarget);
DirectX::XMVECTOR ans;
float t = Easing::InQuad(cameraMoveTime, 2.0f, 1.0f, 0.0f);
ans = DirectX::XMVectorLerp(_cameraT, _origin, t);
DirectX::XMFLOAT3 _ans = {};
DirectX::XMStoreFloat3(&_ans, ans);
DirectX::XMFLOAT3 _target =
{
_ans.x,
0.0f,
_ans.z * -1.0f
};
Camera::GetInstance().SetTarget(_target);
cameraMoveTime += 2.0f * elapsedTime;
if (cameraMoveTime > 2.0f)
{
Camera::GetInstance().SetTarget({ 0.0f, 0.0f, 0.0f });
Reset();
bg->Reset();
return SceneState::COUNT;
}
return SceneState::TUTORIAL;
}
GetInputXbox();
bg->Update(characterSystem->GetPlayerAddress(), characterSystem->GetEnemyManagerAddress(), elapsedTime);
combo->Update(elapsedTime);
characterSystem->GetPlayerAddress()->SetReinforce(bg->CheckPlayerFillPos(characterSystem->GetPlayerAddress()->GetPos()));
characterSystem->TutorialUpdate(combo->GetLevel(), elapsedTime);
if (characterSystem->GetPlayerAddress()->GetEnemyAllKillFlg())
{
bg->UltimateEffectAndCalcFill(characterSystem->GetPlayerAddress());
characterSystem->GetPlayerAddress()->SetEnemyAllKillFlg(false);
}
trackingScore->SetTrackingPos(characterSystem->GetPlayerAddress()->GetPos());
trackingScore->Update(elapsedTime);
PlayerShotSystem::GetInstance()->Update(elapsedTime);
playerHpUi->Update(elapsedTime);
playerHpUi->SetPlayerCircleUiPos(characterSystem->GetPlayerAddress()->GetPos());
playerHpUi->SetPlayerHpUiPosPos(characterSystem->GetPlayerAddress()->GetPos());
playerHpUi->SetPlayerNowHp(characterSystem->GetPlayerAddress()->GetHp());
playerHpUi->SetPlayerShotGauge(abs(characterSystem->GetPlayerAddress()->GetDushGauge() - 360.0f));
playerHpUi->SetFloorUIDisply(characterSystem->GetPlayerAddress()->GetFillChipDestory());
playerHpUi->SetULTGauge(bg->GetNowFillNum());
combo->SetComboTextPos(characterSystem->GetPlayerAddress()->GetPos());
combo->SetComboNumTextPos(characterSystem->GetPlayerAddress()->GetPos());
CollisionJudge::PlayerVSStage(characterSystem->GetPlayerAddress(), bg);
//CollisionJudge::PlayerVSEnemy(characterSystem->getPlayerAddress(), characterSystem->getEnemyManagerAddress(), combo.get());
CollisionJudge::PlayerVSTrakingScore(characterSystem->GetPlayerAddress(), trackingScore.get());
CollisionJudge::PlayerDestroyEffectVSEnemy(characterSystem->GetPlayerAddress(), characterSystem->GetEnemyManagerAddress());
CollisionJudge::PlayerShotVSStage(PlayerShotSystem::GetInstance(), bg, characterSystem.get());
//CollisionJudge::PlayerShotVSEnemy(PlayerShotSystem::GetInstance(), characterSystem.get(), combo.get(), score.get(), bg.get(), trackingScore.get(), characterSystem->getPlayerAddress()->getReinforce());
// Aボタンを押したらチュートリアルを一つずつスキップ
if (PAD->xb.A_BUTTON && !buttonTrg)
{
buttonTrg = true;
if (state == State::Move && static_cast<int>(displyNum) == 12)
{
state = State::Dash;
displyNum = 0.0f;
buttonAnimFrame = 0.0f;
return SceneState::TUTORIAL;
}
else if (state == State::Dash && static_cast<int>(displyNum) == 14)
{
state = State::Shot;
displyNum = 0.0f;
buttonAnimFrame = 0.0f;
return SceneState::TUTORIAL;
}
else if (state == State::Shot && static_cast<int>(displyNum) == 17)
{
state = State::Fill;
displyNum = 0.0f;
buttonAnimFrame = 0.0f;
return SceneState::TUTORIAL;
}
else if (state == State::Fill && static_cast<int>(displyNum) == 17)
{
state = State::Power;
displyNum = 0.0f;
buttonAnimFrame = 0.0f;
return SceneState::TUTORIAL;
}
else if (state == State::Power && static_cast<int>(displyNum) == 18)
{
isCameraMove = true;
cameraTarget = characterSystem->GetPlayerAddress()->GetPos();
ParticleSystem::GetInstance()->playerDestroyParticle->Burst(1000, characterSystem->GetPlayerAddress()->GetPos(), pFrameWork.GetElapsedTime(), characterSystem->GetPlayerAddress()->GetModelResource(), 0.0f, 0.0f);
return SceneState::TUTORIAL;
//return SceneState::TUTORIAL;
}
SkipText();
}
else if (!PAD->xb.A_BUTTON)
{
buttonTrg = false;
}
// タイプライター
switch (state)
{
case State::Move:
displyNum += 5.0f * elapsedTime;
buttonAnimFrame += 3.0f * elapsedTime;
if (displyNum > 12.0f)
{
displyNum = 12.0f;
}
if (buttonAnimFrame > 8.0f)
{
buttonAnimFrame = 0.0f;
}
break;
case State::Dash:
displyNum += 5.0f * elapsedTime;
buttonAnimFrame += 3.0f * elapsedTime;
if (displyNum > 14.0f)
{
displyNum = 14.0f;
}
if (buttonAnimFrame > 8.0f)
{
buttonAnimFrame = 0.0f;
}
break;
case State::Shot:
displyNum += 5.0f * elapsedTime;
buttonAnimFrame -= 3.0f * elapsedTime;
if (displyNum > 17.0f)
{
displyNum = 17.0f;
}
if (buttonAnimFrame < 0.0f)
{
buttonAnimFrame = 8.0f;
}
break;
case State::Fill:
displyNum += 5.0f * elapsedTime;
buttonAnimFrame += 3.0f * elapsedTime;
if (displyNum > 17.0f)
{
displyNum = 17.0f;
}
if (buttonAnimFrame > 8.0f)
{
buttonAnimFrame = 0.0f;
}
break;
case State::Power:
displyNum += 5.0f * elapsedTime;
buttonAnimFrame += 3.0f * elapsedTime;
if (displyNum > 18.0f)
{
displyNum = 18.0f;
}
if (buttonAnimFrame > 8.0f)
{
buttonAnimFrame = 0.0f;
}
break;
default:
break;
}
#ifdef _DEBUG
ImGui::Begin("Tutorial");
ImGui::Image(framebuffers[0]->renderTargetShaderResourceView.Get(), ImVec2(100, 100));
ImGui::Image(framebuffers[1]->renderTargetShaderResourceView.Get(), ImVec2(100, 100));
ImGui::End();
#endif // _DEBUG
return SceneState::TUTORIAL;
}
void Tutorial::Render(std::shared_ptr<BG> bg)
{
framebuffers[0]->Clear(pFrameWork.GetContext(), 0.0f, 0.0f, 0.0f, 1.0f);
framebuffers[0]->Activate(pFrameWork.GetContext());
framebuffers[0]->DeActivate(pFrameWork.GetContext());
framebuffers[1]->Clear(pFrameWork.GetContext(), 0.0f, 0.0f, 0.0f, 1.0f);
framebuffers[1]->Activate(pFrameWork.GetContext());
framebuffers[1]->DeActivate(pFrameWork.GetContext());
framebuffers[2]->Clear(pFrameWork.GetContext(), 0.0f, 0.0f, 0.0f, 1.0f);
framebuffers[2]->Activate(pFrameWork.GetContext());
pSceneManager->blend_states[pSceneManager->ALPHA]->Activate(pFrameWork.GetContext());
characterSystem->GetPlayerAddress()->GetPlayerUltimate()->Render();
bg->Render();
if (!isCameraMove)
{
textTex->Begin();
textTex->Render(textPos, 0.0f, 0.0f, 1920.0f, 1080.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 17.0f * (1920.0f / 1080.0f), 17.0f }, { 30.0f, 30.0f, 30.0f, 1.0f }, { 1.0f, 1.0f, 1.0, 1.0f }, false);
textTex->End();
trackingScore->Render();
pSceneManager->blend_states[pSceneManager->ALPHA]->DeActivate(pFrameWork.GetContext());
characterSystem->Render();
};
pSceneManager->blend_states[pSceneManager->ALPHA]->DeActivate(pFrameWork.GetContext());
ParticleSystem::GetInstance()->BloomRender();
pSceneManager->blend_states[pSceneManager->ALPHA]->Activate(pFrameWork.GetContext());
PlayerShotSystem::GetInstance()->Render();
framebuffers[2]->DeActivate(pFrameWork.GetContext());
///generate bloom texture from scene framebuffer
bloomEffect->generate(pFrameWork.GetContext(), framebuffers[2]->renderTargetShaderResourceView.Get());
//convolute bloom texture to scene framebuffer
framebuffers[3]->Clear(pFrameWork.GetContext(), 0.0f, 0.0f, 0.0f, 1.0f);
framebuffers[3]->Activate(pFrameWork.GetContext());
bloomEffect->Blit(pFrameWork.GetContext());
framebuffers[3]->DeActivate(pFrameWork.GetContext());
tonemap_effect->Blit(pFrameWork.GetContext(), framebuffers[3]->renderTargetShaderResourceView.Get(), pFrameWork.GetElapsedTime(), true);
pSceneManager->blend_states[pSceneManager->ALPHA]->Activate(pFrameWork.GetContext());
ParticleSystem::GetInstance()->NotBloomRender();
pSceneManager->blend_states[pSceneManager->ALPHA]->DeActivate(pFrameWork.GetContext());
if (!isCameraMove)
{
pSceneManager->blend_states[pSceneManager->ALPHA]->Activate(pFrameWork.GetContext());
playerHpUi->Render();
combo->Render();
pSceneManager->blend_states[pSceneManager->ALPHA]->DeActivate(pFrameWork.GetContext());
float _x = 0.0f, _y = 0.0f, _z = 0.0f;
int csatButtonAnimFrame = static_cast<int>(buttonAnimFrame);
switch (state)
{
case State::Move:
textTex->Begin();
for (int i = 0; i < static_cast<int>(displyNum); i++)
{
_x = textPos.x + 10.0f - (1.85f * i);
_y = textPos.y;
_z = textPos.z;
textTex->Render({ _x, _y, _z }, 0.0f + 100 * i, 1080.0f, 100.0f, 100.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 1.5f, 1.5f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0, 1.0f }, false);
}
textTex->End();
_x = textPos.x + 10.0f;
_y = textPos.y;
_z = textPos.z + 3.0f;
buttonTex->Begin();
buttonTex->Render({ _x, _y, _z }, 0.0f + (512.0f * csatButtonAnimFrame), 512.0f, 512.0f, 512.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 3.0f, 3.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, {1.0f, 1.0f, 1.0f, 1.0f}, false);
buttonTex->End();
break;
case State::Dash:
textTex->Begin();
for (int i = 0; i < static_cast<int>(displyNum); i++)
{
_x = textPos.x + 12.0f - (1.85f * i);
_y = textPos.y;
_z = textPos.z;
textTex->Render({ _x, _y, _z }, 0.0f + 100 * i, 1080.0f + 100.0f * 1.0f, 100.0f, 100.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 1.3f, 1.3f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0, 1.0f }, false);
}
textTex->End();
buttonTex->Begin();
_x = textPos.x + 5.0f;
_y = textPos.y;
_z = textPos.z + 3.0f;
buttonTex->Render({ _x, _y, _z }, 0.0f + (512.0f * csatButtonAnimFrame), 512.0f, 512.0f, 512.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 3.0f, 3.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, false);
_x = textPos.x + 10.0f;
buttonTex->Render({ _x, _y, _z }, 0.0f + (512.0f * (csatButtonAnimFrame % 2)), 512.0f * 2.0f, 512.0f, 512.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 3.0f, 3.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, false);
buttonTex->End();
break;
case State::Shot:
textTex->Begin();
for (int i = 0; i < static_cast<int>(displyNum); i++)
{
_x = textPos.x + 12.0f - (1.35f * i);
_y = textPos.y;
_z = textPos.z;
textTex->Render({ _x, _y, _z }, 0.0f + 100 * i, 1080.0f + 100.0f * 2.0f, 100.0f, 100.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 1.2f, 1.2f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0, 1.0f }, false);
}
textTex->End();
_x = textPos.x - 6.0f;
_y = textPos.y;
_z = textPos.z + 3.0f;
buttonTex->Begin();
buttonTex->Render({ _x, _y, _z }, 0.0f + (512.0f * csatButtonAnimFrame), 512.0f, 512.0f, 512.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 3.0f, 3.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, false);
buttonTex->End();
break;
case State::Fill:
textTex->Begin();
for (int i = 0; i < static_cast<int>(displyNum); i++)
{
_x = textPos.x + 12.0f - (1.35f * i);
_y = textPos.y;
_z = textPos.z;
textTex->Render({ _x, _y, _z }, 0.0f + 100 * i, 1080.0f + 100.0f * 3.0f, 100.0f, 100.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 1.2f, 1.2f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0, 1.0f }, false);
}
textTex->End();
break;
case State::Power:
textTex->Begin();
for (int i = 0; i < static_cast<int>(displyNum); i++)
{
_x = textPos.x + 12.0f - (1.35f * i);
_y = textPos.y;
_z = textPos.z;
textTex->Render({ _x, _y, _z }, 0.0f + 100 * i, 1080.0f + 100.0f * 4.0f, 100.0f, 100.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 1.2f, 1.2f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0, 1.0f }, false);
}
textTex->End();
break;
default:
break;
}
_x = textPos.x - 10.0f;
_y = textPos.y;
_z = textPos.z + 3.0f;
buttonTex->Begin();
buttonTex->Render({ _x, _y, _z }, 0.0f + (512.0f * (csatButtonAnimFrame % 2)), 0.0f, 512.0f, 512.0f, { -90.0f * 0.01745f, 0.0f, 0.0f }, { 3.0f, 3.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, false);
buttonTex->End();
}
}
void Tutorial::Finalize()
{
}
void Tutorial::SkipText()
{
if (state == State::Move)
{
displyNum = 12.0f;
}
else if (state == State::Dash)
{
displyNum = 14.0f;
}
else if (state == State::Shot)
{
displyNum = 17.0f;
}
else if (state == State::Fill)
{
displyNum = 17.0f;
}
else if (state == State::Power)
{
displyNum = 18.0f;
}
}
void Tutorial::SetEditParameter(std::shared_ptr<Edit::EditPrameter> ptr)
{
editParameter = ptr;
} | [
"km01ry06@gmail.com"
] | km01ry06@gmail.com |
4ad002970ca510fe9aa81ec3f6a0f1df32ebe917 | df6280b18e435819f852d65822d385b6de3d800b | /UR3CPP/UR3Intermediator.h | 66f86780d14ae3509242ae2bec11c67802b7b36e | [] | no_license | piokac/mocap2optitrack | 5630d130e3e2ec846a7de18640c5799c4e979129 | d9a636a785cbf2cb3ec7737e2753ee224c990d06 | refs/heads/master | 2020-03-18T14:29:31.820450 | 2018-07-09T18:54:32 | 2018-07-09T18:54:32 | 134,851,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,781 | h | /**
05Robot - Computer Vision Module
@author P.Kaczmarek,J.Tomczynski,T.Mankowski
@version 1.0 2017
*/
#ifndef UR3INTERMEDIATOR_H
#define UR3INTERMEDIATOR_H
#pragma once
#include "UR3Message.h"
#include <QObject>
#include <QTcpSocket>
#include <QTcpServer>
#include <QMutex>
#include <QFile>
#include <QTextStream>
#include <QElapsedTimer>
#include <QNetworkInterface>
/** \addtogroup UR
* @{
*/
/**
* @brief Base class for communication with UR robot using TCP/IP interface
*/
class UR3Intermediator: public QObject
{
Q_OBJECT
public:
/**
* @brief default constructor, initializes class with starting properties
* @param ipAddress Robot TCP/IP interface IP.
* @param port Robot TCP/IP interface port. Default 30002.
* @param ackServerPort Port for acknowledgment messages of command execution.
*/
UR3Intermediator(QString ipAddress = "192.168.0.109", int port = 30002, int ackServerPort = 9090);
/**
* @brief Connects to a robot based on \ref IpAddress and \ref Port. Establishes acknowledgment server on port \ref ackServerPort
* @return true on success, false otherwise
*/
bool ConnectToRobot();
/**
* @brief Disconnects from robot
* @return true on success, false otherwise
*/
void DisconnectFromRobot();
/**
* @brief Generates command string for MoveJ command - move in robot joint space
* @param Position target position as 6 element vector - joint configuration [rad] or TCP position [mm; RV]
* @param isBaseCS specifies if position is given in joint configuration (false) or as TCP position (true)
* @param Acceleration specifies acceleration as joint acceleration (\ref isBaseCS=false) or as TCP acceleration (\ref isBaseCS=true)
* @param Speed specifies speed as joint speed (\ref isBaseCS=false) or as TCP speed (\ref isBaseCS=true)
* @param blendRadius blend radius between specified and following motion [mm], omitted if 0
* @return command string to be feed into \ref addCommandToExecuteList
*/
QString MoveJ(QVector<double> Position, bool isBaseCS, double Acceleration= 2.0, double Speed = 4, double blendRadius = 0);
/**
* @brief Generates command string for MoveL command - linear move in TCP space
* @param TargetPose target position as 6 element vector describing TCP position [mm; RV]
* @param toolAcceleration tool acceleration
* @param toolSpeed tool speed
* @param time time
* @param blendRadius blend radius between specified and following motion [mm]
* @return command string to be feed into \ref addCommandToExecuteList
*/
QString MoveL(QVector<double> TargetPose,double toolAcceleration=1.2,double toolSpeed=.25,double time=0, double blendRadius=0);
/**
* @brief Generates command string for setting Tool Center Point
* @param pose pose describing transformation from robot flange to new TCP
* @return command string to be feed into \ref addCommandToExecuteList
*/
QString setTCP(QVector<double> pose);
/**
* @brief Generates command string for robot to sleep an amount of time
* @param seconds time [s]
* @return command string to be feed into \ref addCommandToExecuteList
*/
QString robotSleep(float seconds);
/**
* @brief Generates command string to set tool digital output signal level
* @param output id of the tool output (0 or 1)
* @param state signal level
* @return command string to be feed into \ref addCommandToExecuteList
*/
QString setToolOutput(int output, bool state);
/**
* @brief main method for sending commands to robot. addCommandToExecuteList adds commands generated by MoveJ, MoveL, setTCP, robotSleep or setToolOutput to be executed
* when robot is not running. Above commands can be concatenated to create a longer script to be send to robot at ounce. Internal UR3Intermediator mechanism queues
* the commands and sends them when robot finished former command
* @param cmd string containing a command to be executed
*/
void addCommandToExecuteList(QString cmd);
/**
* @brief Robot TCP/IP interface port. Default 30002.
*/
int Port;
/**
* @brief Robot TCP/IP interface IP.
*/
QString IpAddress;
/**
* @brief Port for acknowledgment messages of command execution.
*/
int ackServerPort;
QString setOutput(int output, bool state);
signals:
/**
* @brief emitted when a new pose/data information has been received from robot
* @param x new data received
* @param flag determines type of message: 'j' - joint, 'p' - cartesian pose, 'f' - forces, 'c' - currents
*/
void newPose(QVector<double> x, char flag);
/**
* @brief emitted on \ref ConnectToRobot()
* @param Result true on success, false otherwise
*/
void ConnectionAction(QString,bool Result);
/**
* @brief emitted on robot disconnection
*/
void DisconnectionAction();
/**
* @brief emmited when new command from command list has been send to robot for execution
*/
void CommandExecutionStart();
/**
* @brief emiited on command execution confirmation/acknowledgment reception
*/
void CommandFinished();
/**
* @brief emiited when robot is in emergancy or protective stop state
*/
void robotEmergancyStoped();
private:
//Fields
int current_timestamp; //< Licznik slużący do rysowania koła
QElapsedTimer timerrr;
bool _running = false;
QVector<double> _moveJTargetPos;//< opis pola
QVector<double> _moveLTargetPose;
QVector<double> _lastJointPos;
QVector<double> _lastPolozenie;
QVector<double> _lastForceValue;
QString SaveFileName; //< Ścieżka do pliku
QVector<double> rotationVector;
UR3Message ActualRobotInfo;
char * _data;
QByteArray _DataFlow;
QTcpSocket* _socket;
bool _connected = false;
QString getAckServerIp(QString UR3IP);
QTcpServer* _ackServer;
QTcpSocket* _ackServerSocket = NULL;
QString _ackServerIP;
bool _ackLock = false;
//Methods
void Execute(QString command);
void GetRobotData();
void GetRobotMessage(char * data, unsigned int &offset, int size);
void ReadDataFlow();
void RealTime(unsigned int &offset);
void timerEvent(QTimerEvent *event);
bool CheckIfRunning();
UR3Message GetActualUR3State() { return ActualRobotInfo; }
private slots:
void OnSocketNewBytesWritten();
void onSlotDisconnect();
void ackServerSetup();
void ackServerNewConnection();
void ackServerNewMsg();
private:
QMutex mutex;
QVector<QString> cmds;
//Macierz *M;
};
/** @}*/
#endif // UR3INTERMEDIATOR_H
| [
"Piotr Kaczmarek"
] | Piotr Kaczmarek |
cf9129edf2efc56859f5fe7d57b881ab4b34cd2a | 19be686d8ad49f37f1c73a1f66d75a647ccdb214 | /FEM/grid.h | 64fefdde4140c9ba12321cbba2d2267bf03ca5bb | [] | no_license | NazariyJaworskiGitHub/physicalenvironmentdesign | fba9195fd9410a2846433a72fa8312b222506582 | e7d119725c206c3cbb1aeb537e7e29bd4cf24d10 | refs/heads/master | 2022-04-12T01:25:34.129952 | 2020-02-24T08:27:42 | 2020-02-24T08:27:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,170 | h | #ifndef GRID_H
#define GRID_H
#include <QMap>
#include "boundarycondition.h"
#include "domain.h"
#include "simplexelement.h"
#include <MathUtils>
namespace FEM
{
template <
typename _NodeType_,
int _nDimensions_,
typename _ElementType_,
typename _DimType_ = MathUtils::Real>
// Tip! For now, grid can hold only the same type of elements
class Grid
{
protected: DefinedVectorType<_NodeType_*> _myNodes;
protected: DefinedVectorType<_ElementType_*> _myFiniteElements;
protected: DefinedVectorType<const _DimType_*> _myFiniteElementConductionCoefficients;
protected: QMap<int, const BoundaryCondition<_DimType_>*> _myNodeBindedBoundaryConditions;
protected: QMap<int, QPair<int, const BoundaryCondition<_DimType_>*>> _myElementBindedBoundaryConditions;
public : _NodeType_ &createNode(const _NodeType_ &target)
{
_myNodes.push_back(new _NodeType_(target));
return *_myNodes.back();
}
public : _NodeType_ & getNode(int nodeIndex)
#ifdef _DEBUG_MODE
const throw (std::out_of_range)
{
if(nodeIndex>=0 && nodeIndex < _myNodes.size())
{
return *_myNodes[nodeIndex];
}
else throw std::out_of_range("Grid::getNode(), nodeIndex out of range");
}
#else
const noexcept{return *_myNodes[nodeIndex];}
#endif
public : _ElementType_ & createFiniteElement(const int *nodeIndexes,
const _DimType_* conductionCoefficients = nullptr)
{
_myFiniteElements.push_back(new _ElementType_(&(this->_myNodes),nodeIndexes));
this->_myFiniteElementConductionCoefficients.push_back(conductionCoefficients);
return *_myFiniteElements.back();
}
public : _ElementType_ & getElement(int elementIndex)
#ifdef _DEBUG_MODE
const throw (std::out_of_range)
{
if(elementIndex>=0 && elementIndex < _myFiniteElements.size())
{
return *_myFiniteElements[elementIndex];
}
else throw std::out_of_range("Grid::getElement(), nodeIndex out of range");
}
#else
const noexcept{return *_myFiniteElements[elementIndex];}
#endif
public : const DefinedVectorType<_NodeType_*> & getNodesList() const noexcept{
return _myNodes;}
public : const DefinedVectorType<_ElementType_*> & getElementsList() const noexcept{
return _myFiniteElements;}
public : Domain<_DimType_> constructDomainEllipticEquation() const
{
Domain<_DimType_> _d;
_d.getForceVector().resize(_myNodes.size(),1);
_d.getStiffnessMatrix().resize(_myNodes.size(), _myNodes.size());
for(int _elementIndex=0; _elementIndex<_myFiniteElements.size(); ++_elementIndex) // Go through all elements
{
// [ K11 K12 ]
// [ K21 K22 ]
auto _localStiffnessMatrix = _myFiniteElements[_elementIndex]->calculateStiffnessMatrixEllipticEquation(
_myFiniteElementConductionCoefficients[_elementIndex]);
// Apply Neumann boundary conditions
// e.g.:
// T22 = 20
// then
// [ K11 0 ] [-20*K12]
// [ 0 1 ] [ 20 ]
for(int _nodeIndex1=0;_nodeIndex1<_ElementType_::getNodesNumber();++_nodeIndex1) // Go through all nodes
{
int _globalNodeIndex = _myFiniteElements[_elementIndex]->getNodeIndexes()[_nodeIndex1];
if(_myNodeBindedBoundaryConditions.contains(_globalNodeIndex))
{
for(int _nodeIndex2=0;_nodeIndex2<_ElementType_::getNodesNumber();++_nodeIndex2)
{
// F -= cond * K.column(k)
_d.getForceVector().coeffRef(_myFiniteElements[_elementIndex]->getNodeIndexes()[_nodeIndex2],0) -=
_myNodeBindedBoundaryConditions[_globalNodeIndex]->getPotential() *
_localStiffnessMatrix(_nodeIndex2,_nodeIndex1);
// Set zero entire stiffnessMatrix row
_localStiffnessMatrix(_nodeIndex1,_nodeIndex2) = _DimType_(0.0);
// Set zero entire stiffnessMatrix column
_localStiffnessMatrix(_nodeIndex2,_nodeIndex1) = _DimType_(0.0);
}
// F[k] = cond
_d.getForceVector().coeffRef(_globalNodeIndex,0) =
_myNodeBindedBoundaryConditions[_globalNodeIndex]->getPotential();
// K[k][k] = 1
_localStiffnessMatrix(_nodeIndex1,_nodeIndex1) = _DimType_(1.0);
}
}
/// \todo make generalization for complex elements
// Apply Dirichlet boundary conditions
//
// It is flux * I([N]^T)dS
// For simplex elements: I([N]^T)dS = ((nDim-1)!*S)/(nDim)! = S/nDim
if(_myElementBindedBoundaryConditions.contains(_elementIndex))
{
_DimType_ _fluxValue =
_myFiniteElements[_elementIndex]->calculateSubElementVolume(
_myElementBindedBoundaryConditions[_elementIndex].first) *
_myElementBindedBoundaryConditions[_elementIndex].second->getFlux() /
_nDimensions_;
for(int _nodeIndex=0;_nodeIndex<_ElementType_::getNodesNumber();++_nodeIndex)
{
// Exclude opposite to the side node
if(_nodeIndex == _myElementBindedBoundaryConditions[_elementIndex].first)
continue;
_d.getForceVector().coeffRef(
_myFiniteElements[_elementIndex]->getNodeIndexes()[_nodeIndex], //globalNodeIndex
0) = //column
_fluxValue;
}
}
// Construct global stiffnessMatrix by locals
for(int _nodeIndex1=0;_nodeIndex1<_ElementType_::getNodesNumber();++_nodeIndex1)
for(int _nodeIndex2=0;_nodeIndex2<_ElementType_::getNodesNumber();++_nodeIndex2)
/// \todo use Triplets!!!
_d.getStiffnessMatrix().coeffRef(
_myFiniteElements[_elementIndex]->getNodeIndexes()[_nodeIndex1],
_myFiniteElements[_elementIndex]->getNodeIndexes()[_nodeIndex2]) +=
_localStiffnessMatrix(_nodeIndex1,_nodeIndex2);
}
return _d;
}
public : void bindBoundaryConditionToNode(int nodeIndex,
const BoundaryCondition<_DimType_> *boundaryCondition) throw (std::out_of_range)
{
if(nodeIndex>=0 && nodeIndex < _myNodes.size())
{
_myNodeBindedBoundaryConditions.insert(nodeIndex,boundaryCondition);
}
else throw std::out_of_range("Grid::bindBoundaryConditionToNode(), nodeIndex out of range");
}
/// For simplex elements, elementBoundaryId - is the index of opposite node
public : void bindBoundaryConditionToElement(int elementIndex, int elementBoundaryId,
const BoundaryCondition<_DimType_> *boundaryCondition) throw (std::out_of_range)
{
if(elementIndex>=0 && elementIndex < _myFiniteElements.size())
{
_myElementBindedBoundaryConditions.insert(elementIndex, qMakePair(elementBoundaryId, boundaryCondition));
}
else throw std::out_of_range("Grid::bindBoundaryConditionToElement(), nodeIndex out of range");
}
public : Grid(){}
public : ~Grid()
{
for(auto _i: _myNodes)
delete(_i);
_myNodes.clear();
for(auto _i: _myFiniteElements)
delete(_i);
_myFiniteElements.clear();
}
};
typedef Grid <
MathUtils::Node1D,
1,
Edge<MathUtils::Node1D, MathUtils::Real>,
MathUtils::Real> EdgeGrid;
typedef Grid <
MathUtils::Node2D,
2,
Triangle<MathUtils::Node2D, MathUtils::Real>,
MathUtils::Real> TriangularGrid;
typedef Grid <
MathUtils::Node3D,
3,
Tetrahedron<MathUtils::Node3D, MathUtils::Real>,
MathUtils::Real> TetrahedralGrid;
}
#endif // GRID_H
| [
"Passazhur@gmail.com@fbf05d7f-0995-0f14-e1a3-7aaf52e8406a"
] | Passazhur@gmail.com@fbf05d7f-0995-0f14-e1a3-7aaf52e8406a |
29769c975a59a49abce32907180b34aec7018d75 | 42c3d061692757a7029a3ebf3c52840eb53a89f4 | /OSSupport/Win/FileTimeToTimeSpec.cpp | c9ed9beffc76956cc15ed521d3e4eaa617aaa2d0 | [
"BSL-1.0"
] | permissive | neilgroves/MlbDev | 510b4877e85fc18e86941006debd5b65fdbac5dc | aee71572e444aa82b8ce05328e716807e1600521 | refs/heads/master | 2021-01-16T22:20:18.065564 | 2014-02-21T12:35:32 | 2014-02-21T12:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,345 | cpp | // ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// MLB Operating System Support (OSSupport) Library Module File
// ////////////////////////////////////////////////////////////////////////////
/*
File Name : %M%
File Version : %I%
Last Extracted : %D% %T%
Last Updated : %E% %U%
File Description : Converts from Windows 'FILETIME' structures to
'MLB::Utility::TimeSpec' structures.
Revision History : 1998-04-08 --- Creation.
Michael L. Brock
Copyright Michael L. Brock 1998 - 2014.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// Required include files...
// ////////////////////////////////////////////////////////////////////////////
#include <OSSupport_Win.h>
// ////////////////////////////////////////////////////////////////////////////
namespace MLB {
namespace OSSupport {
// ////////////////////////////////////////////////////////////////////////////
union OS_WIN32_FILETIME_64 {
FILETIME filetime;
unsigned __int64 u_scalar;
};
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
MLB::Utility::TimeSpec &FileTimeToTimeSpecAbsolute(const FILETIME &src,
MLB::Utility::TimeSpec &dst)
{
OS_WIN32_FILETIME_64 tmp_src;
tmp_src.filetime = src;
if (tmp_src.u_scalar >= OS_WIN32_FILETIME_EPOCH_BIAS) {
dst.tv_sec =
static_cast<long>((tmp_src.u_scalar - OS_WIN32_FILETIME_EPOCH_BIAS) /
10000000i64);
dst.tv_nsec =
static_cast<long>((tmp_src.u_scalar * 100i64) % 1000000000i64);
}
else
MLB::Utility::TimeSpec(0, 0).swap(dst);
return(dst);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
MLB::Utility::TimeSpec FileTimeToTimeSpecAbsolute(const FILETIME &src)
{
MLB::Utility::TimeSpec dst;
return(FileTimeToTimeSpecAbsolute(src, dst));
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
MLB::Utility::TimeSpec &FileTimeToTimeSpecInterval(const FILETIME &src,
MLB::Utility::TimeSpec &dst)
{
OS_WIN32_FILETIME_64 tmp_src;
tmp_src.filetime = src;
dst.tv_sec = static_cast<long>((tmp_src.u_scalar / 10i64) / 1000000i64);
dst.tv_nsec = static_cast<long>((tmp_src.u_scalar / 10i64) % 1000000000i64);
return(dst);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
MLB::Utility::TimeSpec FileTimeToTimeSpecInterval(const FILETIME &src)
{
MLB::Utility::TimeSpec dst;
return(FileTimeToTimeSpecInterval(src, dst));
}
// ////////////////////////////////////////////////////////////////////////////
} // namespace OSSupport
} // namespace MLB
| [
"michael.brock@gmail.com"
] | michael.brock@gmail.com |
a132484916c401f5b5b34841dd9f0c77162b508b | 1f40e2b0f2ed7041a271108a3cb560029ce651cc | /include/libcaf_io/caf/io/abstract_broker.hpp | 8719a991ab91e99722b7508bbae627652c66a6eb | [] | no_license | grantbrown/actor-framework-minimal | d47235cc55a5d888f9e885a1b1c0674cf6f17999 | b55457f4b60db3a0667c866faa57f878810dd32d | refs/heads/master | 2021-01-16T18:06:35.361320 | 2015-08-03T20:41:06 | 2015-08-03T20:41:06 | 40,146,615 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,141 | hpp | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_IO_ABSTRACT_BROKER_HPP
#define CAF_IO_ABSTRACT_BROKER_HPP
#include <map>
#include <vector>
#include "caf/detail/intrusive_partitioned_list.hpp"
#include "caf/io/fwd.hpp"
#include "caf/local_actor.hpp"
#include "caf/io/accept_handle.hpp"
#include "caf/io/receive_policy.hpp"
#include "caf/io/system_messages.hpp"
#include "caf/io/connection_handle.hpp"
#include "caf/io/network/native_socket.hpp"
#include "caf/io/network/stream_manager.hpp"
#include "caf/io/network/acceptor_manager.hpp"
namespace caf {
namespace io {
class middleman;
class abstract_broker : public local_actor {
public:
using buffer_type = std::vector<char>;
class continuation;
void enqueue(const actor_addr&, message_id,
message, execution_unit*) override;
void enqueue(mailbox_element_ptr, execution_unit*) override;
void launch(execution_unit* eu, bool lazy, bool hide);
void cleanup(uint32_t reason);
/// Manages a low-level IO device for the `broker`.
class servant {
public:
friend class abstract_broker;
void set_broker(abstract_broker* ptr);
virtual ~servant();
protected:
virtual void remove_from_broker() = 0;
virtual message disconnect_message() = 0;
inline abstract_broker* parent() {
return broker_;
}
servant(abstract_broker* ptr);
void disconnect(bool invoke_disconnect_message);
bool disconnected_;
abstract_broker* broker_;
};
/// Manages a stream.
class scribe : public network::stream_manager, public servant {
public:
scribe(abstract_broker* parent, connection_handle hdl);
~scribe();
/// Implicitly starts the read loop on first call.
virtual void configure_read(receive_policy::config config) = 0;
/// Grants access to the output buffer.
virtual buffer_type& wr_buf() = 0;
/// Flushes the output buffer, i.e., sends the content of
/// the buffer via the network.
virtual void flush() = 0;
inline connection_handle hdl() const {
return hdl_;
}
void io_failure(network::operation op) override;
protected:
virtual buffer_type& rd_buf() = 0;
inline new_data_msg& read_msg() {
return read_msg_.get_as_mutable<new_data_msg>(0);
}
inline const new_data_msg& read_msg() const {
return read_msg_.get_as<new_data_msg>(0);
}
void remove_from_broker() override;
message disconnect_message() override;
void consume(const void* data, size_t num_bytes) override;
connection_handle hdl_;
message read_msg_;
};
using scribe_pointer = intrusive_ptr<scribe>;
/// Manages incoming connections.
class doorman : public network::acceptor_manager, public servant {
public:
doorman(abstract_broker* parent, accept_handle hdl);
~doorman();
inline accept_handle hdl() const {
return hdl_;
}
void io_failure(network::operation op) override;
// needs to be launched explicitly
virtual void launch() = 0;
protected:
void remove_from_broker() override;
message disconnect_message() override;
inline new_connection_msg& accept_msg() {
return accept_msg_.get_as_mutable<new_connection_msg>(0);
}
inline const new_connection_msg& accept_msg() const {
return accept_msg_.get_as<new_connection_msg>(0);
}
accept_handle hdl_;
message accept_msg_;
};
using doorman_pointer = intrusive_ptr<doorman>;
// a broker needs friends
friend class scribe;
friend class doorman;
friend class continuation;
virtual ~abstract_broker();
/// Modifies the receive policy for given connection.
/// @param hdl Identifies the affected connection.
/// @param config Contains the new receive policy.
void configure_read(connection_handle hdl, receive_policy::config config);
/// Returns the write buffer for given connection.
buffer_type& wr_buf(connection_handle hdl);
/// Writes `data` into the buffer for given connection.
void write(connection_handle hdl, size_t data_size, const void* data);
/// Sends the content of the buffer for given connection.
void flush(connection_handle hdl);
/// Returns the number of open connections.
inline size_t num_connections() const {
return scribes_.size();
}
std::vector<connection_handle> connections() const;
/// @cond PRIVATE
inline void add_scribe(const scribe_pointer& ptr) {
scribes_.emplace(ptr->hdl(), ptr);
}
connection_handle add_tcp_scribe(const std::string& host, uint16_t port);
void assign_tcp_scribe(connection_handle hdl);
connection_handle add_tcp_scribe(network::native_socket fd);
inline void add_doorman(const doorman_pointer& ptr) {
doormen_.emplace(ptr->hdl(), ptr);
if (is_initialized()) {
ptr->launch();
}
}
std::pair<accept_handle, uint16_t> add_tcp_doorman(uint16_t port = 0,
const char* in = nullptr,
bool reuse_addr = false);
void assign_tcp_doorman(accept_handle hdl);
accept_handle add_tcp_doorman(network::native_socket fd);
void invoke_message(mailbox_element_ptr& msg);
void invoke_message(const actor_addr& sender,
message_id mid, message& msg);
/// Closes all connections and acceptors.
void close_all();
/// Closes the connection identified by `handle`.
/// Unwritten data will still be send.
void close(connection_handle handle);
/// Closes the acceptor identified by `handle`.
void close(accept_handle handle);
/// Checks whether a connection for `handle` exists.
bool valid(connection_handle handle);
/// Checks whether an acceptor for `handle` exists.
bool valid(accept_handle handle);
protected:
abstract_broker();
abstract_broker(middleman& parent_ref);
/// @endcond
inline middleman& parent() {
return mm_;
}
network::multiplexer& backend();
template <class Handle, class T>
static T& by_id(Handle hdl, std::map<Handle, intrusive_ptr<T>>& elements) {
auto i = elements.find(hdl);
if (i == elements.end()) {
throw std::invalid_argument("invalid handle");
}
return *(i->second);
}
// throws on error
inline scribe& by_id(connection_handle hdl) {
return by_id(hdl, scribes_);
}
// throws on error
inline doorman& by_id(accept_handle hdl) { return by_id(hdl, doormen_); }
bool invoke_message_from_cache();
std::map<accept_handle, doorman_pointer> doormen_;
std::map<connection_handle, scribe_pointer> scribes_;
middleman& mm_;
detail::intrusive_partitioned_list<mailbox_element, detail::disposer> cache_;
};
} // namespace io
} // namespace caf
#endif // CAF_IO_ABSTRACT_BROKER_HPP
| [
"grant.brown73@gmail.com"
] | grant.brown73@gmail.com |
0aa23864f53d53a1c62ade7f1783ecb959773692 | 5efc4f397b24997f1a8d3498634758f0e01a1e0a | /Chapter 11/CCI_ch11_prob5/CCI_ch11_prob5/MyBinarySearch.h | 3bb8596a1abad4097a26b4cae2ce5c9ebbd6954e | [] | no_license | vnpjeremy/Cracking-the-Coding-Interview | 328a3f31ce2e888aaddaec130f150bbf6854d8c8 | 8dc5e5a79fc42c0d43b0b6903524d9729e9ba87f | refs/heads/master | 2021-01-11T07:22:49.466438 | 2016-11-15T05:57:12 | 2016-11-15T05:57:12 | 68,850,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,406 | h | #pragma once
#include <array>
#include <cassert>
#include <string>
//this is no longer valid for template generiticiy. Strings only.
size_t findMid( std::string const*const arrayInput,
size_t const LH,
size_t const RH,
size_t const midSeed )
{
//assume no asserts needed for out-of-bounds calling
if(!arrayInput[midSeed].empty())
return midSeed;
//assume smallest-to-greatest, again, for BS
size_t candLHS = midSeed - 1, candRHS = midSeed + 1, counterLHS = 1, counterRHS = 1;
while(1)
{
if(candLHS <= RH && !arrayInput[candLHS].empty())
return candLHS;
if(candRHS <= RH && !arrayInput[candRHS].empty())
return candRHS;
candLHS = midSeed - counterLHS++;
candRHS = midSeed + counterRHS++;
if(candLHS > RH && candRHS > RH)
break; //wasn't found. Exit infinite loop.
}
return RH;
}
//could pass this as std::aray<std::string, N>. It depends on API preference.
size_t myBinarySearch( std::string const*const arrayInput,
size_t const LH,
size_t const RH,
std::string const searchValue )
{
/* Assume ascending order */
if(LH > RH)
return RH;
//assert(LH < RH); logical, but this condition is met when the searched for value is the [0] element in the array. Can't include.
assert(!searchValue.empty());
size_t midIndex = LH + (RH - LH) / 2;
midIndex = findMid(arrayInput, LH, RH, midIndex);
std::string const mid = arrayInput[midIndex];
if(mid == searchValue)
return midIndex;
/* We've begun an infinite loop. Calling with the same argument. String not found. */
if(midIndex + 1 == LH || midIndex - 1 == RH)
return RH;
/* The mid calculation tips off binary search that the string isn't found. But we have to 'scoot' to
find a non-null mid string, which is computed identically every time and causing an infinite loop.
Must handle uniquely because of this change in the algorithm. */
if(mid < searchValue)
return myBinarySearch(arrayInput, midIndex + 1, RH, searchValue);
if(searchValue < mid)
return myBinarySearch(arrayInput, LH, midIndex - 1, searchValue);
return midIndex;
} | [
"kreppsjs@gmail.com"
] | kreppsjs@gmail.com |
725150aa4202144eed90741b87679479e095512d | 27d97ce3d9f156af7de75b957ca7e52911a8ca12 | /algorithm/946.cpp | a2cae8599212e1f684ae766e660738c9bfb22495 | [] | no_license | EluvK/LeetCode | aa098801e0d03f672fe8aedd8166a78ca8361a0c | 9e51889eb94ca82c9de1e9abaac12b7335c6bc14 | refs/heads/master | 2021-12-11T13:23:15.297749 | 2020-03-29T04:31:33 | 2020-03-29T04:31:33 | 232,340,761 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 888 | cpp | class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> st;
while(!st.empty()) st.pop();
int len=popped.size(),ind=0;
map<int,int> mp;
for(int i=0;i<len;i++){
if(ind==len){
if(st.empty()) return false;
if(st.top()!=popped[i]) return false;
st.pop();
continue;
}
if(mp[popped[i]]==-1){
if(st.empty()) return false;
if(st.top()!=popped[i]) return false;
}
else{
do{
if(ind==len) return false;
st.push(pushed[ind]);
mp[pushed[ind]]=-1;
}while(pushed[ind++]!=popped[i]);
}
st.pop();
}
return true;
}
};
| [
"36977935+EucalyptSAMA@users.noreply.github.com"
] | 36977935+EucalyptSAMA@users.noreply.github.com |
b4e7b6da74f6e4aea07318642da3e35c6f884e69 | b10543704745b1bb9641519bc648d8f7394953d9 | /src/SimpleSound/soundspace.cpp | d1e47003e5ab12db4ab76427bc69322cee776cea | [] | no_license | scaryspacebat/SimpleUI | 339a19a2845cb3b906a9912a5af713ee5c18a7e0 | c6d2af1b10b03718bf25af8af11a16edece6e75f | refs/heads/master | 2020-03-10T22:13:29.821044 | 2018-06-08T00:15:41 | 2018-06-08T00:15:41 | 129,614,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,841 | cpp | #include "soundspace.hpp"
#include "../log.h"
#define MAX_V 32767
soundspace::soundspace()
{
log::writeToLog( "Creating soundspace" );
log::addTab();
sps=44100; // samples per second
bps=16; // bits per sample
volume=1.0;
nr_blocks=3;
nr_channels=1;
c_block=0;
p_blocks=0;
blocks = new WAVEHDR[nr_blocks];
blocksize=sps*0.1;
absolute_time=0;
for( int i=0; i<nr_blocks; i++ )
{
ZeroMemory( &blocks[i], sizeof( WAVEHDR ) );
blocks[i].dwBufferLength = blocksize*nr_channels;
blocks[i].lpData = ( LPSTR )( new short[blocksize*nr_channels] );
}
log::removeTab();
log::writeToLog( "Finished creating soundspace" );
}
soundspace::~soundspace()
{
//dtor
waveOutClose( hWaveOut );
}
void soundspace::init()
{
log::writeToLog( "Initiating soundspace" );
log::addTab();
//ctor
wfx.nSamplesPerSec = sps; /* sample rate */
wfx.wBitsPerSample = bps; /* sample size */
wfx.nChannels = nr_channels; /* channels*/
/*
* WAVEFORMATEX also has other fields which need filling.
* as long as the three fields above are filled this should
* work for any PCM (pulse code modulation) format.
*/
wfx.cbSize = 0; /* size of _extra_ info */
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nBlockAlign = ( wfx.wBitsPerSample >> 3 ) * wfx.nChannels;
wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec;
/*
* try to open the default wave device. WAVE_MAPPER is
* a constant defined in mmsystem.h, it always points to the
* default wave device on the system (some people have 2 or
* more sound cards).
*/
if( waveOutOpen(
&hWaveOut,
WAVE_MAPPER,
&wfx,
0,
0,
CALLBACK_NULL
) != MMSYSERR_NOERROR )
{
log::writeToLog( "Unable to open WAVE_MAPPER device", -1 );
//ExitProcess(1);
}
log::removeTab();
log::writeToLog( "Finished initiating soundspace" );
log::nextLine();
return;
}
void soundspace::update()
{
int dummy = 0;
while( ( ( blocks[c_block].dwFlags & WHDR_INQUEUE )==0 || ( blocks[c_block].dwFlags & WHDR_DONE )!=0 ) && sounds.size()>0 && cmpsr.size()>0 )
{
dummy++;
waveOutUnprepareHeader( hWaveOut, &blocks[c_block], sizeof( WAVEHDR ) );
double t_begin = static_cast<double>( p_blocks )*( static_cast<double>( blocksize )/static_cast<double>( sps ) );
double t_end = static_cast<double>( p_blocks+1 )*( static_cast<double>( blocksize )/static_cast<double>( sps ) );
// remove all expired sounds
int c=0;
while( c < sounds.size() )
{
if( sounds[c]->get_duration()!=-1 && sounds[c]->get_beginning()+sounds[c]->get_duration() < t_end )
{
delete sounds[c];
sounds.erase( sounds.begin()+c );
}
else
c++;
}
// add new sounds
for( int i=0; i<cmpsr.size(); i++ )
cmpsr[i]->update( t_begin, t_end );
// fill the current block
for( int i=0; i<blocksize; i++ )
{
for( int ch=0; ch<nr_channels; ch++ )
{
double d = volume*getAmplitude( static_cast<double>( i*2 )/static_cast<double>( sps )+t_begin, ch );
// Limiter with hard knee
if( d>0.8 )
d=0.8+( d-0.8 )*0.5;
else if( d<-0.8 )
d=-0.8-( d+0.8 )*0.5;
if( d>0.9 )
d=0.9+( d-0.9 )*0.5;
else if( d<-0.9 )
d=-0.9-( d+0.9 )*0.5;
// Hard Clipping
if( d < -1 )
d=-1;
else if( d > 1 )
d=1;
( ( short* )( blocks[c_block].lpData ) )[i*nr_channels+ch] = d*MAX_V;
}
}
waveOutPrepareHeader( hWaveOut, &blocks[c_block], sizeof( WAVEHDR ) );
waveOutWrite( hWaveOut, &blocks[c_block], sizeof( WAVEHDR ) );
p_blocks++;
c_block=( c_block+1 )%nr_blocks;
}
if( dummy>1 )
log::writeToLog( "Couldn't generate soundbuffer fast enough! Queued blocks: "+std::to_string( dummy ) );
return;
}
void soundspace::addComposer( composer* c )
{
c->setParent( this );
cmpsr.push_back( c );
return;
}
double soundspace::getAmplitude( double t, int c )
{
double r=0;
absolute_time=t;
for( int i=0; i<sounds.size(); i++ )
r+=sounds[i]->play( t, c );
return r;
}
void soundspace::addSound( sound* snd )
{
snd->setParent( this );
sounds.push_back( snd );
return;
}
double soundspace::getAbsoluteTime()
{
return absolute_time;
}
| [
"38399058+scaryspacebat@users.noreply.github.com"
] | 38399058+scaryspacebat@users.noreply.github.com |
8a7d514ad3bb423139b80d3360bbbc06c35fd182 | 79503ad3f3ac3e58483fdd8aa1516b3eeb0bb514 | /include/KeyboardEvents.h | 10b73a069ceef672b3c24a7751dd44139dcf6d96 | [] | no_license | jinnee/opge | c4484277b1ee5c94e626da4aaadc92462b75628b | 285e0be8a2e106d40e7250da77b0f8a97dcf1b0a | refs/heads/master | 2019-08-06T07:18:36.094364 | 2017-10-14T17:14:13 | 2017-10-14T17:14:13 | 26,861,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 199 | h | #ifndef KEYBOARDEVENTS
#define KEYBOARDEVENTS
class KeyboardEvents
{
public:
virtual void onKeyDown(Sint16 key) = 0;
virtual void onKeyUp(Sint16 key) = 0;
};
#endif // KEYBOARDEVENTS
| [
"jan@infinity.(none)"
] | jan@infinity.(none) |
10f1a671e0b9e612a1154e0726bf3df0b254469a | 7bf1f0f4507fb8285be393b3a2bd6fa6b6debb9e | /shadow/operators/flatten_op.cpp | 5aa6e72f7fe9ea840d8e5ff1051a7a0d2c4649ed | [
"Apache-2.0"
] | permissive | junluan/shadow | f376d28d51030c8010c2926949f23462710c9845 | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | refs/heads/master | 2021-07-06T12:31:51.218310 | 2021-05-24T06:20:40 | 2021-05-24T06:20:40 | 54,448,369 | 20 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 1,213 | cpp | #include "core/operator.hpp"
namespace Shadow {
class FlattenOp : public Operator {
public:
FlattenOp(const shadow::OpParam& op_param, Workspace* ws)
: Operator(op_param, ws) {
axis_ = get_single_argument<int>("axis", 1);
CHECK_GE(axis_, 0);
end_axis_ = get_single_argument<int>("end_axis", -1);
}
void Run(const std::vector<std::shared_ptr<Blob>>& inputs,
std::vector<std::shared_ptr<Blob>>& outputs) override {
const auto& input = inputs[0];
auto& output = outputs[0];
CHECK_NE(input, output);
int num_axes = input->num_axes();
if (end_axis_ == -1) {
end_axis_ = num_axes - 1;
}
CHECK_LT(end_axis_, num_axes);
CHECK_LE(axis_, end_axis_);
VecInt out_shape;
for (int d = 0; d < axis_; ++d) {
out_shape.push_back(input->shape(d));
}
out_shape.push_back(input->count(axis_, end_axis_ + 1));
for (int d = end_axis_ + 1; d < input->num_axes(); ++d) {
out_shape.push_back(input->shape(d));
}
output->share_data(input->data<void>(), out_shape);
CHECK_EQ(output->count(), input->count());
}
private:
int axis_, end_axis_;
};
REGISTER_OPERATOR(Flatten, FlattenOp);
} // namespace Shadow
| [
"mutate@aliyun.com"
] | mutate@aliyun.com |
d82564d8480d8f9da02bf023deb926b51eb72f7a | 15c9f33cf301dff82e39daa51dfbe27ad166a2e1 | /Data_Structure/union_find.cpp | c060f19cd0827a0e72486ee6a48b59f05318ccf3 | [] | no_license | sndtkrh/kyogi-lib | 4c5cf8d4bab4747be37ec33b283f78aa6813c01b | fb239e55e524ff3f50f3d47de559802fe76e4400 | refs/heads/master | 2021-01-02T09:44:47.500817 | 2017-12-23T15:16:33 | 2017-12-23T15:16:33 | 99,285,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | cpp | // Union-Find 木
/*
* 互いに素な集合族を扱うためのデータ構造.
* 各操作のならし計算量は$\mathcal{O}(\alpha(n))$である.
* ここで$\alpha(n)$はアッカーマン関数の逆関数である.
* - verified by: http://codeforces.com/contest/438/problem/B
*/
#ifndef UNIONFIND
#define UNIONFIND
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class UFT {
vector<int> parent;
vector<int> rank; //木の高さ
vector<int> size; //その頂点が属している集合の大きさ(必要な場合だけ)
public:
UFT(int n){
parent = vector<int>(n);
rank = vector<int>(n,0);
size = vector<int>(n,1);
for(int i = 0; i < n; i++)
parent[i] = i;
}
int find_root(int x){
if ( parent[x] == x ) return x;
return parent[x] = find_root( parent[x] );
}
void unite(int x, int y){
int u = find_root(x);
int v = find_root(y);
if ( u == v ) return;
if ( rank[u] < rank[v] ){
parent[u] = v;
size[v] += size[u];
}else{
parent[v] = u;
size[u] += size[v];
if ( rank[u] == rank[v] ) rank[x]++;
}
}
bool is_same ( int x, int y ){
return find_root(x) == find_root(y);
}
int size_of ( int x ){
return size[ find_root(x) ];
}
};
#endif
| [
"sndtkrh@users.noreply.github.com"
] | sndtkrh@users.noreply.github.com |
0dcab12d50b04753e9a40b99a1b7798f4fe2dad5 | c43e8b81b190877a933204300ada72925d36eed9 | /columnar.cpp | 446407c9dcbdb8995a1f05fb12c7c336685c63d0 | [] | no_license | shams7734/ISSLab | 90a69dd7fe0ca24c8199af7dd6b5037ee77aab24 | 53144370f5a8d98e70d1cbc65e79d8fd08b3da3c | refs/heads/master | 2020-03-10T13:38:27.805243 | 2018-04-13T18:47:45 | 2018-04-13T18:47:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 659 | cpp | /* Implementation of Single Columnar Transportation Technique.
In this user needs to input the number of column and the plain text .
2015kucp1034
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
int i,k,key;
int length;
char str[100];
printf("Enter number of columns\n");
scanf("%d",&key);
vector<char > ch[key];
printf("Enter the plain text\n");
scanf("%s",str);
length=strlen(str);
k=0;
for(i=0;k<length;)
{
if(i==key)
i=0;
ch[i].push_back(str[k]);
i++;k++;
}
printf("The encrypted text\n");
for(i=0;i<key;i++)
{
for(auto it=ch[i].begin();it<ch[i].end();it++)
{
printf("%c",*it);
}
}
printf("\n");
}
| [
"2015kucp1034@iiitkota.ac.in"
] | 2015kucp1034@iiitkota.ac.in |
19e8e02afec7fc4e0d42cae76bd5637cd4d6ad18 | 795a7a7557b32aa0ad2482e4bf249aa2ddac44c9 | /ecmd-core/ext/fapi2/perlapi/fapi2ClientPerlapi.H | 282f5ffc710833bb03f2dcd89f70119a75733ddb | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mklight/eCMD | cce3c81d72010ff4fc03764798359c7756fccff9 | 1dd4a8467a09488613158a4b292f012a91617297 | refs/heads/master | 2021-04-03T01:52:40.285799 | 2020-05-29T14:32:14 | 2020-05-29T14:32:14 | 64,481,432 | 0 | 0 | Apache-2.0 | 2020-04-09T18:44:27 | 2016-07-29T13:11:27 | C | UTF-8 | C++ | false | false | 3,123 | h | //IBM_PROLOG_BEGIN_TAG
/*
* Copyright 2017 IBM International Business Machines Corp.
*
* 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.
*/
//IBM_PROLOG_END_TAG
#ifndef fapi2ClientPerlapi_h
#define fapi2ClientPerlapi_h
/**
* @file fapi2ClientPerlapi.H
* @brief Cronus & IP eCMD Perlapi Extension
* Extension Owner : Matt Light
@section fapi2 FAPI2 (Hardware Procedure Framework) Extension
In Perl only extension intialization is provided.<br>
Include files :
<ul>
<li> fapi2ClientPerlapi.H </li>
</ul>
*/
//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <ecmdReturnCodes.H>
#include <ecmdStructs.H>
#include <ecmdDataBuffer.H>
#include <fapi2Structs.H>
//--------------------------------------------------------------------
// Forward References
//--------------------------------------------------------------------
/* Functions in here are defined as extern C for the following reasons:
1) Keeps Function names small by preventing C++ "mangling"
2) Allows (C-based) perl interpreter to access these functions
*/
#ifndef DOCUMENTATION
namespace FAPI2PERLAPI {
#endif
/** @name Load/Unload Functions */
//@{
/**
@brief Initialize eCMD FAPI2 Extension DLL
@param i_clientVersion Comma seperated list of eCMD Perl api major numbers this script supports, see details
@retval ECMD_SUCCESS if successful load
@retval ECMD_INVALID_DLL_VERSION if Dll version loaded doesn't match client version
@retval nonzero if unsuccessful
@post eCMD FAPI2 Extension is initialized and version checked
VERSIONS :
eCMD at times has to make changes to add/remove functionality and parameters to functions. This could cause
incompatability in your script if you used functions that have changed. The i_clientVersion string is used
to tell eCMD which major releases you support such that your script will not continue execution if it encounters
a version that is either not known about or not supported. This is similar to how the eCMD C-Api works except in
Perl you can support multiple versions with one script as long as the changes that were made between the versions
do not affect your script.
USAGE :
if (fapi2InitExtension("ver3,ver4")) { die "Fatal errors initializing DLL"; }
*/
int fapi2InitExtension(const char * i_clientVersion);
//@}
#ifndef DOCUMENTATION
} // End namespace
#endif
#endif /* fapi2ClientCapi_h */
| [
"mklight@us.ibm.com"
] | mklight@us.ibm.com |
25d1e0f44f2f14d8cc81d149d091358c576d27d4 | f86ba52896bdd0feb103de75b79b3e64c0903f7b | /piscine c (jun'19)/EvalExpr/Ppn/StdAfx.h | dbd1f758d0aa7c41b6be8002dfe2611a9c64d17e | [] | no_license | JB-doogls/42-projects | 30139ed32bc7a46ec93313023253827c7de4d1f8 | a35150cfe4c8ec1fbd4aaf39998d53689d9faa1b | refs/heads/master | 2020-07-23T01:45:34.081205 | 2020-01-22T14:16:30 | 2020-01-22T14:16:30 | 207,404,169 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,106 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__E43C296B_FC2C_449A_8729_EB3F8A30CE11__INCLUDED_)
#define AFX_STDAFX_H__E43C296B_FC2C_449A_8729_EB3F8A30CE11__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#include <afx.h>
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
#include <iostream>
// TODO: reference additional headers your program requires here
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__E43C296B_FC2C_449A_8729_EB3F8A30CE11__INCLUDED_)
| [
"jbdoogls@edoll.21vv"
] | jbdoogls@edoll.21vv |
526f87a1f01dcae30aa13aac518971ea5e9131b4 | 38f42e0aa2511057ffe0585bba8bd5a0e36f82d1 | /mp6/tests/unit_tests.cpp | a0eabb15d8323db240b485d3a5a085cf192f74b2 | [] | no_license | diditong/UIUC-CS225-FA2018 | 149f4b8dd5d869e5cfda15861a2a9cd97358f437 | 280a02f2d32ebd104a80512b1a82e13f3e66841c | refs/heads/master | 2020-12-13T14:10:13.120463 | 2020-01-17T00:33:09 | 2020-01-17T00:33:09 | 234,437,920 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,205 | cpp | #include "../cs225/catch/catch.hpp"
#include "../cs225/PNG.h"
#include "../cs225/HSLAPixel.h"
#include "../skipList.h"
#include "../skipNode.h"
int probability = 50;
int maxLevel = 50;
void assertEqual(vector<int> a, vector<int> b, bool rev = false) {
REQUIRE(a.size() == b.size());
for(size_t i = 0; i < a.size(); i++) {
REQUIRE(a[i] == b[i]);
}
}
void removeSentinels(vector<int> & a) {
a.erase(a.begin());
a.pop_back();
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
//////////////////////// Start of Tests ////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
TEST_CASE("SkipList::traverse after ctor returns a list with two sentinel nodes", "[weight=5][part=1]") {
SkipList list(probability, maxLevel);
vector<int> result = list.traverse();
// The expected size is equal to two due to the sentinel nodes
REQUIRE(result.size() == 2);
}
TEST_CASE("SkipList::traverse::size == 1 after one element was added", "[weight=5][part=1]") {
SkipList list(probability, maxLevel);
list.insert(42, HSLAPixel(180, 1, 0.5));
vector<int> result = list.traverse();
removeSentinels(result);
REQUIRE(result.size() == 1);
}
TEST_CASE("SkipList::traverse::size == 1 after three elements were added with the same key", "[weight=5][part=1]") {
SkipList list(probability, maxLevel);
list.insert(42, HSLAPixel(180, 1, 0.5));
//list.printKeys();
list.insert(42, HSLAPixel(210, 1, 0.5));
//list.printKeys();
list.insert(42, HSLAPixel(240, 1, 0.5));
//list.printKeys();
list.insert(42, HSLAPixel(220, 1, 0.5));
//list.printKeys();
list.insert(42, HSLAPixel(215, 1, 0.5));
// list.printKeys();
vector<int> result = list.traverse();
removeSentinels(result);
REQUIRE(result.size() == 1);
}
TEST_CASE("Tests search() with a single node -- existent", "[weight=5][part=2]") {
SkipList list(probability, maxLevel);
int key = 7;
HSLAPixel c(137, 137, 137);
list.insert(key, c);
HSLAPixel ret = list.search(7);
REQUIRE(ret == c);
}
TEST_CASE("Tests search() with a single node -- non-existent", "[weight=5][part=2]") {
SkipList list(probability, maxLevel);
int key = 7;
HSLAPixel c(137, 137, 137);
list.insert(key, c);
HSLAPixel ret = list.search(5);
REQUIRE(ret == HSLAPixel(0, 0, 0, 0.5));
}
TEST_CASE("Tests search() with several nodes -- existent", "[weight=10][part=2]") {
SkipList list(probability, maxLevel);
int key = 7;
HSLAPixel c(137, 137, 137);
for(int i = 1; i < 100; i += 2)
{
if(i == 7)
list.insert(i, HSLAPixel(42, 42, 42));
else
list.insert(i, c);
}
HSLAPixel ret = list.search(7);
REQUIRE(ret == HSLAPixel(42, 42, 42));
}
TEST_CASE("Tests inserting ascending values", "[weight=5][part=2]") {
SkipList list(probability, maxLevel);
vector<int> soln;
HSLAPixel c(137, 137, 137);
for(int i = 1; i < 999; i += 3) {
list.insert(i, c);
soln.push_back(i);
}
// get the traverse map
vector<int> check = list.traverse();
removeSentinels(check);
// compare to solution
assertEqual(check, soln);
}
TEST_CASE("Tests inserting ascending values (reversed check)", "[weight=5][part=2]") {
SkipList list(probability, maxLevel);
vector<int> soln;
HSLAPixel c(137, 137, 137);
for(int i = 1; i < 999; i += 3)
{
list.insert(i, c);
soln.push_back(i);
}
// get the traverse map
vector<int> check = list.traverseReverse();
removeSentinels(check);
// compare to solution
assertEqual(check, soln);
}
TEST_CASE("Tests inserting random values", "[weight=10][part=2]") {
SkipList list(probability, maxLevel);
vector<int> soln;
vector<int> keys;
HSLAPixel c(137, 137, 137);
for(int i = 1; i < 999; i += 3)
{
keys.push_back(i);
soln.push_back(i);
}
random_shuffle(keys.begin(), keys.end());
for(int k : keys)
list.insert(k, c);
// get the backwards traverse map
vector<int> check = list.traverseReverse();
removeSentinels(check);
// compare to solution
assertEqual(check, soln, true);
}
TEST_CASE("Tests removing nodes (easy)", "[weight=5][part=2]") {
SkipList list(probability, maxLevel);
vector<int> soln;
HSLAPixel c(137, 137, 137);
for(int i = 1; i <= 10; i++)
{
if(i != 7)
{
list.insert(i, c);
if(i != 3)
soln.push_back(i);
}
}
bool ret1 = list.remove(3);
bool ret2 = list.remove(7);
//list.printKeys();
//list.printKeysReverse();
REQUIRE(ret1 == true);
REQUIRE(ret2 == false);
// get traverse map
vector<int> check = list.traverse();
removeSentinels(check);
// compare to solution
assertEqual(check, soln);
check = list.traverseReverse();
removeSentinels(check);
assertEqual(check, soln, true);
}
TEST_CASE("Tests constructors - 1", "[weight=2][part=2]") {
SkipList list (1337, HSLAPixel(137, 0.137, 0.137));
list.insert(42, HSLAPixel(42, 0.42, 0.42));
list.insert(9999, HSLAPixel(99, 0.99, 0.99));
vector<int> soln;
soln.push_back(42);
soln.push_back(1337);
soln.push_back(9999);
vector<int> check = list.traverse();
removeSentinels(check);
assertEqual(check, soln);
check = list.traverseReverse();
removeSentinels(check);
assertEqual(check, soln, true);
}
TEST_CASE("Tests constructors - 2", "[weight=2][part=2]") {
SkipList * list = new SkipList(probability, maxLevel);
list->insert(42, HSLAPixel(42, 0.42, 0.42));
delete list;
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
///////////////////////// End of Tests /////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
| [
"jtong8@illinois.edu"
] | jtong8@illinois.edu |
9a534df7887419136ef90dc332b5e1a248b172e0 | 3282ccae547452b96c4409e6b5a447f34b8fdf64 | /SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimBuildingElementProxy.cxx | ea9bc31d1f1a0ef65805a41b2e1853ab54b5d7c1 | [
"MIT"
] | permissive | EnEff-BIM/EnEffBIM-Framework | c8bde8178bb9ed7d5e3e5cdf6d469a009bcb52de | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | refs/heads/master | 2021-01-18T00:16:06.546875 | 2017-04-18T08:03:40 | 2017-04-18T08:03:40 | 28,960,534 | 3 | 0 | null | 2017-04-18T08:03:40 | 2015-01-08T10:19:18 | C++ | UTF-8 | C++ | false | false | 256,387 | cxx | // Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "SimBuildingElementProxy.hxx"
namespace schema
{
namespace simxml
{
namespace BuildingModel
{
// SimBuildingElementProxy
//
const SimBuildingElementProxy::Name_optional& SimBuildingElementProxy::
Name () const
{
return this->Name_;
}
SimBuildingElementProxy::Name_optional& SimBuildingElementProxy::
Name ()
{
return this->Name_;
}
void SimBuildingElementProxy::
Name (const Name_type& x)
{
this->Name_.set (x);
}
void SimBuildingElementProxy::
Name (const Name_optional& x)
{
this->Name_ = x;
}
void SimBuildingElementProxy::
Name (::std::auto_ptr< Name_type > x)
{
this->Name_.set (x);
}
const SimBuildingElementProxy::Representation_optional& SimBuildingElementProxy::
Representation () const
{
return this->Representation_;
}
SimBuildingElementProxy::Representation_optional& SimBuildingElementProxy::
Representation ()
{
return this->Representation_;
}
void SimBuildingElementProxy::
Representation (const Representation_type& x)
{
this->Representation_.set (x);
}
void SimBuildingElementProxy::
Representation (const Representation_optional& x)
{
this->Representation_ = x;
}
void SimBuildingElementProxy::
Representation (::std::auto_ptr< Representation_type > x)
{
this->Representation_.set (x);
}
const SimBuildingElementProxy::CompositionType_optional& SimBuildingElementProxy::
CompositionType () const
{
return this->CompositionType_;
}
SimBuildingElementProxy::CompositionType_optional& SimBuildingElementProxy::
CompositionType ()
{
return this->CompositionType_;
}
void SimBuildingElementProxy::
CompositionType (const CompositionType_type& x)
{
this->CompositionType_.set (x);
}
void SimBuildingElementProxy::
CompositionType (const CompositionType_optional& x)
{
this->CompositionType_ = x;
}
void SimBuildingElementProxy::
CompositionType (::std::auto_ptr< CompositionType_type > x)
{
this->CompositionType_.set (x);
}
const SimBuildingElementProxy::AHUHeight_optional& SimBuildingElementProxy::
AHUHeight () const
{
return this->AHUHeight_;
}
SimBuildingElementProxy::AHUHeight_optional& SimBuildingElementProxy::
AHUHeight ()
{
return this->AHUHeight_;
}
void SimBuildingElementProxy::
AHUHeight (const AHUHeight_type& x)
{
this->AHUHeight_.set (x);
}
void SimBuildingElementProxy::
AHUHeight (const AHUHeight_optional& x)
{
this->AHUHeight_ = x;
}
const SimBuildingElementProxy::AHUWidth_optional& SimBuildingElementProxy::
AHUWidth () const
{
return this->AHUWidth_;
}
SimBuildingElementProxy::AHUWidth_optional& SimBuildingElementProxy::
AHUWidth ()
{
return this->AHUWidth_;
}
void SimBuildingElementProxy::
AHUWidth (const AHUWidth_type& x)
{
this->AHUWidth_.set (x);
}
void SimBuildingElementProxy::
AHUWidth (const AHUWidth_optional& x)
{
this->AHUWidth_ = x;
}
const SimBuildingElementProxy::AirFlow_optional& SimBuildingElementProxy::
AirFlow () const
{
return this->AirFlow_;
}
SimBuildingElementProxy::AirFlow_optional& SimBuildingElementProxy::
AirFlow ()
{
return this->AirFlow_;
}
void SimBuildingElementProxy::
AirFlow (const AirFlow_type& x)
{
this->AirFlow_.set (x);
}
void SimBuildingElementProxy::
AirFlow (const AirFlow_optional& x)
{
this->AirFlow_ = x;
}
const SimBuildingElementProxy::AirflowReturn_optional& SimBuildingElementProxy::
AirflowReturn () const
{
return this->AirflowReturn_;
}
SimBuildingElementProxy::AirflowReturn_optional& SimBuildingElementProxy::
AirflowReturn ()
{
return this->AirflowReturn_;
}
void SimBuildingElementProxy::
AirflowReturn (const AirflowReturn_type& x)
{
this->AirflowReturn_.set (x);
}
void SimBuildingElementProxy::
AirflowReturn (const AirflowReturn_optional& x)
{
this->AirflowReturn_ = x;
}
const SimBuildingElementProxy::AirflowSupply_optional& SimBuildingElementProxy::
AirflowSupply () const
{
return this->AirflowSupply_;
}
SimBuildingElementProxy::AirflowSupply_optional& SimBuildingElementProxy::
AirflowSupply ()
{
return this->AirflowSupply_;
}
void SimBuildingElementProxy::
AirflowSupply (const AirflowSupply_type& x)
{
this->AirflowSupply_.set (x);
}
void SimBuildingElementProxy::
AirflowSupply (const AirflowSupply_optional& x)
{
this->AirflowSupply_ = x;
}
const SimBuildingElementProxy::AirPressure_optional& SimBuildingElementProxy::
AirPressure () const
{
return this->AirPressure_;
}
SimBuildingElementProxy::AirPressure_optional& SimBuildingElementProxy::
AirPressure ()
{
return this->AirPressure_;
}
void SimBuildingElementProxy::
AirPressure (const AirPressure_type& x)
{
this->AirPressure_.set (x);
}
void SimBuildingElementProxy::
AirPressure (const AirPressure_optional& x)
{
this->AirPressure_ = x;
}
const SimBuildingElementProxy::AirwayLength_optional& SimBuildingElementProxy::
AirwayLength () const
{
return this->AirwayLength_;
}
SimBuildingElementProxy::AirwayLength_optional& SimBuildingElementProxy::
AirwayLength ()
{
return this->AirwayLength_;
}
void SimBuildingElementProxy::
AirwayLength (const AirwayLength_type& x)
{
this->AirwayLength_.set (x);
}
void SimBuildingElementProxy::
AirwayLength (const AirwayLength_optional& x)
{
this->AirwayLength_ = x;
}
const SimBuildingElementProxy::AlternatorVoltage_optional& SimBuildingElementProxy::
AlternatorVoltage () const
{
return this->AlternatorVoltage_;
}
SimBuildingElementProxy::AlternatorVoltage_optional& SimBuildingElementProxy::
AlternatorVoltage ()
{
return this->AlternatorVoltage_;
}
void SimBuildingElementProxy::
AlternatorVoltage (const AlternatorVoltage_type& x)
{
this->AlternatorVoltage_.set (x);
}
void SimBuildingElementProxy::
AlternatorVoltage (const AlternatorVoltage_optional& x)
{
this->AlternatorVoltage_ = x;
}
const SimBuildingElementProxy::Ang_optional& SimBuildingElementProxy::
Ang () const
{
return this->Ang_;
}
SimBuildingElementProxy::Ang_optional& SimBuildingElementProxy::
Ang ()
{
return this->Ang_;
}
void SimBuildingElementProxy::
Ang (const Ang_type& x)
{
this->Ang_.set (x);
}
void SimBuildingElementProxy::
Ang (const Ang_optional& x)
{
this->Ang_ = x;
}
const SimBuildingElementProxy::ApparentLoad_optional& SimBuildingElementProxy::
ApparentLoad () const
{
return this->ApparentLoad_;
}
SimBuildingElementProxy::ApparentLoad_optional& SimBuildingElementProxy::
ApparentLoad ()
{
return this->ApparentLoad_;
}
void SimBuildingElementProxy::
ApparentLoad (const ApparentLoad_type& x)
{
this->ApparentLoad_.set (x);
}
void SimBuildingElementProxy::
ApparentLoad (const ApparentLoad_optional& x)
{
this->ApparentLoad_ = x;
}
const SimBuildingElementProxy::ApparentLoadPhaseA_optional& SimBuildingElementProxy::
ApparentLoadPhaseA () const
{
return this->ApparentLoadPhaseA_;
}
SimBuildingElementProxy::ApparentLoadPhaseA_optional& SimBuildingElementProxy::
ApparentLoadPhaseA ()
{
return this->ApparentLoadPhaseA_;
}
void SimBuildingElementProxy::
ApparentLoadPhaseA (const ApparentLoadPhaseA_type& x)
{
this->ApparentLoadPhaseA_.set (x);
}
void SimBuildingElementProxy::
ApparentLoadPhaseA (const ApparentLoadPhaseA_optional& x)
{
this->ApparentLoadPhaseA_ = x;
}
const SimBuildingElementProxy::ApparentLoadPhaseB_optional& SimBuildingElementProxy::
ApparentLoadPhaseB () const
{
return this->ApparentLoadPhaseB_;
}
SimBuildingElementProxy::ApparentLoadPhaseB_optional& SimBuildingElementProxy::
ApparentLoadPhaseB ()
{
return this->ApparentLoadPhaseB_;
}
void SimBuildingElementProxy::
ApparentLoadPhaseB (const ApparentLoadPhaseB_type& x)
{
this->ApparentLoadPhaseB_.set (x);
}
void SimBuildingElementProxy::
ApparentLoadPhaseB (const ApparentLoadPhaseB_optional& x)
{
this->ApparentLoadPhaseB_ = x;
}
const SimBuildingElementProxy::ApparentLoadPhaseC_optional& SimBuildingElementProxy::
ApparentLoadPhaseC () const
{
return this->ApparentLoadPhaseC_;
}
SimBuildingElementProxy::ApparentLoadPhaseC_optional& SimBuildingElementProxy::
ApparentLoadPhaseC ()
{
return this->ApparentLoadPhaseC_;
}
void SimBuildingElementProxy::
ApparentLoadPhaseC (const ApparentLoadPhaseC_type& x)
{
this->ApparentLoadPhaseC_.set (x);
}
void SimBuildingElementProxy::
ApparentLoadPhaseC (const ApparentLoadPhaseC_optional& x)
{
this->ApparentLoadPhaseC_ = x;
}
const SimBuildingElementProxy::AverageSolarTransmittance_optional& SimBuildingElementProxy::
AverageSolarTransmittance () const
{
return this->AverageSolarTransmittance_;
}
SimBuildingElementProxy::AverageSolarTransmittance_optional& SimBuildingElementProxy::
AverageSolarTransmittance ()
{
return this->AverageSolarTransmittance_;
}
void SimBuildingElementProxy::
AverageSolarTransmittance (const AverageSolarTransmittance_type& x)
{
this->AverageSolarTransmittance_.set (x);
}
void SimBuildingElementProxy::
AverageSolarTransmittance (const AverageSolarTransmittance_optional& x)
{
this->AverageSolarTransmittance_ = x;
}
const SimBuildingElementProxy::AverageVisibleTransmittance_optional& SimBuildingElementProxy::
AverageVisibleTransmittance () const
{
return this->AverageVisibleTransmittance_;
}
SimBuildingElementProxy::AverageVisibleTransmittance_optional& SimBuildingElementProxy::
AverageVisibleTransmittance ()
{
return this->AverageVisibleTransmittance_;
}
void SimBuildingElementProxy::
AverageVisibleTransmittance (const AverageVisibleTransmittance_type& x)
{
this->AverageVisibleTransmittance_.set (x);
}
void SimBuildingElementProxy::
AverageVisibleTransmittance (const AverageVisibleTransmittance_optional& x)
{
this->AverageVisibleTransmittance_ = x;
}
const SimBuildingElementProxy::Azimuth_optional& SimBuildingElementProxy::
Azimuth () const
{
return this->Azimuth_;
}
SimBuildingElementProxy::Azimuth_optional& SimBuildingElementProxy::
Azimuth ()
{
return this->Azimuth_;
}
void SimBuildingElementProxy::
Azimuth (const Azimuth_type& x)
{
this->Azimuth_.set (x);
}
void SimBuildingElementProxy::
Azimuth (const Azimuth_optional& x)
{
this->Azimuth_ = x;
}
const SimBuildingElementProxy::BaseHeight_optional& SimBuildingElementProxy::
BaseHeight () const
{
return this->BaseHeight_;
}
SimBuildingElementProxy::BaseHeight_optional& SimBuildingElementProxy::
BaseHeight ()
{
return this->BaseHeight_;
}
void SimBuildingElementProxy::
BaseHeight (const BaseHeight_type& x)
{
this->BaseHeight_.set (x);
}
void SimBuildingElementProxy::
BaseHeight (const BaseHeight_optional& x)
{
this->BaseHeight_ = x;
}
const SimBuildingElementProxy::BaseLength_optional& SimBuildingElementProxy::
BaseLength () const
{
return this->BaseLength_;
}
SimBuildingElementProxy::BaseLength_optional& SimBuildingElementProxy::
BaseLength ()
{
return this->BaseLength_;
}
void SimBuildingElementProxy::
BaseLength (const BaseLength_type& x)
{
this->BaseLength_.set (x);
}
void SimBuildingElementProxy::
BaseLength (const BaseLength_optional& x)
{
this->BaseLength_ = x;
}
const SimBuildingElementProxy::Buildingstoreyname_optional& SimBuildingElementProxy::
Buildingstoreyname () const
{
return this->Buildingstoreyname_;
}
SimBuildingElementProxy::Buildingstoreyname_optional& SimBuildingElementProxy::
Buildingstoreyname ()
{
return this->Buildingstoreyname_;
}
void SimBuildingElementProxy::
Buildingstoreyname (const Buildingstoreyname_type& x)
{
this->Buildingstoreyname_.set (x);
}
void SimBuildingElementProxy::
Buildingstoreyname (const Buildingstoreyname_optional& x)
{
this->Buildingstoreyname_ = x;
}
void SimBuildingElementProxy::
Buildingstoreyname (::std::auto_ptr< Buildingstoreyname_type > x)
{
this->Buildingstoreyname_.set (x);
}
const SimBuildingElementProxy::C1Offset1_optional& SimBuildingElementProxy::
C1Offset1 () const
{
return this->C1Offset1_;
}
SimBuildingElementProxy::C1Offset1_optional& SimBuildingElementProxy::
C1Offset1 ()
{
return this->C1Offset1_;
}
void SimBuildingElementProxy::
C1Offset1 (const C1Offset1_type& x)
{
this->C1Offset1_.set (x);
}
void SimBuildingElementProxy::
C1Offset1 (const C1Offset1_optional& x)
{
this->C1Offset1_ = x;
}
const SimBuildingElementProxy::C1Offset2_optional& SimBuildingElementProxy::
C1Offset2 () const
{
return this->C1Offset2_;
}
SimBuildingElementProxy::C1Offset2_optional& SimBuildingElementProxy::
C1Offset2 ()
{
return this->C1Offset2_;
}
void SimBuildingElementProxy::
C1Offset2 (const C1Offset2_type& x)
{
this->C1Offset2_.set (x);
}
void SimBuildingElementProxy::
C1Offset2 (const C1Offset2_optional& x)
{
this->C1Offset2_ = x;
}
const SimBuildingElementProxy::C2Offset1_optional& SimBuildingElementProxy::
C2Offset1 () const
{
return this->C2Offset1_;
}
SimBuildingElementProxy::C2Offset1_optional& SimBuildingElementProxy::
C2Offset1 ()
{
return this->C2Offset1_;
}
void SimBuildingElementProxy::
C2Offset1 (const C2Offset1_type& x)
{
this->C2Offset1_.set (x);
}
void SimBuildingElementProxy::
C2Offset1 (const C2Offset1_optional& x)
{
this->C2Offset1_ = x;
}
const SimBuildingElementProxy::C2Offset2_optional& SimBuildingElementProxy::
C2Offset2 () const
{
return this->C2Offset2_;
}
SimBuildingElementProxy::C2Offset2_optional& SimBuildingElementProxy::
C2Offset2 ()
{
return this->C2Offset2_;
}
void SimBuildingElementProxy::
C2Offset2 (const C2Offset2_type& x)
{
this->C2Offset2_.set (x);
}
void SimBuildingElementProxy::
C2Offset2 (const C2Offset2_optional& x)
{
this->C2Offset2_ = x;
}
const SimBuildingElementProxy::C3Offset1_optional& SimBuildingElementProxy::
C3Offset1 () const
{
return this->C3Offset1_;
}
SimBuildingElementProxy::C3Offset1_optional& SimBuildingElementProxy::
C3Offset1 ()
{
return this->C3Offset1_;
}
void SimBuildingElementProxy::
C3Offset1 (const C3Offset1_type& x)
{
this->C3Offset1_.set (x);
}
void SimBuildingElementProxy::
C3Offset1 (const C3Offset1_optional& x)
{
this->C3Offset1_ = x;
}
const SimBuildingElementProxy::C4Offset2_optional& SimBuildingElementProxy::
C4Offset2 () const
{
return this->C4Offset2_;
}
SimBuildingElementProxy::C4Offset2_optional& SimBuildingElementProxy::
C4Offset2 ()
{
return this->C4Offset2_;
}
void SimBuildingElementProxy::
C4Offset2 (const C4Offset2_type& x)
{
this->C4Offset2_.set (x);
}
void SimBuildingElementProxy::
C4Offset2 (const C4Offset2_optional& x)
{
this->C4Offset2_ = x;
}
const SimBuildingElementProxy::C5Offset1_optional& SimBuildingElementProxy::
C5Offset1 () const
{
return this->C5Offset1_;
}
SimBuildingElementProxy::C5Offset1_optional& SimBuildingElementProxy::
C5Offset1 ()
{
return this->C5Offset1_;
}
void SimBuildingElementProxy::
C5Offset1 (const C5Offset1_type& x)
{
this->C5Offset1_.set (x);
}
void SimBuildingElementProxy::
C5Offset1 (const C5Offset1_optional& x)
{
this->C5Offset1_ = x;
}
const SimBuildingElementProxy::C5Offset2_optional& SimBuildingElementProxy::
C5Offset2 () const
{
return this->C5Offset2_;
}
SimBuildingElementProxy::C5Offset2_optional& SimBuildingElementProxy::
C5Offset2 ()
{
return this->C5Offset2_;
}
void SimBuildingElementProxy::
C5Offset2 (const C5Offset2_type& x)
{
this->C5Offset2_.set (x);
}
void SimBuildingElementProxy::
C5Offset2 (const C5Offset2_optional& x)
{
this->C5Offset2_ = x;
}
const SimBuildingElementProxy::C6Offset1_optional& SimBuildingElementProxy::
C6Offset1 () const
{
return this->C6Offset1_;
}
SimBuildingElementProxy::C6Offset1_optional& SimBuildingElementProxy::
C6Offset1 ()
{
return this->C6Offset1_;
}
void SimBuildingElementProxy::
C6Offset1 (const C6Offset1_type& x)
{
this->C6Offset1_.set (x);
}
void SimBuildingElementProxy::
C6Offset1 (const C6Offset1_optional& x)
{
this->C6Offset1_ = x;
}
const SimBuildingElementProxy::C6Offset2_optional& SimBuildingElementProxy::
C6Offset2 () const
{
return this->C6Offset2_;
}
SimBuildingElementProxy::C6Offset2_optional& SimBuildingElementProxy::
C6Offset2 ()
{
return this->C6Offset2_;
}
void SimBuildingElementProxy::
C6Offset2 (const C6Offset2_type& x)
{
this->C6Offset2_.set (x);
}
void SimBuildingElementProxy::
C6Offset2 (const C6Offset2_optional& x)
{
this->C6Offset2_ = x;
}
const SimBuildingElementProxy::ChilledWaterFlow_optional& SimBuildingElementProxy::
ChilledWaterFlow () const
{
return this->ChilledWaterFlow_;
}
SimBuildingElementProxy::ChilledWaterFlow_optional& SimBuildingElementProxy::
ChilledWaterFlow ()
{
return this->ChilledWaterFlow_;
}
void SimBuildingElementProxy::
ChilledWaterFlow (const ChilledWaterFlow_type& x)
{
this->ChilledWaterFlow_.set (x);
}
void SimBuildingElementProxy::
ChilledWaterFlow (const ChilledWaterFlow_optional& x)
{
this->ChilledWaterFlow_ = x;
}
const SimBuildingElementProxy::ChilledWaterPressureDrop_optional& SimBuildingElementProxy::
ChilledWaterPressureDrop () const
{
return this->ChilledWaterPressureDrop_;
}
SimBuildingElementProxy::ChilledWaterPressureDrop_optional& SimBuildingElementProxy::
ChilledWaterPressureDrop ()
{
return this->ChilledWaterPressureDrop_;
}
void SimBuildingElementProxy::
ChilledWaterPressureDrop (const ChilledWaterPressureDrop_type& x)
{
this->ChilledWaterPressureDrop_.set (x);
}
void SimBuildingElementProxy::
ChilledWaterPressureDrop (const ChilledWaterPressureDrop_optional& x)
{
this->ChilledWaterPressureDrop_ = x;
}
const SimBuildingElementProxy::CircuitNaming_optional& SimBuildingElementProxy::
CircuitNaming () const
{
return this->CircuitNaming_;
}
SimBuildingElementProxy::CircuitNaming_optional& SimBuildingElementProxy::
CircuitNaming ()
{
return this->CircuitNaming_;
}
void SimBuildingElementProxy::
CircuitNaming (const CircuitNaming_type& x)
{
this->CircuitNaming_.set (x);
}
void SimBuildingElementProxy::
CircuitNaming (const CircuitNaming_optional& x)
{
this->CircuitNaming_ = x;
}
void SimBuildingElementProxy::
CircuitNaming (::std::auto_ptr< CircuitNaming_type > x)
{
this->CircuitNaming_.set (x);
}
const SimBuildingElementProxy::Color_optional& SimBuildingElementProxy::
Color () const
{
return this->Color_;
}
SimBuildingElementProxy::Color_optional& SimBuildingElementProxy::
Color ()
{
return this->Color_;
}
void SimBuildingElementProxy::
Color (const Color_type& x)
{
this->Color_.set (x);
}
void SimBuildingElementProxy::
Color (const Color_optional& x)
{
this->Color_ = x;
}
void SimBuildingElementProxy::
Color (::std::auto_ptr< Color_type > x)
{
this->Color_.set (x);
}
const SimBuildingElementProxy::Connectionoffset_optional& SimBuildingElementProxy::
Connectionoffset () const
{
return this->Connectionoffset_;
}
SimBuildingElementProxy::Connectionoffset_optional& SimBuildingElementProxy::
Connectionoffset ()
{
return this->Connectionoffset_;
}
void SimBuildingElementProxy::
Connectionoffset (const Connectionoffset_type& x)
{
this->Connectionoffset_.set (x);
}
void SimBuildingElementProxy::
Connectionoffset (const Connectionoffset_optional& x)
{
this->Connectionoffset_ = x;
}
const SimBuildingElementProxy::ContainerName_optional& SimBuildingElementProxy::
ContainerName () const
{
return this->ContainerName_;
}
SimBuildingElementProxy::ContainerName_optional& SimBuildingElementProxy::
ContainerName ()
{
return this->ContainerName_;
}
void SimBuildingElementProxy::
ContainerName (const ContainerName_type& x)
{
this->ContainerName_.set (x);
}
void SimBuildingElementProxy::
ContainerName (const ContainerName_optional& x)
{
this->ContainerName_ = x;
}
void SimBuildingElementProxy::
ContainerName (::std::auto_ptr< ContainerName_type > x)
{
this->ContainerName_.set (x);
}
const SimBuildingElementProxy::ContainerType_optional& SimBuildingElementProxy::
ContainerType () const
{
return this->ContainerType_;
}
SimBuildingElementProxy::ContainerType_optional& SimBuildingElementProxy::
ContainerType ()
{
return this->ContainerType_;
}
void SimBuildingElementProxy::
ContainerType (const ContainerType_type& x)
{
this->ContainerType_.set (x);
}
void SimBuildingElementProxy::
ContainerType (const ContainerType_optional& x)
{
this->ContainerType_ = x;
}
void SimBuildingElementProxy::
ContainerType (::std::auto_ptr< ContainerType_type > x)
{
this->ContainerType_.set (x);
}
const SimBuildingElementProxy::CoolAirFlow_optional& SimBuildingElementProxy::
CoolAirFlow () const
{
return this->CoolAirFlow_;
}
SimBuildingElementProxy::CoolAirFlow_optional& SimBuildingElementProxy::
CoolAirFlow ()
{
return this->CoolAirFlow_;
}
void SimBuildingElementProxy::
CoolAirFlow (const CoolAirFlow_type& x)
{
this->CoolAirFlow_.set (x);
}
void SimBuildingElementProxy::
CoolAirFlow (const CoolAirFlow_optional& x)
{
this->CoolAirFlow_ = x;
}
const SimBuildingElementProxy::CoolAirInletDiameter_optional& SimBuildingElementProxy::
CoolAirInletDiameter () const
{
return this->CoolAirInletDiameter_;
}
SimBuildingElementProxy::CoolAirInletDiameter_optional& SimBuildingElementProxy::
CoolAirInletDiameter ()
{
return this->CoolAirInletDiameter_;
}
void SimBuildingElementProxy::
CoolAirInletDiameter (const CoolAirInletDiameter_type& x)
{
this->CoolAirInletDiameter_.set (x);
}
void SimBuildingElementProxy::
CoolAirInletDiameter (const CoolAirInletDiameter_optional& x)
{
this->CoolAirInletDiameter_ = x;
}
const SimBuildingElementProxy::CoolAirInletRadius_optional& SimBuildingElementProxy::
CoolAirInletRadius () const
{
return this->CoolAirInletRadius_;
}
SimBuildingElementProxy::CoolAirInletRadius_optional& SimBuildingElementProxy::
CoolAirInletRadius ()
{
return this->CoolAirInletRadius_;
}
void SimBuildingElementProxy::
CoolAirInletRadius (const CoolAirInletRadius_type& x)
{
this->CoolAirInletRadius_.set (x);
}
void SimBuildingElementProxy::
CoolAirInletRadius (const CoolAirInletRadius_optional& x)
{
this->CoolAirInletRadius_ = x;
}
const SimBuildingElementProxy::CoolAirPressureDrop_optional& SimBuildingElementProxy::
CoolAirPressureDrop () const
{
return this->CoolAirPressureDrop_;
}
SimBuildingElementProxy::CoolAirPressureDrop_optional& SimBuildingElementProxy::
CoolAirPressureDrop ()
{
return this->CoolAirPressureDrop_;
}
void SimBuildingElementProxy::
CoolAirPressureDrop (const CoolAirPressureDrop_type& x)
{
this->CoolAirPressureDrop_.set (x);
}
void SimBuildingElementProxy::
CoolAirPressureDrop (const CoolAirPressureDrop_optional& x)
{
this->CoolAirPressureDrop_ = x;
}
const SimBuildingElementProxy::CoolingCoilInletRadius_optional& SimBuildingElementProxy::
CoolingCoilInletRadius () const
{
return this->CoolingCoilInletRadius_;
}
SimBuildingElementProxy::CoolingCoilInletRadius_optional& SimBuildingElementProxy::
CoolingCoilInletRadius ()
{
return this->CoolingCoilInletRadius_;
}
void SimBuildingElementProxy::
CoolingCoilInletRadius (const CoolingCoilInletRadius_type& x)
{
this->CoolingCoilInletRadius_.set (x);
}
void SimBuildingElementProxy::
CoolingCoilInletRadius (const CoolingCoilInletRadius_optional& x)
{
this->CoolingCoilInletRadius_ = x;
}
const SimBuildingElementProxy::CoolingCoilOutletRadius_optional& SimBuildingElementProxy::
CoolingCoilOutletRadius () const
{
return this->CoolingCoilOutletRadius_;
}
SimBuildingElementProxy::CoolingCoilOutletRadius_optional& SimBuildingElementProxy::
CoolingCoilOutletRadius ()
{
return this->CoolingCoilOutletRadius_;
}
void SimBuildingElementProxy::
CoolingCoilOutletRadius (const CoolingCoilOutletRadius_type& x)
{
this->CoolingCoilOutletRadius_.set (x);
}
void SimBuildingElementProxy::
CoolingCoilOutletRadius (const CoolingCoilOutletRadius_optional& x)
{
this->CoolingCoilOutletRadius_ = x;
}
const SimBuildingElementProxy::CoolingWaterDiameter_optional& SimBuildingElementProxy::
CoolingWaterDiameter () const
{
return this->CoolingWaterDiameter_;
}
SimBuildingElementProxy::CoolingWaterDiameter_optional& SimBuildingElementProxy::
CoolingWaterDiameter ()
{
return this->CoolingWaterDiameter_;
}
void SimBuildingElementProxy::
CoolingWaterDiameter (const CoolingWaterDiameter_type& x)
{
this->CoolingWaterDiameter_.set (x);
}
void SimBuildingElementProxy::
CoolingWaterDiameter (const CoolingWaterDiameter_optional& x)
{
this->CoolingWaterDiameter_ = x;
}
const SimBuildingElementProxy::CoolingWaterFlow_optional& SimBuildingElementProxy::
CoolingWaterFlow () const
{
return this->CoolingWaterFlow_;
}
SimBuildingElementProxy::CoolingWaterFlow_optional& SimBuildingElementProxy::
CoolingWaterFlow ()
{
return this->CoolingWaterFlow_;
}
void SimBuildingElementProxy::
CoolingWaterFlow (const CoolingWaterFlow_type& x)
{
this->CoolingWaterFlow_.set (x);
}
void SimBuildingElementProxy::
CoolingWaterFlow (const CoolingWaterFlow_optional& x)
{
this->CoolingWaterFlow_ = x;
}
const SimBuildingElementProxy::CoolingWaterPressureDrop_optional& SimBuildingElementProxy::
CoolingWaterPressureDrop () const
{
return this->CoolingWaterPressureDrop_;
}
SimBuildingElementProxy::CoolingWaterPressureDrop_optional& SimBuildingElementProxy::
CoolingWaterPressureDrop ()
{
return this->CoolingWaterPressureDrop_;
}
void SimBuildingElementProxy::
CoolingWaterPressureDrop (const CoolingWaterPressureDrop_type& x)
{
this->CoolingWaterPressureDrop_.set (x);
}
void SimBuildingElementProxy::
CoolingWaterPressureDrop (const CoolingWaterPressureDrop_optional& x)
{
this->CoolingWaterPressureDrop_ = x;
}
const SimBuildingElementProxy::CoolingWaterRadius_optional& SimBuildingElementProxy::
CoolingWaterRadius () const
{
return this->CoolingWaterRadius_;
}
SimBuildingElementProxy::CoolingWaterRadius_optional& SimBuildingElementProxy::
CoolingWaterRadius ()
{
return this->CoolingWaterRadius_;
}
void SimBuildingElementProxy::
CoolingWaterRadius (const CoolingWaterRadius_type& x)
{
this->CoolingWaterRadius_.set (x);
}
void SimBuildingElementProxy::
CoolingWaterRadius (const CoolingWaterRadius_optional& x)
{
this->CoolingWaterRadius_ = x;
}
const SimBuildingElementProxy::Diameter1_optional& SimBuildingElementProxy::
Diameter1 () const
{
return this->Diameter1_;
}
SimBuildingElementProxy::Diameter1_optional& SimBuildingElementProxy::
Diameter1 ()
{
return this->Diameter1_;
}
void SimBuildingElementProxy::
Diameter1 (const Diameter1_type& x)
{
this->Diameter1_.set (x);
}
void SimBuildingElementProxy::
Diameter1 (const Diameter1_optional& x)
{
this->Diameter1_ = x;
}
const SimBuildingElementProxy::Distance_optional& SimBuildingElementProxy::
Distance () const
{
return this->Distance_;
}
SimBuildingElementProxy::Distance_optional& SimBuildingElementProxy::
Distance ()
{
return this->Distance_;
}
void SimBuildingElementProxy::
Distance (const Distance_type& x)
{
this->Distance_.set (x);
}
void SimBuildingElementProxy::
Distance (const Distance_optional& x)
{
this->Distance_ = x;
}
const SimBuildingElementProxy::Distance1_optional& SimBuildingElementProxy::
Distance1 () const
{
return this->Distance1_;
}
SimBuildingElementProxy::Distance1_optional& SimBuildingElementProxy::
Distance1 ()
{
return this->Distance1_;
}
void SimBuildingElementProxy::
Distance1 (const Distance1_type& x)
{
this->Distance1_.set (x);
}
void SimBuildingElementProxy::
Distance1 (const Distance1_optional& x)
{
this->Distance1_ = x;
}
const SimBuildingElementProxy::Distance2_optional& SimBuildingElementProxy::
Distance2 () const
{
return this->Distance2_;
}
SimBuildingElementProxy::Distance2_optional& SimBuildingElementProxy::
Distance2 ()
{
return this->Distance2_;
}
void SimBuildingElementProxy::
Distance2 (const Distance2_type& x)
{
this->Distance2_.set (x);
}
void SimBuildingElementProxy::
Distance2 (const Distance2_optional& x)
{
this->Distance2_ = x;
}
const SimBuildingElementProxy::DrainFlow_optional& SimBuildingElementProxy::
DrainFlow () const
{
return this->DrainFlow_;
}
SimBuildingElementProxy::DrainFlow_optional& SimBuildingElementProxy::
DrainFlow ()
{
return this->DrainFlow_;
}
void SimBuildingElementProxy::
DrainFlow (const DrainFlow_type& x)
{
this->DrainFlow_.set (x);
}
void SimBuildingElementProxy::
DrainFlow (const DrainFlow_optional& x)
{
this->DrainFlow_ = x;
}
const SimBuildingElementProxy::DrainOffset1_optional& SimBuildingElementProxy::
DrainOffset1 () const
{
return this->DrainOffset1_;
}
SimBuildingElementProxy::DrainOffset1_optional& SimBuildingElementProxy::
DrainOffset1 ()
{
return this->DrainOffset1_;
}
void SimBuildingElementProxy::
DrainOffset1 (const DrainOffset1_type& x)
{
this->DrainOffset1_.set (x);
}
void SimBuildingElementProxy::
DrainOffset1 (const DrainOffset1_optional& x)
{
this->DrainOffset1_ = x;
}
const SimBuildingElementProxy::DrainRadius_optional& SimBuildingElementProxy::
DrainRadius () const
{
return this->DrainRadius_;
}
SimBuildingElementProxy::DrainRadius_optional& SimBuildingElementProxy::
DrainRadius ()
{
return this->DrainRadius_;
}
void SimBuildingElementProxy::
DrainRadius (const DrainRadius_type& x)
{
this->DrainRadius_.set (x);
}
void SimBuildingElementProxy::
DrainRadius (const DrainRadius_optional& x)
{
this->DrainRadius_ = x;
}
const SimBuildingElementProxy::DuctHeight_optional& SimBuildingElementProxy::
DuctHeight () const
{
return this->DuctHeight_;
}
SimBuildingElementProxy::DuctHeight_optional& SimBuildingElementProxy::
DuctHeight ()
{
return this->DuctHeight_;
}
void SimBuildingElementProxy::
DuctHeight (const DuctHeight_type& x)
{
this->DuctHeight_.set (x);
}
void SimBuildingElementProxy::
DuctHeight (const DuctHeight_optional& x)
{
this->DuctHeight_ = x;
}
const SimBuildingElementProxy::DuctWidth_optional& SimBuildingElementProxy::
DuctWidth () const
{
return this->DuctWidth_;
}
SimBuildingElementProxy::DuctWidth_optional& SimBuildingElementProxy::
DuctWidth ()
{
return this->DuctWidth_;
}
void SimBuildingElementProxy::
DuctWidth (const DuctWidth_type& x)
{
this->DuctWidth_.set (x);
}
void SimBuildingElementProxy::
DuctWidth (const DuctWidth_optional& x)
{
this->DuctWidth_ = x;
}
const SimBuildingElementProxy::ElectricalCircuitName_optional& SimBuildingElementProxy::
ElectricalCircuitName () const
{
return this->ElectricalCircuitName_;
}
SimBuildingElementProxy::ElectricalCircuitName_optional& SimBuildingElementProxy::
ElectricalCircuitName ()
{
return this->ElectricalCircuitName_;
}
void SimBuildingElementProxy::
ElectricalCircuitName (const ElectricalCircuitName_type& x)
{
this->ElectricalCircuitName_.set (x);
}
void SimBuildingElementProxy::
ElectricalCircuitName (const ElectricalCircuitName_optional& x)
{
this->ElectricalCircuitName_ = x;
}
void SimBuildingElementProxy::
ElectricalCircuitName (::std::auto_ptr< ElectricalCircuitName_type > x)
{
this->ElectricalCircuitName_.set (x);
}
const SimBuildingElementProxy::ElectricalData_optional& SimBuildingElementProxy::
ElectricalData () const
{
return this->ElectricalData_;
}
SimBuildingElementProxy::ElectricalData_optional& SimBuildingElementProxy::
ElectricalData ()
{
return this->ElectricalData_;
}
void SimBuildingElementProxy::
ElectricalData (const ElectricalData_type& x)
{
this->ElectricalData_.set (x);
}
void SimBuildingElementProxy::
ElectricalData (const ElectricalData_optional& x)
{
this->ElectricalData_ = x;
}
void SimBuildingElementProxy::
ElectricalData (::std::auto_ptr< ElectricalData_type > x)
{
this->ElectricalData_.set (x);
}
const SimBuildingElementProxy::Enclosure_optional& SimBuildingElementProxy::
Enclosure () const
{
return this->Enclosure_;
}
SimBuildingElementProxy::Enclosure_optional& SimBuildingElementProxy::
Enclosure ()
{
return this->Enclosure_;
}
void SimBuildingElementProxy::
Enclosure (const Enclosure_type& x)
{
this->Enclosure_.set (x);
}
void SimBuildingElementProxy::
Enclosure (const Enclosure_optional& x)
{
this->Enclosure_ = x;
}
void SimBuildingElementProxy::
Enclosure (::std::auto_ptr< Enclosure_type > x)
{
this->Enclosure_.set (x);
}
const SimBuildingElementProxy::ExternalStaticPressure_optional& SimBuildingElementProxy::
ExternalStaticPressure () const
{
return this->ExternalStaticPressure_;
}
SimBuildingElementProxy::ExternalStaticPressure_optional& SimBuildingElementProxy::
ExternalStaticPressure ()
{
return this->ExternalStaticPressure_;
}
void SimBuildingElementProxy::
ExternalStaticPressure (const ExternalStaticPressure_type& x)
{
this->ExternalStaticPressure_.set (x);
}
void SimBuildingElementProxy::
ExternalStaticPressure (const ExternalStaticPressure_optional& x)
{
this->ExternalStaticPressure_ = x;
}
const SimBuildingElementProxy::ExternalTotalPressure_optional& SimBuildingElementProxy::
ExternalTotalPressure () const
{
return this->ExternalTotalPressure_;
}
SimBuildingElementProxy::ExternalTotalPressure_optional& SimBuildingElementProxy::
ExternalTotalPressure ()
{
return this->ExternalTotalPressure_;
}
void SimBuildingElementProxy::
ExternalTotalPressure (const ExternalTotalPressure_type& x)
{
this->ExternalTotalPressure_.set (x);
}
void SimBuildingElementProxy::
ExternalTotalPressure (const ExternalTotalPressure_optional& x)
{
this->ExternalTotalPressure_ = x;
}
const SimBuildingElementProxy::FanAirFlow_optional& SimBuildingElementProxy::
FanAirFlow () const
{
return this->FanAirFlow_;
}
SimBuildingElementProxy::FanAirFlow_optional& SimBuildingElementProxy::
FanAirFlow ()
{
return this->FanAirFlow_;
}
void SimBuildingElementProxy::
FanAirFlow (const FanAirFlow_type& x)
{
this->FanAirFlow_.set (x);
}
void SimBuildingElementProxy::
FanAirFlow (const FanAirFlow_optional& x)
{
this->FanAirFlow_ = x;
}
const SimBuildingElementProxy::FanDiameter_optional& SimBuildingElementProxy::
FanDiameter () const
{
return this->FanDiameter_;
}
SimBuildingElementProxy::FanDiameter_optional& SimBuildingElementProxy::
FanDiameter ()
{
return this->FanDiameter_;
}
void SimBuildingElementProxy::
FanDiameter (const FanDiameter_type& x)
{
this->FanDiameter_.set (x);
}
void SimBuildingElementProxy::
FanDiameter (const FanDiameter_optional& x)
{
this->FanDiameter_ = x;
}
const SimBuildingElementProxy::FanRadius_optional& SimBuildingElementProxy::
FanRadius () const
{
return this->FanRadius_;
}
SimBuildingElementProxy::FanRadius_optional& SimBuildingElementProxy::
FanRadius ()
{
return this->FanRadius_;
}
void SimBuildingElementProxy::
FanRadius (const FanRadius_type& x)
{
this->FanRadius_.set (x);
}
void SimBuildingElementProxy::
FanRadius (const FanRadius_optional& x)
{
this->FanRadius_ = x;
}
const SimBuildingElementProxy::GeneratorHeight_optional& SimBuildingElementProxy::
GeneratorHeight () const
{
return this->GeneratorHeight_;
}
SimBuildingElementProxy::GeneratorHeight_optional& SimBuildingElementProxy::
GeneratorHeight ()
{
return this->GeneratorHeight_;
}
void SimBuildingElementProxy::
GeneratorHeight (const GeneratorHeight_type& x)
{
this->GeneratorHeight_.set (x);
}
void SimBuildingElementProxy::
GeneratorHeight (const GeneratorHeight_optional& x)
{
this->GeneratorHeight_ = x;
}
const SimBuildingElementProxy::GeneratorLength_optional& SimBuildingElementProxy::
GeneratorLength () const
{
return this->GeneratorLength_;
}
SimBuildingElementProxy::GeneratorLength_optional& SimBuildingElementProxy::
GeneratorLength ()
{
return this->GeneratorLength_;
}
void SimBuildingElementProxy::
GeneratorLength (const GeneratorLength_type& x)
{
this->GeneratorLength_.set (x);
}
void SimBuildingElementProxy::
GeneratorLength (const GeneratorLength_optional& x)
{
this->GeneratorLength_ = x;
}
const SimBuildingElementProxy::GeneratorWidth_optional& SimBuildingElementProxy::
GeneratorWidth () const
{
return this->GeneratorWidth_;
}
SimBuildingElementProxy::GeneratorWidth_optional& SimBuildingElementProxy::
GeneratorWidth ()
{
return this->GeneratorWidth_;
}
void SimBuildingElementProxy::
GeneratorWidth (const GeneratorWidth_type& x)
{
this->GeneratorWidth_.set (x);
}
void SimBuildingElementProxy::
GeneratorWidth (const GeneratorWidth_optional& x)
{
this->GeneratorWidth_ = x;
}
const SimBuildingElementProxy::GroupName_optional& SimBuildingElementProxy::
GroupName () const
{
return this->GroupName_;
}
SimBuildingElementProxy::GroupName_optional& SimBuildingElementProxy::
GroupName ()
{
return this->GroupName_;
}
void SimBuildingElementProxy::
GroupName (const GroupName_type& x)
{
this->GroupName_.set (x);
}
void SimBuildingElementProxy::
GroupName (const GroupName_optional& x)
{
this->GroupName_ = x;
}
void SimBuildingElementProxy::
GroupName (::std::auto_ptr< GroupName_type > x)
{
this->GroupName_.set (x);
}
const SimBuildingElementProxy::HalfAirOutletHeight_optional& SimBuildingElementProxy::
HalfAirOutletHeight () const
{
return this->HalfAirOutletHeight_;
}
SimBuildingElementProxy::HalfAirOutletHeight_optional& SimBuildingElementProxy::
HalfAirOutletHeight ()
{
return this->HalfAirOutletHeight_;
}
void SimBuildingElementProxy::
HalfAirOutletHeight (const HalfAirOutletHeight_type& x)
{
this->HalfAirOutletHeight_.set (x);
}
void SimBuildingElementProxy::
HalfAirOutletHeight (const HalfAirOutletHeight_optional& x)
{
this->HalfAirOutletHeight_ = x;
}
const SimBuildingElementProxy::HalfAirOutletWidth_optional& SimBuildingElementProxy::
HalfAirOutletWidth () const
{
return this->HalfAirOutletWidth_;
}
SimBuildingElementProxy::HalfAirOutletWidth_optional& SimBuildingElementProxy::
HalfAirOutletWidth ()
{
return this->HalfAirOutletWidth_;
}
void SimBuildingElementProxy::
HalfAirOutletWidth (const HalfAirOutletWidth_type& x)
{
this->HalfAirOutletWidth_.set (x);
}
void SimBuildingElementProxy::
HalfAirOutletWidth (const HalfAirOutletWidth_optional& x)
{
this->HalfAirOutletWidth_ = x;
}
const SimBuildingElementProxy::HalfOverallHeight_optional& SimBuildingElementProxy::
HalfOverallHeight () const
{
return this->HalfOverallHeight_;
}
SimBuildingElementProxy::HalfOverallHeight_optional& SimBuildingElementProxy::
HalfOverallHeight ()
{
return this->HalfOverallHeight_;
}
void SimBuildingElementProxy::
HalfOverallHeight (const HalfOverallHeight_type& x)
{
this->HalfOverallHeight_.set (x);
}
void SimBuildingElementProxy::
HalfOverallHeight (const HalfOverallHeight_optional& x)
{
this->HalfOverallHeight_ = x;
}
const SimBuildingElementProxy::HalfOverallWidth_optional& SimBuildingElementProxy::
HalfOverallWidth () const
{
return this->HalfOverallWidth_;
}
SimBuildingElementProxy::HalfOverallWidth_optional& SimBuildingElementProxy::
HalfOverallWidth ()
{
return this->HalfOverallWidth_;
}
void SimBuildingElementProxy::
HalfOverallWidth (const HalfOverallWidth_type& x)
{
this->HalfOverallWidth_.set (x);
}
void SimBuildingElementProxy::
HalfOverallWidth (const HalfOverallWidth_optional& x)
{
this->HalfOverallWidth_ = x;
}
const SimBuildingElementProxy::HalfWidth4_optional& SimBuildingElementProxy::
HalfWidth4 () const
{
return this->HalfWidth4_;
}
SimBuildingElementProxy::HalfWidth4_optional& SimBuildingElementProxy::
HalfWidth4 ()
{
return this->HalfWidth4_;
}
void SimBuildingElementProxy::
HalfWidth4 (const HalfWidth4_type& x)
{
this->HalfWidth4_.set (x);
}
void SimBuildingElementProxy::
HalfWidth4 (const HalfWidth4_optional& x)
{
this->HalfWidth4_ = x;
}
const SimBuildingElementProxy::HeatAirFlow_optional& SimBuildingElementProxy::
HeatAirFlow () const
{
return this->HeatAirFlow_;
}
SimBuildingElementProxy::HeatAirFlow_optional& SimBuildingElementProxy::
HeatAirFlow ()
{
return this->HeatAirFlow_;
}
void SimBuildingElementProxy::
HeatAirFlow (const HeatAirFlow_type& x)
{
this->HeatAirFlow_.set (x);
}
void SimBuildingElementProxy::
HeatAirFlow (const HeatAirFlow_optional& x)
{
this->HeatAirFlow_ = x;
}
const SimBuildingElementProxy::HeatAirInletDiameter_optional& SimBuildingElementProxy::
HeatAirInletDiameter () const
{
return this->HeatAirInletDiameter_;
}
SimBuildingElementProxy::HeatAirInletDiameter_optional& SimBuildingElementProxy::
HeatAirInletDiameter ()
{
return this->HeatAirInletDiameter_;
}
void SimBuildingElementProxy::
HeatAirInletDiameter (const HeatAirInletDiameter_type& x)
{
this->HeatAirInletDiameter_.set (x);
}
void SimBuildingElementProxy::
HeatAirInletDiameter (const HeatAirInletDiameter_optional& x)
{
this->HeatAirInletDiameter_ = x;
}
const SimBuildingElementProxy::HeatAirInletRadius_optional& SimBuildingElementProxy::
HeatAirInletRadius () const
{
return this->HeatAirInletRadius_;
}
SimBuildingElementProxy::HeatAirInletRadius_optional& SimBuildingElementProxy::
HeatAirInletRadius ()
{
return this->HeatAirInletRadius_;
}
void SimBuildingElementProxy::
HeatAirInletRadius (const HeatAirInletRadius_type& x)
{
this->HeatAirInletRadius_.set (x);
}
void SimBuildingElementProxy::
HeatAirInletRadius (const HeatAirInletRadius_optional& x)
{
this->HeatAirInletRadius_ = x;
}
const SimBuildingElementProxy::HeatAirPressureDrop_optional& SimBuildingElementProxy::
HeatAirPressureDrop () const
{
return this->HeatAirPressureDrop_;
}
SimBuildingElementProxy::HeatAirPressureDrop_optional& SimBuildingElementProxy::
HeatAirPressureDrop ()
{
return this->HeatAirPressureDrop_;
}
void SimBuildingElementProxy::
HeatAirPressureDrop (const HeatAirPressureDrop_type& x)
{
this->HeatAirPressureDrop_.set (x);
}
void SimBuildingElementProxy::
HeatAirPressureDrop (const HeatAirPressureDrop_optional& x)
{
this->HeatAirPressureDrop_ = x;
}
const SimBuildingElementProxy::HeatLoss_optional& SimBuildingElementProxy::
HeatLoss () const
{
return this->HeatLoss_;
}
SimBuildingElementProxy::HeatLoss_optional& SimBuildingElementProxy::
HeatLoss ()
{
return this->HeatLoss_;
}
void SimBuildingElementProxy::
HeatLoss (const HeatLoss_type& x)
{
this->HeatLoss_.set (x);
}
void SimBuildingElementProxy::
HeatLoss (const HeatLoss_optional& x)
{
this->HeatLoss_ = x;
}
const SimBuildingElementProxy::HeatingCoilInletRadius_optional& SimBuildingElementProxy::
HeatingCoilInletRadius () const
{
return this->HeatingCoilInletRadius_;
}
SimBuildingElementProxy::HeatingCoilInletRadius_optional& SimBuildingElementProxy::
HeatingCoilInletRadius ()
{
return this->HeatingCoilInletRadius_;
}
void SimBuildingElementProxy::
HeatingCoilInletRadius (const HeatingCoilInletRadius_type& x)
{
this->HeatingCoilInletRadius_.set (x);
}
void SimBuildingElementProxy::
HeatingCoilInletRadius (const HeatingCoilInletRadius_optional& x)
{
this->HeatingCoilInletRadius_ = x;
}
const SimBuildingElementProxy::HeatingCoilOutletRadius_optional& SimBuildingElementProxy::
HeatingCoilOutletRadius () const
{
return this->HeatingCoilOutletRadius_;
}
SimBuildingElementProxy::HeatingCoilOutletRadius_optional& SimBuildingElementProxy::
HeatingCoilOutletRadius ()
{
return this->HeatingCoilOutletRadius_;
}
void SimBuildingElementProxy::
HeatingCoilOutletRadius (const HeatingCoilOutletRadius_type& x)
{
this->HeatingCoilOutletRadius_.set (x);
}
void SimBuildingElementProxy::
HeatingCoilOutletRadius (const HeatingCoilOutletRadius_optional& x)
{
this->HeatingCoilOutletRadius_ = x;
}
const SimBuildingElementProxy::Height1_optional& SimBuildingElementProxy::
Height1 () const
{
return this->Height1_;
}
SimBuildingElementProxy::Height1_optional& SimBuildingElementProxy::
Height1 ()
{
return this->Height1_;
}
void SimBuildingElementProxy::
Height1 (const Height1_type& x)
{
this->Height1_.set (x);
}
void SimBuildingElementProxy::
Height1 (const Height1_optional& x)
{
this->Height1_ = x;
}
const SimBuildingElementProxy::Height2_optional& SimBuildingElementProxy::
Height2 () const
{
return this->Height2_;
}
SimBuildingElementProxy::Height2_optional& SimBuildingElementProxy::
Height2 ()
{
return this->Height2_;
}
void SimBuildingElementProxy::
Height2 (const Height2_type& x)
{
this->Height2_.set (x);
}
void SimBuildingElementProxy::
Height2 (const Height2_optional& x)
{
this->Height2_ = x;
}
const SimBuildingElementProxy::Height3_optional& SimBuildingElementProxy::
Height3 () const
{
return this->Height3_;
}
SimBuildingElementProxy::Height3_optional& SimBuildingElementProxy::
Height3 ()
{
return this->Height3_;
}
void SimBuildingElementProxy::
Height3 (const Height3_type& x)
{
this->Height3_.set (x);
}
void SimBuildingElementProxy::
Height3 (const Height3_optional& x)
{
this->Height3_ = x;
}
const SimBuildingElementProxy::Height4_optional& SimBuildingElementProxy::
Height4 () const
{
return this->Height4_;
}
SimBuildingElementProxy::Height4_optional& SimBuildingElementProxy::
Height4 ()
{
return this->Height4_;
}
void SimBuildingElementProxy::
Height4 (const Height4_type& x)
{
this->Height4_.set (x);
}
void SimBuildingElementProxy::
Height4 (const Height4_optional& x)
{
this->Height4_ = x;
}
const SimBuildingElementProxy::Height5_optional& SimBuildingElementProxy::
Height5 () const
{
return this->Height5_;
}
SimBuildingElementProxy::Height5_optional& SimBuildingElementProxy::
Height5 ()
{
return this->Height5_;
}
void SimBuildingElementProxy::
Height5 (const Height5_type& x)
{
this->Height5_.set (x);
}
void SimBuildingElementProxy::
Height5 (const Height5_optional& x)
{
this->Height5_ = x;
}
const SimBuildingElementProxy::Height6_optional& SimBuildingElementProxy::
Height6 () const
{
return this->Height6_;
}
SimBuildingElementProxy::Height6_optional& SimBuildingElementProxy::
Height6 ()
{
return this->Height6_;
}
void SimBuildingElementProxy::
Height6 (const Height6_type& x)
{
this->Height6_.set (x);
}
void SimBuildingElementProxy::
Height6 (const Height6_optional& x)
{
this->Height6_ = x;
}
const SimBuildingElementProxy::Height7_optional& SimBuildingElementProxy::
Height7 () const
{
return this->Height7_;
}
SimBuildingElementProxy::Height7_optional& SimBuildingElementProxy::
Height7 ()
{
return this->Height7_;
}
void SimBuildingElementProxy::
Height7 (const Height7_type& x)
{
this->Height7_.set (x);
}
void SimBuildingElementProxy::
Height7 (const Height7_optional& x)
{
this->Height7_ = x;
}
const SimBuildingElementProxy::Height8_optional& SimBuildingElementProxy::
Height8 () const
{
return this->Height8_;
}
SimBuildingElementProxy::Height8_optional& SimBuildingElementProxy::
Height8 ()
{
return this->Height8_;
}
void SimBuildingElementProxy::
Height8 (const Height8_type& x)
{
this->Height8_.set (x);
}
void SimBuildingElementProxy::
Height8 (const Height8_optional& x)
{
this->Height8_ = x;
}
const SimBuildingElementProxy::Height9_optional& SimBuildingElementProxy::
Height9 () const
{
return this->Height9_;
}
SimBuildingElementProxy::Height9_optional& SimBuildingElementProxy::
Height9 ()
{
return this->Height9_;
}
void SimBuildingElementProxy::
Height9 (const Height9_type& x)
{
this->Height9_.set (x);
}
void SimBuildingElementProxy::
Height9 (const Height9_optional& x)
{
this->Height9_ = x;
}
const SimBuildingElementProxy::Host_optional& SimBuildingElementProxy::
Host () const
{
return this->Host_;
}
SimBuildingElementProxy::Host_optional& SimBuildingElementProxy::
Host ()
{
return this->Host_;
}
void SimBuildingElementProxy::
Host (const Host_type& x)
{
this->Host_.set (x);
}
void SimBuildingElementProxy::
Host (const Host_optional& x)
{
this->Host_ = x;
}
void SimBuildingElementProxy::
Host (::std::auto_ptr< Host_type > x)
{
this->Host_.set (x);
}
const SimBuildingElementProxy::HotWaterFlow_optional& SimBuildingElementProxy::
HotWaterFlow () const
{
return this->HotWaterFlow_;
}
SimBuildingElementProxy::HotWaterFlow_optional& SimBuildingElementProxy::
HotWaterFlow ()
{
return this->HotWaterFlow_;
}
void SimBuildingElementProxy::
HotWaterFlow (const HotWaterFlow_type& x)
{
this->HotWaterFlow_.set (x);
}
void SimBuildingElementProxy::
HotWaterFlow (const HotWaterFlow_optional& x)
{
this->HotWaterFlow_ = x;
}
const SimBuildingElementProxy::HotWaterPressureDrop_optional& SimBuildingElementProxy::
HotWaterPressureDrop () const
{
return this->HotWaterPressureDrop_;
}
SimBuildingElementProxy::HotWaterPressureDrop_optional& SimBuildingElementProxy::
HotWaterPressureDrop ()
{
return this->HotWaterPressureDrop_;
}
void SimBuildingElementProxy::
HotWaterPressureDrop (const HotWaterPressureDrop_type& x)
{
this->HotWaterPressureDrop_.set (x);
}
void SimBuildingElementProxy::
HotWaterPressureDrop (const HotWaterPressureDrop_optional& x)
{
this->HotWaterPressureDrop_ = x;
}
const SimBuildingElementProxy::Inclination_optional& SimBuildingElementProxy::
Inclination () const
{
return this->Inclination_;
}
SimBuildingElementProxy::Inclination_optional& SimBuildingElementProxy::
Inclination ()
{
return this->Inclination_;
}
void SimBuildingElementProxy::
Inclination (const Inclination_type& x)
{
this->Inclination_.set (x);
}
void SimBuildingElementProxy::
Inclination (const Inclination_optional& x)
{
this->Inclination_ = x;
}
const SimBuildingElementProxy::InletDiameter_optional& SimBuildingElementProxy::
InletDiameter () const
{
return this->InletDiameter_;
}
SimBuildingElementProxy::InletDiameter_optional& SimBuildingElementProxy::
InletDiameter ()
{
return this->InletDiameter_;
}
void SimBuildingElementProxy::
InletDiameter (const InletDiameter_type& x)
{
this->InletDiameter_.set (x);
}
void SimBuildingElementProxy::
InletDiameter (const InletDiameter_optional& x)
{
this->InletDiameter_ = x;
}
const SimBuildingElementProxy::InletRadius_optional& SimBuildingElementProxy::
InletRadius () const
{
return this->InletRadius_;
}
SimBuildingElementProxy::InletRadius_optional& SimBuildingElementProxy::
InletRadius ()
{
return this->InletRadius_;
}
void SimBuildingElementProxy::
InletRadius (const InletRadius_type& x)
{
this->InletRadius_.set (x);
}
void SimBuildingElementProxy::
InletRadius (const InletRadius_optional& x)
{
this->InletRadius_ = x;
}
const SimBuildingElementProxy::Length1_optional& SimBuildingElementProxy::
Length1 () const
{
return this->Length1_;
}
SimBuildingElementProxy::Length1_optional& SimBuildingElementProxy::
Length1 ()
{
return this->Length1_;
}
void SimBuildingElementProxy::
Length1 (const Length1_type& x)
{
this->Length1_.set (x);
}
void SimBuildingElementProxy::
Length1 (const Length1_optional& x)
{
this->Length1_ = x;
}
const SimBuildingElementProxy::Length2_optional& SimBuildingElementProxy::
Length2 () const
{
return this->Length2_;
}
SimBuildingElementProxy::Length2_optional& SimBuildingElementProxy::
Length2 ()
{
return this->Length2_;
}
void SimBuildingElementProxy::
Length2 (const Length2_type& x)
{
this->Length2_.set (x);
}
void SimBuildingElementProxy::
Length2 (const Length2_optional& x)
{
this->Length2_ = x;
}
const SimBuildingElementProxy::Length3_optional& SimBuildingElementProxy::
Length3 () const
{
return this->Length3_;
}
SimBuildingElementProxy::Length3_optional& SimBuildingElementProxy::
Length3 ()
{
return this->Length3_;
}
void SimBuildingElementProxy::
Length3 (const Length3_type& x)
{
this->Length3_.set (x);
}
void SimBuildingElementProxy::
Length3 (const Length3_optional& x)
{
this->Length3_ = x;
}
const SimBuildingElementProxy::Length4_optional& SimBuildingElementProxy::
Length4 () const
{
return this->Length4_;
}
SimBuildingElementProxy::Length4_optional& SimBuildingElementProxy::
Length4 ()
{
return this->Length4_;
}
void SimBuildingElementProxy::
Length4 (const Length4_type& x)
{
this->Length4_.set (x);
}
void SimBuildingElementProxy::
Length4 (const Length4_optional& x)
{
this->Length4_ = x;
}
const SimBuildingElementProxy::Length5_optional& SimBuildingElementProxy::
Length5 () const
{
return this->Length5_;
}
SimBuildingElementProxy::Length5_optional& SimBuildingElementProxy::
Length5 ()
{
return this->Length5_;
}
void SimBuildingElementProxy::
Length5 (const Length5_type& x)
{
this->Length5_.set (x);
}
void SimBuildingElementProxy::
Length5 (const Length5_optional& x)
{
this->Length5_ = x;
}
const SimBuildingElementProxy::Length6_optional& SimBuildingElementProxy::
Length6 () const
{
return this->Length6_;
}
SimBuildingElementProxy::Length6_optional& SimBuildingElementProxy::
Length6 ()
{
return this->Length6_;
}
void SimBuildingElementProxy::
Length6 (const Length6_type& x)
{
this->Length6_.set (x);
}
void SimBuildingElementProxy::
Length6 (const Length6_optional& x)
{
this->Length6_ = x;
}
const SimBuildingElementProxy::Length7_optional& SimBuildingElementProxy::
Length7 () const
{
return this->Length7_;
}
SimBuildingElementProxy::Length7_optional& SimBuildingElementProxy::
Length7 ()
{
return this->Length7_;
}
void SimBuildingElementProxy::
Length7 (const Length7_type& x)
{
this->Length7_.set (x);
}
void SimBuildingElementProxy::
Length7 (const Length7_optional& x)
{
this->Length7_ = x;
}
const SimBuildingElementProxy::Length8_optional& SimBuildingElementProxy::
Length8 () const
{
return this->Length8_;
}
SimBuildingElementProxy::Length8_optional& SimBuildingElementProxy::
Length8 ()
{
return this->Length8_;
}
void SimBuildingElementProxy::
Length8 (const Length8_type& x)
{
this->Length8_.set (x);
}
void SimBuildingElementProxy::
Length8 (const Length8_optional& x)
{
this->Length8_ = x;
}
const SimBuildingElementProxy::Length9_optional& SimBuildingElementProxy::
Length9 () const
{
return this->Length9_;
}
SimBuildingElementProxy::Length9_optional& SimBuildingElementProxy::
Length9 ()
{
return this->Length9_;
}
void SimBuildingElementProxy::
Length9 (const Length9_type& x)
{
this->Length9_.set (x);
}
void SimBuildingElementProxy::
Length9 (const Length9_optional& x)
{
this->Length9_ = x;
}
const SimBuildingElementProxy::Length10_optional& SimBuildingElementProxy::
Length10 () const
{
return this->Length10_;
}
SimBuildingElementProxy::Length10_optional& SimBuildingElementProxy::
Length10 ()
{
return this->Length10_;
}
void SimBuildingElementProxy::
Length10 (const Length10_type& x)
{
this->Length10_.set (x);
}
void SimBuildingElementProxy::
Length10 (const Length10_optional& x)
{
this->Length10_ = x;
}
const SimBuildingElementProxy::Length11_optional& SimBuildingElementProxy::
Length11 () const
{
return this->Length11_;
}
SimBuildingElementProxy::Length11_optional& SimBuildingElementProxy::
Length11 ()
{
return this->Length11_;
}
void SimBuildingElementProxy::
Length11 (const Length11_type& x)
{
this->Length11_.set (x);
}
void SimBuildingElementProxy::
Length11 (const Length11_optional& x)
{
this->Length11_ = x;
}
const SimBuildingElementProxy::Length12_optional& SimBuildingElementProxy::
Length12 () const
{
return this->Length12_;
}
SimBuildingElementProxy::Length12_optional& SimBuildingElementProxy::
Length12 ()
{
return this->Length12_;
}
void SimBuildingElementProxy::
Length12 (const Length12_type& x)
{
this->Length12_.set (x);
}
void SimBuildingElementProxy::
Length12 (const Length12_optional& x)
{
this->Length12_ = x;
}
const SimBuildingElementProxy::Length13_optional& SimBuildingElementProxy::
Length13 () const
{
return this->Length13_;
}
SimBuildingElementProxy::Length13_optional& SimBuildingElementProxy::
Length13 ()
{
return this->Length13_;
}
void SimBuildingElementProxy::
Length13 (const Length13_type& x)
{
this->Length13_.set (x);
}
void SimBuildingElementProxy::
Length13 (const Length13_optional& x)
{
this->Length13_ = x;
}
const SimBuildingElementProxy::Level_optional& SimBuildingElementProxy::
Level () const
{
return this->Level_;
}
SimBuildingElementProxy::Level_optional& SimBuildingElementProxy::
Level ()
{
return this->Level_;
}
void SimBuildingElementProxy::
Level (const Level_type& x)
{
this->Level_.set (x);
}
void SimBuildingElementProxy::
Level (const Level_optional& x)
{
this->Level_ = x;
}
void SimBuildingElementProxy::
Level (::std::auto_ptr< Level_type > x)
{
this->Level_.set (x);
}
const SimBuildingElementProxy::LoadClassification_optional& SimBuildingElementProxy::
LoadClassification () const
{
return this->LoadClassification_;
}
SimBuildingElementProxy::LoadClassification_optional& SimBuildingElementProxy::
LoadClassification ()
{
return this->LoadClassification_;
}
void SimBuildingElementProxy::
LoadClassification (const LoadClassification_type& x)
{
this->LoadClassification_.set (x);
}
void SimBuildingElementProxy::
LoadClassification (const LoadClassification_optional& x)
{
this->LoadClassification_ = x;
}
void SimBuildingElementProxy::
LoadClassification (::std::auto_ptr< LoadClassification_type > x)
{
this->LoadClassification_.set (x);
}
const SimBuildingElementProxy::MakeUpWaterFlow_optional& SimBuildingElementProxy::
MakeUpWaterFlow () const
{
return this->MakeUpWaterFlow_;
}
SimBuildingElementProxy::MakeUpWaterFlow_optional& SimBuildingElementProxy::
MakeUpWaterFlow ()
{
return this->MakeUpWaterFlow_;
}
void SimBuildingElementProxy::
MakeUpWaterFlow (const MakeUpWaterFlow_type& x)
{
this->MakeUpWaterFlow_.set (x);
}
void SimBuildingElementProxy::
MakeUpWaterFlow (const MakeUpWaterFlow_optional& x)
{
this->MakeUpWaterFlow_ = x;
}
const SimBuildingElementProxy::MakeUpWaterPressureDrop_optional& SimBuildingElementProxy::
MakeUpWaterPressureDrop () const
{
return this->MakeUpWaterPressureDrop_;
}
SimBuildingElementProxy::MakeUpWaterPressureDrop_optional& SimBuildingElementProxy::
MakeUpWaterPressureDrop ()
{
return this->MakeUpWaterPressureDrop_;
}
void SimBuildingElementProxy::
MakeUpWaterPressureDrop (const MakeUpWaterPressureDrop_type& x)
{
this->MakeUpWaterPressureDrop_.set (x);
}
void SimBuildingElementProxy::
MakeUpWaterPressureDrop (const MakeUpWaterPressureDrop_optional& x)
{
this->MakeUpWaterPressureDrop_ = x;
}
const SimBuildingElementProxy::MakeUpWaterRadius_optional& SimBuildingElementProxy::
MakeUpWaterRadius () const
{
return this->MakeUpWaterRadius_;
}
SimBuildingElementProxy::MakeUpWaterRadius_optional& SimBuildingElementProxy::
MakeUpWaterRadius ()
{
return this->MakeUpWaterRadius_;
}
void SimBuildingElementProxy::
MakeUpWaterRadius (const MakeUpWaterRadius_type& x)
{
this->MakeUpWaterRadius_.set (x);
}
void SimBuildingElementProxy::
MakeUpWaterRadius (const MakeUpWaterRadius_optional& x)
{
this->MakeUpWaterRadius_ = x;
}
const SimBuildingElementProxy::ManufacturerArticleNumber_optional& SimBuildingElementProxy::
ManufacturerArticleNumber () const
{
return this->ManufacturerArticleNumber_;
}
SimBuildingElementProxy::ManufacturerArticleNumber_optional& SimBuildingElementProxy::
ManufacturerArticleNumber ()
{
return this->ManufacturerArticleNumber_;
}
void SimBuildingElementProxy::
ManufacturerArticleNumber (const ManufacturerArticleNumber_type& x)
{
this->ManufacturerArticleNumber_.set (x);
}
void SimBuildingElementProxy::
ManufacturerArticleNumber (const ManufacturerArticleNumber_optional& x)
{
this->ManufacturerArticleNumber_ = x;
}
void SimBuildingElementProxy::
ManufacturerArticleNumber (::std::auto_ptr< ManufacturerArticleNumber_type > x)
{
this->ManufacturerArticleNumber_.set (x);
}
const SimBuildingElementProxy::ManufacturerModelName_optional& SimBuildingElementProxy::
ManufacturerModelName () const
{
return this->ManufacturerModelName_;
}
SimBuildingElementProxy::ManufacturerModelName_optional& SimBuildingElementProxy::
ManufacturerModelName ()
{
return this->ManufacturerModelName_;
}
void SimBuildingElementProxy::
ManufacturerModelName (const ManufacturerModelName_type& x)
{
this->ManufacturerModelName_.set (x);
}
void SimBuildingElementProxy::
ManufacturerModelName (const ManufacturerModelName_optional& x)
{
this->ManufacturerModelName_ = x;
}
void SimBuildingElementProxy::
ManufacturerModelName (::std::auto_ptr< ManufacturerModelName_type > x)
{
this->ManufacturerModelName_.set (x);
}
const SimBuildingElementProxy::ManufacturerModelNumber_optional& SimBuildingElementProxy::
ManufacturerModelNumber () const
{
return this->ManufacturerModelNumber_;
}
SimBuildingElementProxy::ManufacturerModelNumber_optional& SimBuildingElementProxy::
ManufacturerModelNumber ()
{
return this->ManufacturerModelNumber_;
}
void SimBuildingElementProxy::
ManufacturerModelNumber (const ManufacturerModelNumber_type& x)
{
this->ManufacturerModelNumber_.set (x);
}
void SimBuildingElementProxy::
ManufacturerModelNumber (const ManufacturerModelNumber_optional& x)
{
this->ManufacturerModelNumber_ = x;
}
void SimBuildingElementProxy::
ManufacturerModelNumber (::std::auto_ptr< ManufacturerModelNumber_type > x)
{
this->ManufacturerModelNumber_.set (x);
}
const SimBuildingElementProxy::ManufacturerName_optional& SimBuildingElementProxy::
ManufacturerName () const
{
return this->ManufacturerName_;
}
SimBuildingElementProxy::ManufacturerName_optional& SimBuildingElementProxy::
ManufacturerName ()
{
return this->ManufacturerName_;
}
void SimBuildingElementProxy::
ManufacturerName (const ManufacturerName_type& x)
{
this->ManufacturerName_.set (x);
}
void SimBuildingElementProxy::
ManufacturerName (const ManufacturerName_optional& x)
{
this->ManufacturerName_ = x;
}
void SimBuildingElementProxy::
ManufacturerName (::std::auto_ptr< ManufacturerName_type > x)
{
this->ManufacturerName_.set (x);
}
const SimBuildingElementProxy::ManufacturerYearofProduction_optional& SimBuildingElementProxy::
ManufacturerYearofProduction () const
{
return this->ManufacturerYearofProduction_;
}
SimBuildingElementProxy::ManufacturerYearofProduction_optional& SimBuildingElementProxy::
ManufacturerYearofProduction ()
{
return this->ManufacturerYearofProduction_;
}
void SimBuildingElementProxy::
ManufacturerYearofProduction (const ManufacturerYearofProduction_type& x)
{
this->ManufacturerYearofProduction_.set (x);
}
void SimBuildingElementProxy::
ManufacturerYearofProduction (const ManufacturerYearofProduction_optional& x)
{
this->ManufacturerYearofProduction_ = x;
}
void SimBuildingElementProxy::
ManufacturerYearofProduction (::std::auto_ptr< ManufacturerYearofProduction_type > x)
{
this->ManufacturerYearofProduction_.set (x);
}
const SimBuildingElementProxy::Mark_optional& SimBuildingElementProxy::
Mark () const
{
return this->Mark_;
}
SimBuildingElementProxy::Mark_optional& SimBuildingElementProxy::
Mark ()
{
return this->Mark_;
}
void SimBuildingElementProxy::
Mark (const Mark_type& x)
{
this->Mark_.set (x);
}
void SimBuildingElementProxy::
Mark (const Mark_optional& x)
{
this->Mark_ = x;
}
void SimBuildingElementProxy::
Mark (::std::auto_ptr< Mark_type > x)
{
this->Mark_.set (x);
}
const SimBuildingElementProxy::Material_optional& SimBuildingElementProxy::
Material () const
{
return this->Material_;
}
SimBuildingElementProxy::Material_optional& SimBuildingElementProxy::
Material ()
{
return this->Material_;
}
void SimBuildingElementProxy::
Material (const Material_type& x)
{
this->Material_.set (x);
}
void SimBuildingElementProxy::
Material (const Material_optional& x)
{
this->Material_ = x;
}
void SimBuildingElementProxy::
Material (::std::auto_ptr< Material_type > x)
{
this->Material_.set (x);
}
const SimBuildingElementProxy::Max1PoleBreakers_optional& SimBuildingElementProxy::
Max1PoleBreakers () const
{
return this->Max1PoleBreakers_;
}
SimBuildingElementProxy::Max1PoleBreakers_optional& SimBuildingElementProxy::
Max1PoleBreakers ()
{
return this->Max1PoleBreakers_;
}
void SimBuildingElementProxy::
Max1PoleBreakers (const Max1PoleBreakers_type& x)
{
this->Max1PoleBreakers_.set (x);
}
void SimBuildingElementProxy::
Max1PoleBreakers (const Max1PoleBreakers_optional& x)
{
this->Max1PoleBreakers_ = x;
}
const SimBuildingElementProxy::MaxFlow_optional& SimBuildingElementProxy::
MaxFlow () const
{
return this->MaxFlow_;
}
SimBuildingElementProxy::MaxFlow_optional& SimBuildingElementProxy::
MaxFlow ()
{
return this->MaxFlow_;
}
void SimBuildingElementProxy::
MaxFlow (const MaxFlow_type& x)
{
this->MaxFlow_.set (x);
}
void SimBuildingElementProxy::
MaxFlow (const MaxFlow_optional& x)
{
this->MaxFlow_ = x;
}
const SimBuildingElementProxy::MinFlow_optional& SimBuildingElementProxy::
MinFlow () const
{
return this->MinFlow_;
}
SimBuildingElementProxy::MinFlow_optional& SimBuildingElementProxy::
MinFlow ()
{
return this->MinFlow_;
}
void SimBuildingElementProxy::
MinFlow (const MinFlow_type& x)
{
this->MinFlow_.set (x);
}
void SimBuildingElementProxy::
MinFlow (const MinFlow_optional& x)
{
this->MinFlow_ = x;
}
const SimBuildingElementProxy::Model_optional& SimBuildingElementProxy::
Model () const
{
return this->Model_;
}
SimBuildingElementProxy::Model_optional& SimBuildingElementProxy::
Model ()
{
return this->Model_;
}
void SimBuildingElementProxy::
Model (const Model_type& x)
{
this->Model_.set (x);
}
void SimBuildingElementProxy::
Model (const Model_optional& x)
{
this->Model_ = x;
}
void SimBuildingElementProxy::
Model (::std::auto_ptr< Model_type > x)
{
this->Model_.set (x);
}
const SimBuildingElementProxy::MotorHP_optional& SimBuildingElementProxy::
MotorHP () const
{
return this->MotorHP_;
}
SimBuildingElementProxy::MotorHP_optional& SimBuildingElementProxy::
MotorHP ()
{
return this->MotorHP_;
}
void SimBuildingElementProxy::
MotorHP (const MotorHP_type& x)
{
this->MotorHP_.set (x);
}
void SimBuildingElementProxy::
MotorHP (const MotorHP_optional& x)
{
this->MotorHP_ = x;
}
const SimBuildingElementProxy::NumberOfFans_optional& SimBuildingElementProxy::
NumberOfFans () const
{
return this->NumberOfFans_;
}
SimBuildingElementProxy::NumberOfFans_optional& SimBuildingElementProxy::
NumberOfFans ()
{
return this->NumberOfFans_;
}
void SimBuildingElementProxy::
NumberOfFans (const NumberOfFans_type& x)
{
this->NumberOfFans_.set (x);
}
void SimBuildingElementProxy::
NumberOfFans (const NumberOfFans_optional& x)
{
this->NumberOfFans_ = x;
}
const SimBuildingElementProxy::NumberOfPoles_optional& SimBuildingElementProxy::
NumberOfPoles () const
{
return this->NumberOfPoles_;
}
SimBuildingElementProxy::NumberOfPoles_optional& SimBuildingElementProxy::
NumberOfPoles ()
{
return this->NumberOfPoles_;
}
void SimBuildingElementProxy::
NumberOfPoles (const NumberOfPoles_type& x)
{
this->NumberOfPoles_.set (x);
}
void SimBuildingElementProxy::
NumberOfPoles (const NumberOfPoles_optional& x)
{
this->NumberOfPoles_ = x;
}
const SimBuildingElementProxy::ObjectClassName_optional& SimBuildingElementProxy::
ObjectClassName () const
{
return this->ObjectClassName_;
}
SimBuildingElementProxy::ObjectClassName_optional& SimBuildingElementProxy::
ObjectClassName ()
{
return this->ObjectClassName_;
}
void SimBuildingElementProxy::
ObjectClassName (const ObjectClassName_type& x)
{
this->ObjectClassName_.set (x);
}
void SimBuildingElementProxy::
ObjectClassName (const ObjectClassName_optional& x)
{
this->ObjectClassName_ = x;
}
void SimBuildingElementProxy::
ObjectClassName (::std::auto_ptr< ObjectClassName_type > x)
{
this->ObjectClassName_.set (x);
}
const SimBuildingElementProxy::Offset_optional& SimBuildingElementProxy::
Offset () const
{
return this->Offset_;
}
SimBuildingElementProxy::Offset_optional& SimBuildingElementProxy::
Offset ()
{
return this->Offset_;
}
void SimBuildingElementProxy::
Offset (const Offset_type& x)
{
this->Offset_.set (x);
}
void SimBuildingElementProxy::
Offset (const Offset_optional& x)
{
this->Offset_ = x;
}
const SimBuildingElementProxy::OmniclassNumber_optional& SimBuildingElementProxy::
OmniclassNumber () const
{
return this->OmniclassNumber_;
}
SimBuildingElementProxy::OmniclassNumber_optional& SimBuildingElementProxy::
OmniclassNumber ()
{
return this->OmniclassNumber_;
}
void SimBuildingElementProxy::
OmniclassNumber (const OmniclassNumber_type& x)
{
this->OmniclassNumber_.set (x);
}
void SimBuildingElementProxy::
OmniclassNumber (const OmniclassNumber_optional& x)
{
this->OmniclassNumber_ = x;
}
void SimBuildingElementProxy::
OmniclassNumber (::std::auto_ptr< OmniclassNumber_type > x)
{
this->OmniclassNumber_.set (x);
}
const SimBuildingElementProxy::OmniclassTitle_optional& SimBuildingElementProxy::
OmniclassTitle () const
{
return this->OmniclassTitle_;
}
SimBuildingElementProxy::OmniclassTitle_optional& SimBuildingElementProxy::
OmniclassTitle ()
{
return this->OmniclassTitle_;
}
void SimBuildingElementProxy::
OmniclassTitle (const OmniclassTitle_type& x)
{
this->OmniclassTitle_.set (x);
}
void SimBuildingElementProxy::
OmniclassTitle (const OmniclassTitle_optional& x)
{
this->OmniclassTitle_ = x;
}
void SimBuildingElementProxy::
OmniclassTitle (::std::auto_ptr< OmniclassTitle_type > x)
{
this->OmniclassTitle_.set (x);
}
const SimBuildingElementProxy::OutletDiameter_optional& SimBuildingElementProxy::
OutletDiameter () const
{
return this->OutletDiameter_;
}
SimBuildingElementProxy::OutletDiameter_optional& SimBuildingElementProxy::
OutletDiameter ()
{
return this->OutletDiameter_;
}
void SimBuildingElementProxy::
OutletDiameter (const OutletDiameter_type& x)
{
this->OutletDiameter_.set (x);
}
void SimBuildingElementProxy::
OutletDiameter (const OutletDiameter_optional& x)
{
this->OutletDiameter_ = x;
}
const SimBuildingElementProxy::OutletRadius_optional& SimBuildingElementProxy::
OutletRadius () const
{
return this->OutletRadius_;
}
SimBuildingElementProxy::OutletRadius_optional& SimBuildingElementProxy::
OutletRadius ()
{
return this->OutletRadius_;
}
void SimBuildingElementProxy::
OutletRadius (const OutletRadius_type& x)
{
this->OutletRadius_.set (x);
}
void SimBuildingElementProxy::
OutletRadius (const OutletRadius_optional& x)
{
this->OutletRadius_ = x;
}
const SimBuildingElementProxy::OverallHeight_optional& SimBuildingElementProxy::
OverallHeight () const
{
return this->OverallHeight_;
}
SimBuildingElementProxy::OverallHeight_optional& SimBuildingElementProxy::
OverallHeight ()
{
return this->OverallHeight_;
}
void SimBuildingElementProxy::
OverallHeight (const OverallHeight_type& x)
{
this->OverallHeight_.set (x);
}
void SimBuildingElementProxy::
OverallHeight (const OverallHeight_optional& x)
{
this->OverallHeight_ = x;
}
const SimBuildingElementProxy::OverallLength_optional& SimBuildingElementProxy::
OverallLength () const
{
return this->OverallLength_;
}
SimBuildingElementProxy::OverallLength_optional& SimBuildingElementProxy::
OverallLength ()
{
return this->OverallLength_;
}
void SimBuildingElementProxy::
OverallLength (const OverallLength_type& x)
{
this->OverallLength_.set (x);
}
void SimBuildingElementProxy::
OverallLength (const OverallLength_optional& x)
{
this->OverallLength_ = x;
}
const SimBuildingElementProxy::OverallWidth_optional& SimBuildingElementProxy::
OverallWidth () const
{
return this->OverallWidth_;
}
SimBuildingElementProxy::OverallWidth_optional& SimBuildingElementProxy::
OverallWidth ()
{
return this->OverallWidth_;
}
void SimBuildingElementProxy::
OverallWidth (const OverallWidth_type& x)
{
this->OverallWidth_.set (x);
}
void SimBuildingElementProxy::
OverallWidth (const OverallWidth_optional& x)
{
this->OverallWidth_ = x;
}
const SimBuildingElementProxy::PanelHeight_optional& SimBuildingElementProxy::
PanelHeight () const
{
return this->PanelHeight_;
}
SimBuildingElementProxy::PanelHeight_optional& SimBuildingElementProxy::
PanelHeight ()
{
return this->PanelHeight_;
}
void SimBuildingElementProxy::
PanelHeight (const PanelHeight_type& x)
{
this->PanelHeight_.set (x);
}
void SimBuildingElementProxy::
PanelHeight (const PanelHeight_optional& x)
{
this->PanelHeight_ = x;
}
const SimBuildingElementProxy::Partshape_optional& SimBuildingElementProxy::
Partshape () const
{
return this->Partshape_;
}
SimBuildingElementProxy::Partshape_optional& SimBuildingElementProxy::
Partshape ()
{
return this->Partshape_;
}
void SimBuildingElementProxy::
Partshape (const Partshape_type& x)
{
this->Partshape_.set (x);
}
void SimBuildingElementProxy::
Partshape (const Partshape_optional& x)
{
this->Partshape_ = x;
}
void SimBuildingElementProxy::
Partshape (::std::auto_ptr< Partshape_type > x)
{
this->Partshape_.set (x);
}
const SimBuildingElementProxy::PhaseCreated_optional& SimBuildingElementProxy::
PhaseCreated () const
{
return this->PhaseCreated_;
}
SimBuildingElementProxy::PhaseCreated_optional& SimBuildingElementProxy::
PhaseCreated ()
{
return this->PhaseCreated_;
}
void SimBuildingElementProxy::
PhaseCreated (const PhaseCreated_type& x)
{
this->PhaseCreated_.set (x);
}
void SimBuildingElementProxy::
PhaseCreated (const PhaseCreated_optional& x)
{
this->PhaseCreated_ = x;
}
void SimBuildingElementProxy::
PhaseCreated (::std::auto_ptr< PhaseCreated_type > x)
{
this->PhaseCreated_.set (x);
}
const SimBuildingElementProxy::PipeRadius_optional& SimBuildingElementProxy::
PipeRadius () const
{
return this->PipeRadius_;
}
SimBuildingElementProxy::PipeRadius_optional& SimBuildingElementProxy::
PipeRadius ()
{
return this->PipeRadius_;
}
void SimBuildingElementProxy::
PipeRadius (const PipeRadius_type& x)
{
this->PipeRadius_.set (x);
}
void SimBuildingElementProxy::
PipeRadius (const PipeRadius_optional& x)
{
this->PipeRadius_ = x;
}
const SimBuildingElementProxy::PrimaryNumberofPoles_optional& SimBuildingElementProxy::
PrimaryNumberofPoles () const
{
return this->PrimaryNumberofPoles_;
}
SimBuildingElementProxy::PrimaryNumberofPoles_optional& SimBuildingElementProxy::
PrimaryNumberofPoles ()
{
return this->PrimaryNumberofPoles_;
}
void SimBuildingElementProxy::
PrimaryNumberofPoles (const PrimaryNumberofPoles_type& x)
{
this->PrimaryNumberofPoles_.set (x);
}
void SimBuildingElementProxy::
PrimaryNumberofPoles (const PrimaryNumberofPoles_optional& x)
{
this->PrimaryNumberofPoles_ = x;
}
const SimBuildingElementProxy::PrimaryVoltage_optional& SimBuildingElementProxy::
PrimaryVoltage () const
{
return this->PrimaryVoltage_;
}
SimBuildingElementProxy::PrimaryVoltage_optional& SimBuildingElementProxy::
PrimaryVoltage ()
{
return this->PrimaryVoltage_;
}
void SimBuildingElementProxy::
PrimaryVoltage (const PrimaryVoltage_type& x)
{
this->PrimaryVoltage_.set (x);
}
void SimBuildingElementProxy::
PrimaryVoltage (const PrimaryVoltage_optional& x)
{
this->PrimaryVoltage_ = x;
}
const SimBuildingElementProxy::PumpHeight_optional& SimBuildingElementProxy::
PumpHeight () const
{
return this->PumpHeight_;
}
SimBuildingElementProxy::PumpHeight_optional& SimBuildingElementProxy::
PumpHeight ()
{
return this->PumpHeight_;
}
void SimBuildingElementProxy::
PumpHeight (const PumpHeight_type& x)
{
this->PumpHeight_.set (x);
}
void SimBuildingElementProxy::
PumpHeight (const PumpHeight_optional& x)
{
this->PumpHeight_ = x;
}
const SimBuildingElementProxy::PumpLength_optional& SimBuildingElementProxy::
PumpLength () const
{
return this->PumpLength_;
}
SimBuildingElementProxy::PumpLength_optional& SimBuildingElementProxy::
PumpLength ()
{
return this->PumpLength_;
}
void SimBuildingElementProxy::
PumpLength (const PumpLength_type& x)
{
this->PumpLength_.set (x);
}
void SimBuildingElementProxy::
PumpLength (const PumpLength_optional& x)
{
this->PumpLength_ = x;
}
const SimBuildingElementProxy::PumpWidth_optional& SimBuildingElementProxy::
PumpWidth () const
{
return this->PumpWidth_;
}
SimBuildingElementProxy::PumpWidth_optional& SimBuildingElementProxy::
PumpWidth ()
{
return this->PumpWidth_;
}
void SimBuildingElementProxy::
PumpWidth (const PumpWidth_type& x)
{
this->PumpWidth_.set (x);
}
void SimBuildingElementProxy::
PumpWidth (const PumpWidth_optional& x)
{
this->PumpWidth_ = x;
}
const SimBuildingElementProxy::Radius1_optional& SimBuildingElementProxy::
Radius1 () const
{
return this->Radius1_;
}
SimBuildingElementProxy::Radius1_optional& SimBuildingElementProxy::
Radius1 ()
{
return this->Radius1_;
}
void SimBuildingElementProxy::
Radius1 (const Radius1_type& x)
{
this->Radius1_.set (x);
}
void SimBuildingElementProxy::
Radius1 (const Radius1_optional& x)
{
this->Radius1_ = x;
}
const SimBuildingElementProxy::Radius2_optional& SimBuildingElementProxy::
Radius2 () const
{
return this->Radius2_;
}
SimBuildingElementProxy::Radius2_optional& SimBuildingElementProxy::
Radius2 ()
{
return this->Radius2_;
}
void SimBuildingElementProxy::
Radius2 (const Radius2_type& x)
{
this->Radius2_.set (x);
}
void SimBuildingElementProxy::
Radius2 (const Radius2_optional& x)
{
this->Radius2_ = x;
}
const SimBuildingElementProxy::Radius3_optional& SimBuildingElementProxy::
Radius3 () const
{
return this->Radius3_;
}
SimBuildingElementProxy::Radius3_optional& SimBuildingElementProxy::
Radius3 ()
{
return this->Radius3_;
}
void SimBuildingElementProxy::
Radius3 (const Radius3_type& x)
{
this->Radius3_.set (x);
}
void SimBuildingElementProxy::
Radius3 (const Radius3_optional& x)
{
this->Radius3_ = x;
}
const SimBuildingElementProxy::Radius4_optional& SimBuildingElementProxy::
Radius4 () const
{
return this->Radius4_;
}
SimBuildingElementProxy::Radius4_optional& SimBuildingElementProxy::
Radius4 ()
{
return this->Radius4_;
}
void SimBuildingElementProxy::
Radius4 (const Radius4_type& x)
{
this->Radius4_.set (x);
}
void SimBuildingElementProxy::
Radius4 (const Radius4_optional& x)
{
this->Radius4_ = x;
}
const SimBuildingElementProxy::Radius5_optional& SimBuildingElementProxy::
Radius5 () const
{
return this->Radius5_;
}
SimBuildingElementProxy::Radius5_optional& SimBuildingElementProxy::
Radius5 ()
{
return this->Radius5_;
}
void SimBuildingElementProxy::
Radius5 (const Radius5_type& x)
{
this->Radius5_.set (x);
}
void SimBuildingElementProxy::
Radius5 (const Radius5_optional& x)
{
this->Radius5_ = x;
}
const SimBuildingElementProxy::Radius6_optional& SimBuildingElementProxy::
Radius6 () const
{
return this->Radius6_;
}
SimBuildingElementProxy::Radius6_optional& SimBuildingElementProxy::
Radius6 ()
{
return this->Radius6_;
}
void SimBuildingElementProxy::
Radius6 (const Radius6_type& x)
{
this->Radius6_.set (x);
}
void SimBuildingElementProxy::
Radius6 (const Radius6_optional& x)
{
this->Radius6_ = x;
}
const SimBuildingElementProxy::Reference_optional& SimBuildingElementProxy::
Reference () const
{
return this->Reference_;
}
SimBuildingElementProxy::Reference_optional& SimBuildingElementProxy::
Reference ()
{
return this->Reference_;
}
void SimBuildingElementProxy::
Reference (const Reference_type& x)
{
this->Reference_.set (x);
}
void SimBuildingElementProxy::
Reference (const Reference_optional& x)
{
this->Reference_ = x;
}
void SimBuildingElementProxy::
Reference (::std::auto_ptr< Reference_type > x)
{
this->Reference_.set (x);
}
const SimBuildingElementProxy::Reflectance_optional& SimBuildingElementProxy::
Reflectance () const
{
return this->Reflectance_;
}
SimBuildingElementProxy::Reflectance_optional& SimBuildingElementProxy::
Reflectance ()
{
return this->Reflectance_;
}
void SimBuildingElementProxy::
Reflectance (const Reflectance_type& x)
{
this->Reflectance_.set (x);
}
void SimBuildingElementProxy::
Reflectance (const Reflectance_optional& x)
{
this->Reflectance_ = x;
}
const SimBuildingElementProxy::ReturnAirInletFlow_optional& SimBuildingElementProxy::
ReturnAirInletFlow () const
{
return this->ReturnAirInletFlow_;
}
SimBuildingElementProxy::ReturnAirInletFlow_optional& SimBuildingElementProxy::
ReturnAirInletFlow ()
{
return this->ReturnAirInletFlow_;
}
void SimBuildingElementProxy::
ReturnAirInletFlow (const ReturnAirInletFlow_type& x)
{
this->ReturnAirInletFlow_.set (x);
}
void SimBuildingElementProxy::
ReturnAirInletFlow (const ReturnAirInletFlow_optional& x)
{
this->ReturnAirInletFlow_ = x;
}
const SimBuildingElementProxy::ReturnAirInletHeight_optional& SimBuildingElementProxy::
ReturnAirInletHeight () const
{
return this->ReturnAirInletHeight_;
}
SimBuildingElementProxy::ReturnAirInletHeight_optional& SimBuildingElementProxy::
ReturnAirInletHeight ()
{
return this->ReturnAirInletHeight_;
}
void SimBuildingElementProxy::
ReturnAirInletHeight (const ReturnAirInletHeight_type& x)
{
this->ReturnAirInletHeight_.set (x);
}
void SimBuildingElementProxy::
ReturnAirInletHeight (const ReturnAirInletHeight_optional& x)
{
this->ReturnAirInletHeight_ = x;
}
const SimBuildingElementProxy::ReturnAirInletWidth_optional& SimBuildingElementProxy::
ReturnAirInletWidth () const
{
return this->ReturnAirInletWidth_;
}
SimBuildingElementProxy::ReturnAirInletWidth_optional& SimBuildingElementProxy::
ReturnAirInletWidth ()
{
return this->ReturnAirInletWidth_;
}
void SimBuildingElementProxy::
ReturnAirInletWidth (const ReturnAirInletWidth_type& x)
{
this->ReturnAirInletWidth_.set (x);
}
void SimBuildingElementProxy::
ReturnAirInletWidth (const ReturnAirInletWidth_optional& x)
{
this->ReturnAirInletWidth_ = x;
}
const SimBuildingElementProxy::ReturnDuctHeight_optional& SimBuildingElementProxy::
ReturnDuctHeight () const
{
return this->ReturnDuctHeight_;
}
SimBuildingElementProxy::ReturnDuctHeight_optional& SimBuildingElementProxy::
ReturnDuctHeight ()
{
return this->ReturnDuctHeight_;
}
void SimBuildingElementProxy::
ReturnDuctHeight (const ReturnDuctHeight_type& x)
{
this->ReturnDuctHeight_.set (x);
}
void SimBuildingElementProxy::
ReturnDuctHeight (const ReturnDuctHeight_optional& x)
{
this->ReturnDuctHeight_ = x;
}
const SimBuildingElementProxy::ReturnDuctWidth_optional& SimBuildingElementProxy::
ReturnDuctWidth () const
{
return this->ReturnDuctWidth_;
}
SimBuildingElementProxy::ReturnDuctWidth_optional& SimBuildingElementProxy::
ReturnDuctWidth ()
{
return this->ReturnDuctWidth_;
}
void SimBuildingElementProxy::
ReturnDuctWidth (const ReturnDuctWidth_type& x)
{
this->ReturnDuctWidth_.set (x);
}
void SimBuildingElementProxy::
ReturnDuctWidth (const ReturnDuctWidth_optional& x)
{
this->ReturnDuctWidth_ = x;
}
const SimBuildingElementProxy::Returnheight_optional& SimBuildingElementProxy::
Returnheight () const
{
return this->Returnheight_;
}
SimBuildingElementProxy::Returnheight_optional& SimBuildingElementProxy::
Returnheight ()
{
return this->Returnheight_;
}
void SimBuildingElementProxy::
Returnheight (const Returnheight_type& x)
{
this->Returnheight_.set (x);
}
void SimBuildingElementProxy::
Returnheight (const Returnheight_optional& x)
{
this->Returnheight_ = x;
}
const SimBuildingElementProxy::Returnwidth_optional& SimBuildingElementProxy::
Returnwidth () const
{
return this->Returnwidth_;
}
SimBuildingElementProxy::Returnwidth_optional& SimBuildingElementProxy::
Returnwidth ()
{
return this->Returnwidth_;
}
void SimBuildingElementProxy::
Returnwidth (const Returnwidth_type& x)
{
this->Returnwidth_.set (x);
}
void SimBuildingElementProxy::
Returnwidth (const Returnwidth_optional& x)
{
this->Returnwidth_ = x;
}
const SimBuildingElementProxy::ReturnY_Offset_optional& SimBuildingElementProxy::
ReturnY_Offset () const
{
return this->ReturnY_Offset_;
}
SimBuildingElementProxy::ReturnY_Offset_optional& SimBuildingElementProxy::
ReturnY_Offset ()
{
return this->ReturnY_Offset_;
}
void SimBuildingElementProxy::
ReturnY_Offset (const ReturnY_Offset_type& x)
{
this->ReturnY_Offset_.set (x);
}
void SimBuildingElementProxy::
ReturnY_Offset (const ReturnY_Offset_optional& x)
{
this->ReturnY_Offset_ = x;
}
const SimBuildingElementProxy::ReturnZ_Offset_optional& SimBuildingElementProxy::
ReturnZ_Offset () const
{
return this->ReturnZ_Offset_;
}
SimBuildingElementProxy::ReturnZ_Offset_optional& SimBuildingElementProxy::
ReturnZ_Offset ()
{
return this->ReturnZ_Offset_;
}
void SimBuildingElementProxy::
ReturnZ_Offset (const ReturnZ_Offset_type& x)
{
this->ReturnZ_Offset_.set (x);
}
void SimBuildingElementProxy::
ReturnZ_Offset (const ReturnZ_Offset_optional& x)
{
this->ReturnZ_Offset_ = x;
}
const SimBuildingElementProxy::Roughness_optional& SimBuildingElementProxy::
Roughness () const
{
return this->Roughness_;
}
SimBuildingElementProxy::Roughness_optional& SimBuildingElementProxy::
Roughness ()
{
return this->Roughness_;
}
void SimBuildingElementProxy::
Roughness (const Roughness_type& x)
{
this->Roughness_.set (x);
}
void SimBuildingElementProxy::
Roughness (const Roughness_optional& x)
{
this->Roughness_ = x;
}
const SimBuildingElementProxy::ShadingDeviceType_optional& SimBuildingElementProxy::
ShadingDeviceType () const
{
return this->ShadingDeviceType_;
}
SimBuildingElementProxy::ShadingDeviceType_optional& SimBuildingElementProxy::
ShadingDeviceType ()
{
return this->ShadingDeviceType_;
}
void SimBuildingElementProxy::
ShadingDeviceType (const ShadingDeviceType_type& x)
{
this->ShadingDeviceType_.set (x);
}
void SimBuildingElementProxy::
ShadingDeviceType (const ShadingDeviceType_optional& x)
{
this->ShadingDeviceType_ = x;
}
void SimBuildingElementProxy::
ShadingDeviceType (::std::auto_ptr< ShadingDeviceType_type > x)
{
this->ShadingDeviceType_.set (x);
}
const SimBuildingElementProxy::SupplyAirInletDiameter_optional& SimBuildingElementProxy::
SupplyAirInletDiameter () const
{
return this->SupplyAirInletDiameter_;
}
SimBuildingElementProxy::SupplyAirInletDiameter_optional& SimBuildingElementProxy::
SupplyAirInletDiameter ()
{
return this->SupplyAirInletDiameter_;
}
void SimBuildingElementProxy::
SupplyAirInletDiameter (const SupplyAirInletDiameter_type& x)
{
this->SupplyAirInletDiameter_.set (x);
}
void SimBuildingElementProxy::
SupplyAirInletDiameter (const SupplyAirInletDiameter_optional& x)
{
this->SupplyAirInletDiameter_ = x;
}
const SimBuildingElementProxy::SupplyAirInletFlow_optional& SimBuildingElementProxy::
SupplyAirInletFlow () const
{
return this->SupplyAirInletFlow_;
}
SimBuildingElementProxy::SupplyAirInletFlow_optional& SimBuildingElementProxy::
SupplyAirInletFlow ()
{
return this->SupplyAirInletFlow_;
}
void SimBuildingElementProxy::
SupplyAirInletFlow (const SupplyAirInletFlow_type& x)
{
this->SupplyAirInletFlow_.set (x);
}
void SimBuildingElementProxy::
SupplyAirInletFlow (const SupplyAirInletFlow_optional& x)
{
this->SupplyAirInletFlow_ = x;
}
const SimBuildingElementProxy::SupplyAirInletHeight_optional& SimBuildingElementProxy::
SupplyAirInletHeight () const
{
return this->SupplyAirInletHeight_;
}
SimBuildingElementProxy::SupplyAirInletHeight_optional& SimBuildingElementProxy::
SupplyAirInletHeight ()
{
return this->SupplyAirInletHeight_;
}
void SimBuildingElementProxy::
SupplyAirInletHeight (const SupplyAirInletHeight_type& x)
{
this->SupplyAirInletHeight_.set (x);
}
void SimBuildingElementProxy::
SupplyAirInletHeight (const SupplyAirInletHeight_optional& x)
{
this->SupplyAirInletHeight_ = x;
}
const SimBuildingElementProxy::SupplyAirInletRadius_optional& SimBuildingElementProxy::
SupplyAirInletRadius () const
{
return this->SupplyAirInletRadius_;
}
SimBuildingElementProxy::SupplyAirInletRadius_optional& SimBuildingElementProxy::
SupplyAirInletRadius ()
{
return this->SupplyAirInletRadius_;
}
void SimBuildingElementProxy::
SupplyAirInletRadius (const SupplyAirInletRadius_type& x)
{
this->SupplyAirInletRadius_.set (x);
}
void SimBuildingElementProxy::
SupplyAirInletRadius (const SupplyAirInletRadius_optional& x)
{
this->SupplyAirInletRadius_ = x;
}
const SimBuildingElementProxy::SupplyAirInletWidth_optional& SimBuildingElementProxy::
SupplyAirInletWidth () const
{
return this->SupplyAirInletWidth_;
}
SimBuildingElementProxy::SupplyAirInletWidth_optional& SimBuildingElementProxy::
SupplyAirInletWidth ()
{
return this->SupplyAirInletWidth_;
}
void SimBuildingElementProxy::
SupplyAirInletWidth (const SupplyAirInletWidth_type& x)
{
this->SupplyAirInletWidth_.set (x);
}
void SimBuildingElementProxy::
SupplyAirInletWidth (const SupplyAirInletWidth_optional& x)
{
this->SupplyAirInletWidth_ = x;
}
const SimBuildingElementProxy::SupplyAirOutletFlow_optional& SimBuildingElementProxy::
SupplyAirOutletFlow () const
{
return this->SupplyAirOutletFlow_;
}
SimBuildingElementProxy::SupplyAirOutletFlow_optional& SimBuildingElementProxy::
SupplyAirOutletFlow ()
{
return this->SupplyAirOutletFlow_;
}
void SimBuildingElementProxy::
SupplyAirOutletFlow (const SupplyAirOutletFlow_type& x)
{
this->SupplyAirOutletFlow_.set (x);
}
void SimBuildingElementProxy::
SupplyAirOutletFlow (const SupplyAirOutletFlow_optional& x)
{
this->SupplyAirOutletFlow_ = x;
}
const SimBuildingElementProxy::SupplyAirOutletHeight_optional& SimBuildingElementProxy::
SupplyAirOutletHeight () const
{
return this->SupplyAirOutletHeight_;
}
SimBuildingElementProxy::SupplyAirOutletHeight_optional& SimBuildingElementProxy::
SupplyAirOutletHeight ()
{
return this->SupplyAirOutletHeight_;
}
void SimBuildingElementProxy::
SupplyAirOutletHeight (const SupplyAirOutletHeight_type& x)
{
this->SupplyAirOutletHeight_.set (x);
}
void SimBuildingElementProxy::
SupplyAirOutletHeight (const SupplyAirOutletHeight_optional& x)
{
this->SupplyAirOutletHeight_ = x;
}
const SimBuildingElementProxy::SupplyAirOutletWidth_optional& SimBuildingElementProxy::
SupplyAirOutletWidth () const
{
return this->SupplyAirOutletWidth_;
}
SimBuildingElementProxy::SupplyAirOutletWidth_optional& SimBuildingElementProxy::
SupplyAirOutletWidth ()
{
return this->SupplyAirOutletWidth_;
}
void SimBuildingElementProxy::
SupplyAirOutletWidth (const SupplyAirOutletWidth_type& x)
{
this->SupplyAirOutletWidth_.set (x);
}
void SimBuildingElementProxy::
SupplyAirOutletWidth (const SupplyAirOutletWidth_optional& x)
{
this->SupplyAirOutletWidth_ = x;
}
const SimBuildingElementProxy::SupplyAirPressureDrop_optional& SimBuildingElementProxy::
SupplyAirPressureDrop () const
{
return this->SupplyAirPressureDrop_;
}
SimBuildingElementProxy::SupplyAirPressureDrop_optional& SimBuildingElementProxy::
SupplyAirPressureDrop ()
{
return this->SupplyAirPressureDrop_;
}
void SimBuildingElementProxy::
SupplyAirPressureDrop (const SupplyAirPressureDrop_type& x)
{
this->SupplyAirPressureDrop_.set (x);
}
void SimBuildingElementProxy::
SupplyAirPressureDrop (const SupplyAirPressureDrop_optional& x)
{
this->SupplyAirPressureDrop_ = x;
}
const SimBuildingElementProxy::SupplyDuctHeight_optional& SimBuildingElementProxy::
SupplyDuctHeight () const
{
return this->SupplyDuctHeight_;
}
SimBuildingElementProxy::SupplyDuctHeight_optional& SimBuildingElementProxy::
SupplyDuctHeight ()
{
return this->SupplyDuctHeight_;
}
void SimBuildingElementProxy::
SupplyDuctHeight (const SupplyDuctHeight_type& x)
{
this->SupplyDuctHeight_.set (x);
}
void SimBuildingElementProxy::
SupplyDuctHeight (const SupplyDuctHeight_optional& x)
{
this->SupplyDuctHeight_ = x;
}
const SimBuildingElementProxy::SupplyDuctWidth_optional& SimBuildingElementProxy::
SupplyDuctWidth () const
{
return this->SupplyDuctWidth_;
}
SimBuildingElementProxy::SupplyDuctWidth_optional& SimBuildingElementProxy::
SupplyDuctWidth ()
{
return this->SupplyDuctWidth_;
}
void SimBuildingElementProxy::
SupplyDuctWidth (const SupplyDuctWidth_type& x)
{
this->SupplyDuctWidth_.set (x);
}
void SimBuildingElementProxy::
SupplyDuctWidth (const SupplyDuctWidth_optional& x)
{
this->SupplyDuctWidth_ = x;
}
const SimBuildingElementProxy::Supplyheight_optional& SimBuildingElementProxy::
Supplyheight () const
{
return this->Supplyheight_;
}
SimBuildingElementProxy::Supplyheight_optional& SimBuildingElementProxy::
Supplyheight ()
{
return this->Supplyheight_;
}
void SimBuildingElementProxy::
Supplyheight (const Supplyheight_type& x)
{
this->Supplyheight_.set (x);
}
void SimBuildingElementProxy::
Supplyheight (const Supplyheight_optional& x)
{
this->Supplyheight_ = x;
}
const SimBuildingElementProxy::Supplywidth_optional& SimBuildingElementProxy::
Supplywidth () const
{
return this->Supplywidth_;
}
SimBuildingElementProxy::Supplywidth_optional& SimBuildingElementProxy::
Supplywidth ()
{
return this->Supplywidth_;
}
void SimBuildingElementProxy::
Supplywidth (const Supplywidth_type& x)
{
this->Supplywidth_.set (x);
}
void SimBuildingElementProxy::
Supplywidth (const Supplywidth_optional& x)
{
this->Supplywidth_ = x;
}
const SimBuildingElementProxy::Supply_ReturnSymbols_optional& SimBuildingElementProxy::
Supply_ReturnSymbols () const
{
return this->Supply_ReturnSymbols_;
}
SimBuildingElementProxy::Supply_ReturnSymbols_optional& SimBuildingElementProxy::
Supply_ReturnSymbols ()
{
return this->Supply_ReturnSymbols_;
}
void SimBuildingElementProxy::
Supply_ReturnSymbols (const Supply_ReturnSymbols_type& x)
{
this->Supply_ReturnSymbols_.set (x);
}
void SimBuildingElementProxy::
Supply_ReturnSymbols (const Supply_ReturnSymbols_optional& x)
{
this->Supply_ReturnSymbols_ = x;
}
const SimBuildingElementProxy::SupplyY_Offset_optional& SimBuildingElementProxy::
SupplyY_Offset () const
{
return this->SupplyY_Offset_;
}
SimBuildingElementProxy::SupplyY_Offset_optional& SimBuildingElementProxy::
SupplyY_Offset ()
{
return this->SupplyY_Offset_;
}
void SimBuildingElementProxy::
SupplyY_Offset (const SupplyY_Offset_type& x)
{
this->SupplyY_Offset_.set (x);
}
void SimBuildingElementProxy::
SupplyY_Offset (const SupplyY_Offset_optional& x)
{
this->SupplyY_Offset_ = x;
}
const SimBuildingElementProxy::SupplyZ_Offset_optional& SimBuildingElementProxy::
SupplyZ_Offset () const
{
return this->SupplyZ_Offset_;
}
SimBuildingElementProxy::SupplyZ_Offset_optional& SimBuildingElementProxy::
SupplyZ_Offset ()
{
return this->SupplyZ_Offset_;
}
void SimBuildingElementProxy::
SupplyZ_Offset (const SupplyZ_Offset_type& x)
{
this->SupplyZ_Offset_.set (x);
}
void SimBuildingElementProxy::
SupplyZ_Offset (const SupplyZ_Offset_optional& x)
{
this->SupplyZ_Offset_ = x;
}
const SimBuildingElementProxy::SystemClassification_optional& SimBuildingElementProxy::
SystemClassification () const
{
return this->SystemClassification_;
}
SimBuildingElementProxy::SystemClassification_optional& SimBuildingElementProxy::
SystemClassification ()
{
return this->SystemClassification_;
}
void SimBuildingElementProxy::
SystemClassification (const SystemClassification_type& x)
{
this->SystemClassification_.set (x);
}
void SimBuildingElementProxy::
SystemClassification (const SystemClassification_optional& x)
{
this->SystemClassification_ = x;
}
void SimBuildingElementProxy::
SystemClassification (::std::auto_ptr< SystemClassification_type > x)
{
this->SystemClassification_.set (x);
}
const SimBuildingElementProxy::SystemName_optional& SimBuildingElementProxy::
SystemName () const
{
return this->SystemName_;
}
SimBuildingElementProxy::SystemName_optional& SimBuildingElementProxy::
SystemName ()
{
return this->SystemName_;
}
void SimBuildingElementProxy::
SystemName (const SystemName_type& x)
{
this->SystemName_.set (x);
}
void SimBuildingElementProxy::
SystemName (const SystemName_optional& x)
{
this->SystemName_ = x;
}
void SimBuildingElementProxy::
SystemName (::std::auto_ptr< SystemName_type > x)
{
this->SystemName_.set (x);
}
const SimBuildingElementProxy::TiltRange_optional& SimBuildingElementProxy::
TiltRange () const
{
return this->TiltRange_;
}
SimBuildingElementProxy::TiltRange_optional& SimBuildingElementProxy::
TiltRange ()
{
return this->TiltRange_;
}
void SimBuildingElementProxy::
TiltRange (const TiltRange_type& x)
{
this->TiltRange_.set (x);
}
void SimBuildingElementProxy::
TiltRange (const TiltRange_optional& x)
{
this->TiltRange_ = x;
}
const SimBuildingElementProxy::TotalConnected_optional& SimBuildingElementProxy::
TotalConnected () const
{
return this->TotalConnected_;
}
SimBuildingElementProxy::TotalConnected_optional& SimBuildingElementProxy::
TotalConnected ()
{
return this->TotalConnected_;
}
void SimBuildingElementProxy::
TotalConnected (const TotalConnected_type& x)
{
this->TotalConnected_.set (x);
}
void SimBuildingElementProxy::
TotalConnected (const TotalConnected_optional& x)
{
this->TotalConnected_ = x;
}
const SimBuildingElementProxy::TotalDemandFactor_optional& SimBuildingElementProxy::
TotalDemandFactor () const
{
return this->TotalDemandFactor_;
}
SimBuildingElementProxy::TotalDemandFactor_optional& SimBuildingElementProxy::
TotalDemandFactor ()
{
return this->TotalDemandFactor_;
}
void SimBuildingElementProxy::
TotalDemandFactor (const TotalDemandFactor_type& x)
{
this->TotalDemandFactor_.set (x);
}
void SimBuildingElementProxy::
TotalDemandFactor (const TotalDemandFactor_optional& x)
{
this->TotalDemandFactor_ = x;
}
const SimBuildingElementProxy::TotalEstimatedDemand_optional& SimBuildingElementProxy::
TotalEstimatedDemand () const
{
return this->TotalEstimatedDemand_;
}
SimBuildingElementProxy::TotalEstimatedDemand_optional& SimBuildingElementProxy::
TotalEstimatedDemand ()
{
return this->TotalEstimatedDemand_;
}
void SimBuildingElementProxy::
TotalEstimatedDemand (const TotalEstimatedDemand_type& x)
{
this->TotalEstimatedDemand_.set (x);
}
void SimBuildingElementProxy::
TotalEstimatedDemand (const TotalEstimatedDemand_optional& x)
{
this->TotalEstimatedDemand_ = x;
}
const SimBuildingElementProxy::TowerHeight_optional& SimBuildingElementProxy::
TowerHeight () const
{
return this->TowerHeight_;
}
SimBuildingElementProxy::TowerHeight_optional& SimBuildingElementProxy::
TowerHeight ()
{
return this->TowerHeight_;
}
void SimBuildingElementProxy::
TowerHeight (const TowerHeight_type& x)
{
this->TowerHeight_.set (x);
}
void SimBuildingElementProxy::
TowerHeight (const TowerHeight_optional& x)
{
this->TowerHeight_ = x;
}
const SimBuildingElementProxy::TowerLength_optional& SimBuildingElementProxy::
TowerLength () const
{
return this->TowerLength_;
}
SimBuildingElementProxy::TowerLength_optional& SimBuildingElementProxy::
TowerLength ()
{
return this->TowerLength_;
}
void SimBuildingElementProxy::
TowerLength (const TowerLength_type& x)
{
this->TowerLength_.set (x);
}
void SimBuildingElementProxy::
TowerLength (const TowerLength_optional& x)
{
this->TowerLength_ = x;
}
const SimBuildingElementProxy::TowerWidth_optional& SimBuildingElementProxy::
TowerWidth () const
{
return this->TowerWidth_;
}
SimBuildingElementProxy::TowerWidth_optional& SimBuildingElementProxy::
TowerWidth ()
{
return this->TowerWidth_;
}
void SimBuildingElementProxy::
TowerWidth (const TowerWidth_type& x)
{
this->TowerWidth_.set (x);
}
void SimBuildingElementProxy::
TowerWidth (const TowerWidth_optional& x)
{
this->TowerWidth_ = x;
}
const SimBuildingElementProxy::TransformerHeight_optional& SimBuildingElementProxy::
TransformerHeight () const
{
return this->TransformerHeight_;
}
SimBuildingElementProxy::TransformerHeight_optional& SimBuildingElementProxy::
TransformerHeight ()
{
return this->TransformerHeight_;
}
void SimBuildingElementProxy::
TransformerHeight (const TransformerHeight_type& x)
{
this->TransformerHeight_.set (x);
}
void SimBuildingElementProxy::
TransformerHeight (const TransformerHeight_optional& x)
{
this->TransformerHeight_ = x;
}
const SimBuildingElementProxy::TransformerLength_optional& SimBuildingElementProxy::
TransformerLength () const
{
return this->TransformerLength_;
}
SimBuildingElementProxy::TransformerLength_optional& SimBuildingElementProxy::
TransformerLength ()
{
return this->TransformerLength_;
}
void SimBuildingElementProxy::
TransformerLength (const TransformerLength_type& x)
{
this->TransformerLength_.set (x);
}
void SimBuildingElementProxy::
TransformerLength (const TransformerLength_optional& x)
{
this->TransformerLength_ = x;
}
const SimBuildingElementProxy::TransformerWidth_optional& SimBuildingElementProxy::
TransformerWidth () const
{
return this->TransformerWidth_;
}
SimBuildingElementProxy::TransformerWidth_optional& SimBuildingElementProxy::
TransformerWidth ()
{
return this->TransformerWidth_;
}
void SimBuildingElementProxy::
TransformerWidth (const TransformerWidth_type& x)
{
this->TransformerWidth_.set (x);
}
void SimBuildingElementProxy::
TransformerWidth (const TransformerWidth_optional& x)
{
this->TransformerWidth_ = x;
}
const SimBuildingElementProxy::UniformatClassification_optional& SimBuildingElementProxy::
UniformatClassification () const
{
return this->UniformatClassification_;
}
SimBuildingElementProxy::UniformatClassification_optional& SimBuildingElementProxy::
UniformatClassification ()
{
return this->UniformatClassification_;
}
void SimBuildingElementProxy::
UniformatClassification (const UniformatClassification_type& x)
{
this->UniformatClassification_.set (x);
}
void SimBuildingElementProxy::
UniformatClassification (const UniformatClassification_optional& x)
{
this->UniformatClassification_ = x;
}
void SimBuildingElementProxy::
UniformatClassification (::std::auto_ptr< UniformatClassification_type > x)
{
this->UniformatClassification_.set (x);
}
const SimBuildingElementProxy::Unitdepth_optional& SimBuildingElementProxy::
Unitdepth () const
{
return this->Unitdepth_;
}
SimBuildingElementProxy::Unitdepth_optional& SimBuildingElementProxy::
Unitdepth ()
{
return this->Unitdepth_;
}
void SimBuildingElementProxy::
Unitdepth (const Unitdepth_type& x)
{
this->Unitdepth_.set (x);
}
void SimBuildingElementProxy::
Unitdepth (const Unitdepth_optional& x)
{
this->Unitdepth_ = x;
}
const SimBuildingElementProxy::UnitHeight_optional& SimBuildingElementProxy::
UnitHeight () const
{
return this->UnitHeight_;
}
SimBuildingElementProxy::UnitHeight_optional& SimBuildingElementProxy::
UnitHeight ()
{
return this->UnitHeight_;
}
void SimBuildingElementProxy::
UnitHeight (const UnitHeight_type& x)
{
this->UnitHeight_.set (x);
}
void SimBuildingElementProxy::
UnitHeight (const UnitHeight_optional& x)
{
this->UnitHeight_ = x;
}
const SimBuildingElementProxy::UnitLength_optional& SimBuildingElementProxy::
UnitLength () const
{
return this->UnitLength_;
}
SimBuildingElementProxy::UnitLength_optional& SimBuildingElementProxy::
UnitLength ()
{
return this->UnitLength_;
}
void SimBuildingElementProxy::
UnitLength (const UnitLength_type& x)
{
this->UnitLength_.set (x);
}
void SimBuildingElementProxy::
UnitLength (const UnitLength_optional& x)
{
this->UnitLength_ = x;
}
const SimBuildingElementProxy::UnitWidth_optional& SimBuildingElementProxy::
UnitWidth () const
{
return this->UnitWidth_;
}
SimBuildingElementProxy::UnitWidth_optional& SimBuildingElementProxy::
UnitWidth ()
{
return this->UnitWidth_;
}
void SimBuildingElementProxy::
UnitWidth (const UnitWidth_type& x)
{
this->UnitWidth_.set (x);
}
void SimBuildingElementProxy::
UnitWidth (const UnitWidth_optional& x)
{
this->UnitWidth_ = x;
}
const SimBuildingElementProxy::Visible1_optional& SimBuildingElementProxy::
Visible1 () const
{
return this->Visible1_;
}
SimBuildingElementProxy::Visible1_optional& SimBuildingElementProxy::
Visible1 ()
{
return this->Visible1_;
}
void SimBuildingElementProxy::
Visible1 (const Visible1_type& x)
{
this->Visible1_.set (x);
}
void SimBuildingElementProxy::
Visible1 (const Visible1_optional& x)
{
this->Visible1_ = x;
}
const SimBuildingElementProxy::Visible2_optional& SimBuildingElementProxy::
Visible2 () const
{
return this->Visible2_;
}
SimBuildingElementProxy::Visible2_optional& SimBuildingElementProxy::
Visible2 ()
{
return this->Visible2_;
}
void SimBuildingElementProxy::
Visible2 (const Visible2_type& x)
{
this->Visible2_.set (x);
}
void SimBuildingElementProxy::
Visible2 (const Visible2_optional& x)
{
this->Visible2_ = x;
}
const SimBuildingElementProxy::Voltage_optional& SimBuildingElementProxy::
Voltage () const
{
return this->Voltage_;
}
SimBuildingElementProxy::Voltage_optional& SimBuildingElementProxy::
Voltage ()
{
return this->Voltage_;
}
void SimBuildingElementProxy::
Voltage (const Voltage_type& x)
{
this->Voltage_.set (x);
}
void SimBuildingElementProxy::
Voltage (const Voltage_optional& x)
{
this->Voltage_ = x;
}
const SimBuildingElementProxy::WaterFlow_optional& SimBuildingElementProxy::
WaterFlow () const
{
return this->WaterFlow_;
}
SimBuildingElementProxy::WaterFlow_optional& SimBuildingElementProxy::
WaterFlow ()
{
return this->WaterFlow_;
}
void SimBuildingElementProxy::
WaterFlow (const WaterFlow_type& x)
{
this->WaterFlow_.set (x);
}
void SimBuildingElementProxy::
WaterFlow (const WaterFlow_optional& x)
{
this->WaterFlow_ = x;
}
const SimBuildingElementProxy::WaterPressure_optional& SimBuildingElementProxy::
WaterPressure () const
{
return this->WaterPressure_;
}
SimBuildingElementProxy::WaterPressure_optional& SimBuildingElementProxy::
WaterPressure ()
{
return this->WaterPressure_;
}
void SimBuildingElementProxy::
WaterPressure (const WaterPressure_type& x)
{
this->WaterPressure_.set (x);
}
void SimBuildingElementProxy::
WaterPressure (const WaterPressure_optional& x)
{
this->WaterPressure_ = x;
}
const SimBuildingElementProxy::Width1_optional& SimBuildingElementProxy::
Width1 () const
{
return this->Width1_;
}
SimBuildingElementProxy::Width1_optional& SimBuildingElementProxy::
Width1 ()
{
return this->Width1_;
}
void SimBuildingElementProxy::
Width1 (const Width1_type& x)
{
this->Width1_.set (x);
}
void SimBuildingElementProxy::
Width1 (const Width1_optional& x)
{
this->Width1_ = x;
}
const SimBuildingElementProxy::Width2_optional& SimBuildingElementProxy::
Width2 () const
{
return this->Width2_;
}
SimBuildingElementProxy::Width2_optional& SimBuildingElementProxy::
Width2 ()
{
return this->Width2_;
}
void SimBuildingElementProxy::
Width2 (const Width2_type& x)
{
this->Width2_.set (x);
}
void SimBuildingElementProxy::
Width2 (const Width2_optional& x)
{
this->Width2_ = x;
}
const SimBuildingElementProxy::Width3_optional& SimBuildingElementProxy::
Width3 () const
{
return this->Width3_;
}
SimBuildingElementProxy::Width3_optional& SimBuildingElementProxy::
Width3 ()
{
return this->Width3_;
}
void SimBuildingElementProxy::
Width3 (const Width3_type& x)
{
this->Width3_.set (x);
}
void SimBuildingElementProxy::
Width3 (const Width3_optional& x)
{
this->Width3_ = x;
}
const SimBuildingElementProxy::Width4_optional& SimBuildingElementProxy::
Width4 () const
{
return this->Width4_;
}
SimBuildingElementProxy::Width4_optional& SimBuildingElementProxy::
Width4 ()
{
return this->Width4_;
}
void SimBuildingElementProxy::
Width4 (const Width4_type& x)
{
this->Width4_.set (x);
}
void SimBuildingElementProxy::
Width4 (const Width4_optional& x)
{
this->Width4_ = x;
}
const SimBuildingElementProxy::Width5_optional& SimBuildingElementProxy::
Width5 () const
{
return this->Width5_;
}
SimBuildingElementProxy::Width5_optional& SimBuildingElementProxy::
Width5 ()
{
return this->Width5_;
}
void SimBuildingElementProxy::
Width5 (const Width5_type& x)
{
this->Width5_.set (x);
}
void SimBuildingElementProxy::
Width5 (const Width5_optional& x)
{
this->Width5_ = x;
}
const SimBuildingElementProxy::Width6_optional& SimBuildingElementProxy::
Width6 () const
{
return this->Width6_;
}
SimBuildingElementProxy::Width6_optional& SimBuildingElementProxy::
Width6 ()
{
return this->Width6_;
}
void SimBuildingElementProxy::
Width6 (const Width6_type& x)
{
this->Width6_.set (x);
}
void SimBuildingElementProxy::
Width6 (const Width6_optional& x)
{
this->Width6_ = x;
}
const SimBuildingElementProxy::Width7_optional& SimBuildingElementProxy::
Width7 () const
{
return this->Width7_;
}
SimBuildingElementProxy::Width7_optional& SimBuildingElementProxy::
Width7 ()
{
return this->Width7_;
}
void SimBuildingElementProxy::
Width7 (const Width7_type& x)
{
this->Width7_.set (x);
}
void SimBuildingElementProxy::
Width7 (const Width7_optional& x)
{
this->Width7_ = x;
}
}
}
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
}
namespace schema
{
namespace simxml
{
namespace BuildingModel
{
// SimBuildingElementProxy
//
SimBuildingElementProxy::
SimBuildingElementProxy ()
: ::schema::simxml::SimModelCore::SimBuildingElement (),
Name_ (this),
Representation_ (this),
CompositionType_ (this),
AHUHeight_ (this),
AHUWidth_ (this),
AirFlow_ (this),
AirflowReturn_ (this),
AirflowSupply_ (this),
AirPressure_ (this),
AirwayLength_ (this),
AlternatorVoltage_ (this),
Ang_ (this),
ApparentLoad_ (this),
ApparentLoadPhaseA_ (this),
ApparentLoadPhaseB_ (this),
ApparentLoadPhaseC_ (this),
AverageSolarTransmittance_ (this),
AverageVisibleTransmittance_ (this),
Azimuth_ (this),
BaseHeight_ (this),
BaseLength_ (this),
Buildingstoreyname_ (this),
C1Offset1_ (this),
C1Offset2_ (this),
C2Offset1_ (this),
C2Offset2_ (this),
C3Offset1_ (this),
C4Offset2_ (this),
C5Offset1_ (this),
C5Offset2_ (this),
C6Offset1_ (this),
C6Offset2_ (this),
ChilledWaterFlow_ (this),
ChilledWaterPressureDrop_ (this),
CircuitNaming_ (this),
Color_ (this),
Connectionoffset_ (this),
ContainerName_ (this),
ContainerType_ (this),
CoolAirFlow_ (this),
CoolAirInletDiameter_ (this),
CoolAirInletRadius_ (this),
CoolAirPressureDrop_ (this),
CoolingCoilInletRadius_ (this),
CoolingCoilOutletRadius_ (this),
CoolingWaterDiameter_ (this),
CoolingWaterFlow_ (this),
CoolingWaterPressureDrop_ (this),
CoolingWaterRadius_ (this),
Diameter1_ (this),
Distance_ (this),
Distance1_ (this),
Distance2_ (this),
DrainFlow_ (this),
DrainOffset1_ (this),
DrainRadius_ (this),
DuctHeight_ (this),
DuctWidth_ (this),
ElectricalCircuitName_ (this),
ElectricalData_ (this),
Enclosure_ (this),
ExternalStaticPressure_ (this),
ExternalTotalPressure_ (this),
FanAirFlow_ (this),
FanDiameter_ (this),
FanRadius_ (this),
GeneratorHeight_ (this),
GeneratorLength_ (this),
GeneratorWidth_ (this),
GroupName_ (this),
HalfAirOutletHeight_ (this),
HalfAirOutletWidth_ (this),
HalfOverallHeight_ (this),
HalfOverallWidth_ (this),
HalfWidth4_ (this),
HeatAirFlow_ (this),
HeatAirInletDiameter_ (this),
HeatAirInletRadius_ (this),
HeatAirPressureDrop_ (this),
HeatLoss_ (this),
HeatingCoilInletRadius_ (this),
HeatingCoilOutletRadius_ (this),
Height1_ (this),
Height2_ (this),
Height3_ (this),
Height4_ (this),
Height5_ (this),
Height6_ (this),
Height7_ (this),
Height8_ (this),
Height9_ (this),
Host_ (this),
HotWaterFlow_ (this),
HotWaterPressureDrop_ (this),
Inclination_ (this),
InletDiameter_ (this),
InletRadius_ (this),
Length1_ (this),
Length2_ (this),
Length3_ (this),
Length4_ (this),
Length5_ (this),
Length6_ (this),
Length7_ (this),
Length8_ (this),
Length9_ (this),
Length10_ (this),
Length11_ (this),
Length12_ (this),
Length13_ (this),
Level_ (this),
LoadClassification_ (this),
MakeUpWaterFlow_ (this),
MakeUpWaterPressureDrop_ (this),
MakeUpWaterRadius_ (this),
ManufacturerArticleNumber_ (this),
ManufacturerModelName_ (this),
ManufacturerModelNumber_ (this),
ManufacturerName_ (this),
ManufacturerYearofProduction_ (this),
Mark_ (this),
Material_ (this),
Max1PoleBreakers_ (this),
MaxFlow_ (this),
MinFlow_ (this),
Model_ (this),
MotorHP_ (this),
NumberOfFans_ (this),
NumberOfPoles_ (this),
ObjectClassName_ (this),
Offset_ (this),
OmniclassNumber_ (this),
OmniclassTitle_ (this),
OutletDiameter_ (this),
OutletRadius_ (this),
OverallHeight_ (this),
OverallLength_ (this),
OverallWidth_ (this),
PanelHeight_ (this),
Partshape_ (this),
PhaseCreated_ (this),
PipeRadius_ (this),
PrimaryNumberofPoles_ (this),
PrimaryVoltage_ (this),
PumpHeight_ (this),
PumpLength_ (this),
PumpWidth_ (this),
Radius1_ (this),
Radius2_ (this),
Radius3_ (this),
Radius4_ (this),
Radius5_ (this),
Radius6_ (this),
Reference_ (this),
Reflectance_ (this),
ReturnAirInletFlow_ (this),
ReturnAirInletHeight_ (this),
ReturnAirInletWidth_ (this),
ReturnDuctHeight_ (this),
ReturnDuctWidth_ (this),
Returnheight_ (this),
Returnwidth_ (this),
ReturnY_Offset_ (this),
ReturnZ_Offset_ (this),
Roughness_ (this),
ShadingDeviceType_ (this),
SupplyAirInletDiameter_ (this),
SupplyAirInletFlow_ (this),
SupplyAirInletHeight_ (this),
SupplyAirInletRadius_ (this),
SupplyAirInletWidth_ (this),
SupplyAirOutletFlow_ (this),
SupplyAirOutletHeight_ (this),
SupplyAirOutletWidth_ (this),
SupplyAirPressureDrop_ (this),
SupplyDuctHeight_ (this),
SupplyDuctWidth_ (this),
Supplyheight_ (this),
Supplywidth_ (this),
Supply_ReturnSymbols_ (this),
SupplyY_Offset_ (this),
SupplyZ_Offset_ (this),
SystemClassification_ (this),
SystemName_ (this),
TiltRange_ (this),
TotalConnected_ (this),
TotalDemandFactor_ (this),
TotalEstimatedDemand_ (this),
TowerHeight_ (this),
TowerLength_ (this),
TowerWidth_ (this),
TransformerHeight_ (this),
TransformerLength_ (this),
TransformerWidth_ (this),
UniformatClassification_ (this),
Unitdepth_ (this),
UnitHeight_ (this),
UnitLength_ (this),
UnitWidth_ (this),
Visible1_ (this),
Visible2_ (this),
Voltage_ (this),
WaterFlow_ (this),
WaterPressure_ (this),
Width1_ (this),
Width2_ (this),
Width3_ (this),
Width4_ (this),
Width5_ (this),
Width6_ (this),
Width7_ (this)
{
}
SimBuildingElementProxy::
SimBuildingElementProxy (const RefId_type& RefId)
: ::schema::simxml::SimModelCore::SimBuildingElement (RefId),
Name_ (this),
Representation_ (this),
CompositionType_ (this),
AHUHeight_ (this),
AHUWidth_ (this),
AirFlow_ (this),
AirflowReturn_ (this),
AirflowSupply_ (this),
AirPressure_ (this),
AirwayLength_ (this),
AlternatorVoltage_ (this),
Ang_ (this),
ApparentLoad_ (this),
ApparentLoadPhaseA_ (this),
ApparentLoadPhaseB_ (this),
ApparentLoadPhaseC_ (this),
AverageSolarTransmittance_ (this),
AverageVisibleTransmittance_ (this),
Azimuth_ (this),
BaseHeight_ (this),
BaseLength_ (this),
Buildingstoreyname_ (this),
C1Offset1_ (this),
C1Offset2_ (this),
C2Offset1_ (this),
C2Offset2_ (this),
C3Offset1_ (this),
C4Offset2_ (this),
C5Offset1_ (this),
C5Offset2_ (this),
C6Offset1_ (this),
C6Offset2_ (this),
ChilledWaterFlow_ (this),
ChilledWaterPressureDrop_ (this),
CircuitNaming_ (this),
Color_ (this),
Connectionoffset_ (this),
ContainerName_ (this),
ContainerType_ (this),
CoolAirFlow_ (this),
CoolAirInletDiameter_ (this),
CoolAirInletRadius_ (this),
CoolAirPressureDrop_ (this),
CoolingCoilInletRadius_ (this),
CoolingCoilOutletRadius_ (this),
CoolingWaterDiameter_ (this),
CoolingWaterFlow_ (this),
CoolingWaterPressureDrop_ (this),
CoolingWaterRadius_ (this),
Diameter1_ (this),
Distance_ (this),
Distance1_ (this),
Distance2_ (this),
DrainFlow_ (this),
DrainOffset1_ (this),
DrainRadius_ (this),
DuctHeight_ (this),
DuctWidth_ (this),
ElectricalCircuitName_ (this),
ElectricalData_ (this),
Enclosure_ (this),
ExternalStaticPressure_ (this),
ExternalTotalPressure_ (this),
FanAirFlow_ (this),
FanDiameter_ (this),
FanRadius_ (this),
GeneratorHeight_ (this),
GeneratorLength_ (this),
GeneratorWidth_ (this),
GroupName_ (this),
HalfAirOutletHeight_ (this),
HalfAirOutletWidth_ (this),
HalfOverallHeight_ (this),
HalfOverallWidth_ (this),
HalfWidth4_ (this),
HeatAirFlow_ (this),
HeatAirInletDiameter_ (this),
HeatAirInletRadius_ (this),
HeatAirPressureDrop_ (this),
HeatLoss_ (this),
HeatingCoilInletRadius_ (this),
HeatingCoilOutletRadius_ (this),
Height1_ (this),
Height2_ (this),
Height3_ (this),
Height4_ (this),
Height5_ (this),
Height6_ (this),
Height7_ (this),
Height8_ (this),
Height9_ (this),
Host_ (this),
HotWaterFlow_ (this),
HotWaterPressureDrop_ (this),
Inclination_ (this),
InletDiameter_ (this),
InletRadius_ (this),
Length1_ (this),
Length2_ (this),
Length3_ (this),
Length4_ (this),
Length5_ (this),
Length6_ (this),
Length7_ (this),
Length8_ (this),
Length9_ (this),
Length10_ (this),
Length11_ (this),
Length12_ (this),
Length13_ (this),
Level_ (this),
LoadClassification_ (this),
MakeUpWaterFlow_ (this),
MakeUpWaterPressureDrop_ (this),
MakeUpWaterRadius_ (this),
ManufacturerArticleNumber_ (this),
ManufacturerModelName_ (this),
ManufacturerModelNumber_ (this),
ManufacturerName_ (this),
ManufacturerYearofProduction_ (this),
Mark_ (this),
Material_ (this),
Max1PoleBreakers_ (this),
MaxFlow_ (this),
MinFlow_ (this),
Model_ (this),
MotorHP_ (this),
NumberOfFans_ (this),
NumberOfPoles_ (this),
ObjectClassName_ (this),
Offset_ (this),
OmniclassNumber_ (this),
OmniclassTitle_ (this),
OutletDiameter_ (this),
OutletRadius_ (this),
OverallHeight_ (this),
OverallLength_ (this),
OverallWidth_ (this),
PanelHeight_ (this),
Partshape_ (this),
PhaseCreated_ (this),
PipeRadius_ (this),
PrimaryNumberofPoles_ (this),
PrimaryVoltage_ (this),
PumpHeight_ (this),
PumpLength_ (this),
PumpWidth_ (this),
Radius1_ (this),
Radius2_ (this),
Radius3_ (this),
Radius4_ (this),
Radius5_ (this),
Radius6_ (this),
Reference_ (this),
Reflectance_ (this),
ReturnAirInletFlow_ (this),
ReturnAirInletHeight_ (this),
ReturnAirInletWidth_ (this),
ReturnDuctHeight_ (this),
ReturnDuctWidth_ (this),
Returnheight_ (this),
Returnwidth_ (this),
ReturnY_Offset_ (this),
ReturnZ_Offset_ (this),
Roughness_ (this),
ShadingDeviceType_ (this),
SupplyAirInletDiameter_ (this),
SupplyAirInletFlow_ (this),
SupplyAirInletHeight_ (this),
SupplyAirInletRadius_ (this),
SupplyAirInletWidth_ (this),
SupplyAirOutletFlow_ (this),
SupplyAirOutletHeight_ (this),
SupplyAirOutletWidth_ (this),
SupplyAirPressureDrop_ (this),
SupplyDuctHeight_ (this),
SupplyDuctWidth_ (this),
Supplyheight_ (this),
Supplywidth_ (this),
Supply_ReturnSymbols_ (this),
SupplyY_Offset_ (this),
SupplyZ_Offset_ (this),
SystemClassification_ (this),
SystemName_ (this),
TiltRange_ (this),
TotalConnected_ (this),
TotalDemandFactor_ (this),
TotalEstimatedDemand_ (this),
TowerHeight_ (this),
TowerLength_ (this),
TowerWidth_ (this),
TransformerHeight_ (this),
TransformerLength_ (this),
TransformerWidth_ (this),
UniformatClassification_ (this),
Unitdepth_ (this),
UnitHeight_ (this),
UnitLength_ (this),
UnitWidth_ (this),
Visible1_ (this),
Visible2_ (this),
Voltage_ (this),
WaterFlow_ (this),
WaterPressure_ (this),
Width1_ (this),
Width2_ (this),
Width3_ (this),
Width4_ (this),
Width5_ (this),
Width6_ (this),
Width7_ (this)
{
}
SimBuildingElementProxy::
SimBuildingElementProxy (const SimBuildingElementProxy& x,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::SimModelCore::SimBuildingElement (x, f, c),
Name_ (x.Name_, f, this),
Representation_ (x.Representation_, f, this),
CompositionType_ (x.CompositionType_, f, this),
AHUHeight_ (x.AHUHeight_, f, this),
AHUWidth_ (x.AHUWidth_, f, this),
AirFlow_ (x.AirFlow_, f, this),
AirflowReturn_ (x.AirflowReturn_, f, this),
AirflowSupply_ (x.AirflowSupply_, f, this),
AirPressure_ (x.AirPressure_, f, this),
AirwayLength_ (x.AirwayLength_, f, this),
AlternatorVoltage_ (x.AlternatorVoltage_, f, this),
Ang_ (x.Ang_, f, this),
ApparentLoad_ (x.ApparentLoad_, f, this),
ApparentLoadPhaseA_ (x.ApparentLoadPhaseA_, f, this),
ApparentLoadPhaseB_ (x.ApparentLoadPhaseB_, f, this),
ApparentLoadPhaseC_ (x.ApparentLoadPhaseC_, f, this),
AverageSolarTransmittance_ (x.AverageSolarTransmittance_, f, this),
AverageVisibleTransmittance_ (x.AverageVisibleTransmittance_, f, this),
Azimuth_ (x.Azimuth_, f, this),
BaseHeight_ (x.BaseHeight_, f, this),
BaseLength_ (x.BaseLength_, f, this),
Buildingstoreyname_ (x.Buildingstoreyname_, f, this),
C1Offset1_ (x.C1Offset1_, f, this),
C1Offset2_ (x.C1Offset2_, f, this),
C2Offset1_ (x.C2Offset1_, f, this),
C2Offset2_ (x.C2Offset2_, f, this),
C3Offset1_ (x.C3Offset1_, f, this),
C4Offset2_ (x.C4Offset2_, f, this),
C5Offset1_ (x.C5Offset1_, f, this),
C5Offset2_ (x.C5Offset2_, f, this),
C6Offset1_ (x.C6Offset1_, f, this),
C6Offset2_ (x.C6Offset2_, f, this),
ChilledWaterFlow_ (x.ChilledWaterFlow_, f, this),
ChilledWaterPressureDrop_ (x.ChilledWaterPressureDrop_, f, this),
CircuitNaming_ (x.CircuitNaming_, f, this),
Color_ (x.Color_, f, this),
Connectionoffset_ (x.Connectionoffset_, f, this),
ContainerName_ (x.ContainerName_, f, this),
ContainerType_ (x.ContainerType_, f, this),
CoolAirFlow_ (x.CoolAirFlow_, f, this),
CoolAirInletDiameter_ (x.CoolAirInletDiameter_, f, this),
CoolAirInletRadius_ (x.CoolAirInletRadius_, f, this),
CoolAirPressureDrop_ (x.CoolAirPressureDrop_, f, this),
CoolingCoilInletRadius_ (x.CoolingCoilInletRadius_, f, this),
CoolingCoilOutletRadius_ (x.CoolingCoilOutletRadius_, f, this),
CoolingWaterDiameter_ (x.CoolingWaterDiameter_, f, this),
CoolingWaterFlow_ (x.CoolingWaterFlow_, f, this),
CoolingWaterPressureDrop_ (x.CoolingWaterPressureDrop_, f, this),
CoolingWaterRadius_ (x.CoolingWaterRadius_, f, this),
Diameter1_ (x.Diameter1_, f, this),
Distance_ (x.Distance_, f, this),
Distance1_ (x.Distance1_, f, this),
Distance2_ (x.Distance2_, f, this),
DrainFlow_ (x.DrainFlow_, f, this),
DrainOffset1_ (x.DrainOffset1_, f, this),
DrainRadius_ (x.DrainRadius_, f, this),
DuctHeight_ (x.DuctHeight_, f, this),
DuctWidth_ (x.DuctWidth_, f, this),
ElectricalCircuitName_ (x.ElectricalCircuitName_, f, this),
ElectricalData_ (x.ElectricalData_, f, this),
Enclosure_ (x.Enclosure_, f, this),
ExternalStaticPressure_ (x.ExternalStaticPressure_, f, this),
ExternalTotalPressure_ (x.ExternalTotalPressure_, f, this),
FanAirFlow_ (x.FanAirFlow_, f, this),
FanDiameter_ (x.FanDiameter_, f, this),
FanRadius_ (x.FanRadius_, f, this),
GeneratorHeight_ (x.GeneratorHeight_, f, this),
GeneratorLength_ (x.GeneratorLength_, f, this),
GeneratorWidth_ (x.GeneratorWidth_, f, this),
GroupName_ (x.GroupName_, f, this),
HalfAirOutletHeight_ (x.HalfAirOutletHeight_, f, this),
HalfAirOutletWidth_ (x.HalfAirOutletWidth_, f, this),
HalfOverallHeight_ (x.HalfOverallHeight_, f, this),
HalfOverallWidth_ (x.HalfOverallWidth_, f, this),
HalfWidth4_ (x.HalfWidth4_, f, this),
HeatAirFlow_ (x.HeatAirFlow_, f, this),
HeatAirInletDiameter_ (x.HeatAirInletDiameter_, f, this),
HeatAirInletRadius_ (x.HeatAirInletRadius_, f, this),
HeatAirPressureDrop_ (x.HeatAirPressureDrop_, f, this),
HeatLoss_ (x.HeatLoss_, f, this),
HeatingCoilInletRadius_ (x.HeatingCoilInletRadius_, f, this),
HeatingCoilOutletRadius_ (x.HeatingCoilOutletRadius_, f, this),
Height1_ (x.Height1_, f, this),
Height2_ (x.Height2_, f, this),
Height3_ (x.Height3_, f, this),
Height4_ (x.Height4_, f, this),
Height5_ (x.Height5_, f, this),
Height6_ (x.Height6_, f, this),
Height7_ (x.Height7_, f, this),
Height8_ (x.Height8_, f, this),
Height9_ (x.Height9_, f, this),
Host_ (x.Host_, f, this),
HotWaterFlow_ (x.HotWaterFlow_, f, this),
HotWaterPressureDrop_ (x.HotWaterPressureDrop_, f, this),
Inclination_ (x.Inclination_, f, this),
InletDiameter_ (x.InletDiameter_, f, this),
InletRadius_ (x.InletRadius_, f, this),
Length1_ (x.Length1_, f, this),
Length2_ (x.Length2_, f, this),
Length3_ (x.Length3_, f, this),
Length4_ (x.Length4_, f, this),
Length5_ (x.Length5_, f, this),
Length6_ (x.Length6_, f, this),
Length7_ (x.Length7_, f, this),
Length8_ (x.Length8_, f, this),
Length9_ (x.Length9_, f, this),
Length10_ (x.Length10_, f, this),
Length11_ (x.Length11_, f, this),
Length12_ (x.Length12_, f, this),
Length13_ (x.Length13_, f, this),
Level_ (x.Level_, f, this),
LoadClassification_ (x.LoadClassification_, f, this),
MakeUpWaterFlow_ (x.MakeUpWaterFlow_, f, this),
MakeUpWaterPressureDrop_ (x.MakeUpWaterPressureDrop_, f, this),
MakeUpWaterRadius_ (x.MakeUpWaterRadius_, f, this),
ManufacturerArticleNumber_ (x.ManufacturerArticleNumber_, f, this),
ManufacturerModelName_ (x.ManufacturerModelName_, f, this),
ManufacturerModelNumber_ (x.ManufacturerModelNumber_, f, this),
ManufacturerName_ (x.ManufacturerName_, f, this),
ManufacturerYearofProduction_ (x.ManufacturerYearofProduction_, f, this),
Mark_ (x.Mark_, f, this),
Material_ (x.Material_, f, this),
Max1PoleBreakers_ (x.Max1PoleBreakers_, f, this),
MaxFlow_ (x.MaxFlow_, f, this),
MinFlow_ (x.MinFlow_, f, this),
Model_ (x.Model_, f, this),
MotorHP_ (x.MotorHP_, f, this),
NumberOfFans_ (x.NumberOfFans_, f, this),
NumberOfPoles_ (x.NumberOfPoles_, f, this),
ObjectClassName_ (x.ObjectClassName_, f, this),
Offset_ (x.Offset_, f, this),
OmniclassNumber_ (x.OmniclassNumber_, f, this),
OmniclassTitle_ (x.OmniclassTitle_, f, this),
OutletDiameter_ (x.OutletDiameter_, f, this),
OutletRadius_ (x.OutletRadius_, f, this),
OverallHeight_ (x.OverallHeight_, f, this),
OverallLength_ (x.OverallLength_, f, this),
OverallWidth_ (x.OverallWidth_, f, this),
PanelHeight_ (x.PanelHeight_, f, this),
Partshape_ (x.Partshape_, f, this),
PhaseCreated_ (x.PhaseCreated_, f, this),
PipeRadius_ (x.PipeRadius_, f, this),
PrimaryNumberofPoles_ (x.PrimaryNumberofPoles_, f, this),
PrimaryVoltage_ (x.PrimaryVoltage_, f, this),
PumpHeight_ (x.PumpHeight_, f, this),
PumpLength_ (x.PumpLength_, f, this),
PumpWidth_ (x.PumpWidth_, f, this),
Radius1_ (x.Radius1_, f, this),
Radius2_ (x.Radius2_, f, this),
Radius3_ (x.Radius3_, f, this),
Radius4_ (x.Radius4_, f, this),
Radius5_ (x.Radius5_, f, this),
Radius6_ (x.Radius6_, f, this),
Reference_ (x.Reference_, f, this),
Reflectance_ (x.Reflectance_, f, this),
ReturnAirInletFlow_ (x.ReturnAirInletFlow_, f, this),
ReturnAirInletHeight_ (x.ReturnAirInletHeight_, f, this),
ReturnAirInletWidth_ (x.ReturnAirInletWidth_, f, this),
ReturnDuctHeight_ (x.ReturnDuctHeight_, f, this),
ReturnDuctWidth_ (x.ReturnDuctWidth_, f, this),
Returnheight_ (x.Returnheight_, f, this),
Returnwidth_ (x.Returnwidth_, f, this),
ReturnY_Offset_ (x.ReturnY_Offset_, f, this),
ReturnZ_Offset_ (x.ReturnZ_Offset_, f, this),
Roughness_ (x.Roughness_, f, this),
ShadingDeviceType_ (x.ShadingDeviceType_, f, this),
SupplyAirInletDiameter_ (x.SupplyAirInletDiameter_, f, this),
SupplyAirInletFlow_ (x.SupplyAirInletFlow_, f, this),
SupplyAirInletHeight_ (x.SupplyAirInletHeight_, f, this),
SupplyAirInletRadius_ (x.SupplyAirInletRadius_, f, this),
SupplyAirInletWidth_ (x.SupplyAirInletWidth_, f, this),
SupplyAirOutletFlow_ (x.SupplyAirOutletFlow_, f, this),
SupplyAirOutletHeight_ (x.SupplyAirOutletHeight_, f, this),
SupplyAirOutletWidth_ (x.SupplyAirOutletWidth_, f, this),
SupplyAirPressureDrop_ (x.SupplyAirPressureDrop_, f, this),
SupplyDuctHeight_ (x.SupplyDuctHeight_, f, this),
SupplyDuctWidth_ (x.SupplyDuctWidth_, f, this),
Supplyheight_ (x.Supplyheight_, f, this),
Supplywidth_ (x.Supplywidth_, f, this),
Supply_ReturnSymbols_ (x.Supply_ReturnSymbols_, f, this),
SupplyY_Offset_ (x.SupplyY_Offset_, f, this),
SupplyZ_Offset_ (x.SupplyZ_Offset_, f, this),
SystemClassification_ (x.SystemClassification_, f, this),
SystemName_ (x.SystemName_, f, this),
TiltRange_ (x.TiltRange_, f, this),
TotalConnected_ (x.TotalConnected_, f, this),
TotalDemandFactor_ (x.TotalDemandFactor_, f, this),
TotalEstimatedDemand_ (x.TotalEstimatedDemand_, f, this),
TowerHeight_ (x.TowerHeight_, f, this),
TowerLength_ (x.TowerLength_, f, this),
TowerWidth_ (x.TowerWidth_, f, this),
TransformerHeight_ (x.TransformerHeight_, f, this),
TransformerLength_ (x.TransformerLength_, f, this),
TransformerWidth_ (x.TransformerWidth_, f, this),
UniformatClassification_ (x.UniformatClassification_, f, this),
Unitdepth_ (x.Unitdepth_, f, this),
UnitHeight_ (x.UnitHeight_, f, this),
UnitLength_ (x.UnitLength_, f, this),
UnitWidth_ (x.UnitWidth_, f, this),
Visible1_ (x.Visible1_, f, this),
Visible2_ (x.Visible2_, f, this),
Voltage_ (x.Voltage_, f, this),
WaterFlow_ (x.WaterFlow_, f, this),
WaterPressure_ (x.WaterPressure_, f, this),
Width1_ (x.Width1_, f, this),
Width2_ (x.Width2_, f, this),
Width3_ (x.Width3_, f, this),
Width4_ (x.Width4_, f, this),
Width5_ (x.Width5_, f, this),
Width6_ (x.Width6_, f, this),
Width7_ (x.Width7_, f, this)
{
}
SimBuildingElementProxy::
SimBuildingElementProxy (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::SimModelCore::SimBuildingElement (e, f | ::xml_schema::flags::base, c),
Name_ (this),
Representation_ (this),
CompositionType_ (this),
AHUHeight_ (this),
AHUWidth_ (this),
AirFlow_ (this),
AirflowReturn_ (this),
AirflowSupply_ (this),
AirPressure_ (this),
AirwayLength_ (this),
AlternatorVoltage_ (this),
Ang_ (this),
ApparentLoad_ (this),
ApparentLoadPhaseA_ (this),
ApparentLoadPhaseB_ (this),
ApparentLoadPhaseC_ (this),
AverageSolarTransmittance_ (this),
AverageVisibleTransmittance_ (this),
Azimuth_ (this),
BaseHeight_ (this),
BaseLength_ (this),
Buildingstoreyname_ (this),
C1Offset1_ (this),
C1Offset2_ (this),
C2Offset1_ (this),
C2Offset2_ (this),
C3Offset1_ (this),
C4Offset2_ (this),
C5Offset1_ (this),
C5Offset2_ (this),
C6Offset1_ (this),
C6Offset2_ (this),
ChilledWaterFlow_ (this),
ChilledWaterPressureDrop_ (this),
CircuitNaming_ (this),
Color_ (this),
Connectionoffset_ (this),
ContainerName_ (this),
ContainerType_ (this),
CoolAirFlow_ (this),
CoolAirInletDiameter_ (this),
CoolAirInletRadius_ (this),
CoolAirPressureDrop_ (this),
CoolingCoilInletRadius_ (this),
CoolingCoilOutletRadius_ (this),
CoolingWaterDiameter_ (this),
CoolingWaterFlow_ (this),
CoolingWaterPressureDrop_ (this),
CoolingWaterRadius_ (this),
Diameter1_ (this),
Distance_ (this),
Distance1_ (this),
Distance2_ (this),
DrainFlow_ (this),
DrainOffset1_ (this),
DrainRadius_ (this),
DuctHeight_ (this),
DuctWidth_ (this),
ElectricalCircuitName_ (this),
ElectricalData_ (this),
Enclosure_ (this),
ExternalStaticPressure_ (this),
ExternalTotalPressure_ (this),
FanAirFlow_ (this),
FanDiameter_ (this),
FanRadius_ (this),
GeneratorHeight_ (this),
GeneratorLength_ (this),
GeneratorWidth_ (this),
GroupName_ (this),
HalfAirOutletHeight_ (this),
HalfAirOutletWidth_ (this),
HalfOverallHeight_ (this),
HalfOverallWidth_ (this),
HalfWidth4_ (this),
HeatAirFlow_ (this),
HeatAirInletDiameter_ (this),
HeatAirInletRadius_ (this),
HeatAirPressureDrop_ (this),
HeatLoss_ (this),
HeatingCoilInletRadius_ (this),
HeatingCoilOutletRadius_ (this),
Height1_ (this),
Height2_ (this),
Height3_ (this),
Height4_ (this),
Height5_ (this),
Height6_ (this),
Height7_ (this),
Height8_ (this),
Height9_ (this),
Host_ (this),
HotWaterFlow_ (this),
HotWaterPressureDrop_ (this),
Inclination_ (this),
InletDiameter_ (this),
InletRadius_ (this),
Length1_ (this),
Length2_ (this),
Length3_ (this),
Length4_ (this),
Length5_ (this),
Length6_ (this),
Length7_ (this),
Length8_ (this),
Length9_ (this),
Length10_ (this),
Length11_ (this),
Length12_ (this),
Length13_ (this),
Level_ (this),
LoadClassification_ (this),
MakeUpWaterFlow_ (this),
MakeUpWaterPressureDrop_ (this),
MakeUpWaterRadius_ (this),
ManufacturerArticleNumber_ (this),
ManufacturerModelName_ (this),
ManufacturerModelNumber_ (this),
ManufacturerName_ (this),
ManufacturerYearofProduction_ (this),
Mark_ (this),
Material_ (this),
Max1PoleBreakers_ (this),
MaxFlow_ (this),
MinFlow_ (this),
Model_ (this),
MotorHP_ (this),
NumberOfFans_ (this),
NumberOfPoles_ (this),
ObjectClassName_ (this),
Offset_ (this),
OmniclassNumber_ (this),
OmniclassTitle_ (this),
OutletDiameter_ (this),
OutletRadius_ (this),
OverallHeight_ (this),
OverallLength_ (this),
OverallWidth_ (this),
PanelHeight_ (this),
Partshape_ (this),
PhaseCreated_ (this),
PipeRadius_ (this),
PrimaryNumberofPoles_ (this),
PrimaryVoltage_ (this),
PumpHeight_ (this),
PumpLength_ (this),
PumpWidth_ (this),
Radius1_ (this),
Radius2_ (this),
Radius3_ (this),
Radius4_ (this),
Radius5_ (this),
Radius6_ (this),
Reference_ (this),
Reflectance_ (this),
ReturnAirInletFlow_ (this),
ReturnAirInletHeight_ (this),
ReturnAirInletWidth_ (this),
ReturnDuctHeight_ (this),
ReturnDuctWidth_ (this),
Returnheight_ (this),
Returnwidth_ (this),
ReturnY_Offset_ (this),
ReturnZ_Offset_ (this),
Roughness_ (this),
ShadingDeviceType_ (this),
SupplyAirInletDiameter_ (this),
SupplyAirInletFlow_ (this),
SupplyAirInletHeight_ (this),
SupplyAirInletRadius_ (this),
SupplyAirInletWidth_ (this),
SupplyAirOutletFlow_ (this),
SupplyAirOutletHeight_ (this),
SupplyAirOutletWidth_ (this),
SupplyAirPressureDrop_ (this),
SupplyDuctHeight_ (this),
SupplyDuctWidth_ (this),
Supplyheight_ (this),
Supplywidth_ (this),
Supply_ReturnSymbols_ (this),
SupplyY_Offset_ (this),
SupplyZ_Offset_ (this),
SystemClassification_ (this),
SystemName_ (this),
TiltRange_ (this),
TotalConnected_ (this),
TotalDemandFactor_ (this),
TotalEstimatedDemand_ (this),
TowerHeight_ (this),
TowerLength_ (this),
TowerWidth_ (this),
TransformerHeight_ (this),
TransformerLength_ (this),
TransformerWidth_ (this),
UniformatClassification_ (this),
Unitdepth_ (this),
UnitHeight_ (this),
UnitLength_ (this),
UnitWidth_ (this),
Visible1_ (this),
Visible2_ (this),
Voltage_ (this),
WaterFlow_ (this),
WaterPressure_ (this),
Width1_ (this),
Width2_ (this),
Width3_ (this),
Width4_ (this),
Width5_ (this),
Width6_ (this),
Width7_ (this)
{
if ((f & ::xml_schema::flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, true, false, true);
this->parse (p, f);
}
}
void SimBuildingElementProxy::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::flags f)
{
this->::schema::simxml::SimModelCore::SimBuildingElement::parse (p, f);
for (; p.more_content (); p.next_content (false))
{
const ::xercesc::DOMElement& i (p.cur_element ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
// Name
//
if (n.name () == "Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Name_type > r (
Name_traits::create (i, f, this));
if (!this->Name_)
{
this->Name_.set (r);
continue;
}
}
// Representation
//
if (n.name () == "Representation" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Representation_type > r (
Representation_traits::create (i, f, this));
if (!this->Representation_)
{
this->Representation_.set (r);
continue;
}
}
// CompositionType
//
if (n.name () == "CompositionType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< CompositionType_type > r (
CompositionType_traits::create (i, f, this));
if (!this->CompositionType_)
{
this->CompositionType_.set (r);
continue;
}
}
// AHUHeight
//
if (n.name () == "AHUHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AHUHeight_)
{
this->AHUHeight_.set (AHUHeight_traits::create (i, f, this));
continue;
}
}
// AHUWidth
//
if (n.name () == "AHUWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AHUWidth_)
{
this->AHUWidth_.set (AHUWidth_traits::create (i, f, this));
continue;
}
}
// AirFlow
//
if (n.name () == "AirFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AirFlow_)
{
this->AirFlow_.set (AirFlow_traits::create (i, f, this));
continue;
}
}
// AirflowReturn
//
if (n.name () == "AirflowReturn" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AirflowReturn_)
{
this->AirflowReturn_.set (AirflowReturn_traits::create (i, f, this));
continue;
}
}
// AirflowSupply
//
if (n.name () == "AirflowSupply" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AirflowSupply_)
{
this->AirflowSupply_.set (AirflowSupply_traits::create (i, f, this));
continue;
}
}
// AirPressure
//
if (n.name () == "AirPressure" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AirPressure_)
{
this->AirPressure_.set (AirPressure_traits::create (i, f, this));
continue;
}
}
// AirwayLength
//
if (n.name () == "AirwayLength" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AirwayLength_)
{
this->AirwayLength_.set (AirwayLength_traits::create (i, f, this));
continue;
}
}
// AlternatorVoltage
//
if (n.name () == "AlternatorVoltage" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AlternatorVoltage_)
{
this->AlternatorVoltage_.set (AlternatorVoltage_traits::create (i, f, this));
continue;
}
}
// Ang
//
if (n.name () == "Ang" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Ang_)
{
this->Ang_.set (Ang_traits::create (i, f, this));
continue;
}
}
// ApparentLoad
//
if (n.name () == "ApparentLoad" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ApparentLoad_)
{
this->ApparentLoad_.set (ApparentLoad_traits::create (i, f, this));
continue;
}
}
// ApparentLoadPhaseA
//
if (n.name () == "ApparentLoadPhaseA" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ApparentLoadPhaseA_)
{
this->ApparentLoadPhaseA_.set (ApparentLoadPhaseA_traits::create (i, f, this));
continue;
}
}
// ApparentLoadPhaseB
//
if (n.name () == "ApparentLoadPhaseB" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ApparentLoadPhaseB_)
{
this->ApparentLoadPhaseB_.set (ApparentLoadPhaseB_traits::create (i, f, this));
continue;
}
}
// ApparentLoadPhaseC
//
if (n.name () == "ApparentLoadPhaseC" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ApparentLoadPhaseC_)
{
this->ApparentLoadPhaseC_.set (ApparentLoadPhaseC_traits::create (i, f, this));
continue;
}
}
// AverageSolarTransmittance
//
if (n.name () == "AverageSolarTransmittance" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AverageSolarTransmittance_)
{
this->AverageSolarTransmittance_.set (AverageSolarTransmittance_traits::create (i, f, this));
continue;
}
}
// AverageVisibleTransmittance
//
if (n.name () == "AverageVisibleTransmittance" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->AverageVisibleTransmittance_)
{
this->AverageVisibleTransmittance_.set (AverageVisibleTransmittance_traits::create (i, f, this));
continue;
}
}
// Azimuth
//
if (n.name () == "Azimuth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Azimuth_)
{
this->Azimuth_.set (Azimuth_traits::create (i, f, this));
continue;
}
}
// BaseHeight
//
if (n.name () == "BaseHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->BaseHeight_)
{
this->BaseHeight_.set (BaseHeight_traits::create (i, f, this));
continue;
}
}
// BaseLength
//
if (n.name () == "BaseLength" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->BaseLength_)
{
this->BaseLength_.set (BaseLength_traits::create (i, f, this));
continue;
}
}
// Buildingstoreyname
//
if (n.name () == "Buildingstoreyname" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Buildingstoreyname_type > r (
Buildingstoreyname_traits::create (i, f, this));
if (!this->Buildingstoreyname_)
{
this->Buildingstoreyname_.set (r);
continue;
}
}
// C1Offset1
//
if (n.name () == "C1Offset1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C1Offset1_)
{
this->C1Offset1_.set (C1Offset1_traits::create (i, f, this));
continue;
}
}
// C1Offset2
//
if (n.name () == "C1Offset2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C1Offset2_)
{
this->C1Offset2_.set (C1Offset2_traits::create (i, f, this));
continue;
}
}
// C2Offset1
//
if (n.name () == "C2Offset1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C2Offset1_)
{
this->C2Offset1_.set (C2Offset1_traits::create (i, f, this));
continue;
}
}
// C2Offset2
//
if (n.name () == "C2Offset2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C2Offset2_)
{
this->C2Offset2_.set (C2Offset2_traits::create (i, f, this));
continue;
}
}
// C3Offset1
//
if (n.name () == "C3Offset1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C3Offset1_)
{
this->C3Offset1_.set (C3Offset1_traits::create (i, f, this));
continue;
}
}
// C4Offset2
//
if (n.name () == "C4Offset2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C4Offset2_)
{
this->C4Offset2_.set (C4Offset2_traits::create (i, f, this));
continue;
}
}
// C5Offset1
//
if (n.name () == "C5Offset1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C5Offset1_)
{
this->C5Offset1_.set (C5Offset1_traits::create (i, f, this));
continue;
}
}
// C5Offset2
//
if (n.name () == "C5Offset2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C5Offset2_)
{
this->C5Offset2_.set (C5Offset2_traits::create (i, f, this));
continue;
}
}
// C6Offset1
//
if (n.name () == "C6Offset1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C6Offset1_)
{
this->C6Offset1_.set (C6Offset1_traits::create (i, f, this));
continue;
}
}
// C6Offset2
//
if (n.name () == "C6Offset2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->C6Offset2_)
{
this->C6Offset2_.set (C6Offset2_traits::create (i, f, this));
continue;
}
}
// ChilledWaterFlow
//
if (n.name () == "ChilledWaterFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ChilledWaterFlow_)
{
this->ChilledWaterFlow_.set (ChilledWaterFlow_traits::create (i, f, this));
continue;
}
}
// ChilledWaterPressureDrop
//
if (n.name () == "ChilledWaterPressureDrop" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ChilledWaterPressureDrop_)
{
this->ChilledWaterPressureDrop_.set (ChilledWaterPressureDrop_traits::create (i, f, this));
continue;
}
}
// CircuitNaming
//
if (n.name () == "CircuitNaming" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< CircuitNaming_type > r (
CircuitNaming_traits::create (i, f, this));
if (!this->CircuitNaming_)
{
this->CircuitNaming_.set (r);
continue;
}
}
// Color
//
if (n.name () == "Color" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Color_type > r (
Color_traits::create (i, f, this));
if (!this->Color_)
{
this->Color_.set (r);
continue;
}
}
// Connectionoffset
//
if (n.name () == "Connectionoffset" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Connectionoffset_)
{
this->Connectionoffset_.set (Connectionoffset_traits::create (i, f, this));
continue;
}
}
// ContainerName
//
if (n.name () == "ContainerName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ContainerName_type > r (
ContainerName_traits::create (i, f, this));
if (!this->ContainerName_)
{
this->ContainerName_.set (r);
continue;
}
}
// ContainerType
//
if (n.name () == "ContainerType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ContainerType_type > r (
ContainerType_traits::create (i, f, this));
if (!this->ContainerType_)
{
this->ContainerType_.set (r);
continue;
}
}
// CoolAirFlow
//
if (n.name () == "CoolAirFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolAirFlow_)
{
this->CoolAirFlow_.set (CoolAirFlow_traits::create (i, f, this));
continue;
}
}
// CoolAirInletDiameter
//
if (n.name () == "CoolAirInletDiameter" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolAirInletDiameter_)
{
this->CoolAirInletDiameter_.set (CoolAirInletDiameter_traits::create (i, f, this));
continue;
}
}
// CoolAirInletRadius
//
if (n.name () == "CoolAirInletRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolAirInletRadius_)
{
this->CoolAirInletRadius_.set (CoolAirInletRadius_traits::create (i, f, this));
continue;
}
}
// CoolAirPressureDrop
//
if (n.name () == "CoolAirPressureDrop" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolAirPressureDrop_)
{
this->CoolAirPressureDrop_.set (CoolAirPressureDrop_traits::create (i, f, this));
continue;
}
}
// CoolingCoilInletRadius
//
if (n.name () == "CoolingCoilInletRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolingCoilInletRadius_)
{
this->CoolingCoilInletRadius_.set (CoolingCoilInletRadius_traits::create (i, f, this));
continue;
}
}
// CoolingCoilOutletRadius
//
if (n.name () == "CoolingCoilOutletRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolingCoilOutletRadius_)
{
this->CoolingCoilOutletRadius_.set (CoolingCoilOutletRadius_traits::create (i, f, this));
continue;
}
}
// CoolingWaterDiameter
//
if (n.name () == "CoolingWaterDiameter" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolingWaterDiameter_)
{
this->CoolingWaterDiameter_.set (CoolingWaterDiameter_traits::create (i, f, this));
continue;
}
}
// CoolingWaterFlow
//
if (n.name () == "CoolingWaterFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolingWaterFlow_)
{
this->CoolingWaterFlow_.set (CoolingWaterFlow_traits::create (i, f, this));
continue;
}
}
// CoolingWaterPressureDrop
//
if (n.name () == "CoolingWaterPressureDrop" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolingWaterPressureDrop_)
{
this->CoolingWaterPressureDrop_.set (CoolingWaterPressureDrop_traits::create (i, f, this));
continue;
}
}
// CoolingWaterRadius
//
if (n.name () == "CoolingWaterRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->CoolingWaterRadius_)
{
this->CoolingWaterRadius_.set (CoolingWaterRadius_traits::create (i, f, this));
continue;
}
}
// Diameter1
//
if (n.name () == "Diameter1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Diameter1_)
{
this->Diameter1_.set (Diameter1_traits::create (i, f, this));
continue;
}
}
// Distance
//
if (n.name () == "Distance" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Distance_)
{
this->Distance_.set (Distance_traits::create (i, f, this));
continue;
}
}
// Distance1
//
if (n.name () == "Distance1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Distance1_)
{
this->Distance1_.set (Distance1_traits::create (i, f, this));
continue;
}
}
// Distance2
//
if (n.name () == "Distance2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Distance2_)
{
this->Distance2_.set (Distance2_traits::create (i, f, this));
continue;
}
}
// DrainFlow
//
if (n.name () == "DrainFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->DrainFlow_)
{
this->DrainFlow_.set (DrainFlow_traits::create (i, f, this));
continue;
}
}
// DrainOffset1
//
if (n.name () == "DrainOffset1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->DrainOffset1_)
{
this->DrainOffset1_.set (DrainOffset1_traits::create (i, f, this));
continue;
}
}
// DrainRadius
//
if (n.name () == "DrainRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->DrainRadius_)
{
this->DrainRadius_.set (DrainRadius_traits::create (i, f, this));
continue;
}
}
// DuctHeight
//
if (n.name () == "DuctHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->DuctHeight_)
{
this->DuctHeight_.set (DuctHeight_traits::create (i, f, this));
continue;
}
}
// DuctWidth
//
if (n.name () == "DuctWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->DuctWidth_)
{
this->DuctWidth_.set (DuctWidth_traits::create (i, f, this));
continue;
}
}
// ElectricalCircuitName
//
if (n.name () == "ElectricalCircuitName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ElectricalCircuitName_type > r (
ElectricalCircuitName_traits::create (i, f, this));
if (!this->ElectricalCircuitName_)
{
this->ElectricalCircuitName_.set (r);
continue;
}
}
// ElectricalData
//
if (n.name () == "ElectricalData" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ElectricalData_type > r (
ElectricalData_traits::create (i, f, this));
if (!this->ElectricalData_)
{
this->ElectricalData_.set (r);
continue;
}
}
// Enclosure
//
if (n.name () == "Enclosure" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Enclosure_type > r (
Enclosure_traits::create (i, f, this));
if (!this->Enclosure_)
{
this->Enclosure_.set (r);
continue;
}
}
// ExternalStaticPressure
//
if (n.name () == "ExternalStaticPressure" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ExternalStaticPressure_)
{
this->ExternalStaticPressure_.set (ExternalStaticPressure_traits::create (i, f, this));
continue;
}
}
// ExternalTotalPressure
//
if (n.name () == "ExternalTotalPressure" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ExternalTotalPressure_)
{
this->ExternalTotalPressure_.set (ExternalTotalPressure_traits::create (i, f, this));
continue;
}
}
// FanAirFlow
//
if (n.name () == "FanAirFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->FanAirFlow_)
{
this->FanAirFlow_.set (FanAirFlow_traits::create (i, f, this));
continue;
}
}
// FanDiameter
//
if (n.name () == "FanDiameter" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->FanDiameter_)
{
this->FanDiameter_.set (FanDiameter_traits::create (i, f, this));
continue;
}
}
// FanRadius
//
if (n.name () == "FanRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->FanRadius_)
{
this->FanRadius_.set (FanRadius_traits::create (i, f, this));
continue;
}
}
// GeneratorHeight
//
if (n.name () == "GeneratorHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->GeneratorHeight_)
{
this->GeneratorHeight_.set (GeneratorHeight_traits::create (i, f, this));
continue;
}
}
// GeneratorLength
//
if (n.name () == "GeneratorLength" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->GeneratorLength_)
{
this->GeneratorLength_.set (GeneratorLength_traits::create (i, f, this));
continue;
}
}
// GeneratorWidth
//
if (n.name () == "GeneratorWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->GeneratorWidth_)
{
this->GeneratorWidth_.set (GeneratorWidth_traits::create (i, f, this));
continue;
}
}
// GroupName
//
if (n.name () == "GroupName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< GroupName_type > r (
GroupName_traits::create (i, f, this));
if (!this->GroupName_)
{
this->GroupName_.set (r);
continue;
}
}
// HalfAirOutletHeight
//
if (n.name () == "HalfAirOutletHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HalfAirOutletHeight_)
{
this->HalfAirOutletHeight_.set (HalfAirOutletHeight_traits::create (i, f, this));
continue;
}
}
// HalfAirOutletWidth
//
if (n.name () == "HalfAirOutletWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HalfAirOutletWidth_)
{
this->HalfAirOutletWidth_.set (HalfAirOutletWidth_traits::create (i, f, this));
continue;
}
}
// HalfOverallHeight
//
if (n.name () == "HalfOverallHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HalfOverallHeight_)
{
this->HalfOverallHeight_.set (HalfOverallHeight_traits::create (i, f, this));
continue;
}
}
// HalfOverallWidth
//
if (n.name () == "HalfOverallWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HalfOverallWidth_)
{
this->HalfOverallWidth_.set (HalfOverallWidth_traits::create (i, f, this));
continue;
}
}
// HalfWidth4
//
if (n.name () == "HalfWidth4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HalfWidth4_)
{
this->HalfWidth4_.set (HalfWidth4_traits::create (i, f, this));
continue;
}
}
// HeatAirFlow
//
if (n.name () == "HeatAirFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HeatAirFlow_)
{
this->HeatAirFlow_.set (HeatAirFlow_traits::create (i, f, this));
continue;
}
}
// HeatAirInletDiameter
//
if (n.name () == "HeatAirInletDiameter" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HeatAirInletDiameter_)
{
this->HeatAirInletDiameter_.set (HeatAirInletDiameter_traits::create (i, f, this));
continue;
}
}
// HeatAirInletRadius
//
if (n.name () == "HeatAirInletRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HeatAirInletRadius_)
{
this->HeatAirInletRadius_.set (HeatAirInletRadius_traits::create (i, f, this));
continue;
}
}
// HeatAirPressureDrop
//
if (n.name () == "HeatAirPressureDrop" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HeatAirPressureDrop_)
{
this->HeatAirPressureDrop_.set (HeatAirPressureDrop_traits::create (i, f, this));
continue;
}
}
// HeatLoss
//
if (n.name () == "HeatLoss" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HeatLoss_)
{
this->HeatLoss_.set (HeatLoss_traits::create (i, f, this));
continue;
}
}
// HeatingCoilInletRadius
//
if (n.name () == "HeatingCoilInletRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HeatingCoilInletRadius_)
{
this->HeatingCoilInletRadius_.set (HeatingCoilInletRadius_traits::create (i, f, this));
continue;
}
}
// HeatingCoilOutletRadius
//
if (n.name () == "HeatingCoilOutletRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HeatingCoilOutletRadius_)
{
this->HeatingCoilOutletRadius_.set (HeatingCoilOutletRadius_traits::create (i, f, this));
continue;
}
}
// Height1
//
if (n.name () == "Height1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Height1_)
{
this->Height1_.set (Height1_traits::create (i, f, this));
continue;
}
}
// Height2
//
if (n.name () == "Height2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Height2_)
{
this->Height2_.set (Height2_traits::create (i, f, this));
continue;
}
}
// Height3
//
if (n.name () == "Height3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Height3_)
{
this->Height3_.set (Height3_traits::create (i, f, this));
continue;
}
}
// Height4
//
if (n.name () == "Height4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Height4_)
{
this->Height4_.set (Height4_traits::create (i, f, this));
continue;
}
}
// Height5
//
if (n.name () == "Height5" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Height5_)
{
this->Height5_.set (Height5_traits::create (i, f, this));
continue;
}
}
// Height6
//
if (n.name () == "Height6" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Height6_)
{
this->Height6_.set (Height6_traits::create (i, f, this));
continue;
}
}
// Height7
//
if (n.name () == "Height7" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Height7_)
{
this->Height7_.set (Height7_traits::create (i, f, this));
continue;
}
}
// Height8
//
if (n.name () == "Height8" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Height8_)
{
this->Height8_.set (Height8_traits::create (i, f, this));
continue;
}
}
// Height9
//
if (n.name () == "Height9" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Height9_)
{
this->Height9_.set (Height9_traits::create (i, f, this));
continue;
}
}
// Host
//
if (n.name () == "Host" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Host_type > r (
Host_traits::create (i, f, this));
if (!this->Host_)
{
this->Host_.set (r);
continue;
}
}
// HotWaterFlow
//
if (n.name () == "HotWaterFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HotWaterFlow_)
{
this->HotWaterFlow_.set (HotWaterFlow_traits::create (i, f, this));
continue;
}
}
// HotWaterPressureDrop
//
if (n.name () == "HotWaterPressureDrop" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->HotWaterPressureDrop_)
{
this->HotWaterPressureDrop_.set (HotWaterPressureDrop_traits::create (i, f, this));
continue;
}
}
// Inclination
//
if (n.name () == "Inclination" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Inclination_)
{
this->Inclination_.set (Inclination_traits::create (i, f, this));
continue;
}
}
// InletDiameter
//
if (n.name () == "InletDiameter" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->InletDiameter_)
{
this->InletDiameter_.set (InletDiameter_traits::create (i, f, this));
continue;
}
}
// InletRadius
//
if (n.name () == "InletRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->InletRadius_)
{
this->InletRadius_.set (InletRadius_traits::create (i, f, this));
continue;
}
}
// Length1
//
if (n.name () == "Length1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length1_)
{
this->Length1_.set (Length1_traits::create (i, f, this));
continue;
}
}
// Length2
//
if (n.name () == "Length2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length2_)
{
this->Length2_.set (Length2_traits::create (i, f, this));
continue;
}
}
// Length3
//
if (n.name () == "Length3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length3_)
{
this->Length3_.set (Length3_traits::create (i, f, this));
continue;
}
}
// Length4
//
if (n.name () == "Length4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length4_)
{
this->Length4_.set (Length4_traits::create (i, f, this));
continue;
}
}
// Length5
//
if (n.name () == "Length5" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length5_)
{
this->Length5_.set (Length5_traits::create (i, f, this));
continue;
}
}
// Length6
//
if (n.name () == "Length6" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length6_)
{
this->Length6_.set (Length6_traits::create (i, f, this));
continue;
}
}
// Length7
//
if (n.name () == "Length7" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length7_)
{
this->Length7_.set (Length7_traits::create (i, f, this));
continue;
}
}
// Length8
//
if (n.name () == "Length8" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length8_)
{
this->Length8_.set (Length8_traits::create (i, f, this));
continue;
}
}
// Length9
//
if (n.name () == "Length9" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length9_)
{
this->Length9_.set (Length9_traits::create (i, f, this));
continue;
}
}
// Length10
//
if (n.name () == "Length10" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length10_)
{
this->Length10_.set (Length10_traits::create (i, f, this));
continue;
}
}
// Length11
//
if (n.name () == "Length11" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length11_)
{
this->Length11_.set (Length11_traits::create (i, f, this));
continue;
}
}
// Length12
//
if (n.name () == "Length12" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length12_)
{
this->Length12_.set (Length12_traits::create (i, f, this));
continue;
}
}
// Length13
//
if (n.name () == "Length13" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Length13_)
{
this->Length13_.set (Length13_traits::create (i, f, this));
continue;
}
}
// Level
//
if (n.name () == "Level" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Level_type > r (
Level_traits::create (i, f, this));
if (!this->Level_)
{
this->Level_.set (r);
continue;
}
}
// LoadClassification
//
if (n.name () == "LoadClassification" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< LoadClassification_type > r (
LoadClassification_traits::create (i, f, this));
if (!this->LoadClassification_)
{
this->LoadClassification_.set (r);
continue;
}
}
// MakeUpWaterFlow
//
if (n.name () == "MakeUpWaterFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->MakeUpWaterFlow_)
{
this->MakeUpWaterFlow_.set (MakeUpWaterFlow_traits::create (i, f, this));
continue;
}
}
// MakeUpWaterPressureDrop
//
if (n.name () == "MakeUpWaterPressureDrop" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->MakeUpWaterPressureDrop_)
{
this->MakeUpWaterPressureDrop_.set (MakeUpWaterPressureDrop_traits::create (i, f, this));
continue;
}
}
// MakeUpWaterRadius
//
if (n.name () == "MakeUpWaterRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->MakeUpWaterRadius_)
{
this->MakeUpWaterRadius_.set (MakeUpWaterRadius_traits::create (i, f, this));
continue;
}
}
// ManufacturerArticleNumber
//
if (n.name () == "ManufacturerArticleNumber" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ManufacturerArticleNumber_type > r (
ManufacturerArticleNumber_traits::create (i, f, this));
if (!this->ManufacturerArticleNumber_)
{
this->ManufacturerArticleNumber_.set (r);
continue;
}
}
// ManufacturerModelName
//
if (n.name () == "ManufacturerModelName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ManufacturerModelName_type > r (
ManufacturerModelName_traits::create (i, f, this));
if (!this->ManufacturerModelName_)
{
this->ManufacturerModelName_.set (r);
continue;
}
}
// ManufacturerModelNumber
//
if (n.name () == "ManufacturerModelNumber" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ManufacturerModelNumber_type > r (
ManufacturerModelNumber_traits::create (i, f, this));
if (!this->ManufacturerModelNumber_)
{
this->ManufacturerModelNumber_.set (r);
continue;
}
}
// ManufacturerName
//
if (n.name () == "ManufacturerName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ManufacturerName_type > r (
ManufacturerName_traits::create (i, f, this));
if (!this->ManufacturerName_)
{
this->ManufacturerName_.set (r);
continue;
}
}
// ManufacturerYearofProduction
//
if (n.name () == "ManufacturerYearofProduction" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ManufacturerYearofProduction_type > r (
ManufacturerYearofProduction_traits::create (i, f, this));
if (!this->ManufacturerYearofProduction_)
{
this->ManufacturerYearofProduction_.set (r);
continue;
}
}
// Mark
//
if (n.name () == "Mark" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Mark_type > r (
Mark_traits::create (i, f, this));
if (!this->Mark_)
{
this->Mark_.set (r);
continue;
}
}
// Material
//
if (n.name () == "Material" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Material_type > r (
Material_traits::create (i, f, this));
if (!this->Material_)
{
this->Material_.set (r);
continue;
}
}
// Max1PoleBreakers
//
if (n.name () == "Max1PoleBreakers" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Max1PoleBreakers_)
{
this->Max1PoleBreakers_.set (Max1PoleBreakers_traits::create (i, f, this));
continue;
}
}
// MaxFlow
//
if (n.name () == "MaxFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->MaxFlow_)
{
this->MaxFlow_.set (MaxFlow_traits::create (i, f, this));
continue;
}
}
// MinFlow
//
if (n.name () == "MinFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->MinFlow_)
{
this->MinFlow_.set (MinFlow_traits::create (i, f, this));
continue;
}
}
// Model
//
if (n.name () == "Model" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Model_type > r (
Model_traits::create (i, f, this));
if (!this->Model_)
{
this->Model_.set (r);
continue;
}
}
// MotorHP
//
if (n.name () == "MotorHP" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->MotorHP_)
{
this->MotorHP_.set (MotorHP_traits::create (i, f, this));
continue;
}
}
// NumberOfFans
//
if (n.name () == "NumberOfFans" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->NumberOfFans_)
{
this->NumberOfFans_.set (NumberOfFans_traits::create (i, f, this));
continue;
}
}
// NumberOfPoles
//
if (n.name () == "NumberOfPoles" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->NumberOfPoles_)
{
this->NumberOfPoles_.set (NumberOfPoles_traits::create (i, f, this));
continue;
}
}
// ObjectClassName
//
if (n.name () == "ObjectClassName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ObjectClassName_type > r (
ObjectClassName_traits::create (i, f, this));
if (!this->ObjectClassName_)
{
this->ObjectClassName_.set (r);
continue;
}
}
// Offset
//
if (n.name () == "Offset" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Offset_)
{
this->Offset_.set (Offset_traits::create (i, f, this));
continue;
}
}
// OmniclassNumber
//
if (n.name () == "OmniclassNumber" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< OmniclassNumber_type > r (
OmniclassNumber_traits::create (i, f, this));
if (!this->OmniclassNumber_)
{
this->OmniclassNumber_.set (r);
continue;
}
}
// OmniclassTitle
//
if (n.name () == "OmniclassTitle" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< OmniclassTitle_type > r (
OmniclassTitle_traits::create (i, f, this));
if (!this->OmniclassTitle_)
{
this->OmniclassTitle_.set (r);
continue;
}
}
// OutletDiameter
//
if (n.name () == "OutletDiameter" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->OutletDiameter_)
{
this->OutletDiameter_.set (OutletDiameter_traits::create (i, f, this));
continue;
}
}
// OutletRadius
//
if (n.name () == "OutletRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->OutletRadius_)
{
this->OutletRadius_.set (OutletRadius_traits::create (i, f, this));
continue;
}
}
// OverallHeight
//
if (n.name () == "OverallHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->OverallHeight_)
{
this->OverallHeight_.set (OverallHeight_traits::create (i, f, this));
continue;
}
}
// OverallLength
//
if (n.name () == "OverallLength" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->OverallLength_)
{
this->OverallLength_.set (OverallLength_traits::create (i, f, this));
continue;
}
}
// OverallWidth
//
if (n.name () == "OverallWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->OverallWidth_)
{
this->OverallWidth_.set (OverallWidth_traits::create (i, f, this));
continue;
}
}
// PanelHeight
//
if (n.name () == "PanelHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->PanelHeight_)
{
this->PanelHeight_.set (PanelHeight_traits::create (i, f, this));
continue;
}
}
// Partshape
//
if (n.name () == "Partshape" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Partshape_type > r (
Partshape_traits::create (i, f, this));
if (!this->Partshape_)
{
this->Partshape_.set (r);
continue;
}
}
// PhaseCreated
//
if (n.name () == "PhaseCreated" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< PhaseCreated_type > r (
PhaseCreated_traits::create (i, f, this));
if (!this->PhaseCreated_)
{
this->PhaseCreated_.set (r);
continue;
}
}
// PipeRadius
//
if (n.name () == "PipeRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->PipeRadius_)
{
this->PipeRadius_.set (PipeRadius_traits::create (i, f, this));
continue;
}
}
// PrimaryNumberofPoles
//
if (n.name () == "PrimaryNumberofPoles" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->PrimaryNumberofPoles_)
{
this->PrimaryNumberofPoles_.set (PrimaryNumberofPoles_traits::create (i, f, this));
continue;
}
}
// PrimaryVoltage
//
if (n.name () == "PrimaryVoltage" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->PrimaryVoltage_)
{
this->PrimaryVoltage_.set (PrimaryVoltage_traits::create (i, f, this));
continue;
}
}
// PumpHeight
//
if (n.name () == "PumpHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->PumpHeight_)
{
this->PumpHeight_.set (PumpHeight_traits::create (i, f, this));
continue;
}
}
// PumpLength
//
if (n.name () == "PumpLength" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->PumpLength_)
{
this->PumpLength_.set (PumpLength_traits::create (i, f, this));
continue;
}
}
// PumpWidth
//
if (n.name () == "PumpWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->PumpWidth_)
{
this->PumpWidth_.set (PumpWidth_traits::create (i, f, this));
continue;
}
}
// Radius1
//
if (n.name () == "Radius1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Radius1_)
{
this->Radius1_.set (Radius1_traits::create (i, f, this));
continue;
}
}
// Radius2
//
if (n.name () == "Radius2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Radius2_)
{
this->Radius2_.set (Radius2_traits::create (i, f, this));
continue;
}
}
// Radius3
//
if (n.name () == "Radius3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Radius3_)
{
this->Radius3_.set (Radius3_traits::create (i, f, this));
continue;
}
}
// Radius4
//
if (n.name () == "Radius4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Radius4_)
{
this->Radius4_.set (Radius4_traits::create (i, f, this));
continue;
}
}
// Radius5
//
if (n.name () == "Radius5" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Radius5_)
{
this->Radius5_.set (Radius5_traits::create (i, f, this));
continue;
}
}
// Radius6
//
if (n.name () == "Radius6" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Radius6_)
{
this->Radius6_.set (Radius6_traits::create (i, f, this));
continue;
}
}
// Reference
//
if (n.name () == "Reference" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< Reference_type > r (
Reference_traits::create (i, f, this));
if (!this->Reference_)
{
this->Reference_.set (r);
continue;
}
}
// Reflectance
//
if (n.name () == "Reflectance" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Reflectance_)
{
this->Reflectance_.set (Reflectance_traits::create (i, f, this));
continue;
}
}
// ReturnAirInletFlow
//
if (n.name () == "ReturnAirInletFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ReturnAirInletFlow_)
{
this->ReturnAirInletFlow_.set (ReturnAirInletFlow_traits::create (i, f, this));
continue;
}
}
// ReturnAirInletHeight
//
if (n.name () == "ReturnAirInletHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ReturnAirInletHeight_)
{
this->ReturnAirInletHeight_.set (ReturnAirInletHeight_traits::create (i, f, this));
continue;
}
}
// ReturnAirInletWidth
//
if (n.name () == "ReturnAirInletWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ReturnAirInletWidth_)
{
this->ReturnAirInletWidth_.set (ReturnAirInletWidth_traits::create (i, f, this));
continue;
}
}
// ReturnDuctHeight
//
if (n.name () == "ReturnDuctHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ReturnDuctHeight_)
{
this->ReturnDuctHeight_.set (ReturnDuctHeight_traits::create (i, f, this));
continue;
}
}
// ReturnDuctWidth
//
if (n.name () == "ReturnDuctWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ReturnDuctWidth_)
{
this->ReturnDuctWidth_.set (ReturnDuctWidth_traits::create (i, f, this));
continue;
}
}
// Returnheight
//
if (n.name () == "Returnheight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Returnheight_)
{
this->Returnheight_.set (Returnheight_traits::create (i, f, this));
continue;
}
}
// Returnwidth
//
if (n.name () == "Returnwidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Returnwidth_)
{
this->Returnwidth_.set (Returnwidth_traits::create (i, f, this));
continue;
}
}
// ReturnY_Offset
//
if (n.name () == "ReturnY_Offset" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ReturnY_Offset_)
{
this->ReturnY_Offset_.set (ReturnY_Offset_traits::create (i, f, this));
continue;
}
}
// ReturnZ_Offset
//
if (n.name () == "ReturnZ_Offset" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->ReturnZ_Offset_)
{
this->ReturnZ_Offset_.set (ReturnZ_Offset_traits::create (i, f, this));
continue;
}
}
// Roughness
//
if (n.name () == "Roughness" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Roughness_)
{
this->Roughness_.set (Roughness_traits::create (i, f, this));
continue;
}
}
// ShadingDeviceType
//
if (n.name () == "ShadingDeviceType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< ShadingDeviceType_type > r (
ShadingDeviceType_traits::create (i, f, this));
if (!this->ShadingDeviceType_)
{
this->ShadingDeviceType_.set (r);
continue;
}
}
// SupplyAirInletDiameter
//
if (n.name () == "SupplyAirInletDiameter" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyAirInletDiameter_)
{
this->SupplyAirInletDiameter_.set (SupplyAirInletDiameter_traits::create (i, f, this));
continue;
}
}
// SupplyAirInletFlow
//
if (n.name () == "SupplyAirInletFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyAirInletFlow_)
{
this->SupplyAirInletFlow_.set (SupplyAirInletFlow_traits::create (i, f, this));
continue;
}
}
// SupplyAirInletHeight
//
if (n.name () == "SupplyAirInletHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyAirInletHeight_)
{
this->SupplyAirInletHeight_.set (SupplyAirInletHeight_traits::create (i, f, this));
continue;
}
}
// SupplyAirInletRadius
//
if (n.name () == "SupplyAirInletRadius" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyAirInletRadius_)
{
this->SupplyAirInletRadius_.set (SupplyAirInletRadius_traits::create (i, f, this));
continue;
}
}
// SupplyAirInletWidth
//
if (n.name () == "SupplyAirInletWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyAirInletWidth_)
{
this->SupplyAirInletWidth_.set (SupplyAirInletWidth_traits::create (i, f, this));
continue;
}
}
// SupplyAirOutletFlow
//
if (n.name () == "SupplyAirOutletFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyAirOutletFlow_)
{
this->SupplyAirOutletFlow_.set (SupplyAirOutletFlow_traits::create (i, f, this));
continue;
}
}
// SupplyAirOutletHeight
//
if (n.name () == "SupplyAirOutletHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyAirOutletHeight_)
{
this->SupplyAirOutletHeight_.set (SupplyAirOutletHeight_traits::create (i, f, this));
continue;
}
}
// SupplyAirOutletWidth
//
if (n.name () == "SupplyAirOutletWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyAirOutletWidth_)
{
this->SupplyAirOutletWidth_.set (SupplyAirOutletWidth_traits::create (i, f, this));
continue;
}
}
// SupplyAirPressureDrop
//
if (n.name () == "SupplyAirPressureDrop" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyAirPressureDrop_)
{
this->SupplyAirPressureDrop_.set (SupplyAirPressureDrop_traits::create (i, f, this));
continue;
}
}
// SupplyDuctHeight
//
if (n.name () == "SupplyDuctHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyDuctHeight_)
{
this->SupplyDuctHeight_.set (SupplyDuctHeight_traits::create (i, f, this));
continue;
}
}
// SupplyDuctWidth
//
if (n.name () == "SupplyDuctWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyDuctWidth_)
{
this->SupplyDuctWidth_.set (SupplyDuctWidth_traits::create (i, f, this));
continue;
}
}
// Supplyheight
//
if (n.name () == "Supplyheight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Supplyheight_)
{
this->Supplyheight_.set (Supplyheight_traits::create (i, f, this));
continue;
}
}
// Supplywidth
//
if (n.name () == "Supplywidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Supplywidth_)
{
this->Supplywidth_.set (Supplywidth_traits::create (i, f, this));
continue;
}
}
// Supply_ReturnSymbols
//
if (n.name () == "Supply_ReturnSymbols" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Supply_ReturnSymbols_)
{
this->Supply_ReturnSymbols_.set (Supply_ReturnSymbols_traits::create (i, f, this));
continue;
}
}
// SupplyY_Offset
//
if (n.name () == "SupplyY_Offset" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyY_Offset_)
{
this->SupplyY_Offset_.set (SupplyY_Offset_traits::create (i, f, this));
continue;
}
}
// SupplyZ_Offset
//
if (n.name () == "SupplyZ_Offset" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->SupplyZ_Offset_)
{
this->SupplyZ_Offset_.set (SupplyZ_Offset_traits::create (i, f, this));
continue;
}
}
// SystemClassification
//
if (n.name () == "SystemClassification" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< SystemClassification_type > r (
SystemClassification_traits::create (i, f, this));
if (!this->SystemClassification_)
{
this->SystemClassification_.set (r);
continue;
}
}
// SystemName
//
if (n.name () == "SystemName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< SystemName_type > r (
SystemName_traits::create (i, f, this));
if (!this->SystemName_)
{
this->SystemName_.set (r);
continue;
}
}
// TiltRange
//
if (n.name () == "TiltRange" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TiltRange_)
{
this->TiltRange_.set (TiltRange_traits::create (i, f, this));
continue;
}
}
// TotalConnected
//
if (n.name () == "TotalConnected" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TotalConnected_)
{
this->TotalConnected_.set (TotalConnected_traits::create (i, f, this));
continue;
}
}
// TotalDemandFactor
//
if (n.name () == "TotalDemandFactor" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TotalDemandFactor_)
{
this->TotalDemandFactor_.set (TotalDemandFactor_traits::create (i, f, this));
continue;
}
}
// TotalEstimatedDemand
//
if (n.name () == "TotalEstimatedDemand" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TotalEstimatedDemand_)
{
this->TotalEstimatedDemand_.set (TotalEstimatedDemand_traits::create (i, f, this));
continue;
}
}
// TowerHeight
//
if (n.name () == "TowerHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TowerHeight_)
{
this->TowerHeight_.set (TowerHeight_traits::create (i, f, this));
continue;
}
}
// TowerLength
//
if (n.name () == "TowerLength" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TowerLength_)
{
this->TowerLength_.set (TowerLength_traits::create (i, f, this));
continue;
}
}
// TowerWidth
//
if (n.name () == "TowerWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TowerWidth_)
{
this->TowerWidth_.set (TowerWidth_traits::create (i, f, this));
continue;
}
}
// TransformerHeight
//
if (n.name () == "TransformerHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TransformerHeight_)
{
this->TransformerHeight_.set (TransformerHeight_traits::create (i, f, this));
continue;
}
}
// TransformerLength
//
if (n.name () == "TransformerLength" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TransformerLength_)
{
this->TransformerLength_.set (TransformerLength_traits::create (i, f, this));
continue;
}
}
// TransformerWidth
//
if (n.name () == "TransformerWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->TransformerWidth_)
{
this->TransformerWidth_.set (TransformerWidth_traits::create (i, f, this));
continue;
}
}
// UniformatClassification
//
if (n.name () == "UniformatClassification" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
::std::auto_ptr< UniformatClassification_type > r (
UniformatClassification_traits::create (i, f, this));
if (!this->UniformatClassification_)
{
this->UniformatClassification_.set (r);
continue;
}
}
// Unitdepth
//
if (n.name () == "Unitdepth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Unitdepth_)
{
this->Unitdepth_.set (Unitdepth_traits::create (i, f, this));
continue;
}
}
// UnitHeight
//
if (n.name () == "UnitHeight" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->UnitHeight_)
{
this->UnitHeight_.set (UnitHeight_traits::create (i, f, this));
continue;
}
}
// UnitLength
//
if (n.name () == "UnitLength" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->UnitLength_)
{
this->UnitLength_.set (UnitLength_traits::create (i, f, this));
continue;
}
}
// UnitWidth
//
if (n.name () == "UnitWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->UnitWidth_)
{
this->UnitWidth_.set (UnitWidth_traits::create (i, f, this));
continue;
}
}
// Visible1
//
if (n.name () == "Visible1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Visible1_)
{
this->Visible1_.set (Visible1_traits::create (i, f, this));
continue;
}
}
// Visible2
//
if (n.name () == "Visible2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Visible2_)
{
this->Visible2_.set (Visible2_traits::create (i, f, this));
continue;
}
}
// Voltage
//
if (n.name () == "Voltage" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Voltage_)
{
this->Voltage_.set (Voltage_traits::create (i, f, this));
continue;
}
}
// WaterFlow
//
if (n.name () == "WaterFlow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->WaterFlow_)
{
this->WaterFlow_.set (WaterFlow_traits::create (i, f, this));
continue;
}
}
// WaterPressure
//
if (n.name () == "WaterPressure" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->WaterPressure_)
{
this->WaterPressure_.set (WaterPressure_traits::create (i, f, this));
continue;
}
}
// Width1
//
if (n.name () == "Width1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Width1_)
{
this->Width1_.set (Width1_traits::create (i, f, this));
continue;
}
}
// Width2
//
if (n.name () == "Width2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Width2_)
{
this->Width2_.set (Width2_traits::create (i, f, this));
continue;
}
}
// Width3
//
if (n.name () == "Width3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Width3_)
{
this->Width3_.set (Width3_traits::create (i, f, this));
continue;
}
}
// Width4
//
if (n.name () == "Width4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Width4_)
{
this->Width4_.set (Width4_traits::create (i, f, this));
continue;
}
}
// Width5
//
if (n.name () == "Width5" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Width5_)
{
this->Width5_.set (Width5_traits::create (i, f, this));
continue;
}
}
// Width6
//
if (n.name () == "Width6" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Width6_)
{
this->Width6_.set (Width6_traits::create (i, f, this));
continue;
}
}
// Width7
//
if (n.name () == "Width7" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/BuildingModel")
{
if (!this->Width7_)
{
this->Width7_.set (Width7_traits::create (i, f, this));
continue;
}
}
break;
}
}
SimBuildingElementProxy* SimBuildingElementProxy::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class SimBuildingElementProxy (*this, f, c);
}
SimBuildingElementProxy& SimBuildingElementProxy::
operator= (const SimBuildingElementProxy& x)
{
if (this != &x)
{
static_cast< ::schema::simxml::SimModelCore::SimBuildingElement& > (*this) = x;
this->Name_ = x.Name_;
this->Representation_ = x.Representation_;
this->CompositionType_ = x.CompositionType_;
this->AHUHeight_ = x.AHUHeight_;
this->AHUWidth_ = x.AHUWidth_;
this->AirFlow_ = x.AirFlow_;
this->AirflowReturn_ = x.AirflowReturn_;
this->AirflowSupply_ = x.AirflowSupply_;
this->AirPressure_ = x.AirPressure_;
this->AirwayLength_ = x.AirwayLength_;
this->AlternatorVoltage_ = x.AlternatorVoltage_;
this->Ang_ = x.Ang_;
this->ApparentLoad_ = x.ApparentLoad_;
this->ApparentLoadPhaseA_ = x.ApparentLoadPhaseA_;
this->ApparentLoadPhaseB_ = x.ApparentLoadPhaseB_;
this->ApparentLoadPhaseC_ = x.ApparentLoadPhaseC_;
this->AverageSolarTransmittance_ = x.AverageSolarTransmittance_;
this->AverageVisibleTransmittance_ = x.AverageVisibleTransmittance_;
this->Azimuth_ = x.Azimuth_;
this->BaseHeight_ = x.BaseHeight_;
this->BaseLength_ = x.BaseLength_;
this->Buildingstoreyname_ = x.Buildingstoreyname_;
this->C1Offset1_ = x.C1Offset1_;
this->C1Offset2_ = x.C1Offset2_;
this->C2Offset1_ = x.C2Offset1_;
this->C2Offset2_ = x.C2Offset2_;
this->C3Offset1_ = x.C3Offset1_;
this->C4Offset2_ = x.C4Offset2_;
this->C5Offset1_ = x.C5Offset1_;
this->C5Offset2_ = x.C5Offset2_;
this->C6Offset1_ = x.C6Offset1_;
this->C6Offset2_ = x.C6Offset2_;
this->ChilledWaterFlow_ = x.ChilledWaterFlow_;
this->ChilledWaterPressureDrop_ = x.ChilledWaterPressureDrop_;
this->CircuitNaming_ = x.CircuitNaming_;
this->Color_ = x.Color_;
this->Connectionoffset_ = x.Connectionoffset_;
this->ContainerName_ = x.ContainerName_;
this->ContainerType_ = x.ContainerType_;
this->CoolAirFlow_ = x.CoolAirFlow_;
this->CoolAirInletDiameter_ = x.CoolAirInletDiameter_;
this->CoolAirInletRadius_ = x.CoolAirInletRadius_;
this->CoolAirPressureDrop_ = x.CoolAirPressureDrop_;
this->CoolingCoilInletRadius_ = x.CoolingCoilInletRadius_;
this->CoolingCoilOutletRadius_ = x.CoolingCoilOutletRadius_;
this->CoolingWaterDiameter_ = x.CoolingWaterDiameter_;
this->CoolingWaterFlow_ = x.CoolingWaterFlow_;
this->CoolingWaterPressureDrop_ = x.CoolingWaterPressureDrop_;
this->CoolingWaterRadius_ = x.CoolingWaterRadius_;
this->Diameter1_ = x.Diameter1_;
this->Distance_ = x.Distance_;
this->Distance1_ = x.Distance1_;
this->Distance2_ = x.Distance2_;
this->DrainFlow_ = x.DrainFlow_;
this->DrainOffset1_ = x.DrainOffset1_;
this->DrainRadius_ = x.DrainRadius_;
this->DuctHeight_ = x.DuctHeight_;
this->DuctWidth_ = x.DuctWidth_;
this->ElectricalCircuitName_ = x.ElectricalCircuitName_;
this->ElectricalData_ = x.ElectricalData_;
this->Enclosure_ = x.Enclosure_;
this->ExternalStaticPressure_ = x.ExternalStaticPressure_;
this->ExternalTotalPressure_ = x.ExternalTotalPressure_;
this->FanAirFlow_ = x.FanAirFlow_;
this->FanDiameter_ = x.FanDiameter_;
this->FanRadius_ = x.FanRadius_;
this->GeneratorHeight_ = x.GeneratorHeight_;
this->GeneratorLength_ = x.GeneratorLength_;
this->GeneratorWidth_ = x.GeneratorWidth_;
this->GroupName_ = x.GroupName_;
this->HalfAirOutletHeight_ = x.HalfAirOutletHeight_;
this->HalfAirOutletWidth_ = x.HalfAirOutletWidth_;
this->HalfOverallHeight_ = x.HalfOverallHeight_;
this->HalfOverallWidth_ = x.HalfOverallWidth_;
this->HalfWidth4_ = x.HalfWidth4_;
this->HeatAirFlow_ = x.HeatAirFlow_;
this->HeatAirInletDiameter_ = x.HeatAirInletDiameter_;
this->HeatAirInletRadius_ = x.HeatAirInletRadius_;
this->HeatAirPressureDrop_ = x.HeatAirPressureDrop_;
this->HeatLoss_ = x.HeatLoss_;
this->HeatingCoilInletRadius_ = x.HeatingCoilInletRadius_;
this->HeatingCoilOutletRadius_ = x.HeatingCoilOutletRadius_;
this->Height1_ = x.Height1_;
this->Height2_ = x.Height2_;
this->Height3_ = x.Height3_;
this->Height4_ = x.Height4_;
this->Height5_ = x.Height5_;
this->Height6_ = x.Height6_;
this->Height7_ = x.Height7_;
this->Height8_ = x.Height8_;
this->Height9_ = x.Height9_;
this->Host_ = x.Host_;
this->HotWaterFlow_ = x.HotWaterFlow_;
this->HotWaterPressureDrop_ = x.HotWaterPressureDrop_;
this->Inclination_ = x.Inclination_;
this->InletDiameter_ = x.InletDiameter_;
this->InletRadius_ = x.InletRadius_;
this->Length1_ = x.Length1_;
this->Length2_ = x.Length2_;
this->Length3_ = x.Length3_;
this->Length4_ = x.Length4_;
this->Length5_ = x.Length5_;
this->Length6_ = x.Length6_;
this->Length7_ = x.Length7_;
this->Length8_ = x.Length8_;
this->Length9_ = x.Length9_;
this->Length10_ = x.Length10_;
this->Length11_ = x.Length11_;
this->Length12_ = x.Length12_;
this->Length13_ = x.Length13_;
this->Level_ = x.Level_;
this->LoadClassification_ = x.LoadClassification_;
this->MakeUpWaterFlow_ = x.MakeUpWaterFlow_;
this->MakeUpWaterPressureDrop_ = x.MakeUpWaterPressureDrop_;
this->MakeUpWaterRadius_ = x.MakeUpWaterRadius_;
this->ManufacturerArticleNumber_ = x.ManufacturerArticleNumber_;
this->ManufacturerModelName_ = x.ManufacturerModelName_;
this->ManufacturerModelNumber_ = x.ManufacturerModelNumber_;
this->ManufacturerName_ = x.ManufacturerName_;
this->ManufacturerYearofProduction_ = x.ManufacturerYearofProduction_;
this->Mark_ = x.Mark_;
this->Material_ = x.Material_;
this->Max1PoleBreakers_ = x.Max1PoleBreakers_;
this->MaxFlow_ = x.MaxFlow_;
this->MinFlow_ = x.MinFlow_;
this->Model_ = x.Model_;
this->MotorHP_ = x.MotorHP_;
this->NumberOfFans_ = x.NumberOfFans_;
this->NumberOfPoles_ = x.NumberOfPoles_;
this->ObjectClassName_ = x.ObjectClassName_;
this->Offset_ = x.Offset_;
this->OmniclassNumber_ = x.OmniclassNumber_;
this->OmniclassTitle_ = x.OmniclassTitle_;
this->OutletDiameter_ = x.OutletDiameter_;
this->OutletRadius_ = x.OutletRadius_;
this->OverallHeight_ = x.OverallHeight_;
this->OverallLength_ = x.OverallLength_;
this->OverallWidth_ = x.OverallWidth_;
this->PanelHeight_ = x.PanelHeight_;
this->Partshape_ = x.Partshape_;
this->PhaseCreated_ = x.PhaseCreated_;
this->PipeRadius_ = x.PipeRadius_;
this->PrimaryNumberofPoles_ = x.PrimaryNumberofPoles_;
this->PrimaryVoltage_ = x.PrimaryVoltage_;
this->PumpHeight_ = x.PumpHeight_;
this->PumpLength_ = x.PumpLength_;
this->PumpWidth_ = x.PumpWidth_;
this->Radius1_ = x.Radius1_;
this->Radius2_ = x.Radius2_;
this->Radius3_ = x.Radius3_;
this->Radius4_ = x.Radius4_;
this->Radius5_ = x.Radius5_;
this->Radius6_ = x.Radius6_;
this->Reference_ = x.Reference_;
this->Reflectance_ = x.Reflectance_;
this->ReturnAirInletFlow_ = x.ReturnAirInletFlow_;
this->ReturnAirInletHeight_ = x.ReturnAirInletHeight_;
this->ReturnAirInletWidth_ = x.ReturnAirInletWidth_;
this->ReturnDuctHeight_ = x.ReturnDuctHeight_;
this->ReturnDuctWidth_ = x.ReturnDuctWidth_;
this->Returnheight_ = x.Returnheight_;
this->Returnwidth_ = x.Returnwidth_;
this->ReturnY_Offset_ = x.ReturnY_Offset_;
this->ReturnZ_Offset_ = x.ReturnZ_Offset_;
this->Roughness_ = x.Roughness_;
this->ShadingDeviceType_ = x.ShadingDeviceType_;
this->SupplyAirInletDiameter_ = x.SupplyAirInletDiameter_;
this->SupplyAirInletFlow_ = x.SupplyAirInletFlow_;
this->SupplyAirInletHeight_ = x.SupplyAirInletHeight_;
this->SupplyAirInletRadius_ = x.SupplyAirInletRadius_;
this->SupplyAirInletWidth_ = x.SupplyAirInletWidth_;
this->SupplyAirOutletFlow_ = x.SupplyAirOutletFlow_;
this->SupplyAirOutletHeight_ = x.SupplyAirOutletHeight_;
this->SupplyAirOutletWidth_ = x.SupplyAirOutletWidth_;
this->SupplyAirPressureDrop_ = x.SupplyAirPressureDrop_;
this->SupplyDuctHeight_ = x.SupplyDuctHeight_;
this->SupplyDuctWidth_ = x.SupplyDuctWidth_;
this->Supplyheight_ = x.Supplyheight_;
this->Supplywidth_ = x.Supplywidth_;
this->Supply_ReturnSymbols_ = x.Supply_ReturnSymbols_;
this->SupplyY_Offset_ = x.SupplyY_Offset_;
this->SupplyZ_Offset_ = x.SupplyZ_Offset_;
this->SystemClassification_ = x.SystemClassification_;
this->SystemName_ = x.SystemName_;
this->TiltRange_ = x.TiltRange_;
this->TotalConnected_ = x.TotalConnected_;
this->TotalDemandFactor_ = x.TotalDemandFactor_;
this->TotalEstimatedDemand_ = x.TotalEstimatedDemand_;
this->TowerHeight_ = x.TowerHeight_;
this->TowerLength_ = x.TowerLength_;
this->TowerWidth_ = x.TowerWidth_;
this->TransformerHeight_ = x.TransformerHeight_;
this->TransformerLength_ = x.TransformerLength_;
this->TransformerWidth_ = x.TransformerWidth_;
this->UniformatClassification_ = x.UniformatClassification_;
this->Unitdepth_ = x.Unitdepth_;
this->UnitHeight_ = x.UnitHeight_;
this->UnitLength_ = x.UnitLength_;
this->UnitWidth_ = x.UnitWidth_;
this->Visible1_ = x.Visible1_;
this->Visible2_ = x.Visible2_;
this->Voltage_ = x.Voltage_;
this->WaterFlow_ = x.WaterFlow_;
this->WaterPressure_ = x.WaterPressure_;
this->Width1_ = x.Width1_;
this->Width2_ = x.Width2_;
this->Width3_ = x.Width3_;
this->Width4_ = x.Width4_;
this->Width5_ = x.Width5_;
this->Width6_ = x.Width6_;
this->Width7_ = x.Width7_;
}
return *this;
}
SimBuildingElementProxy::
~SimBuildingElementProxy ()
{
}
}
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace schema
{
namespace simxml
{
namespace BuildingModel
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| [
"cao@e3d.rwth-aachen.de"
] | cao@e3d.rwth-aachen.de |
da2fad66e5f3824237c52fae984aefe1f1107b16 | 9923a00a9afcd97c2fb02f6ed615adea3fc3fe1d | /Branch/Deprecated/ros_code/rospand/src/pandar-ros-vstyle-gps/pandar_driver/src/driver/driver.cc | 616c07bdee0ecf673cec792d2a24310a7b9ff9a7 | [
"MIT",
"BSD-3-Clause"
] | permissive | Tsinghua-OpenICV/OpenICV | 93df0e3dda406a5b8958f50ee763756a45182bf3 | 3bdb2ba744fabe934b31e36ba9c1e6ced2d5e6fc | refs/heads/master | 2022-03-02T03:09:02.236509 | 2021-12-26T08:09:42 | 2021-12-26T08:09:42 | 225,785,128 | 13 | 9 | null | 2020-08-06T02:42:03 | 2019-12-04T05:17:57 | C++ | UTF-8 | C++ | false | false | 8,031 | cc | /*
* Copyright (C) 2007 Austin Robot Technology, Patrick Beeson
* Copyright (C) 2009-2012 Austin Robot Technology, Jack O'Quin
* Copyright (c) 2017 Hesai Photonics Technology, Yang Sheng
*
* License: Modified BSD Software License Agreement
*
* $Id$
*/
/** \file
*
* ROS driver implementation for the Pandar40 3D LIDARs
*/
#include <string>
#include <cmath>
#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <pandar_msgs/PandarScan.h>
#include <pandar_msgs/PandarGps.h>
#include "driver.h"
namespace pandar_driver
{
PandarDriver::PandarDriver(ros::NodeHandle node,
ros::NodeHandle private_nh)
{
// use private node handle to get parameters
private_nh.param("frame_id", config_.frame_id, std::string("pandar"));
std::string tf_prefix = tf::getPrefixParam(private_nh);
ROS_DEBUG_STREAM("tf_prefix: " << tf_prefix);
config_.frame_id = tf::resolve(tf_prefix, config_.frame_id);
// get model name, validate string, determine packet rate
config_.model = "Pandar40";
std::string model_full_name = std::string("Hesai") + config_.model;
double packet_rate = 3000; // packet frequency (Hz)
std::string deviceName(model_full_name);
private_nh.param("rpm", config_.rpm, 600.0);
ROS_INFO_STREAM(deviceName << " rotating at " << config_.rpm << " RPM");
double frequency = (config_.rpm / 60.0); // expected Hz rate
// default number of packets for each scan is a single revolution
// (fractions rounded up)
config_.npackets = (int) ceil(packet_rate / frequency);
private_nh.getParam("npackets", config_.npackets);
ROS_INFO_STREAM("publishing " << config_.npackets << " packets per scan");
std::string dump_file;
private_nh.param("pcap", dump_file, std::string(""));
int udp_port;
private_nh.param("port", udp_port, (int) DATA_PORT_NUMBER);
// Initialize dynamic reconfigure
srv_ = boost::make_shared <dynamic_reconfigure::Server<pandar_driver::
PandarNodeConfig> > (private_nh);
dynamic_reconfigure::Server<pandar_driver::PandarNodeConfig>::
CallbackType f;
f = boost::bind (&PandarDriver::callback, this, _1, _2);
srv_->setCallback (f); // Set callback function und call initially
// initialize diagnostics
diagnostics_.setHardwareID(deviceName);
const double diag_freq = packet_rate/config_.npackets;
diag_max_freq_ = diag_freq;
diag_min_freq_ = diag_freq;
ROS_INFO("expected frequency: %.3f (Hz)", diag_freq);
using namespace diagnostic_updater;
diag_topic_.reset(new TopicDiagnostic("pandar_packets", diagnostics_,
FrequencyStatusParam(&diag_min_freq_,
&diag_max_freq_,
0.1, 10),
TimeStampStatusParam()));
// open Pandar input device or file
if (dump_file != "") // have PCAP file?
{
// read data from packet capture file
input_.reset(new pandar_driver::InputPCAP(private_nh, udp_port,
packet_rate, dump_file));
}
else
{
// read data from live socket
input_.reset(new pandar_driver::InputSocket(private_nh, udp_port));
}
// raw packet output topic
output_ =
node.advertise<pandar_msgs::PandarScan>("pandar_packets", 10);
// raw packet output topic
gpsoutput_ =
node.advertise<pandar_msgs::PandarGps>("pandar_gps", 1);
}
#define HS_LIDAR_L40_GPS_PACKET_SIZE (512)
#define HS_LIDAR_L40_GPS_PACKET_FLAG_SIZE (2)
#define HS_LIDAR_L40_GPS_PACKET_YEAR_SIZE (2)
#define HS_LIDAR_L40_GPS_PACKET_MONTH_SIZE (2)
#define HS_LIDAR_L40_GPS_PACKET_DAY_SIZE (2)
#define HS_LIDAR_L40_GPS_PACKET_HOUR_SIZE (2)
#define HS_LIDAR_L40_GPS_PACKET_MINUTE_SIZE (2)
#define HS_LIDAR_L40_GPS_PACKET_SECOND_SIZE (2)
#define HS_LIDAR_L40_GPS_ITEM_NUM (7)
//--------------------------------------
typedef struct HS_LIDAR_L40_GPS_PACKET_s{
unsigned short flag;
unsigned short year;
unsigned short month;
unsigned short day;
unsigned short second;
unsigned short minute;
unsigned short hour;
unsigned int fineTime;
// unsigned char unused[496];
}HS_LIDAR_L40_GPS_Packet;
//-------------------------------------------------------------------------------
int HS_L40_GPS_Parse(HS_LIDAR_L40_GPS_Packet *packet , const unsigned char* recvbuf , const int len)
{
if(len != HS_LIDAR_L40_GPS_PACKET_SIZE)
return -1;
int index = 0;
packet->flag = (recvbuf[index] & 0xff)|((recvbuf[index + 1] & 0xff)<< 8);
index += HS_LIDAR_L40_GPS_PACKET_FLAG_SIZE;
packet->year = (recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += HS_LIDAR_L40_GPS_PACKET_YEAR_SIZE;
packet->month = (recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += HS_LIDAR_L40_GPS_PACKET_MONTH_SIZE;
packet->day = (recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += HS_LIDAR_L40_GPS_PACKET_DAY_SIZE;
packet->second = (recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += HS_LIDAR_L40_GPS_PACKET_SECOND_SIZE;
packet->minute = (recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += HS_LIDAR_L40_GPS_PACKET_MINUTE_SIZE;
packet->hour = (recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10 + 8;
index += HS_LIDAR_L40_GPS_PACKET_HOUR_SIZE;
packet->fineTime = (recvbuf[index]& 0xff)| (recvbuf[index + 1]& 0xff) << 8 |
((recvbuf[index + 2 ]& 0xff) << 16) | ((recvbuf[index + 3]& 0xff) << 24);
return 0;
}
/** poll the device
*
* @returns true unless end of file reached
*/
bool PandarDriver::poll(void)
{
int readpacket = config_.npackets / 3;
// Allocate a new shared pointer for zero-copy sharing with other nodelets.
pandar_msgs::PandarScanPtr scan(new pandar_msgs::PandarScan);
scan->packets.resize(readpacket);
// Since the pandar delivers data at a very high rate, keep
// reading and publishing scans as fast as possible.
for (int i = 0; i < readpacket; ++i)
{
while (true)
{
// keep reading until full packet received
int rc = input_->getPacket(&scan->packets[i], config_.time_offset);
if (rc == 0) break; // got a full packet?
if (rc == 2)
{
// gps packet;
HS_LIDAR_L40_GPS_Packet packet;
if(HS_L40_GPS_Parse( &packet , &scan->packets[i].data[0] , HS_LIDAR_L40_GPS_PACKET_SIZE) == 0)
{
pandar_msgs::PandarGpsPtr gps(new pandar_msgs::PandarGps);
gps->stamp = ros::Time::now();
gps->year = packet.year;
gps->month = packet.month;
gps->day = packet.day;
gps->hour = packet.hour;
gps->minute = packet.minute;
gps->second = packet.second;
gps->used = 0;
gpsoutput_.publish(gps);
}
}
if (rc < 0) return false; // end of file reached?
}
}
// publish message using time of last packet read
ROS_DEBUG("Publishing a full Pandar scan.");
scan->header.stamp = scan->packets[readpacket - 1].stamp;
scan->header.frame_id = config_.frame_id;
output_.publish(scan);
// notify diagnostics that a message has been published, updating
// its status
diag_topic_->tick(scan->header.stamp);
diagnostics_.update();
return true;
}
void PandarDriver::callback(pandar_driver::PandarNodeConfig &config,
uint32_t level)
{
ROS_INFO("Reconfigure Request");
config_.time_offset = config.time_offset;
}
} // namespace pandar_driver
| [
"syn17@mails.tsinghua.edu.cn"
] | syn17@mails.tsinghua.edu.cn |
17b6bf207a7af15e10297ff16bc3e81426fd2d5d | 9e2578040686127d5c40e7a7d5f34aee3df06b86 | /Problems/Problem_9/coneshawarma_problem_9.cpp | 7d70a62b9730a51683d5bca1019d03ee18e8f048 | [] | no_license | MU-Enigma/Hacktoberfest_2020 | 9721e7eeedae655c98d71fba6f61b4a04edbfeeb | c396fb81d77c43f26124c5ccaef19426e74f87fc | refs/heads/master | 2023-01-06T15:44:57.788503 | 2020-11-04T16:44:03 | 2020-11-04T16:44:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 225 | cpp | #include<iostream>
#include<string>
int main()
{
string ay= "ay";
string s;
char first;
std::cout << "please enter a string";
getline(cin,s);
first= s[0];
std::cout << s.substr(1)+first+ay;
}
| [
"johaan.vinu@gmail.com"
] | johaan.vinu@gmail.com |
d65cbfff36ecc5d521f39286fa3be636ca1e1211 | a2a46836e961884da910c92e4cc43d0f3b3308d3 | /ch09/c09e26.cpp | cb9fa588829536ae93329df887f9e57c9143443b | [] | no_license | Yuns-Wang/cpp_primer | c841026e7d6aa3293f646d97a06c4e57d5d77b86 | 278f55efa5691eb44a1efc9e9db027095e1f9b9a | refs/heads/master | 2021-07-24T06:37:08.425997 | 2020-04-10T16:19:37 | 2020-04-10T16:19:37 | 134,730,865 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | cpp | #include <vector>
#include <iostream>
#include <list>
using std::vector;
using std::list;
using std::cout;
using std::endl;
int main()
{
int ia[] = {0,1,1,2,3,5,8,13,21,34,55,89};
vector<int> vi(std::begin(ia), std::end(ia));
list<int> li(ia, ia + sizeof(ia)/sizeof(ia[0]));
for (auto begin = vi.begin(); begin != vi.end();)
{
if (*begin % 2 == 0)
begin = vi.erase(begin);
else
++begin;
}
for (auto begin = li.begin(); begin != li.end();)
{
if (*begin % 2 != 0)
begin = li.erase(begin);
else
++begin;
}
for(auto i : vi)
cout << i << " ";
cout << endl;
for(auto i : li)
cout << i << " ";
cout << endl;
return 0;
}
| [
"wyscode@163.com"
] | wyscode@163.com |
debb454bc54d95db8cddfc1d6b0a029782c65ca5 | 6f321a19d6fd0841d8f579ee1b0040289eec4d47 | /MeshDB/kmbMeshDB_Geometry.cpp | e895e91b80ca1bda330a83ec8ea8664095c47244 | [] | no_license | noguchi-k/REVOCAP_Refiner | 260f6d5e1c2bfab534be71e7f34fa8d359c0cb17 | 626d4457ac3787d5ecaf50bb2b1de2e4d144fc13 | refs/heads/master | 2022-09-06T05:24:24.965876 | 2018-08-20T21:50:40 | 2018-08-20T21:50:40 | 267,747,005 | 0 | 0 | null | 2020-05-29T02:31:19 | 2020-05-29T02:31:18 | null | UTF-8 | C++ | false | false | 22,256 | cpp | /*----------------------------------------------------------------------
# #
# Software Name : REVOCAP_PrePost version 1.6 #
# Class Name : MeshDB #
# #
# Written by #
# K. Tokunaga 2012/03/23 #
# #
# Contact Address: IIS, The University of Tokyo CISS #
# #
# "Large Scale Assembly, Structural Correspondence, #
# Multi Dynamics Simulator" #
# #
# Software Name : RevocapMesh version 1.2 #
# #
# Written by #
# K. Tokunaga 2008/03/14 #
# T. Takeda 2008/03/14 #
# K. Amemiya 2008/03/14 #
# #
# Contact Address: RSS21 Project, IIS, The University of Tokyo #
# #
# "Innovative General-Purpose Coupled Analysis System" #
# #
----------------------------------------------------------------------*/
#include "MeshDB/kmbMeshDB.h"
#include "MeshDB/kmbElement.h"
#include "MeshDB/kmbSegment.h"
#include "MeshDB/kmbSegment2.h"
#include "MeshDB/kmbTriangle.h"
#include "MeshDB/kmbTriangle2.h"
#include "MeshDB/kmbQuad.h"
#include "MeshDB/kmbQuad2.h"
#include "MeshDB/kmbTetrahedron.h"
#include "MeshDB/kmbTetrahedron2.h"
#include "MeshDB/kmbHexahedron.h"
#include "MeshDB/kmbHexahedron2.h"
#include "MeshDB/kmbWedge.h"
#include "MeshDB/kmbWedge2.h"
#include "MeshDB/kmbPyramid.h"
#include "MeshDB/kmbPyramid2.h"
#include "MeshDB/kmbFace.h"
#include "MeshDB/kmbDataBindings.h"
#include "MeshDB/kmbNodeNeighborInfo.h"
#include "MeshDB/kmbNodeNeighborFaceInfo.h"
#include "MeshDB/kmbElementContainer.h"
#include "MeshDB/kmbElementEvaluator.h"
#include "MeshDB/kmbBodyOperation.h"
#include "MeshDB/kmbNodeEvaluator.h"
#include "Geometry/kmbGeometry3D.h"
#include "Geometry/kmbSphere.h"
#include "Geometry/kmbCircle.h"
#include "Geometry/kmbPoint3DContainer.h"
#include "Common/kmbCalculator.h"
#include "MeshDB/kmbTypes.h"
#include <cstring>
void
kmb::MeshDB::updateBoundingBox(kmb::bodyIdType bodyId)
{
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
if( body != NULL ){
body->updateBoundingBox( this->getNodes() );
}
}
const kmb::BoundingBox
kmb::MeshDB::getBoundingBox(kmb::bodyIdType bodyId) const
{
const kmb::ElementContainer* body = this->getBodyPtr(bodyId);
if( body != NULL ){
return body->getBoundingBox();
}
return kmb::BoundingBox();
}
double
kmb::MeshDB::getAspectRatio(elementIdType elementId,kmb::bodyIdType bodyId) const
{
kmb::ElementContainer::const_iterator eIter = this->findElement(elementId,bodyId);
return this->evaluator->getAspectRatio( eIter );
}
int
kmb::MeshDB::getEdgeCountOfBody(kmb::bodyIdType bodyId) const
{
const kmb::ElementContainer* body = this->getBodyPtr( bodyId );
if( body ){
kmb::BodyOperation bodyOp( this->getNodes() );
return static_cast<int>( bodyOp.getEdgesOfBody( body ) );
}else{
return 0;
}
}
int
kmb::MeshDB::getNodeCountOfBody(kmb::bodyIdType bodyId) const
{
const kmb::ElementContainer* body = this->getBodyPtr( bodyId );
if( body ){
std::set< kmb::nodeIdType > nodes;
body->getNodesOfBody( nodes );
return static_cast<int>(nodes.size());
}else{
return 0;
}
}
int
kmb::MeshDB::getNaturalCoordinates(kmb::bodyIdType bodyId,kmb::elementIdType elementId,double x,double y,double z,double* values) const
{
kmb::ElementContainer::const_iterator element = this->findElement(elementId,bodyId);
if( !element.isFinished() && values != NULL ){
switch( element.getType() ){
case kmb::TETRAHEDRON:
case kmb::TETRAHEDRON2:
case kmb::HEXAHEDRON:
case kmb::HEXAHEDRON2:
case kmb::PYRAMID:
case kmb::WEDGE:
{
if( evaluator->getNaturalCoordinates( element, x, y, z, values ) ){
return 3;
}
}
break;
default:
break;
}
}
return 0;
}
bool
kmb::MeshDB::getPhysicalCoordinates(bodyIdType bodyId,elementIdType elementId,double s,double t,double u,kmb::Point3D &target) const
{
kmb::ElementContainer::const_iterator element = this->findElement(elementId,bodyId);
if( !element.isFinished() ){
switch( element.getType() ){
case kmb::TETRAHEDRON:
case kmb::TETRAHEDRON2:
case kmb::HEXAHEDRON:
case kmb::PYRAMID:
case kmb::WEDGE:
{
if( evaluator->getPhysicalCoordinates( element, s, t, u, target) ){
return true;
}
}
break;
default:
break;
}
}
return false;
}
void
kmb::MeshDB::shapeFunction( kmb::elementType etype, double* naturalCoords, double* values )
{
switch( etype )
{
case kmb::SEGMENT:
kmb::Segment::shapeFunction(
naturalCoords[0],
values );
break;
case kmb::SEGMENT2:
kmb::Segment2::shapeFunction(
naturalCoords[0],
values );
break;
case kmb::TRIANGLE:
kmb::Triangle::shapeFunction(
naturalCoords[0],
naturalCoords[1],
values );
break;
case kmb::TRIANGLE2:
kmb::Triangle2::shapeFunction(
naturalCoords[0],
naturalCoords[1],
values );
break;
case kmb::QUAD:
kmb::Quad::shapeFunction(
naturalCoords[0],
naturalCoords[1],
values );
break;
case kmb::QUAD2:
kmb::Quad2::shapeFunction(
naturalCoords[0],
naturalCoords[1],
values );
break;
case kmb::TETRAHEDRON:
kmb::Tetrahedron::shapeFunction(
naturalCoords[0],
naturalCoords[1],
naturalCoords[2],
values );
break;
case kmb::TETRAHEDRON2:
kmb::Tetrahedron2::shapeFunction(
naturalCoords[0],
naturalCoords[1],
naturalCoords[2],
values );
break;
case kmb::HEXAHEDRON:
kmb::Hexahedron::shapeFunction(
naturalCoords[0],
naturalCoords[1],
naturalCoords[2],
values );
break;
case kmb::HEXAHEDRON2:
kmb::Hexahedron2::shapeFunction(
naturalCoords[0],
naturalCoords[1],
naturalCoords[2],
values );
break;
case kmb::WEDGE:
kmb::Wedge::shapeFunction(
naturalCoords[0],
naturalCoords[1],
naturalCoords[2],
values );
break;
case kmb::WEDGE2:
kmb::Wedge2::shapeFunction(
naturalCoords[0],
naturalCoords[1],
naturalCoords[2],
values );
break;
case kmb::PYRAMID2:
kmb::Pyramid2::shapeFunction(
naturalCoords[0],
naturalCoords[1],
naturalCoords[2],
values );
break;
case kmb::PYRAMID:
kmb::Pyramid::shapeFunction(
naturalCoords[0],
naturalCoords[1],
naturalCoords[2],
values );
break;
default:
break;
}
}
double
kmb::MeshDB::calcMeshProperty(const char* name,kmb::bodyIdType bodyId)
{
if( strcmp(name,"NormalVectorOnNode")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
if( body && body->isUniqueDim(2) ){
kmb::NodeNeighborInfo neighborInfo;
neighborInfo.appendCoboundary( body );
std::vector< kmb::elementIdType > elements;
kmb::DataBindings* data = this->createDataBindings("NormalVectorOnNode",kmb::DataBindings::NodeVariable,kmb::PhysicalValue::Vector3,"MeshProperty");
kmb::Point3DContainer::iterator nIter = nodes->begin();
while( !nIter.isFinished() ){
elements.clear();
neighborInfo.getSurroundingElements( nIter.getId(), elements );
if( elements.size() > 0 ){
kmb::Vector3D normal(0.0,0.0,0.0);
std::vector<kmb::elementIdType >::iterator eIter = elements.begin();
while( eIter != elements.end() ){
kmb::ElementContainer::iterator element = body->find( *eIter );
kmb::Vector3D v(0.0,0.0,0.0);
this->evaluator->getNormalVector( element, v );
normal += v;
++eIter;
}
normal.normalize();
data->setPhysicalValue( nIter.getId(), new kmb::Vector3Value( normal.x(), normal.y(), normal.z() ) );
}
++nIter;
}
return 0.0;
}
}
else if( strcmp(name,"AspectRatio")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
kmb::ElementEvaluator evaluator(nodes);
if( body && body->isUniqueDim(3) ){
kmb::DataBindings* data = this->getDataBindingsPtr("AspectRatio","MeshProperty");
if( data == NULL ){
data = this->createDataBindings("AspectRatio",kmb::DataBindings::ElementVariable,kmb::PhysicalValue::Scalar,"MeshProperty");
}
if( data == NULL ||
data->getBindingMode() != kmb::DataBindings::ElementVariable ||
data->getValueType() != kmb::PhysicalValue::Scalar )
{
return -1.0;
}
kmb::ElementContainer::iterator eIter = body->begin();
double ratio = 0.0;
while( !eIter.isFinished() ){
ratio = evaluator.getAspectRatio( eIter );
data->setPhysicalValue( eIter.getId(), &ratio );
++eIter;
}
return 0.0;
}
}
else if( strcmp(name,"ElementVolume")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
kmb::ElementEvaluator evaluator(nodes);
if( body && body->isUniqueDim(3) ){
double totalVolume = 0.0;
kmb::DataBindings* data = this->getDataBindingsPtr("ElementVolume","MeshProperty");
if( data == NULL ){
data = this->createDataBindings("ElementVolume",kmb::DataBindings::ElementVariable,kmb::PhysicalValue::Scalar,"MeshProperty");
}
if( data == NULL ||
data->getBindingMode() != kmb::DataBindings::ElementVariable ||
data->getValueType() != kmb::PhysicalValue::Scalar )
{
return -1.0;
}
kmb::ElementContainer::iterator eIter = body->begin();
double vol = 0.0;
while( !eIter.isFinished() ){
vol = evaluator.getVolume( eIter );
data->setPhysicalValue( eIter.getId(), &vol );
totalVolume += vol;
++eIter;
}
return totalVolume;
}
}
else if( strcmp(name,"MaxEdgeLength")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
kmb::ElementEvaluator evaluator(nodes);
if( body ){
kmb::DataBindings* data = this->getDataBindingsPtr("MaxEdgeLength","MeshProperty");
if( data == NULL ){
data = this->createDataBindings("MaxEdgeLength",kmb::DataBindings::ElementVariable,kmb::PhysicalValue::Scalar,"MeshProperty");
}
if( data == NULL ||
data->getBindingMode() != kmb::DataBindings::ElementVariable ||
data->getValueType() != kmb::PhysicalValue::Scalar )
{
return -1.0;
}
kmb::ElementContainer::iterator eIter = body->begin();
double vol = 0.0;
while( !eIter.isFinished() ){
vol = evaluator.getMaxEdgeLength( eIter );
data->setPhysicalValue( eIter.getId(), &vol );
++eIter;
}
return 0.0;
}
}
else if( strcmp(name,"AverageEdgeLength")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
kmb::ElementEvaluator evaluator(nodes);
if( body ){
kmb::DataBindings* data = this->getDataBindingsPtr("AverageEdgeLength","MeshProperty");
if( data == NULL ){
data = this->createDataBindings("AverageEdgeLength",kmb::DataBindings::ElementVariable,kmb::PhysicalValue::Scalar,"MeshProperty");
}
if( data == NULL ||
data->getBindingMode() != kmb::DataBindings::ElementVariable ||
data->getValueType() != kmb::PhysicalValue::Scalar )
{
return -1.0;
}
kmb::ElementContainer::iterator eIter = body->begin();
double vol = 0.0;
while( !eIter.isFinished() ){
vol = evaluator.getAverageEdgeLength( eIter );
data->setPhysicalValue( eIter.getId(), &vol );
++eIter;
}
return 0.0;
}
}
else if( strcmp(name,"EdgeLengthRatio")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
kmb::ElementEvaluator evaluator(nodes);
if( body ){
kmb::DataBindings* data = this->getDataBindingsPtr("EdgeLengthRatio","MeshProperty");
if( data == NULL ){
data = this->createDataBindings("EdgeLengthRatio",kmb::DataBindings::ElementVariable,kmb::PhysicalValue::Scalar,"MeshProperty");
}
if( data == NULL ||
data->getBindingMode() != kmb::DataBindings::ElementVariable ||
data->getValueType() != kmb::PhysicalValue::Scalar )
{
return -1.0;
}
kmb::ElementContainer::iterator eIter = body->begin();
double vol = 0.0;
while( !eIter.isFinished() ){
vol = evaluator.getEdgeLengthRatio( eIter );
data->setPhysicalValue( eIter.getId(), &vol );
++eIter;
}
return 0.0;
}
}
else if( strcmp(name,"MinAngle")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
kmb::ElementEvaluator evaluator(nodes);
if( body && body->getDimension() >= 2 ){
kmb::DataBindings* data = this->getDataBindingsPtr("MinAngle","MeshProperty");
if( data == NULL ){
data = this->createDataBindings("MinAngle",kmb::DataBindings::ElementVariable,kmb::PhysicalValue::Scalar,"MeshProperty");
}
if( data == NULL ||
data->getBindingMode() != kmb::DataBindings::ElementVariable ||
data->getValueType() != kmb::PhysicalValue::Scalar )
{
return -1.0;
}
kmb::ElementContainer::iterator eIter = body->begin();
double ang = 0.0;
while( !eIter.isFinished() ){
ang = evaluator.getMinAngle( eIter );
data->setPhysicalValue( eIter.getId(), &ang );
++eIter;
}
return 0.0;
}
}
else if( strcmp(name,"MaxAngle")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
kmb::ElementEvaluator evaluator(nodes);
if( body && body->getDimension() >= 2 ){
kmb::DataBindings* data = this->getDataBindingsPtr("MaxAngle","MeshProperty");
if( data == NULL ){
data = this->createDataBindings("MaxAngle",kmb::DataBindings::ElementVariable,kmb::PhysicalValue::Scalar,"MeshProperty");
}
if( data == NULL ||
data->getBindingMode() != kmb::DataBindings::ElementVariable ||
data->getValueType() != kmb::PhysicalValue::Scalar )
{
return -1.0;
}
kmb::ElementContainer::iterator eIter = body->begin();
double ang = 0.0;
while( !eIter.isFinished() ){
ang = evaluator.getMaxAngle( eIter );
data->setPhysicalValue( eIter.getId(), &ang );
++eIter;
}
return 0.0;
}
}
else if( strcmp(name,"ConcaveElement")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
kmb::ElementEvaluator evaluator(nodes);
if( body && body->getDimension() >= 2 ){
kmb::DataBindings* data = this->getDataBindingsPtr("ConcaveElement","MeshProperty");
if( data == NULL ){
data = this->createDataBindings("ConcaveElement",kmb::DataBindings::ElementGroup,kmb::PhysicalValue::None,"MeshProperty");
}
if( data == NULL ||
data->getBindingMode() != kmb::DataBindings::ElementGroup ||
data->getValueType() != kmb::PhysicalValue::None )
{
return -1.0;
}
kmb::ElementContainer::iterator eIter = body->begin();
while( !eIter.isFinished() ){
if( evaluator.getConcaveInQuad( eIter ) != -1 ){
data->addId( eIter.getId() );
}
++eIter;
}
return 0.0;
}
}
else if( strcmp(name,"MinJacobian")==0 ){
kmb::ElementContainer* body = this->getBodyPtr(bodyId);
kmb::Point3DContainer* nodes = this->getNodes();
kmb::ElementEvaluator evaluator(nodes);
if( body && body->getDimension() >= 2 ){
kmb::DataBindings* data = this->getDataBindingsPtr("MinJacobian","MeshProperty");
if( data == NULL ){
data = this->createDataBindings("MinJacobian",kmb::DataBindings::ElementVariable,kmb::PhysicalValue::Scalar,"MeshProperty");
}
if( data == NULL ||
data->getBindingMode() != kmb::DataBindings::ElementVariable ||
data->getValueType() != kmb::PhysicalValue::Scalar )
{
return -1.0;
}
kmb::ElementContainer::iterator eIter = body->begin();
double min=0.0, max=0.0;
while( !eIter.isFinished() ){
if( evaluator.getMinMaxJacobian( eIter, min, max ) ){
data->setValue( eIter.getId(), min );
}
++eIter;
}
return 0.0;
}
}
else if( strcmp(name,"Curvature")==0 ){
kmb::NodeEvaluator nevaluator;
nevaluator.setMesh(this);
this->createDataBindings("Curvature",kmb::DataBindings::NodeVariable,kmb::PhysicalValue::Scalar,"MeshProperty");
nevaluator.calcCurvature("Curvature","MeshProperty");
return 0.0;
}
return -1.0;
}
//------------------- 面積・体積 --------------------------
double
kmb::MeshDB::getElementArea(kmb::elementIdType triId,kmb::bodyIdType bodyId) const
{
kmb::ElementContainer::const_iterator element = this->findElement(triId,bodyId);
if( !element.isFinished() && element.getDimension() == 2 && evaluator ){
return this->evaluator->getArea( element );
}else{
return 0.0;
}
}
double
kmb::MeshDB::getElementVolume(kmb::elementIdType elementId,kmb::bodyIdType bodyId) const
{
kmb::ElementContainer::const_iterator element = this->findElement(elementId,bodyId);
if( !element.isFinished() && element.getDimension() == 3 && evaluator ){
return this->evaluator->getVolume( element );
}else{
return 0.0;
}
}
double
kmb::MeshDB::getArea(kmb::bodyIdType bodyId) const
{
double area = 0.0;
// すでに MeshProperty があればそれを使う
const kmb::ElementContainer* body = this->getBodyPtr(bodyId);
if( body && body->isUniqueDim(2) ){
const kmb::DataBindings* data = this->getDataBindingsPtr("ElementArea","MeshProperty");
if( data != NULL &&
data->getBindingMode() != kmb::DataBindings::ElementVariable &&
data->getValueType() != kmb::PhysicalValue::Scalar )
{
kmb::ElementContainer::const_iterator eIter = body->begin();
while( !eIter.isFinished() ){
double v = 0.0;
data->getPhysicalValue( eIter.getId(), &v );
area += v;
++eIter;
}
}else{
const kmb::Point3DContainer* nodes = this->getNodes();
if( nodes ){
kmb::ElementEvaluator evaluator(nodes);
kmb::ElementContainer::const_iterator eIter = body->begin();
while( !eIter.isFinished() ){
area += evaluator.getArea( eIter );
++eIter;
}
}
}
}
return area;
}
double
kmb::MeshDB::getVolume(kmb::bodyIdType bodyId) const
{
double vol = 0.0;
// すでに MeshProperty があればそれを使う
const kmb::ElementContainer* body = this->getBodyPtr(bodyId);
if( body && body->isUniqueDim(3) ){
const kmb::DataBindings* data = this->getDataBindingsPtr("ElementVolume","MeshProperty");
if( data != NULL &&
data->getBindingMode() != kmb::DataBindings::ElementVariable &&
data->getValueType() != kmb::PhysicalValue::Scalar )
{
kmb::ElementContainer::const_iterator eIter = body->begin();
while( !eIter.isFinished() ){
double v = 0.0;
data->getPhysicalValue( eIter.getId(), &v );
vol += v;
++eIter;
}
}else{
const kmb::Point3DContainer* nodes = this->getNodes();
if( nodes ){
kmb::ElementEvaluator evaluator(nodes);
kmb::ElementContainer::const_iterator eIter = body->begin();
while( !eIter.isFinished() ){
vol += evaluator.getVolume( eIter );
++eIter;
}
}
}
}
return vol;
}
//------------------- 端点 --------------------------
kmb::nodeIdType
kmb::MeshDB::getCornerNodeIdOfSurface(kmb::bodyIdType bodyId,kmb::Vector3D dir) const
{
kmb::nodeIdType nodeId = kmb::nullNodeId;
if( dir.isZero() ){
dir.setCoordinate(1.0, 1.0, 1.0);
}
kmb::Minimizer minimizer;
kmb::Point3D point;
const kmb::ElementContainer* elements = this->getBodyPtr(bodyId);
if( elements && elements->getDimension() == 2 ){
for( kmb::ElementContainer::const_iterator eIter = elements->begin();
!eIter.isFinished(); ++eIter)
{
switch( eIter.getType() )
{
case kmb::TRIANGLE:
case kmb::TRIANGLE2:
for(int i=0;i<3;++i){
if( getNode( eIter[i], point ) &&
minimizer.update( dir.x()*point.x() + dir.y()*point.y() + dir.z()*point.z() ) ){
nodeId = eIter[i];
}
}
break;
case kmb::QUAD:
case kmb::QUAD2:
for(int i=0;i<4;++i){
if( getNode( eIter[i], point ) &&
minimizer.update( dir.x()*point.x() + dir.y()*point.y() + dir.z()*point.z() ) ){
nodeId = eIter[i];
}
}
break;
default:
break;
}
}
}
return nodeId;
}
kmb::nodeIdType
kmb::MeshDB::getCornerNodeIdOfFaceGroup(const char* faceGroup,kmb::Vector3D dir) const
{
kmb::nodeIdType nodeId = kmb::nullNodeId;
if( dir.isZero() ){
dir.setCoordinate(1.0, 1.0, 1.0);
}
kmb::Minimizer minimizer;
kmb::Point3D point;
const kmb::DataBindings* data = this->getDataBindingsPtr(faceGroup);
const kmb::ElementContainer* elements = NULL;
kmb::Face f;
if( data &&
( data->getBindingMode() == kmb::DataBindings::FaceGroup || data->getBindingMode() == kmb::DataBindings::FaceVariable ) &&
( elements = this->getBodyPtr( data->getTargetBodyId() ) ) != NULL )
{
for( kmb::DataBindings::const_iterator fIter = data->begin();
!fIter.isFinished(); ++fIter )
{
if( fIter.getFace(f) ){
kmb::ElementContainer::const_iterator eIter = elements->find( f.getElementId() );
kmb::idType i = f.getLocalFaceId();
switch( eIter.getBoundaryType(i) )
{
case kmb::TRIANGLE:
case kmb::TRIANGLE2:
for(int j=0;j<3;++j){
if( getNode( eIter.getBoundaryCellId(i,j), point ) &&
minimizer.update( dir.x()*point.x() + dir.y()*point.y() + dir.z()*point.z() ) ){
nodeId = eIter.getBoundaryCellId(i,j);
}
}
break;
case kmb::QUAD:
case kmb::QUAD2:
for(int j=0;j<4;++j){
if( getNode( eIter.getBoundaryCellId(i,j), point ) &&
minimizer.update( dir.x()*point.x() + dir.y()*point.y() + dir.z()*point.z() ) ){
nodeId = eIter.getBoundaryCellId(i,j);
}
}
break;
default:
break;
}
}
}
}
return nodeId;
}
| [
"ihara@ricos.co.jp"
] | ihara@ricos.co.jp |
1f54ef23d6f0e7f142d26acf000abc4dd29dd71e | d05d188c1ba2479cc24f94ded6b383d581431df0 | /collision.cpp | ce053c3a621e2156e3089532c0c51772d0961f62 | [] | no_license | SamMul815/A- | 0ea2def3cb74b0049d1427e09b93a384bf79beeb | d2c8410bf459fd4e725089192bf775febee55ab2 | refs/heads/master | 2020-04-18T09:50:22.027635 | 2019-01-24T22:43:00 | 2019-01-24T22:43:00 | 167,448,713 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 7,526 | cpp | #include "stdafx.h"
#include "collision.h"
namespace TANGO_UTIL
{
//POINT가 사각형 안에 있니?
bool CheckPointInRect(const RECT& rc, const POINT& pt)
{
if ((rc.left <= pt.x && pt.x <= rc.right) && (rc.top <= pt.y && pt.y <= rc.bottom)) return true;
return false;
}
bool CheckPointInRect(const RECT& rc, int x, int y)
{
if ((rc.left <= x && x <= rc.right) && (rc.top <= y && y <= rc.bottom)) return true;
return false;
}
bool CheckPointInRect(const MYRECT& rc, float x, float y)
{
if ((rc.left <= x && x <= rc.right) && (rc.top <= y && y <= rc.bottom)) return true;
return false;
}
bool CheckPointInRect(const MYRECT& rc, const MYPOINT& pt)
{
if ((rc.left <= pt.x && pt.x <= rc.right) && (rc.top <= pt.y && pt.y <= rc.bottom)) return true;
return false;
}
//POINT가 원 안에 있니?
bool CheckPointInCircle(float cX, float cY, float cR, const MYPOINT& pt)
{
float deltaX = pt.x - cX;
float deltaY = pt.y - cY;
float distance = deltaX * deltaX + deltaY* deltaY;
float radiusSquare = cR * cR;
if (radiusSquare < distance) return false;
return true;
}
bool CheckPointInCircle(float cX, float cY, float cR, float x, float y)
{
float deltaX = x - cX;
float deltaY = y - cY;
float distance = deltaX * deltaX + deltaY* deltaY;
float radiusSquare = cR * cR;
if (radiusSquare < distance) return false;
return true;
}
bool CheckPointInCircle(const MYCIRCLE& rc, float x, float y)
{
float deltaX = x - rc.x;
float deltaY = y - rc.y;
float distance = deltaX * deltaX + deltaY* deltaY;
float radiusSquare = rc.r * rc.r;
if (radiusSquare < distance) return false;
return true;
}
bool CheckPointInCircle(const MYCIRCLE& rc, const MYPOINT& pt)
{
float deltaX = pt.x - rc.x;
float deltaY = pt.y - rc.y;
float distance = deltaX * deltaX + deltaY* deltaY;
float radiusSquare = rc.r * rc.r;
if (radiusSquare < distance) return false;
return true;
}
//사각형이 사각형과 충돌했니?
bool IsCollision(const MYRECT& rc1, const MYRECT& rc2)
{
if ((rc1.left <= rc2.right && rc1.right >= rc2.left) &&
(rc1.top <= rc2.bottom && rc1.bottom >= rc2.top)) return true;
return false;
}
bool IsCollision(const RECT& rc1, const RECT& rc2)
{
if ((rc1.left <= rc2.right && rc1.right >= rc2.left) &&
(rc1.top <= rc2.bottom && rc1.bottom >= rc2.top)) return true;
return false;
}
//원과 원이 충돌했니?
bool IsCollision(const MYCIRCLE& cir1, const MYCIRCLE& cir2)
{
float deltaX = cir2.x - cir1.x;
float deltaY = cir2.y - cir1.y;
float distance = deltaX * deltaX + deltaY * deltaY;
float radius = cir1.r + cir2.r;
float radiusSquare = radius * radius;
if (distance > radiusSquare) return false;
return true;
}
//원과 사각형이 충돌했니?
bool IsCollision(const MYCIRCLE& cir, const RECT& rc)
{
int centerX = FLOAT_TO_INT(cir.x);
int centerY = FLOAT_TO_INT(cir.y);
int radius = FLOAT_TO_INT(cir.r);
if ((rc.left <= centerX && centerX <= rc.right) ||
(rc.top <= centerY && centerY <= rc.bottom))
{
//사각형을 원의 크기만큼 임의로 키워준다
RECT exRect;
exRect.left = rc.left - radius;
exRect.right = rc.right + radius;
exRect.top = rc.top - radius;
exRect.bottom = rc.bottom + radius;
if ((exRect.left <= centerX && centerX <= exRect.right) &&
(exRect.top <= centerY && centerY <= exRect.bottom))
{
return true;
}
}
else
{
//모서리 처리!
if (CheckPointInCircle(cir, (float)rc.left, (float)rc.top)) return true;
if (CheckPointInCircle(cir, (float)rc.right, (float)rc.top)) return true;
if (CheckPointInCircle(cir, (float)rc.left, (float)rc.bottom)) return true;
if (CheckPointInCircle(cir, (float)rc.right, (float)rc.bottom)) return true;
}
return false;
}
bool IsCollision(const MYCIRCLE& cir, const MYRECT& rc)
{
int centerX = FLOAT_TO_INT(cir.x);
int centerY = FLOAT_TO_INT(cir.y);
int radius = FLOAT_TO_INT(cir.r);
if ((rc.left <= centerX && centerX <= rc.right) ||
(rc.top <= centerY && centerY <= rc.bottom))
{
//사각형을 원의 크기만큼 임의로 키워준다
RECT exRect;
exRect.left = rc.left - radius;
exRect.right = rc.right + radius;
exRect.top = rc.top - radius;
exRect.bottom = rc.bottom + radius;
if ((exRect.left <= centerX && centerX <= exRect.right) &&
(exRect.top <= centerY && centerY <= exRect.bottom))
{
return true;
}
}
else
{
//모서리 처리!
if (CheckPointInCircle(cir, (float)rc.left, (float)rc.top)) return true;
if (CheckPointInCircle(cir, (float)rc.right, (float)rc.top)) return true;
if (CheckPointInCircle(cir, (float)rc.left, (float)rc.bottom)) return true;
if (CheckPointInCircle(cir, (float)rc.right, (float)rc.bottom)) return true;
}
return false;
}
//충돌했다면 리액션은 어떻게 취하니?
bool IsCollisionReaction(const RECT& rcHold, RECT& rcMove)
{
RECT rcInter;
if (!IntersectRect(&rcInter, &rcHold, &rcMove)) return false;
int interW = rcInter.right - rcInter.left;
int interH = rcInter.bottom - rcInter.top;
//수직충돌이냐?
if (interW > interH)
{
//위~
if (rcInter.top == rcHold.top)
{
OffsetRect(&rcMove, 0, -interH);
}
//아래~
else if (rcInter.bottom == rcHold.bottom)
{
OffsetRect(&rcMove, 0, interH);
}
}
//수평충돌이냐?
else
{
//좌~
if (rcInter.left == rcHold.left)
{
OffsetRect(&rcMove, -interW, 0);
}
//우~
else if (rcInter.right == rcHold.right)
{
OffsetRect(&rcMove, interW, 0);
}
}
return true;
}
bool IsCollisionReaction(const MYRECT& mrcHold, MYRECT& mrcMove)
{
RECT rcHold;
rcHold.left = FLOAT_TO_INT(mrcHold.left);
rcHold.top = FLOAT_TO_INT(mrcHold.top);
rcHold.right = FLOAT_TO_INT(mrcHold.right);
rcHold.bottom = FLOAT_TO_INT(mrcHold.bottom);
RECT rcMove;
rcMove.left = FLOAT_TO_INT(mrcMove.left);
rcMove.top = FLOAT_TO_INT(mrcMove.top);
rcMove.right = FLOAT_TO_INT(mrcMove.right);
rcMove.bottom = FLOAT_TO_INT(mrcMove.bottom);
RECT rcInter;
if (!IntersectRect(&rcInter, &rcHold, &rcMove)) return false;
int interW = rcInter.right - rcInter.left;
int interH = rcInter.bottom - rcInter.top;
//수직충돌이냐?
if (interW > interH)
{
//위~
if (rcInter.top == rcHold.top)
{
OffsetRect(&rcMove, 0, -interH);
}
//아래~
else if (rcInter.bottom == rcHold.bottom)
{
OffsetRect(&rcMove, 0, interH);
}
}
//수평충돌이냐?
else
{
//좌~
if (rcInter.left == rcHold.left)
{
OffsetRect(&rcMove, -interW, 0);
}
//우~
else if (rcInter.right == rcHold.right)
{
OffsetRect(&rcMove, interW, 0);
}
}
mrcMove.left = static_cast<float>(rcMove.left);
mrcMove.top = static_cast<float>(rcMove.top);
mrcMove.right = static_cast<float>(rcMove.right);
mrcMove.bottom = static_cast<float>(rcMove.bottom);
return true;
}
bool IsCollisionReaction(const MYCIRCLE& cirHold, MYCIRCLE& cirMove)
{
float deltaX = cirMove.x - cirHold.x;
float deltaY = cirMove.y - cirHold.y;
float distance = sqrtf(deltaX * deltaX + deltaY * deltaY);
float radius = cirHold.r + cirMove.r;
if (distance < radius)
{
float angle = GetAngle(cirHold.x, cirHold.y, cirMove.x, cirMove.y);
float moveDelta = radius - distance;
float moveX = cos(angle) * moveDelta;
float moveY = -sin(angle) * moveDelta;
cirMove.Move(moveX, moveY);
return true;
}
return false;
}
} | [
"815youngmin@naver.com"
] | 815youngmin@naver.com |
f6d8acc585eac14d23a0667ff48b324a1244faf8 | 0460ddde818f4533b1bbe86302ec4c314ed076a0 | /JuceLibraryCode/modules/juce_gui_basics/native/juce_linux_Windowing.cpp | 79d3de60b9ac9ef8e49759659606f18658f62c5c | [] | no_license | curiousChrisps/Simple-Synth | adf846056ea72913e1e3da1663ac1fe1a7083918 | 7733c88666eeb01fef70ae5785e9dcfdba63a2af | refs/heads/master | 2021-08-08T02:43:43.106413 | 2017-11-09T11:50:06 | 2017-11-09T11:50:06 | 110,109,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 122,751 | cpp | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
extern Display* display;
extern XContext windowHandleXContext;
typedef void (*WindowMessageReceiveCallback) (XEvent&);
extern WindowMessageReceiveCallback dispatchWindowMessage;
//==============================================================================
struct Atoms
{
Atoms()
{
Protocols = getIfExists ("WM_PROTOCOLS");
ProtocolList [TAKE_FOCUS] = getIfExists ("WM_TAKE_FOCUS");
ProtocolList [DELETE_WINDOW] = getIfExists ("WM_DELETE_WINDOW");
ProtocolList [PING] = getIfExists ("_NET_WM_PING");
ChangeState = getIfExists ("WM_CHANGE_STATE");
State = getIfExists ("WM_STATE");
UserTime = getCreating ("_NET_WM_USER_TIME");
ActiveWin = getCreating ("_NET_ACTIVE_WINDOW");
Pid = getCreating ("_NET_WM_PID");
WindowType = getIfExists ("_NET_WM_WINDOW_TYPE");
WindowState = getIfExists ("_NET_WM_STATE");
XdndAware = getCreating ("XdndAware");
XdndEnter = getCreating ("XdndEnter");
XdndLeave = getCreating ("XdndLeave");
XdndPosition = getCreating ("XdndPosition");
XdndStatus = getCreating ("XdndStatus");
XdndDrop = getCreating ("XdndDrop");
XdndFinished = getCreating ("XdndFinished");
XdndSelection = getCreating ("XdndSelection");
XdndTypeList = getCreating ("XdndTypeList");
XdndActionList = getCreating ("XdndActionList");
XdndActionCopy = getCreating ("XdndActionCopy");
XdndActionPrivate = getCreating ("XdndActionPrivate");
XdndActionDescription = getCreating ("XdndActionDescription");
allowedMimeTypes[0] = getCreating ("UTF8_STRING");
allowedMimeTypes[1] = getCreating ("text/plain;charset=utf-8");
allowedMimeTypes[2] = getCreating ("text/plain");
allowedMimeTypes[3] = getCreating ("text/uri-list");
externalAllowedFileMimeTypes[0] = getCreating ("text/uri-list");
externalAllowedTextMimeTypes[0] = getCreating ("text/plain");
allowedActions[0] = getCreating ("XdndActionMove");
allowedActions[1] = XdndActionCopy;
allowedActions[2] = getCreating ("XdndActionLink");
allowedActions[3] = getCreating ("XdndActionAsk");
allowedActions[4] = XdndActionPrivate;
}
static const Atoms& get()
{
static Atoms atoms;
return atoms;
}
enum ProtocolItems
{
TAKE_FOCUS = 0,
DELETE_WINDOW = 1,
PING = 2
};
Atom Protocols, ProtocolList[3], ChangeState, State, UserTime,
ActiveWin, Pid, WindowType, WindowState,
XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
XdndActionDescription, XdndActionCopy, XdndActionPrivate,
allowedActions[5],
allowedMimeTypes[4],
externalAllowedFileMimeTypes[1],
externalAllowedTextMimeTypes[1];
static const unsigned long DndVersion;
static Atom getIfExists (const char* name) { return XInternAtom (display, name, True); }
static Atom getCreating (const char* name) { return XInternAtom (display, name, False); }
static String getName (const Atom atom)
{
if (atom == None)
return "None";
return String (XGetAtomName (display, atom));
}
static bool isMimeTypeFile (const Atom atom) { return getName (atom).equalsIgnoreCase ("text/uri-list"); }
};
const unsigned long Atoms::DndVersion = 3;
//==============================================================================
struct GetXProperty
{
GetXProperty (Window window, Atom atom, long offset, long length, bool shouldDelete, Atom requestedType)
: data (nullptr)
{
success = (XGetWindowProperty (display, window, atom, offset, length,
(Bool) shouldDelete, requestedType, &actualType,
&actualFormat, &numItems, &bytesLeft, &data) == Success)
&& data != nullptr;
}
~GetXProperty()
{
if (data != nullptr)
XFree (data);
}
bool success;
unsigned char* data;
unsigned long numItems, bytesLeft;
Atom actualType;
int actualFormat;
};
//==============================================================================
namespace Keys
{
enum MouseButtons
{
NoButton = 0,
LeftButton = 1,
MiddleButton = 2,
RightButton = 3,
WheelUp = 4,
WheelDown = 5
};
static int AltMask = 0;
static int NumLockMask = 0;
static bool numLock = false;
static bool capsLock = false;
static char keyStates [32];
static const int extendedKeyModifier = 0x10000000;
}
bool KeyPress::isKeyCurrentlyDown (const int keyCode)
{
int keysym;
if (keyCode & Keys::extendedKeyModifier)
{
keysym = 0xff00 | (keyCode & 0xff);
}
else
{
keysym = keyCode;
if (keysym == (XK_Tab & 0xff)
|| keysym == (XK_Return & 0xff)
|| keysym == (XK_Escape & 0xff)
|| keysym == (XK_BackSpace & 0xff))
{
keysym |= 0xff00;
}
}
ScopedXLock xlock;
const int keycode = XKeysymToKeycode (display, keysym);
const int keybyte = keycode >> 3;
const int keybit = (1 << (keycode & 7));
return (Keys::keyStates [keybyte] & keybit) != 0;
}
//==============================================================================
#if JUCE_USE_XSHM
namespace XSHMHelpers
{
static int trappedErrorCode = 0;
extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
{
trappedErrorCode = err->error_code;
return 0;
}
static bool isShmAvailable() noexcept
{
static bool isChecked = false;
static bool isAvailable = false;
if (! isChecked)
{
isChecked = true;
int major, minor;
Bool pixmaps;
ScopedXLock xlock;
if (XShmQueryVersion (display, &major, &minor, &pixmaps))
{
trappedErrorCode = 0;
XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
XShmSegmentInfo segmentInfo;
zerostruct (segmentInfo);
XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
24, ZPixmap, 0, &segmentInfo, 50, 50);
if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
xImage->bytes_per_line * xImage->height,
IPC_CREAT | 0777)) >= 0)
{
segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
if (segmentInfo.shmaddr != (void*) -1)
{
segmentInfo.readOnly = False;
xImage->data = segmentInfo.shmaddr;
XSync (display, False);
if (XShmAttach (display, &segmentInfo) != 0)
{
XSync (display, False);
XShmDetach (display, &segmentInfo);
isAvailable = true;
}
}
XFlush (display);
XDestroyImage (xImage);
shmdt (segmentInfo.shmaddr);
}
shmctl (segmentInfo.shmid, IPC_RMID, 0);
XSetErrorHandler (oldHandler);
if (trappedErrorCode != 0)
isAvailable = false;
}
}
return isAvailable;
}
}
#endif
//==============================================================================
#if JUCE_USE_XRENDER
namespace XRender
{
typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
typedef XRenderPictFormat* (*tXRenderFindStandardFormat) (Display*, int);
typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
static tXRenderQueryVersion xRenderQueryVersion = nullptr;
static tXRenderFindStandardFormat xRenderFindStandardFormat = nullptr;
static tXRenderFindFormat xRenderFindFormat = nullptr;
static tXRenderFindVisualFormat xRenderFindVisualFormat = nullptr;
static bool isAvailable()
{
static bool hasLoaded = false;
if (! hasLoaded)
{
ScopedXLock xlock;
hasLoaded = true;
if (void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW))
{
xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
xRenderFindStandardFormat = (tXRenderFindStandardFormat) dlsym (h, "XRenderFindStandardFormat");
xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
}
if (xRenderQueryVersion != nullptr
&& xRenderFindStandardFormat != nullptr
&& xRenderFindFormat != nullptr
&& xRenderFindVisualFormat != nullptr)
{
int major, minor;
if (xRenderQueryVersion (display, &major, &minor))
return true;
}
xRenderQueryVersion = nullptr;
}
return xRenderQueryVersion != nullptr;
}
static XRenderPictFormat* findPictureFormat()
{
ScopedXLock xlock;
XRenderPictFormat* pictFormat = nullptr;
if (isAvailable())
{
pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
if (pictFormat == nullptr)
{
XRenderPictFormat desiredFormat;
desiredFormat.type = PictTypeDirect;
desiredFormat.depth = 32;
desiredFormat.direct.alphaMask = 0xff;
desiredFormat.direct.redMask = 0xff;
desiredFormat.direct.greenMask = 0xff;
desiredFormat.direct.blueMask = 0xff;
desiredFormat.direct.alpha = 24;
desiredFormat.direct.red = 16;
desiredFormat.direct.green = 8;
desiredFormat.direct.blue = 0;
pictFormat = xRenderFindFormat (display,
PictFormatType | PictFormatDepth
| PictFormatRedMask | PictFormatRed
| PictFormatGreenMask | PictFormatGreen
| PictFormatBlueMask | PictFormatBlue
| PictFormatAlphaMask | PictFormatAlpha,
&desiredFormat,
0);
}
}
return pictFormat;
}
}
#endif
//==============================================================================
namespace Visuals
{
static Visual* findVisualWithDepth (const int desiredDepth) noexcept
{
ScopedXLock xlock;
Visual* visual = nullptr;
int numVisuals = 0;
long desiredMask = VisualNoMask;
XVisualInfo desiredVisual;
desiredVisual.screen = DefaultScreen (display);
desiredVisual.depth = desiredDepth;
desiredMask = VisualScreenMask | VisualDepthMask;
if (desiredDepth == 32)
{
desiredVisual.c_class = TrueColor;
desiredVisual.red_mask = 0x00FF0000;
desiredVisual.green_mask = 0x0000FF00;
desiredVisual.blue_mask = 0x000000FF;
desiredVisual.bits_per_rgb = 8;
desiredMask |= VisualClassMask;
desiredMask |= VisualRedMaskMask;
desiredMask |= VisualGreenMaskMask;
desiredMask |= VisualBlueMaskMask;
desiredMask |= VisualBitsPerRGBMask;
}
XVisualInfo* xvinfos = XGetVisualInfo (display,
desiredMask,
&desiredVisual,
&numVisuals);
if (xvinfos != nullptr)
{
for (int i = 0; i < numVisuals; i++)
{
if (xvinfos[i].depth == desiredDepth)
{
visual = xvinfos[i].visual;
break;
}
}
XFree (xvinfos);
}
return visual;
}
static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) noexcept
{
Visual* visual = nullptr;
if (desiredDepth == 32)
{
#if JUCE_USE_XSHM
if (XSHMHelpers::isShmAvailable())
{
#if JUCE_USE_XRENDER
if (XRender::isAvailable())
{
XRenderPictFormat* pictFormat = XRender::findPictureFormat();
if (pictFormat != 0)
{
int numVisuals = 0;
XVisualInfo desiredVisual;
desiredVisual.screen = DefaultScreen (display);
desiredVisual.depth = 32;
desiredVisual.bits_per_rgb = 8;
XVisualInfo* xvinfos = XGetVisualInfo (display,
VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
&desiredVisual, &numVisuals);
if (xvinfos != nullptr)
{
for (int i = 0; i < numVisuals; ++i)
{
XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
if (pictVisualFormat != nullptr
&& pictVisualFormat->type == PictTypeDirect
&& pictVisualFormat->direct.alphaMask)
{
visual = xvinfos[i].visual;
matchedDepth = 32;
break;
}
}
XFree (xvinfos);
}
}
}
#endif
if (visual == nullptr)
{
visual = findVisualWithDepth (32);
if (visual != nullptr)
matchedDepth = 32;
}
}
#endif
}
if (visual == nullptr && desiredDepth >= 24)
{
visual = findVisualWithDepth (24);
if (visual != nullptr)
matchedDepth = 24;
}
if (visual == nullptr && desiredDepth >= 16)
{
visual = findVisualWithDepth (16);
if (visual != nullptr)
matchedDepth = 16;
}
return visual;
}
}
//==============================================================================
class XBitmapImage : public ImagePixelData
{
public:
XBitmapImage (const Image::PixelFormat format, const int w, const int h,
const bool clearImage, const int imageDepth_, Visual* visual)
: ImagePixelData (format, w, h),
imageDepth (imageDepth_),
gc (None)
{
jassert (format == Image::RGB || format == Image::ARGB);
pixelStride = (format == Image::RGB) ? 3 : 4;
lineStride = ((w * pixelStride + 3) & ~3);
ScopedXLock xlock;
#if JUCE_USE_XSHM
usingXShm = false;
if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
{
zerostruct (segmentInfo);
segmentInfo.shmid = -1;
segmentInfo.shmaddr = (char *) -1;
segmentInfo.readOnly = False;
xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
if (xImage != nullptr)
{
if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
xImage->bytes_per_line * xImage->height,
IPC_CREAT | 0777)) >= 0)
{
if (segmentInfo.shmid != -1)
{
segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
if (segmentInfo.shmaddr != (void*) -1)
{
segmentInfo.readOnly = False;
xImage->data = segmentInfo.shmaddr;
imageData = (uint8*) segmentInfo.shmaddr;
if (XShmAttach (display, &segmentInfo) != 0)
usingXShm = true;
else
jassertfalse;
}
else
{
shmctl (segmentInfo.shmid, IPC_RMID, 0);
}
}
}
}
}
if (! usingXShm)
#endif
{
imageDataAllocated.allocate (lineStride * h, format == Image::ARGB && clearImage);
imageData = imageDataAllocated;
xImage = (XImage*) ::calloc (1, sizeof (XImage));
xImage->width = w;
xImage->height = h;
xImage->xoffset = 0;
xImage->format = ZPixmap;
xImage->data = (char*) imageData;
xImage->byte_order = ImageByteOrder (display);
xImage->bitmap_unit = BitmapUnit (display);
xImage->bitmap_bit_order = BitmapBitOrder (display);
xImage->bitmap_pad = 32;
xImage->depth = pixelStride * 8;
xImage->bytes_per_line = lineStride;
xImage->bits_per_pixel = pixelStride * 8;
xImage->red_mask = 0x00FF0000;
xImage->green_mask = 0x0000FF00;
xImage->blue_mask = 0x000000FF;
if (imageDepth == 16)
{
const int pixelStride = 2;
const int lineStride = ((w * pixelStride + 3) & ~3);
imageData16Bit.malloc (lineStride * h);
xImage->data = imageData16Bit;
xImage->bitmap_pad = 16;
xImage->depth = pixelStride * 8;
xImage->bytes_per_line = lineStride;
xImage->bits_per_pixel = pixelStride * 8;
xImage->red_mask = visual->red_mask;
xImage->green_mask = visual->green_mask;
xImage->blue_mask = visual->blue_mask;
}
if (! XInitImage (xImage))
jassertfalse;
}
}
~XBitmapImage()
{
ScopedXLock xlock;
if (gc != None)
XFreeGC (display, gc);
#if JUCE_USE_XSHM
if (usingXShm)
{
XShmDetach (display, &segmentInfo);
XFlush (display);
XDestroyImage (xImage);
shmdt (segmentInfo.shmaddr);
shmctl (segmentInfo.shmid, IPC_RMID, 0);
}
else
#endif
{
xImage->data = nullptr;
XDestroyImage (xImage);
}
}
LowLevelGraphicsContext* createLowLevelContext() override
{
return new LowLevelGraphicsSoftwareRenderer (Image (this));
}
void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode) override
{
bitmap.data = imageData + x * pixelStride + y * lineStride;
bitmap.pixelFormat = pixelFormat;
bitmap.lineStride = lineStride;
bitmap.pixelStride = pixelStride;
}
ImagePixelData* clone() override
{
jassertfalse;
return nullptr;
}
ImageType* createType() const override { return new NativeImageType(); }
void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
{
ScopedXLock xlock;
if (gc == None)
{
XGCValues gcvalues;
gcvalues.foreground = None;
gcvalues.background = None;
gcvalues.function = GXcopy;
gcvalues.plane_mask = AllPlanes;
gcvalues.clip_mask = None;
gcvalues.graphics_exposures = False;
gc = XCreateGC (display, window,
GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
&gcvalues);
}
if (imageDepth == 16)
{
const uint32 rMask = xImage->red_mask;
const uint32 gMask = xImage->green_mask;
const uint32 bMask = xImage->blue_mask;
const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
const Image::BitmapData srcData (Image (this), Image::BitmapData::readOnly);
for (int y = sy; y < sy + dh; ++y)
{
const uint8* p = srcData.getPixelPointer (sx, y);
for (int x = sx; x < sx + dw; ++x)
{
const PixelRGB* const pixel = (const PixelRGB*) p;
p += srcData.pixelStride;
XPutPixel (xImage, x, y,
(((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
| (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
| (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
}
}
}
// blit results to screen.
#if JUCE_USE_XSHM
if (usingXShm)
XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
else
#endif
XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
}
private:
//==============================================================================
XImage* xImage;
const int imageDepth;
HeapBlock <uint8> imageDataAllocated;
HeapBlock <char> imageData16Bit;
int pixelStride, lineStride;
uint8* imageData;
GC gc;
#if JUCE_USE_XSHM
XShmSegmentInfo segmentInfo;
bool usingXShm;
#endif
static int getShiftNeeded (const uint32 mask) noexcept
{
for (int i = 32; --i >= 0;)
if (((mask >> i) & 1) != 0)
return i - 7;
jassertfalse;
return 0;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage)
};
//==============================================================================
namespace PixmapHelpers
{
Pixmap createColourPixmapFromImage (Display* display, const Image& image)
{
ScopedXLock xlock;
const int width = image.getWidth();
const int height = image.getHeight();
HeapBlock <uint32> colour (width * height);
int index = 0;
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
colour[index++] = image.getPixelAt (x, y).getARGB();
XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
0, reinterpret_cast<char*> (colour.getData()),
width, height, 32, 0);
Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
width, height, 24);
GC gc = XCreateGC (display, pixmap, 0, 0);
XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
XFreeGC (display, gc);
return pixmap;
}
Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
{
ScopedXLock xlock;
const int width = image.getWidth();
const int height = image.getHeight();
const int stride = (width + 7) >> 3;
HeapBlock <char> mask;
mask.calloc (stride * height);
const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
const int offset = y * stride + (x >> 3);
if (image.getPixelAt (x, y).getAlpha() >= 128)
mask[offset] |= bit;
}
}
return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
mask.getData(), width, height, 1, 0, 1);
}
}
static void* createDraggingHandCursor()
{
static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0, 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217, 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
const int dragHandDataSize = 99;
return CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7).create();
}
//==============================================================================
static int numAlwaysOnTopPeers = 0;
bool juce_areThereAnyAlwaysOnTopWindows()
{
return numAlwaysOnTopPeers > 0;
}
//==============================================================================
class LinuxComponentPeer : public ComponentPeer
{
public:
LinuxComponentPeer (Component& comp, const int windowStyleFlags, Window parentToAddTo)
: ComponentPeer (comp, windowStyleFlags),
windowH (0), parentWindow (0),
fullScreen (false), mapped (false),
visual (nullptr), depth (0),
isAlwaysOnTop (comp.isAlwaysOnTop())
{
// it's dangerous to create a window on a thread other than the message thread..
jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
dispatchWindowMessage = windowMessageReceive;
repainter = new LinuxRepaintManager (*this);
if (isAlwaysOnTop)
++numAlwaysOnTopPeers;
createWindow (parentToAddTo);
setTitle (component.getName());
}
~LinuxComponentPeer()
{
// it's dangerous to delete a window on a thread other than the message thread..
jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
deleteIconPixmaps();
destroyWindow();
windowH = 0;
if (isAlwaysOnTop)
--numAlwaysOnTopPeers;
}
// (this callback is hooked up in the messaging code)
static void windowMessageReceive (XEvent& event)
{
if (event.xany.window != None)
{
if (LinuxComponentPeer* const peer = getPeerFor (event.xany.window))
peer->handleWindowMessage (event);
}
else if (event.xany.type == KeymapNotify)
{
const XKeymapEvent& keymapEvent = (const XKeymapEvent&) event.xkeymap;
memcpy (Keys::keyStates, keymapEvent.key_vector, 32);
}
}
//==============================================================================
void* getNativeHandle() const override
{
return (void*) windowH;
}
static LinuxComponentPeer* getPeerFor (Window windowHandle) noexcept
{
XPointer peer = nullptr;
ScopedXLock xlock;
if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
if (peer != nullptr && ! ComponentPeer::isValidPeer (reinterpret_cast <LinuxComponentPeer*> (peer)))
peer = nullptr;
return reinterpret_cast <LinuxComponentPeer*> (peer);
}
void setVisible (bool shouldBeVisible) override
{
ScopedXLock xlock;
if (shouldBeVisible)
XMapWindow (display, windowH);
else
XUnmapWindow (display, windowH);
}
void setTitle (const String& title) override
{
XTextProperty nameProperty;
char* strings[] = { const_cast <char*> (title.toRawUTF8()) };
ScopedXLock xlock;
if (XStringListToTextProperty (strings, 1, &nameProperty))
{
XSetWMName (display, windowH, &nameProperty);
XSetWMIconName (display, windowH, &nameProperty);
XFree (nameProperty.value);
}
}
void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
{
if (fullScreen && ! isNowFullScreen)
{
// When transitioning back from fullscreen, we might need to remove
// the FULLSCREEN window property
Atom fs = Atoms::getIfExists ("_NET_WM_STATE_FULLSCREEN");
if (fs != None)
{
Window root = RootWindow (display, DefaultScreen (display));
XClientMessageEvent clientMsg;
clientMsg.display = display;
clientMsg.window = windowH;
clientMsg.type = ClientMessage;
clientMsg.format = 32;
clientMsg.message_type = Atoms::get().WindowState;
clientMsg.data.l[0] = 0; // Remove
clientMsg.data.l[1] = fs;
clientMsg.data.l[2] = 0;
clientMsg.data.l[3] = 1; // Normal Source
ScopedXLock xlock;
XSendEvent (display, root, false,
SubstructureRedirectMask | SubstructureNotifyMask,
(XEvent*) &clientMsg);
}
}
fullScreen = isNowFullScreen;
if (windowH != 0)
{
bounds = newBounds.withSize (jmax (1, newBounds.getWidth()),
jmax (1, newBounds.getHeight()));
WeakReference<Component> deletionChecker (&component);
ScopedXLock xlock;
XSizeHints* const hints = XAllocSizeHints();
hints->flags = USSize | USPosition;
hints->x = bounds.getX();
hints->y = bounds.getY();
hints->width = bounds.getWidth();
hints->height = bounds.getHeight();
if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
{
hints->min_width = hints->max_width = hints->width;
hints->min_height = hints->max_height = hints->height;
hints->flags |= PMinSize | PMaxSize;
}
XSetWMNormalHints (display, windowH, hints);
XFree (hints);
XMoveResizeWindow (display, windowH,
bounds.getX() - windowBorder.getLeft(),
bounds.getY() - windowBorder.getTop(),
bounds.getWidth(),
bounds.getHeight());
if (deletionChecker != nullptr)
{
updateBorderSize();
handleMovedOrResized();
}
}
}
Rectangle<int> getBounds() const override { return bounds; }
Point<int> localToGlobal (Point<int> relativePosition) override
{
return relativePosition + bounds.getPosition();
}
Point<int> globalToLocal (Point<int> screenPosition) override
{
return screenPosition - bounds.getPosition();
}
void setAlpha (float /* newAlpha */) override
{
//xxx todo!
}
StringArray getAvailableRenderingEngines() override
{
return StringArray ("Software Renderer");
}
void setMinimised (bool shouldBeMinimised) override
{
if (shouldBeMinimised)
{
Window root = RootWindow (display, DefaultScreen (display));
XClientMessageEvent clientMsg;
clientMsg.display = display;
clientMsg.window = windowH;
clientMsg.type = ClientMessage;
clientMsg.format = 32;
clientMsg.message_type = Atoms::get().ChangeState;
clientMsg.data.l[0] = IconicState;
ScopedXLock xlock;
XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
}
else
{
setVisible (true);
}
}
bool isMinimised() const override
{
ScopedXLock xlock;
const Atoms& atoms = Atoms::get();
GetXProperty prop (windowH, atoms.State, 0, 64, false, atoms.State);
return prop.success
&& prop.actualType == atoms.State
&& prop.actualFormat == 32
&& prop.numItems > 0
&& ((unsigned long*) prop.data)[0] == IconicState;
}
void setFullScreen (const bool shouldBeFullScreen) override
{
Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
setMinimised (false);
if (fullScreen != shouldBeFullScreen)
{
if (shouldBeFullScreen)
r = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
if (! r.isEmpty())
setBounds (r, shouldBeFullScreen);
component.repaint();
}
}
bool isFullScreen() const override
{
return fullScreen;
}
bool isChildWindowOf (Window possibleParent) const
{
Window* windowList = nullptr;
uint32 windowListSize = 0;
Window parent, root;
ScopedXLock xlock;
if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
{
if (windowList != nullptr)
XFree (windowList);
return parent == possibleParent;
}
return false;
}
bool isFrontWindow() const
{
Window* windowList = nullptr;
uint32 windowListSize = 0;
bool result = false;
ScopedXLock xlock;
Window parent, root = RootWindow (display, DefaultScreen (display));
if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
{
for (int i = windowListSize; --i >= 0;)
{
LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
if (peer != 0)
{
result = (peer == this);
break;
}
}
}
if (windowList != nullptr)
XFree (windowList);
return result;
}
bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
{
if (! bounds.withZeroOrigin().contains (localPos))
return false;
for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
{
Component* const c = Desktop::getInstance().getComponent (i);
if (c == &component)
break;
// TODO: needs scaling correctly
if (c->contains (localPos + bounds.getPosition() - c->getScreenPosition()))
return false;
}
if (trueIfInAChildWindow)
return true;
::Window root, child;
int wx, wy;
unsigned int ww, wh, bw, depth;
ScopedXLock xlock;
return XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &depth)
&& XTranslateCoordinates (display, windowH, windowH, localPos.getX(), localPos.getY(), &wx, &wy, &child)
&& child == None;
}
BorderSize<int> getFrameSize() const override
{
return BorderSize<int>();
}
bool setAlwaysOnTop (bool /* alwaysOnTop */) override
{
return false;
}
void toFront (bool makeActive) override
{
if (makeActive)
{
setVisible (true);
grabFocus();
}
{
ScopedXLock xlock;
XEvent ev;
ev.xclient.type = ClientMessage;
ev.xclient.serial = 0;
ev.xclient.send_event = True;
ev.xclient.message_type = Atoms::get().ActiveWin;
ev.xclient.window = windowH;
ev.xclient.format = 32;
ev.xclient.data.l[0] = 2;
ev.xclient.data.l[1] = getUserTime();
ev.xclient.data.l[2] = 0;
ev.xclient.data.l[3] = 0;
ev.xclient.data.l[4] = 0;
XSendEvent (display, RootWindow (display, DefaultScreen (display)),
False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
XWindowAttributes attr;
XGetWindowAttributes (display, windowH, &attr);
if (component.isAlwaysOnTop())
XRaiseWindow (display, windowH);
XSync (display, False);
}
handleBroughtToFront();
}
void toBehind (ComponentPeer* other) override
{
LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
jassert (otherPeer != nullptr); // wrong type of window?
if (otherPeer != nullptr)
{
setMinimised (false);
Window newStack[] = { otherPeer->windowH, windowH };
ScopedXLock xlock;
XRestackWindows (display, newStack, 2);
}
}
bool isFocused() const override
{
int revert = 0;
Window focusedWindow = 0;
ScopedXLock xlock;
XGetInputFocus (display, &focusedWindow, &revert);
return focusedWindow == windowH;
}
void grabFocus() override
{
XWindowAttributes atts;
ScopedXLock xlock;
if (windowH != 0
&& XGetWindowAttributes (display, windowH, &atts)
&& atts.map_state == IsViewable
&& ! isFocused())
{
XSetInputFocus (display, windowH, RevertToParent, getUserTime());
isActiveApplication = true;
}
}
void textInputRequired (const Point<int>&) override {}
void repaint (const Rectangle<int>& area) override
{
repainter->repaint (area.getIntersection (component.getLocalBounds()));
}
void performAnyPendingRepaintsNow() override
{
repainter->performAnyPendingRepaintsNow();
}
void setIcon (const Image& newIcon) override
{
const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
HeapBlock <unsigned long> data (dataSize);
int index = 0;
data[index++] = (unsigned long) newIcon.getWidth();
data[index++] = (unsigned long) newIcon.getHeight();
for (int y = 0; y < newIcon.getHeight(); ++y)
for (int x = 0; x < newIcon.getWidth(); ++x)
data[index++] = (unsigned long) newIcon.getPixelAt (x, y).getARGB();
ScopedXLock xlock;
xchangeProperty (windowH, Atoms::getCreating ("_NET_WM_ICON"), XA_CARDINAL, 32, data.getData(), dataSize);
deleteIconPixmaps();
XWMHints* wmHints = XGetWMHints (display, windowH);
if (wmHints == nullptr)
wmHints = XAllocWMHints();
wmHints->flags |= IconPixmapHint | IconMaskHint;
wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
XSetWMHints (display, windowH, wmHints);
XFree (wmHints);
XSync (display, False);
}
void deleteIconPixmaps()
{
ScopedXLock xlock;
XWMHints* wmHints = XGetWMHints (display, windowH);
if (wmHints != nullptr)
{
if ((wmHints->flags & IconPixmapHint) != 0)
{
wmHints->flags &= ~IconPixmapHint;
XFreePixmap (display, wmHints->icon_pixmap);
}
if ((wmHints->flags & IconMaskHint) != 0)
{
wmHints->flags &= ~IconMaskHint;
XFreePixmap (display, wmHints->icon_mask);
}
XSetWMHints (display, windowH, wmHints);
XFree (wmHints);
}
}
//==============================================================================
void handleWindowMessage (XEvent& event)
{
switch (event.xany.type)
{
case KeyPressEventType: handleKeyPressEvent (event.xkey); break;
case KeyRelease: handleKeyReleaseEvent (event.xkey); break;
case ButtonPress: handleButtonPressEvent (event.xbutton); break;
case ButtonRelease: handleButtonReleaseEvent (event.xbutton); break;
case MotionNotify: handleMotionNotifyEvent (event.xmotion); break;
case EnterNotify: handleEnterNotifyEvent (event.xcrossing); break;
case LeaveNotify: handleLeaveNotifyEvent (event.xcrossing); break;
case FocusIn: handleFocusInEvent(); break;
case FocusOut: handleFocusOutEvent(); break;
case Expose: handleExposeEvent (event.xexpose); break;
case MappingNotify: handleMappingNotify (event.xmapping); break;
case ClientMessage: handleClientMessageEvent (event.xclient, event); break;
case SelectionNotify: handleDragAndDropSelection (event); break;
case ConfigureNotify: handleConfigureNotifyEvent (event.xconfigure); break;
case ReparentNotify: handleReparentNotifyEvent(); break;
case GravityNotify: handleGravityNotify(); break;
case SelectionClear: handleExternalSelectionClear(); break;
case SelectionRequest: handleExternalSelectionRequest (event); break;
case CirculateNotify:
case CreateNotify:
case DestroyNotify:
// Think we can ignore these
break;
case MapNotify:
mapped = true;
handleBroughtToFront();
break;
case UnmapNotify:
mapped = false;
break;
default:
#if JUCE_USE_XSHM
{
ScopedXLock xlock;
if (event.xany.type == XShmGetEventBase (display))
repainter->notifyPaintCompleted();
}
#endif
break;
}
}
void handleKeyPressEvent (XKeyEvent& keyEvent)
{
char utf8 [64] = { 0 };
juce_wchar unicodeChar = 0;
int keyCode = 0;
bool keyDownChange = false;
KeySym sym;
{
ScopedXLock xlock;
updateKeyStates (keyEvent.keycode, true);
const char* oldLocale = ::setlocale (LC_ALL, 0);
::setlocale (LC_ALL, "");
XLookupString (&keyEvent, utf8, sizeof (utf8), &sym, 0);
::setlocale (LC_ALL, oldLocale);
unicodeChar = *CharPointer_UTF8 (utf8);
keyCode = (int) unicodeChar;
if (keyCode < 0x20)
keyCode = XkbKeycodeToKeysym (display, keyEvent.keycode, 0, currentModifiers.isShiftDown() ? 1 : 0);
keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
}
const ModifierKeys oldMods (currentModifiers);
bool keyPressed = false;
if ((sym & 0xff00) == 0xff00)
{
switch (sym) // Translate keypad
{
case XK_KP_Add: keyCode = XK_plus; break;
case XK_KP_Subtract: keyCode = XK_hyphen; break;
case XK_KP_Divide: keyCode = XK_slash; break;
case XK_KP_Multiply: keyCode = XK_asterisk; break;
case XK_KP_Enter: keyCode = XK_Return; break;
case XK_KP_Insert: keyCode = XK_Insert; break;
case XK_Delete:
case XK_KP_Delete: keyCode = XK_Delete; break;
case XK_KP_Left: keyCode = XK_Left; break;
case XK_KP_Right: keyCode = XK_Right; break;
case XK_KP_Up: keyCode = XK_Up; break;
case XK_KP_Down: keyCode = XK_Down; break;
case XK_KP_Home: keyCode = XK_Home; break;
case XK_KP_End: keyCode = XK_End; break;
case XK_KP_Page_Down: keyCode = XK_Page_Down; break;
case XK_KP_Page_Up: keyCode = XK_Page_Up; break;
case XK_KP_0: keyCode = XK_0; break;
case XK_KP_1: keyCode = XK_1; break;
case XK_KP_2: keyCode = XK_2; break;
case XK_KP_3: keyCode = XK_3; break;
case XK_KP_4: keyCode = XK_4; break;
case XK_KP_5: keyCode = XK_5; break;
case XK_KP_6: keyCode = XK_6; break;
case XK_KP_7: keyCode = XK_7; break;
case XK_KP_8: keyCode = XK_8; break;
case XK_KP_9: keyCode = XK_9; break;
default: break;
}
switch (keyCode)
{
case XK_Left:
case XK_Right:
case XK_Up:
case XK_Down:
case XK_Page_Up:
case XK_Page_Down:
case XK_End:
case XK_Home:
case XK_Delete:
case XK_Insert:
keyPressed = true;
keyCode = (keyCode & 0xff) | Keys::extendedKeyModifier;
break;
case XK_Tab:
case XK_Return:
case XK_Escape:
case XK_BackSpace:
keyPressed = true;
keyCode &= 0xff;
break;
default:
if (sym >= XK_F1 && sym <= XK_F16)
{
keyPressed = true;
keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
}
break;
}
}
if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
keyPressed = true;
if (oldMods != currentModifiers)
handleModifierKeysChange();
if (keyDownChange)
handleKeyUpOrDown (true);
if (keyPressed)
handleKeyPress (keyCode, unicodeChar);
}
static bool isKeyReleasePartOfAutoRepeat (const XKeyEvent& keyReleaseEvent)
{
if (XPending (display))
{
XEvent e;
XPeekEvent (display, &e);
// Look for a subsequent key-down event with the same timestamp and keycode
return e.type == KeyPressEventType
&& e.xkey.keycode == keyReleaseEvent.keycode
&& e.xkey.time == keyReleaseEvent.time;
}
return false;
}
void handleKeyReleaseEvent (const XKeyEvent& keyEvent)
{
if (! isKeyReleasePartOfAutoRepeat (keyEvent))
{
updateKeyStates (keyEvent.keycode, false);
KeySym sym;
{
ScopedXLock xlock;
sym = XkbKeycodeToKeysym (display, keyEvent.keycode, 0, 0);
}
const ModifierKeys oldMods (currentModifiers);
const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
if (oldMods != currentModifiers)
handleModifierKeysChange();
if (keyDownChange)
handleKeyUpOrDown (false);
}
}
template <typename EventType>
static Point<int> getMousePos (const EventType& e) noexcept
{
return Point<int> (e.x, e.y);
}
void handleWheelEvent (const XButtonPressedEvent& buttonPressEvent, const float amount)
{
MouseWheelDetails wheel;
wheel.deltaX = 0.0f;
wheel.deltaY = amount;
wheel.isReversed = false;
wheel.isSmooth = false;
handleMouseWheel (0, getMousePos (buttonPressEvent), getEventTime (buttonPressEvent), wheel);
}
void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent, int buttonModifierFlag)
{
currentModifiers = currentModifiers.withFlags (buttonModifierFlag);
toFront (true);
handleMouseEvent (0, getMousePos (buttonPressEvent), currentModifiers, getEventTime (buttonPressEvent));
}
void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent)
{
updateKeyModifiers (buttonPressEvent.state);
switch (pointerMap [buttonPressEvent.button - Button1])
{
case Keys::WheelUp: handleWheelEvent (buttonPressEvent, 50.0f / 256.0f); break;
case Keys::WheelDown: handleWheelEvent (buttonPressEvent, -50.0f / 256.0f); break;
case Keys::LeftButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::leftButtonModifier); break;
case Keys::RightButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::rightButtonModifier); break;
case Keys::MiddleButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::middleButtonModifier); break;
default: break;
}
clearLastMousePos();
}
void handleButtonReleaseEvent (const XButtonReleasedEvent& buttonRelEvent)
{
updateKeyModifiers (buttonRelEvent.state);
if (parentWindow != 0)
updateWindowBounds();
switch (pointerMap [buttonRelEvent.button - Button1])
{
case Keys::LeftButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
case Keys::RightButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
case Keys::MiddleButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
default: break;
}
if (dragState.dragging)
handleExternalDragButtonReleaseEvent();
handleMouseEvent (0, getMousePos (buttonRelEvent), currentModifiers, getEventTime (buttonRelEvent));
clearLastMousePos();
}
void handleMotionNotifyEvent (const XPointerMovedEvent& movedEvent)
{
updateKeyModifiers (movedEvent.state);
lastMousePos = Point<int> (movedEvent.x_root, movedEvent.y_root);
if (dragState.dragging)
handleExternalDragMotionNotify();
handleMouseEvent (0, getMousePos (movedEvent), currentModifiers, getEventTime (movedEvent));
}
void handleEnterNotifyEvent (const XEnterWindowEvent& enterEvent)
{
if (parentWindow != 0)
updateWindowBounds();
clearLastMousePos();
if (! currentModifiers.isAnyMouseButtonDown())
{
updateKeyModifiers (enterEvent.state);
handleMouseEvent (0, getMousePos (enterEvent), currentModifiers, getEventTime (enterEvent));
}
}
void handleLeaveNotifyEvent (const XLeaveWindowEvent& leaveEvent)
{
// Suppress the normal leave if we've got a pointer grab, or if
// it's a bogus one caused by clicking a mouse button when running
// in a Window manager
if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent.mode == NotifyNormal)
|| leaveEvent.mode == NotifyUngrab)
{
updateKeyModifiers (leaveEvent.state);
handleMouseEvent (0, getMousePos (leaveEvent), currentModifiers, getEventTime (leaveEvent));
}
}
void handleFocusInEvent()
{
isActiveApplication = true;
if (isFocused())
handleFocusGain();
}
void handleFocusOutEvent()
{
isActiveApplication = false;
if (! isFocused())
handleFocusLoss();
}
void handleExposeEvent (XExposeEvent& exposeEvent)
{
// Batch together all pending expose events
XEvent nextEvent;
ScopedXLock xlock;
if (exposeEvent.window != windowH)
{
Window child;
XTranslateCoordinates (display, exposeEvent.window, windowH,
exposeEvent.x, exposeEvent.y, &exposeEvent.x, &exposeEvent.y,
&child);
}
repaint (Rectangle<int> (exposeEvent.x, exposeEvent.y,
exposeEvent.width, exposeEvent.height));
while (XEventsQueued (display, QueuedAfterFlush) > 0)
{
XPeekEvent (display, &nextEvent);
if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent.window)
break;
XNextEvent (display, &nextEvent);
const XExposeEvent& nextExposeEvent = (const XExposeEvent&) nextEvent.xexpose;
repaint (Rectangle<int> (nextExposeEvent.x, nextExposeEvent.y,
nextExposeEvent.width, nextExposeEvent.height));
}
}
void handleConfigureNotifyEvent (XConfigureEvent& confEvent)
{
updateWindowBounds();
updateBorderSize();
handleMovedOrResized();
// if the native title bar is dragged, need to tell any active menus, etc.
if ((styleFlags & windowHasTitleBar) != 0
&& component.isCurrentlyBlockedByAnotherModalComponent())
{
if (Component* const currentModalComp = Component::getCurrentlyModalComponent())
currentModalComp->inputAttemptWhenModal();
}
if (confEvent.window == windowH
&& confEvent.above != 0
&& isFrontWindow())
{
handleBroughtToFront();
}
}
void handleReparentNotifyEvent()
{
parentWindow = 0;
Window wRoot = 0;
Window* wChild = nullptr;
unsigned int numChildren;
{
ScopedXLock xlock;
XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
}
if (parentWindow == windowH || parentWindow == wRoot)
parentWindow = 0;
handleGravityNotify();
}
void handleGravityNotify()
{
updateWindowBounds();
updateBorderSize();
handleMovedOrResized();
}
void handleMappingNotify (XMappingEvent& mappingEvent)
{
if (mappingEvent.request != MappingPointer)
{
// Deal with modifier/keyboard mapping
ScopedXLock xlock;
XRefreshKeyboardMapping (&mappingEvent);
updateModifierMappings();
}
}
void handleClientMessageEvent (XClientMessageEvent& clientMsg, XEvent& event)
{
const Atoms& atoms = Atoms::get();
if (clientMsg.message_type == atoms.Protocols && clientMsg.format == 32)
{
const Atom atom = (Atom) clientMsg.data.l[0];
if (atom == atoms.ProtocolList [Atoms::PING])
{
Window root = RootWindow (display, DefaultScreen (display));
clientMsg.window = root;
XSendEvent (display, root, False, NoEventMask, &event);
XFlush (display);
}
else if (atom == atoms.ProtocolList [Atoms::TAKE_FOCUS])
{
if ((getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0)
{
XWindowAttributes atts;
ScopedXLock xlock;
if (clientMsg.window != 0
&& XGetWindowAttributes (display, clientMsg.window, &atts))
{
if (atts.map_state == IsViewable)
XSetInputFocus (display, clientMsg.window, RevertToParent, clientMsg.data.l[1]);
}
}
}
else if (atom == atoms.ProtocolList [Atoms::DELETE_WINDOW])
{
handleUserClosingWindow();
}
}
else if (clientMsg.message_type == atoms.XdndEnter)
{
handleDragAndDropEnter (clientMsg);
}
else if (clientMsg.message_type == atoms.XdndLeave)
{
handleDragExit (dragInfo);
resetDragAndDrop();
}
else if (clientMsg.message_type == atoms.XdndPosition)
{
handleDragAndDropPosition (clientMsg);
}
else if (clientMsg.message_type == atoms.XdndDrop)
{
handleDragAndDropDrop (clientMsg);
}
else if (clientMsg.message_type == atoms.XdndStatus)
{
handleExternalDragAndDropStatus (clientMsg);
}
else if (clientMsg.message_type == atoms.XdndFinished)
{
externalResetDragAndDrop();
}
}
bool externalDragTextInit (const String& text)
{
if (dragState.dragging)
return false;
return externalDragInit (true, text);
}
bool externalDragFileInit (const StringArray& files, bool /*canMoveFiles*/)
{
if (dragState.dragging)
return false;
StringArray uriList;
for (int i = 0; i < files.size(); ++i)
{
const String& f = files[i];
if (f.matchesWildcard ("?*://*", false))
uriList.add (f);
else
uriList.add ("file://" + f);
}
return externalDragInit (false, uriList.joinIntoString ("\r\n"));
}
//==============================================================================
void showMouseCursor (Cursor cursor) noexcept
{
ScopedXLock xlock;
XDefineCursor (display, windowH, cursor);
}
//==============================================================================
bool dontRepaint;
static ModifierKeys currentModifiers;
static bool isActiveApplication;
private:
//==============================================================================
class LinuxRepaintManager : public Timer
{
public:
LinuxRepaintManager (LinuxComponentPeer& p)
: peer (p), lastTimeImageUsed (0)
{
#if JUCE_USE_XSHM
shmPaintsPending = 0;
useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
if (useARGBImagesForRendering)
{
ScopedXLock xlock;
XShmSegmentInfo segmentinfo;
XImage* const testImage
= XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
24, ZPixmap, 0, &segmentinfo, 64, 64);
useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
XDestroyImage (testImage);
}
#endif
}
void timerCallback() override
{
#if JUCE_USE_XSHM
if (shmPaintsPending != 0)
return;
#endif
if (! regionsNeedingRepaint.isEmpty())
{
stopTimer();
performAnyPendingRepaintsNow();
}
else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
{
stopTimer();
image = Image::null;
}
}
void repaint (const Rectangle<int>& area)
{
if (! isTimerRunning())
startTimer (repaintTimerPeriod);
regionsNeedingRepaint.add (area);
}
void performAnyPendingRepaintsNow()
{
#if JUCE_USE_XSHM
if (shmPaintsPending != 0)
{
startTimer (repaintTimerPeriod);
return;
}
#endif
RectangleList<int> originalRepaintRegion (regionsNeedingRepaint);
regionsNeedingRepaint.clear();
const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
if (! totalArea.isEmpty())
{
if (image.isNull() || image.getWidth() < totalArea.getWidth()
|| image.getHeight() < totalArea.getHeight())
{
#if JUCE_USE_XSHM
image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
: Image::RGB,
#else
image = Image (new XBitmapImage (Image::RGB,
#endif
(totalArea.getWidth() + 31) & ~31,
(totalArea.getHeight() + 31) & ~31,
false, peer.depth, peer.visual));
}
startTimer (repaintTimerPeriod);
RectangleList<int> adjustedList (originalRepaintRegion);
adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
if (peer.depth == 32)
for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
image.clear (*i - totalArea.getPosition());
{
ScopedPointer<LowLevelGraphicsContext> context (peer.getComponent().getLookAndFeel()
.createGraphicsContext (image, -totalArea.getPosition(), adjustedList));
peer.handlePaint (*context);
}
for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
{
#if JUCE_USE_XSHM
++shmPaintsPending;
#endif
static_cast<XBitmapImage*> (image.getPixelData())
->blitToWindow (peer.windowH,
i->getX(), i->getY(), i->getWidth(), i->getHeight(),
i->getX() - totalArea.getX(), i->getY() - totalArea.getY());
}
}
lastTimeImageUsed = Time::getApproximateMillisecondCounter();
startTimer (repaintTimerPeriod);
}
#if JUCE_USE_XSHM
void notifyPaintCompleted() noexcept { --shmPaintsPending; }
#endif
private:
enum { repaintTimerPeriod = 1000 / 100 };
LinuxComponentPeer& peer;
Image image;
uint32 lastTimeImageUsed;
RectangleList<int> regionsNeedingRepaint;
#if JUCE_USE_XSHM
bool useARGBImagesForRendering;
int shmPaintsPending;
#endif
JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
};
ScopedPointer <LinuxRepaintManager> repainter;
friend class LinuxRepaintManager;
Window windowH, parentWindow;
Rectangle<int> bounds;
Image taskbarImage;
bool fullScreen, mapped;
Visual* visual;
int depth;
BorderSize<int> windowBorder;
bool isAlwaysOnTop;
enum { KeyPressEventType = 2 };
struct MotifWmHints
{
unsigned long flags;
unsigned long functions;
unsigned long decorations;
long input_mode;
unsigned long status;
};
static void updateKeyStates (const int keycode, const bool press) noexcept
{
const int keybyte = keycode >> 3;
const int keybit = (1 << (keycode & 7));
if (press)
Keys::keyStates [keybyte] |= keybit;
else
Keys::keyStates [keybyte] &= ~keybit;
}
static void updateKeyModifiers (const int status) noexcept
{
int keyMods = 0;
if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
Keys::numLock = ((status & Keys::NumLockMask) != 0);
Keys::capsLock = ((status & LockMask) != 0);
}
static bool updateKeyModifiersFromSym (KeySym sym, const bool press) noexcept
{
int modifier = 0;
bool isModifier = true;
switch (sym)
{
case XK_Shift_L:
case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
case XK_Control_L:
case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
case XK_Alt_L:
case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
case XK_Num_Lock:
if (press)
Keys::numLock = ! Keys::numLock;
break;
case XK_Caps_Lock:
if (press)
Keys::capsLock = ! Keys::capsLock;
break;
case XK_Scroll_Lock:
break;
default:
isModifier = false;
break;
}
currentModifiers = press ? currentModifiers.withFlags (modifier)
: currentModifiers.withoutFlags (modifier);
return isModifier;
}
// Alt and Num lock are not defined by standard X
// modifier constants: check what they're mapped to
static void updateModifierMappings() noexcept
{
ScopedXLock xlock;
const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
Keys::AltMask = 0;
Keys::NumLockMask = 0;
if (XModifierKeymap* const mapping = XGetModifierMapping (display))
{
for (int i = 0; i < 8; i++)
{
if (mapping->modifiermap [i << 1] == altLeftCode)
Keys::AltMask = 1 << i;
else if (mapping->modifiermap [i << 1] == numLockCode)
Keys::NumLockMask = 1 << i;
}
XFreeModifiermap (mapping);
}
}
//==============================================================================
static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
{
XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
}
void removeWindowDecorations (Window wndH)
{
Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
if (hints != None)
{
MotifWmHints motifHints;
zerostruct (motifHints);
motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
motifHints.decorations = 0;
ScopedXLock xlock;
xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
}
hints = Atoms::getIfExists ("_WIN_HINTS");
if (hints != None)
{
long gnomeHints = 0;
ScopedXLock xlock;
xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
}
hints = Atoms::getIfExists ("KWM_WIN_DECORATION");
if (hints != None)
{
long kwmHints = 2; /*KDE_tinyDecoration*/
ScopedXLock xlock;
xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
}
}
void addWindowButtons (Window wndH)
{
ScopedXLock xlock;
Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
if (hints != None)
{
MotifWmHints motifHints;
zerostruct (motifHints);
motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
motifHints.functions = 4 /* MWM_FUNC_MOVE */;
if ((styleFlags & windowHasCloseButton) != 0)
motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
if ((styleFlags & windowHasMinimiseButton) != 0)
{
motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
}
if ((styleFlags & windowHasMaximiseButton) != 0)
{
motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
}
if ((styleFlags & windowIsResizable) != 0)
{
motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
}
xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
}
hints = Atoms::getIfExists ("_NET_WM_ALLOWED_ACTIONS");
if (hints != None)
{
Atom netHints [6];
int num = 0;
if ((styleFlags & windowIsResizable) != 0)
netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_RESIZE");
if ((styleFlags & windowHasMaximiseButton) != 0)
netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_FULLSCREEN");
if ((styleFlags & windowHasMinimiseButton) != 0)
netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_MINIMIZE");
if ((styleFlags & windowHasCloseButton) != 0)
netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_CLOSE");
xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
}
}
void setWindowType()
{
Atom netHints [2];
if ((styleFlags & windowIsTemporary) != 0
|| ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_COMBO");
else
netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_NORMAL");
netHints[1] = Atoms::getIfExists ("_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
xchangeProperty (windowH, Atoms::get().WindowType, XA_ATOM, 32, &netHints, 2);
int numHints = 0;
if ((styleFlags & windowAppearsOnTaskbar) == 0)
netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_SKIP_TASKBAR");
if (component.isAlwaysOnTop())
netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_ABOVE");
if (numHints > 0)
xchangeProperty (windowH, Atoms::get().WindowState, XA_ATOM, 32, &netHints, numHints);
}
void createWindow (Window parentToAddTo)
{
ScopedXLock xlock;
resetDragAndDrop();
// Get defaults for various properties
const int screen = DefaultScreen (display);
Window root = RootWindow (display, screen);
// Try to obtain a 32-bit visual or fallback to 24 or 16
visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
if (visual == nullptr)
{
Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
Process::terminate();
}
// Create and install a colormap suitable fr our visual
Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
XInstallColormap (display, colormap);
// Set up the window attributes
XSetWindowAttributes swa;
swa.border_pixel = 0;
swa.background_pixmap = None;
swa.colormap = colormap;
swa.override_redirect = (component.isAlwaysOnTop() && (styleFlags & windowIsTemporary) != 0) ? True : False;
swa.event_mask = getAllEventsMask();
windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
0, 0, 1, 1,
0, depth, InputOutput, visual,
CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
&swa);
XGrabButton (display, AnyButton, AnyModifier, windowH, False,
ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
GrabModeAsync, GrabModeAsync, None, None);
// Set the window context to identify the window handle object
if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
{
// Failed
jassertfalse;
Logger::outputDebugString ("Failed to create context information for window.\n");
XDestroyWindow (display, windowH);
windowH = 0;
return;
}
// Set window manager hints
XWMHints* wmHints = XAllocWMHints();
wmHints->flags = InputHint | StateHint;
wmHints->input = True; // Locally active input model
wmHints->initial_state = NormalState;
XSetWMHints (display, windowH, wmHints);
XFree (wmHints);
// Set the window type
setWindowType();
// Define decoration
if ((styleFlags & windowHasTitleBar) == 0)
removeWindowDecorations (windowH);
else
addWindowButtons (windowH);
setTitle (component.getName());
const Atoms& atoms = Atoms::get();
// Associate the PID, allowing to be shut down when something goes wrong
unsigned long pid = getpid();
xchangeProperty (windowH, atoms.Pid, XA_CARDINAL, 32, &pid, 1);
// Set window manager protocols
xchangeProperty (windowH, atoms.Protocols, XA_ATOM, 32, atoms.ProtocolList, 2);
// Set drag and drop flags
xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32, atoms.allowedMimeTypes, numElementsInArray (atoms.allowedMimeTypes));
xchangeProperty (windowH, atoms.XdndActionList, XA_ATOM, 32, atoms.allowedActions, numElementsInArray (atoms.allowedActions));
xchangeProperty (windowH, atoms.XdndActionDescription, XA_STRING, 8, "", 0);
xchangeProperty (windowH, atoms.XdndAware, XA_ATOM, 32, &Atoms::DndVersion, 1);
initialisePointerMap();
updateModifierMappings();
}
void destroyWindow()
{
ScopedXLock xlock;
XPointer handlePointer;
if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
XDeleteContext (display, (XID) windowH, windowHandleXContext);
XDestroyWindow (display, windowH);
// Wait for it to complete and then remove any events for this
// window from the event queue.
XSync (display, false);
XEvent event;
while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
{}
}
static int getAllEventsMask() noexcept
{
return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
| EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
| ExposureMask | StructureNotifyMask | FocusChangeMask;
}
template <typename EventType>
static int64 getEventTime (const EventType& t)
{
return getEventTime (t.time);
}
static int64 getEventTime (::Time t)
{
static int64 eventTimeOffset = 0x12345678;
const int64 thisMessageTime = t;
if (eventTimeOffset == 0x12345678)
eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
return eventTimeOffset + thisMessageTime;
}
long getUserTime() const
{
GetXProperty prop (windowH, Atoms::get().UserTime, 0, 65536, false, XA_CARDINAL);
return prop.success ? *(long*) prop.data : 0;
}
void updateBorderSize()
{
if ((styleFlags & windowHasTitleBar) == 0)
{
windowBorder = BorderSize<int> (0);
}
else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
{
ScopedXLock xlock;
Atom hints = Atoms::getIfExists ("_NET_FRAME_EXTENTS");
if (hints != None)
{
GetXProperty prop (windowH, hints, 0, 4, false, XA_CARDINAL);
if (prop.success && prop.actualFormat == 32)
{
const unsigned long* const sizes = (const unsigned long*) prop.data;
windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
(int) sizes[3], (int) sizes[1]);
}
}
}
}
void updateWindowBounds()
{
jassert (windowH != 0);
if (windowH != 0)
{
Window root, child;
int wx = 0, wy = 0;
unsigned int ww = 0, wh = 0, bw, depth;
ScopedXLock xlock;
if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &depth))
if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
wx = wy = 0;
bounds.setBounds (wx, wy, ww, wh);
}
}
//==============================================================================
struct DragState
{
DragState() noexcept
: isText (false), dragging (false), expectingStatus (false),
canDrop (false), targetWindow (None), xdndVersion (-1)
{
}
bool isText;
bool dragging; // currently performing outgoing external dnd as Xdnd source, have grabbed mouse
bool expectingStatus; // XdndPosition sent, waiting for XdndStatus
bool canDrop; // target window signals it will accept the drop
Window targetWindow; // potential drop target
int xdndVersion; // negotiated version with target
Rectangle<int> silentRect;
String textOrFiles;
const Atom* getMimeTypes() const noexcept { return isText ? Atoms::get().externalAllowedTextMimeTypes
: Atoms::get().externalAllowedFileMimeTypes; }
int getNumMimeTypes() const noexcept { return isText ? numElementsInArray (Atoms::get().externalAllowedTextMimeTypes)
: numElementsInArray (Atoms::get().externalAllowedFileMimeTypes); }
bool matchesTarget (Atom targetType) const
{
for (int i = getNumMimeTypes(); --i >= 0;)
if (getMimeTypes()[i] == targetType)
return true;
return false;
}
};
//==============================================================================
void resetDragAndDrop()
{
dragInfo.clear();
dragInfo.position = Point<int> (-1, -1);
dragAndDropCurrentMimeType = 0;
dragAndDropSourceWindow = 0;
srcMimeTypeAtomList.clear();
finishAfterDropDataReceived = false;
}
void resetExternalDragState()
{
dragState = DragState();
}
void sendDragAndDropMessage (XClientMessageEvent& msg)
{
msg.type = ClientMessage;
msg.display = display;
msg.window = dragAndDropSourceWindow;
msg.format = 32;
msg.data.l[0] = windowH;
ScopedXLock xlock;
XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
}
bool sendExternalDragAndDropMessage (XClientMessageEvent& msg, const Window targetWindow)
{
msg.type = ClientMessage;
msg.display = display;
msg.window = targetWindow;
msg.format = 32;
msg.data.l[0] = windowH;
ScopedXLock xlock;
return XSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
}
void sendExternalDragAndDropDrop (const Window targetWindow)
{
XClientMessageEvent msg;
zerostruct (msg);
msg.message_type = Atoms::get().XdndDrop;
msg.data.l[2] = CurrentTime;
sendExternalDragAndDropMessage (msg, targetWindow);
}
void sendExternalDragAndDropEnter (const Window targetWindow)
{
XClientMessageEvent msg;
zerostruct (msg);
msg.message_type = Atoms::get().XdndEnter;
const Atom* mimeTypes = dragState.getMimeTypes();
const int numMimeTypes = dragState.getNumMimeTypes();
msg.data.l[1] = (dragState.xdndVersion << 24) | (numMimeTypes > 3);
msg.data.l[2] = numMimeTypes > 0 ? mimeTypes[0] : 0;
msg.data.l[3] = numMimeTypes > 1 ? mimeTypes[1] : 0;
msg.data.l[4] = numMimeTypes > 2 ? mimeTypes[2] : 0;
sendExternalDragAndDropMessage (msg, targetWindow);
}
void sendExternalDragAndDropPosition (const Window targetWindow)
{
XClientMessageEvent msg;
zerostruct (msg);
msg.message_type = Atoms::get().XdndPosition;
const Point<int> mousePos (Desktop::getInstance().getMousePosition());
if (dragState.silentRect.contains (mousePos)) // we've been asked to keep silent
return;
msg.data.l[1] = 0;
msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
msg.data.l[3] = CurrentTime;
msg.data.l[4] = Atoms::get().XdndActionCopy; // this is all JUCE currently supports
dragState.expectingStatus = sendExternalDragAndDropMessage (msg, targetWindow);
}
void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
{
XClientMessageEvent msg;
zerostruct (msg);
msg.message_type = Atoms::get().XdndStatus;
msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
msg.data.l[4] = dropAction;
sendDragAndDropMessage (msg);
}
void sendExternalDragAndDropLeave (const Window targetWindow)
{
XClientMessageEvent msg;
zerostruct (msg);
msg.message_type = Atoms::get().XdndLeave;
sendExternalDragAndDropMessage (msg, targetWindow);
}
void sendDragAndDropFinish()
{
XClientMessageEvent msg;
zerostruct (msg);
msg.message_type = Atoms::get().XdndFinished;
sendDragAndDropMessage (msg);
}
void handleExternalSelectionClear()
{
if (dragState.dragging)
externalResetDragAndDrop();
}
void handleExternalSelectionRequest (const XEvent& evt)
{
Atom targetType = evt.xselectionrequest.target;
XEvent s;
s.xselection.type = SelectionNotify;
s.xselection.requestor = evt.xselectionrequest.requestor;
s.xselection.selection = evt.xselectionrequest.selection;
s.xselection.target = targetType;
s.xselection.property = None;
s.xselection.time = evt.xselectionrequest.time;
if (dragState.matchesTarget (targetType))
{
s.xselection.property = evt.xselectionrequest.property;
xchangeProperty (evt.xselectionrequest.requestor,
evt.xselectionrequest.property,
targetType, 8,
dragState.textOrFiles.toRawUTF8(),
dragState.textOrFiles.getNumBytesAsUTF8());
}
XSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
}
void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
{
if (dragState.expectingStatus)
{
dragState.expectingStatus = false;
dragState.canDrop = false;
dragState.silentRect = Rectangle<int>();
if ((clientMsg.data.l[1] & 1) != 0
&& ((Atom) clientMsg.data.l[4] == Atoms::get().XdndActionCopy
|| (Atom) clientMsg.data.l[4] == Atoms::get().XdndActionPrivate))
{
if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
dragState.silentRect.setBounds (clientMsg.data.l[2] >> 16,
clientMsg.data.l[2] & 0xffff,
clientMsg.data.l[3] >> 16,
clientMsg.data.l[3] & 0xffff);
dragState.canDrop = true;
}
}
}
void handleExternalDragButtonReleaseEvent()
{
if (dragState.dragging)
XUngrabPointer (display, CurrentTime);
if (dragState.canDrop)
{
sendExternalDragAndDropDrop (dragState.targetWindow);
}
else
{
sendExternalDragAndDropLeave (dragState.targetWindow);
externalResetDragAndDrop();
}
}
void handleExternalDragMotionNotify()
{
Window targetWindow = externalFindDragTargetWindow (RootWindow (display, DefaultScreen (display)));
if (dragState.targetWindow != targetWindow)
{
if (dragState.targetWindow != None)
sendExternalDragAndDropLeave (dragState.targetWindow);
dragState.canDrop = false;
dragState.silentRect = Rectangle<int>();
if (targetWindow == None)
return;
GetXProperty prop (targetWindow, Atoms::get().XdndAware,
0, 2, false, AnyPropertyType);
if (prop.success
&& prop.data != None
&& prop.actualFormat == 32
&& prop.numItems == 1)
{
dragState.xdndVersion = jmin ((int) prop.data[0], (int) Atoms::DndVersion);
}
else
{
dragState.xdndVersion = -1;
return;
}
sendExternalDragAndDropEnter (targetWindow);
dragState.targetWindow = targetWindow;
}
if (! dragState.expectingStatus)
sendExternalDragAndDropPosition (targetWindow);
}
void handleDragAndDropPosition (const XClientMessageEvent& clientMsg)
{
if (dragAndDropSourceWindow == 0)
return;
dragAndDropSourceWindow = clientMsg.data.l[0];
Point<int> dropPos ((int) clientMsg.data.l[2] >> 16,
(int) clientMsg.data.l[2] & 0xffff);
dropPos -= bounds.getPosition();
const Atoms& atoms = Atoms::get();
Atom targetAction = atoms.XdndActionCopy;
for (int i = numElementsInArray (atoms.allowedActions); --i >= 0;)
{
if ((Atom) clientMsg.data.l[4] == atoms.allowedActions[i])
{
targetAction = atoms.allowedActions[i];
break;
}
}
sendDragAndDropStatus (true, targetAction);
if (dragInfo.position != dropPos)
{
dragInfo.position = dropPos;
if (dragInfo.isEmpty())
updateDraggedFileList (clientMsg);
if (! dragInfo.isEmpty())
handleDragMove (dragInfo);
}
}
void handleDragAndDropDrop (const XClientMessageEvent& clientMsg)
{
if (dragInfo.isEmpty())
{
// no data, transaction finished in handleDragAndDropSelection()
finishAfterDropDataReceived = true;
updateDraggedFileList (clientMsg);
}
else
{
handleDragAndDropDataReceived(); // data was already received
}
}
void handleDragAndDropDataReceived()
{
DragInfo dragInfoCopy (dragInfo);
sendDragAndDropFinish();
resetDragAndDrop();
if (! dragInfoCopy.isEmpty())
handleDragDrop (dragInfoCopy);
}
void handleDragAndDropEnter (const XClientMessageEvent& clientMsg)
{
dragInfo.clear();
srcMimeTypeAtomList.clear();
dragAndDropCurrentMimeType = 0;
const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg.data.l[1] & 0xff000000) >> 24;
if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
{
dragAndDropSourceWindow = 0;
return;
}
dragAndDropSourceWindow = clientMsg.data.l[0];
if ((clientMsg.data.l[1] & 1) != 0)
{
ScopedXLock xlock;
GetXProperty prop (dragAndDropSourceWindow, Atoms::get().XdndTypeList, 0, 0x8000000L, false, XA_ATOM);
if (prop.success
&& prop.actualType == XA_ATOM
&& prop.actualFormat == 32
&& prop.numItems != 0)
{
const unsigned long* const types = (const unsigned long*) prop.data;
for (unsigned long i = 0; i < prop.numItems; ++i)
if (types[i] != None)
srcMimeTypeAtomList.add (types[i]);
}
}
if (srcMimeTypeAtomList.size() == 0)
{
for (int i = 2; i < 5; ++i)
if (clientMsg.data.l[i] != None)
srcMimeTypeAtomList.add (clientMsg.data.l[i]);
if (srcMimeTypeAtomList.size() == 0)
{
dragAndDropSourceWindow = 0;
return;
}
}
const Atoms& atoms = Atoms::get();
for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
for (int j = 0; j < numElementsInArray (atoms.allowedMimeTypes); ++j)
if (srcMimeTypeAtomList[i] == atoms.allowedMimeTypes[j])
dragAndDropCurrentMimeType = atoms.allowedMimeTypes[j];
handleDragAndDropPosition (clientMsg);
}
void handleDragAndDropSelection (const XEvent& evt)
{
dragInfo.clear();
if (evt.xselection.property != None)
{
StringArray lines;
{
MemoryBlock dropData;
for (;;)
{
GetXProperty prop (evt.xany.window, evt.xselection.property,
dropData.getSize() / 4, 65536, false, AnyPropertyType);
if (! prop.success)
break;
dropData.append (prop.data, prop.numItems * prop.actualFormat / 8);
if (prop.bytesLeft <= 0)
break;
}
lines.addLines (dropData.toString());
}
if (Atoms::isMimeTypeFile (dragAndDropCurrentMimeType))
{
for (int i = 0; i < lines.size(); ++i)
dragInfo.files.add (URL::removeEscapeChars (lines[i].replace ("file://", String::empty, true)));
dragInfo.files.trim();
dragInfo.files.removeEmptyStrings();
}
else
{
dragInfo.text = lines.joinIntoString ("\n");
}
if (finishAfterDropDataReceived)
handleDragAndDropDataReceived();
}
}
void updateDraggedFileList (const XClientMessageEvent& clientMsg)
{
jassert (dragInfo.isEmpty());
if (dragAndDropSourceWindow != None
&& dragAndDropCurrentMimeType != None)
{
ScopedXLock xlock;
XConvertSelection (display,
Atoms::get().XdndSelection,
dragAndDropCurrentMimeType,
Atoms::getCreating ("JXSelectionWindowProperty"),
windowH,
clientMsg.data.l[2]);
}
}
static bool isWindowDnDAware (Window w)
{
int numProperties = 0;
Atom* const atoms = XListProperties (display, w, &numProperties);
bool dndAwarePropFound = false;
for (int i = 0; i < numProperties; ++i)
if (atoms[i] == Atoms::get().XdndAware)
dndAwarePropFound = true;
if (atoms != nullptr)
XFree (atoms);
return dndAwarePropFound;
}
Window externalFindDragTargetWindow (Window targetWindow)
{
if (targetWindow == None)
return None;
if (isWindowDnDAware (targetWindow))
return targetWindow;
Window child, phonyWin;
int phony;
unsigned int uphony;
XQueryPointer (display, targetWindow, &phonyWin, &child,
&phony, &phony, &phony, &phony, &uphony);
return externalFindDragTargetWindow (child);
}
bool externalDragInit (bool isText, const String& textOrFiles)
{
ScopedXLock xlock;
resetExternalDragState();
dragState.isText = isText;
dragState.textOrFiles = textOrFiles;
dragState.targetWindow = windowH;
const int pointerGrabMask = Button1MotionMask | ButtonReleaseMask;
if (XGrabPointer (display, windowH, True, pointerGrabMask,
GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
{
// No other method of changing the pointer seems to work, this call is needed from this very context
XChangeActivePointerGrab (display, pointerGrabMask, (Cursor) createDraggingHandCursor(), CurrentTime);
const Atoms& atoms = Atoms::get();
XSetSelectionOwner (display, atoms.XdndSelection, windowH, CurrentTime);
// save the available types to XdndTypeList
xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32,
dragState.getMimeTypes(),
dragState.getNumMimeTypes());
dragState.dragging = true;
handleExternalDragMotionNotify();
return true;
}
return false;
}
void externalResetDragAndDrop()
{
if (dragState.dragging)
{
ScopedXLock xlock;
XUngrabPointer (display, CurrentTime);
}
resetExternalDragState();
}
DragState dragState;
DragInfo dragInfo;
Atom dragAndDropCurrentMimeType;
Window dragAndDropSourceWindow;
bool finishAfterDropDataReceived;
Array <Atom> srcMimeTypeAtomList;
int pointerMap[5];
void initialisePointerMap()
{
const int numButtons = XGetPointerMapping (display, 0, 0);
pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
if (numButtons == 2)
{
pointerMap[0] = Keys::LeftButton;
pointerMap[1] = Keys::RightButton;
}
else if (numButtons >= 3)
{
pointerMap[0] = Keys::LeftButton;
pointerMap[1] = Keys::MiddleButton;
pointerMap[2] = Keys::RightButton;
if (numButtons >= 5)
{
pointerMap[3] = Keys::WheelUp;
pointerMap[4] = Keys::WheelDown;
}
}
}
static Point<int> lastMousePos;
static void clearLastMousePos() noexcept
{
lastMousePos = Point<int> (0x100000, 0x100000);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
};
ModifierKeys LinuxComponentPeer::currentModifiers;
bool LinuxComponentPeer::isActiveApplication = false;
Point<int> LinuxComponentPeer::lastMousePos;
//==============================================================================
JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess()
{
return LinuxComponentPeer::isActiveApplication;
}
// N/A on Linux as far as I know.
JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
JUCE_API void JUCE_CALLTYPE Process::hide() {}
//==============================================================================
void ModifierKeys::updateCurrentModifiers() noexcept
{
currentModifiers = LinuxComponentPeer::currentModifiers;
}
ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
{
Window root, child;
int x, y, winx, winy;
unsigned int mask;
int mouseMods = 0;
ScopedXLock xlock;
if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
&root, &child, &x, &y, &winx, &winy, &mask) != False)
{
if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
}
LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
return LinuxComponentPeer::currentModifiers;
}
//==============================================================================
void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /* allowMenusAndBars */)
{
if (enableOrDisable)
kioskModeComponent->setBounds (getDisplays().getMainDisplay().totalArea);
}
//==============================================================================
ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
{
return new LinuxComponentPeer (*this, styleFlags, (Window) nativeWindowToAttachTo);
}
//==============================================================================
static double getDisplayDPI (int index)
{
double dpiX = (DisplayWidth (display, index) * 25.4) / DisplayWidthMM (display, index);
double dpiY = (DisplayHeight (display, index) * 25.4) / DisplayHeightMM (display, index);
return (dpiX + dpiY) / 2.0;
}
void Desktop::Displays::findDisplays (float masterScale)
{
if (display == 0)
return;
ScopedXLock xlock;
#if JUCE_USE_XINERAMA
int major_opcode, first_event, first_error;
if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
{
typedef Bool (*tXineramaIsActive) (::Display*);
typedef XineramaScreenInfo* (*tXineramaQueryScreens) (::Display*, int*);
static tXineramaIsActive xineramaIsActive = nullptr;
static tXineramaQueryScreens xineramaQueryScreens = nullptr;
if (xineramaIsActive == nullptr || xineramaQueryScreens == nullptr)
{
void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
if (h == nullptr)
h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
if (h != nullptr)
{
xineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
xineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
}
}
if (xineramaIsActive != nullptr
&& xineramaQueryScreens != nullptr
&& xineramaIsActive (display))
{
int numMonitors = 0;
if (XineramaScreenInfo* const screens = xineramaQueryScreens (display, &numMonitors))
{
for (int index = 0; index < numMonitors; ++index)
{
for (int j = numMonitors; --j >= 0;)
{
if (screens[j].screen_number == index)
{
Display d;
d.userArea = d.totalArea = Rectangle<int> (screens[j].x_org,
screens[j].y_org,
screens[j].width,
screens[j].height) * masterScale;
d.isMain = (index == 0);
d.scale = masterScale;
d.dpi = getDisplayDPI (index);
displays.add (d);
}
}
}
XFree (screens);
}
}
}
if (displays.size() == 0)
#endif
{
Atom hints = Atoms::getIfExists ("_NET_WORKAREA");
if (hints != None)
{
const int numMonitors = ScreenCount (display);
for (int i = 0; i < numMonitors; ++i)
{
GetXProperty prop (RootWindow (display, i), hints, 0, 4, false, XA_CARDINAL);
if (prop.success && prop.actualType == XA_CARDINAL && prop.actualFormat == 32 && prop.numItems == 4)
{
const long* const position = (const long*) prop.data;
Display d;
d.userArea = d.totalArea = Rectangle<int> (position[0], position[1],
position[2], position[3]) / masterScale;
d.isMain = (displays.size() == 0);
d.scale = masterScale;
d.dpi = getDisplayDPI (i);
displays.add (d);
}
}
}
if (displays.size() == 0)
{
Display d;
d.userArea = d.totalArea = Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
DisplayHeight (display, DefaultScreen (display))) * masterScale;
d.isMain = true;
d.scale = masterScale;
d.dpi = getDisplayDPI (0);
displays.add (d);
}
}
}
//==============================================================================
bool Desktop::addMouseInputSource()
{
if (mouseSources.size() == 0)
{
mouseSources.add (new MouseInputSource (0, true));
return true;
}
return false;
}
bool Desktop::canUseSemiTransparentWindows() noexcept
{
int matchedDepth = 0;
const int desiredDepth = 32;
return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
&& (matchedDepth == desiredDepth);
}
Point<int> MouseInputSource::getCurrentRawMousePosition()
{
Window root, child;
int x, y, winx, winy;
unsigned int mask;
ScopedXLock xlock;
if (XQueryPointer (display,
RootWindow (display, DefaultScreen (display)),
&root, &child,
&x, &y, &winx, &winy, &mask) == False)
{
// Pointer not on the default screen
x = y = -1;
}
return Point<int> (x, y);
}
void MouseInputSource::setRawMousePosition (Point<int> newPosition)
{
ScopedXLock xlock;
Window root = RootWindow (display, DefaultScreen (display));
XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
}
double Desktop::getDefaultMasterScale()
{
return 1.0;
}
Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
{
return upright;
}
//==============================================================================
static bool screenSaverAllowed = true;
void Desktop::setScreenSaverEnabled (const bool isEnabled)
{
if (screenSaverAllowed != isEnabled)
{
screenSaverAllowed = isEnabled;
typedef void (*tXScreenSaverSuspend) (Display*, Bool);
static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
if (xScreenSaverSuspend == nullptr)
if (void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW))
xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
ScopedXLock xlock;
if (xScreenSaverSuspend != nullptr)
xScreenSaverSuspend (display, ! isEnabled);
}
}
bool Desktop::isScreenSaverEnabled()
{
return screenSaverAllowed;
}
//==============================================================================
void* CustomMouseCursorInfo::create() const
{
ScopedXLock xlock;
const unsigned int imageW = image.getWidth();
const unsigned int imageH = image.getHeight();
int hotspotX = hotspot.x;
int hotspotY = hotspot.y;
#if JUCE_USE_XCURSOR
{
typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
typedef XcursorImage* (*tXcursorImageCreate) (int, int);
typedef void (*tXcursorImageDestroy) (XcursorImage*);
typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
static tXcursorSupportsARGB xcursorSupportsARGB = nullptr;
static tXcursorImageCreate xcursorImageCreate = nullptr;
static tXcursorImageDestroy xcursorImageDestroy = nullptr;
static tXcursorImageLoadCursor xcursorImageLoadCursor = nullptr;
static bool hasBeenLoaded = false;
if (! hasBeenLoaded)
{
hasBeenLoaded = true;
if (void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW))
{
xcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
xcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
xcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
xcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
if (xcursorSupportsARGB == nullptr || xcursorImageCreate == nullptr
|| xcursorImageLoadCursor == nullptr || xcursorImageDestroy == nullptr
|| ! xcursorSupportsARGB (display))
xcursorSupportsARGB = nullptr;
}
}
if (xcursorSupportsARGB != nullptr)
{
if (XcursorImage* xcImage = xcursorImageCreate (imageW, imageH))
{
xcImage->xhot = hotspotX;
xcImage->yhot = hotspotY;
XcursorPixel* dest = xcImage->pixels;
for (int y = 0; y < (int) imageH; ++y)
for (int x = 0; x < (int) imageW; ++x)
*dest++ = image.getPixelAt (x, y).getARGB();
void* result = (void*) xcursorImageLoadCursor (display, xcImage);
xcursorImageDestroy (xcImage);
if (result != nullptr)
return result;
}
}
}
#endif
Window root = RootWindow (display, DefaultScreen (display));
unsigned int cursorW, cursorH;
if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
return nullptr;
Image im (Image::ARGB, cursorW, cursorH, true);
{
Graphics g (im);
if (imageW > cursorW || imageH > cursorH)
{
hotspotX = (hotspotX * cursorW) / imageW;
hotspotY = (hotspotY * cursorH) / imageH;
g.drawImageWithin (image, 0, 0, imageW, imageH,
RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
false);
}
else
{
g.drawImageAt (image, 0, 0);
}
}
const int stride = (cursorW + 7) >> 3;
HeapBlock <char> maskPlane, sourcePlane;
maskPlane.calloc (stride * cursorH);
sourcePlane.calloc (stride * cursorH);
const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
for (int y = cursorH; --y >= 0;)
{
for (int x = cursorW; --x >= 0;)
{
const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
const int offset = y * stride + (x >> 3);
const Colour c (im.getPixelAt (x, y));
if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
}
}
Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
XColor white, black;
black.red = black.green = black.blue = 0;
white.red = white.green = white.blue = 0xffff;
void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
XFreePixmap (display, sourcePixmap);
XFreePixmap (display, maskPixmap);
return result;
}
void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
{
ScopedXLock xlock;
if (cursorHandle != nullptr)
XFreeCursor (display, (Cursor) cursorHandle);
}
void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
{
unsigned int shape;
switch (type)
{
case NormalCursor:
case ParentCursor: return None; // Use parent cursor
case NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), 0, 0).create();
case WaitCursor: shape = XC_watch; break;
case IBeamCursor: shape = XC_xterm; break;
case PointingHandCursor: shape = XC_hand2; break;
case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
case TopEdgeResizeCursor: shape = XC_top_side; break;
case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
case LeftEdgeResizeCursor: shape = XC_left_side; break;
case RightEdgeResizeCursor: shape = XC_right_side; break;
case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
case CrosshairCursor: shape = XC_crosshair; break;
case DraggingHandCursor: return createDraggingHandCursor();
case CopyingCursor:
{
static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0, 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
const int copyCursorSize = 119;
return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
}
default:
jassertfalse;
return None;
}
ScopedXLock xlock;
return (void*) XCreateFontCursor (display, shape);
}
void MouseCursor::showInWindow (ComponentPeer* peer) const
{
if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer))
lp->showMouseCursor ((Cursor) getHandle());
}
void MouseCursor::showInAllWindows() const
{
for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
showInWindow (ComponentPeer::getPeer (i));
}
//==============================================================================
Image juce_createIconForFile (const File& /* file */)
{
return Image::null;
}
//==============================================================================
bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
{
if (files.size() == 0)
return false;
if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
if (Component* sourceComp = draggingSource->getComponentUnderMouse())
if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (sourceComp->getPeer()))
return lp->externalDragFileInit (files, canMoveFiles);
// This method must be called in response to a component's mouseDown or mouseDrag event!
jassertfalse;
return false;
}
bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
{
if (text.isEmpty())
return false;
if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
if (Component* sourceComp = draggingSource->getComponentUnderMouse())
if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (sourceComp->getPeer()))
return lp->externalDragTextInit (text);
// This method must be called in response to a component's mouseDown or mouseDrag event!
jassertfalse;
return false;
}
//==============================================================================
void LookAndFeel::playAlertSound()
{
std::cout << "\a" << std::flush;
}
//==============================================================================
#if JUCE_MODAL_LOOPS_PERMITTED
void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
const String& title, const String& message,
Component* /* associatedComponent */)
{
AlertWindow::showMessageBox (iconType, title, message);
}
#endif
void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
const String& title, const String& message,
Component* associatedComponent,
ModalComponentManager::Callback* callback)
{
AlertWindow::showMessageBoxAsync (iconType, title, message, String::empty, associatedComponent, callback);
}
bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
const String& title, const String& message,
Component* associatedComponent,
ModalComponentManager::Callback* callback)
{
return AlertWindow::showOkCancelBox (iconType, title, message, String::empty, String::empty,
associatedComponent, callback);
}
int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
const String& title, const String& message,
Component* associatedComponent,
ModalComponentManager::Callback* callback)
{
return AlertWindow::showYesNoCancelBox (iconType, title, message,
String::empty, String::empty, String::empty,
associatedComponent, callback);
}
//==============================================================================
const int KeyPress::spaceKey = XK_space & 0xff;
const int KeyPress::returnKey = XK_Return & 0xff;
const int KeyPress::escapeKey = XK_Escape & 0xff;
const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::tabKey = XK_Tab & 0xff;
const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
| [
"curious.chrisps@gmail.com"
] | curious.chrisps@gmail.com |
44fe2f03a7500e8f0628ba1691b28e3a413741a4 | 058c23c36aa525fa8d5dca40015abbe264306efc | /Source/MOBA/AbilityTask_WaitForProjectileHit.h | bd002a4fa081afb80f8c9acb1f7444adfa7e0d18 | [] | no_license | demarrem29/MOBA | adf19497fe61d29b962f64c24d56703ea995ba25 | a48d89682ca94240a3ac51feee499e73e8668f25 | refs/heads/master | 2021-06-19T23:20:33.500211 | 2021-04-16T20:38:47 | 2021-04-16T20:38:47 | 202,532,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,140 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Abilities/Tasks/AbilityTask.h"
#include "Projectile.h"
#include "AbilityTask_WaitForProjectileHit.generated.h"
/**
*
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FWaitForProjectileHit);
UCLASS()
class MOBA_API UAbilityTask_WaitForProjectileHit : public UAbilityTask
{
GENERATED_BODY()
UAbilityTask_WaitForProjectileHit(const FObjectInitializer& ObjectInitializer);
UPROPERTY(BlueprintAssignable)
FWaitForProjectileHit OnProjectileHit;
UPROPERTY(VisibleAnywhere)
AProjectile* MyProjectile;
UFUNCTION()
void OnDestroyed(AActor* Actor, EEndPlayReason::Type EndPlayReason);
UFUNCTION(BlueprintCallable, Category = "Ability|Tasks", meta = (DisplayName = "WaitForProjectileHit", HidePin = "OwningAbility", DefaultToSelf = "OwningAbility", BlueprintInternalUseOnly = "TRUE"))
static UAbilityTask_WaitForProjectileHit* WaitForProjectileHit(UGameplayAbility* OwningAbility, AProjectile* SourceProjectile);
virtual void Activate() override;
virtual void OnDestroy(bool AbilityIsEnding) override;
};
| [
"michaellougee29@gmail.com"
] | michaellougee29@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.