blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
0b55fb2f2efdb1f473f64bf0624012e0319dc3b8
9b9512f0f63ddaca315c3eccb63ff19e884a56fa
/tests/cc_given/132.txt.cc
082ff6a9f97e52b1af9b3185ec667d229d877ef9
[]
no_license
yashton/compiler
d793cf69c668ee68928ab74af70e17c53ffadeef
40007da3af04a7ee31380ae29e23dcfbb50a1c8d
refs/heads/master
2020-08-02T15:43:35.181718
2019-09-27T23:04:37
2019-09-27T23:04:37
211,413,896
0
0
null
null
null
null
UTF-8
C++
false
false
4,840
cc
132.txt.cc
(program (define-env $env_t44 (k16 n return)) (define-env $env_t45 (n)) (define-env $env_t41 (k21 return)) (define-env $env_t42 (k21 n return)) (define-env $env_t43 (n return)) (define-env $env_t38 (cc)) (define-env $env_t39 ()) (define-env $env_t40 (return)) (define break (void)) (define return (void)) (define continue (void)) (define $current-handler (void)) (define g$fact (void)) (set-then! g$fact (make-closure (lambda ($env n k14) (app* (make-closure (lambda ($env f cc) (app* f (make-closure (lambda ($env x k) (app* (env-ref $env_t38 $env cc) x)) (make-env $env_t38 (cc cc))) cc)) (make-env $env_t39)) (make-closure (lambda ($env return k15) (app* (make-closure (lambda ($env k16) ((cps <) (env-ref $env_t43 $env n) 0 (make-closure (lambda ($env rv17) (if rv17 (app* (make-closure (lambda ($env k18) (app* (env-ref $env_t40 $env return) #f k18)) (make-env $env_t40 (return (env-ref $env_t44 $env return)))) (env-ref $env_t44 $env k16)) ((cps equal?) (env-ref $env_t44 $env n) 0 (make-closure (lambda ($env rv19) (if rv19 (app* (make-closure (lambda ($env k20) (app* (env-ref $env_t40 $env return) 1 k20)) (make-env $env_t40 (return (env-ref $env_t44 $env return)))) (env-ref $env_t44 $env k16)) (app* (make-closure (lambda ($env k21) ((cps -) (env-ref $env_t43 $env n) 1 (make-closure (lambda ($env rv22) (app* g$fact rv22 (make-closure (lambda ($env rv23) ((cps *) (env-ref $env_t42 $env n) rv23 (make-closure (lambda ($env rv24) (app* (env-ref $env_t41 $env return) rv24 (env-ref $env_t41 $env k21))) (make-env $env_t41 (k21 (env-ref $env_t42 $env k21)) (return (env-ref $env_t42 $env return)))))) (make-env $env_t42 (k21 (env-ref $env_t42 $env k21)) (n (env-ref $env_t42 $env n)) (return (env-ref $env_t42 $env return)))))) (make-env $env_t42 (k21 k21) (n (env-ref $env_t43 $env n)) (return (env-ref $env_t43 $env return)))))) (make-env $env_t43 (n (env-ref $env_t44 $env n)) (return (env-ref $env_t44 $env return)))) (env-ref $env_t44 $env k16)))) (make-env $env_t44 (k16 (env-ref $env_t44 $env k16)) (n (env-ref $env_t44 $env n)) (return (env-ref $env_t44 $env return))))))) (make-env $env_t44 (k16 k16) (n (env-ref $env_t43 $env n)) (return (env-ref $env_t43 $env return)))))) (make-env $env_t43 (n (env-ref $env_t45 $env n)) (return return))) k15)) (make-env $env_t45 (n n))) k14)) (make-env $env_t39)) (app* g$fact 5 (make-closure (lambda ($env rv25) ((cps py-print) rv25 $halt)) (make-env $env_t39)))))
64e5eba74af601d2aefc3d5540cb803342fb070c
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/TileCalorimeter/TileEvent/test/TileMutableDataContainer_test.cxx
56e58dece28c2ecc0ade3b4e0392b3351d634922
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
6,205
cxx
TileMutableDataContainer_test.cxx
/* Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration */ /* */ /** * @file TileEvent/testTileMutableDataContainer_test.cxx * @author scott snyder <snyder@bnl.gov> * @date Oct, 2018 * @brief Test for TileMutableDataContainer. */ #undef NDEBUG #include "TileEvent/TileMutableDataContainer.h" #include "TileEvent/TileRawDataContainer.h" #include "TileEvent/TileRawDataCollection.h" #include "TileEvent/TileRawData.h" #include "TileConditions/TileCablingService.h" #include "TileIdentifier/TileHWID.h" #include "IdDictParser/IdDictParser.h" #include <iostream> #include <cassert> static const size_t NCOLL = 2; static const size_t NCHAN = 10; IdDictParser parser; TileHWID hwid; TileTBID tbid; TileID tileid; class TileCablingSvc { public: static void init_idhelpers() { tileid.set_do_neighbours (false); parser.register_external_entity("TileCalorimeter", "IdDictTileCalorimeter.xml"); IdDictMgr& idd = parser.parse ("IdDictParser/ATLAS_IDS.xml"); hwid.set_quiet (true); tbid.set_quiet (true); tileid.set_quiet (true); assert (hwid.initialize_from_dictionary (idd) == 0); assert (tbid.initialize_from_dictionary (idd) == 0); assert (tileid.initialize_from_dictionary (idd) == 0); TileCablingService* svc = TileCablingService::getInstance(); svc->setTileHWID (&hwid); svc->setTileTBID (&tbid); svc->setTileID (&tileid); } }; class TestElement : public TileRawData { public: using TileRawData::TileRawData; unsigned m_x; }; class TestCollection : public TileRawDataCollection<TestElement> { public: typedef TestElement TElement; using TileRawDataCollection<TestElement>::TileRawDataCollection; }; typedef TileRawDataContainer<TestCollection> TestContainer; typedef TileMutableDataContainer<TestContainer> MutableTestContainer; class TestMutableTestContainer : public MutableTestContainer { public: using MutableTestContainer::MutableTestContainer; using MutableTestContainer::recycle; }; void createCollection (MutableTestContainer& cont, size_t hash) { int frag = cont.hashFunc().identifier(hash); auto coll = std::make_unique<TestCollection> (frag); assert( cont.addCollection (std::move (coll), hash).isSuccess() ); } void addChans (MutableTestContainer& cont, size_t hash) { TileCablingService* cabling = TileCablingService::getInstance(); int frag = cont.hashFunc().identifier (hash); HWIdentifier drawer_id = cabling->getTileHWID()->drawer_id (frag); for (size_t i = 0; i < NCHAN; i++) { HWIdentifier hwid = cabling->getTileHWID()->channel_id (drawer_id, i); int offs = i + hash*NCHAN; auto chan = std::make_unique<TestElement> (hwid); chan->m_x = offs; assert( cont.push_back (std::move (chan)).isSuccess() ); } } std::unique_ptr<MutableTestContainer> create1 (bool createColl) { auto cont = std::make_unique<MutableTestContainer> (createColl); assert( cont->status().isSuccess() ); cont->set_bsflags (98765); if (!createColl) { for (size_t hash = 0; hash < NCOLL; hash++) { createCollection (*cont, hash); } } for (size_t hash = 0; hash < NCOLL; hash++) { addChans (*cont, hash); } return cont; } void checkFind1 (MutableTestContainer& cont_nc, bool created) { const MutableTestContainer& cont = cont_nc; for (size_t hash = 0; hash < NCOLL; hash++) { TestCollection* coll_nc = cont_nc.indexFindPtr (hash); const TestCollection* coll = cont.indexFindPtr (hash); assert (coll_nc == coll); } if (!created) { assert (cont_nc.indexFindPtr(NCOLL) == nullptr); } } void checkFind2 (MutableTestContainer& cont_nc) { for (size_t hash = 0; hash < NCOLL; hash++) { assert (cont_nc.indexFindPtr(hash) == nullptr); } } void modify (MutableTestContainer& cont, float offs) { for (IdentifierHash hash : cont.GetAllCurrentHashes()) { TestCollection* coll = cont.indexFindPtr (hash); for (TestElement* chan : *coll) { chan->m_x += offs; } } } void check (const MutableTestContainer& cont, bool /*created*/, float x_offs) { TileCablingService* cabling = TileCablingService::getInstance(); assert (cont.get_type() == TileFragHash::Default); assert (cont.get_unit() == TileRawChannelUnit::ADCcounts); assert (cont.get_bsflags() == 98765); for (IdentifierHash hash : cont.GetAllCurrentHashes()) { const TestCollection* coll = cont.indexFindPtr (hash); assert (coll->identify() == cont.hashFunc().identifier (hash)); if (x_offs < 0) { assert (coll->size() == 0); } else { HWIdentifier drawer_id = cabling->getTileHWID()->drawer_id (coll->identify()); int i = 0; for (const TestElement* chan : *coll) { int offs = i + hash*NCHAN; HWIdentifier hwid = cabling->getTileHWID()-> channel_id (drawer_id, i); assert (chan->adc_HWID() == hwid); assert (chan->m_x == offs + x_offs); i += 1; } } } } void test1() { std::cout << "test1\n"; { std::unique_ptr<MutableTestContainer> cont1 = create1 (false); checkFind1 (*cont1, false); cont1->lock(); checkFind2 (*cont1); check (*cont1, false, 0); TestContainer& tc1 = *cont1; auto cont1a = std::make_unique<TestMutableTestContainer> (tc1); checkFind1 (*cont1a, false); check (*cont1a, false, 0); modify (*cont1a, 11); cont1a->lock(); checkFind2 (*cont1a); check (*cont1a, false, 11); cont1a->recycle(); assert (cont1a->get_bsflags() == 0); cont1a->set_bsflags (98765); checkFind1 (*cont1a, false); check (*cont1a, false, -1); } { std::unique_ptr<MutableTestContainer> cont2 = create1 (true); checkFind1 (*cont2, true); modify (*cont2, 23); cont2->lock(); checkFind2 (*cont2); check (*cont2, true, 23); TestContainer& tc2 = *cont2; auto cont2a = std::make_unique<MutableTestContainer> (tc2); checkFind1 (*cont2a, true); check (*cont2a, true, 23); modify (*cont2a, 11); cont2a->lock(); checkFind2 (*cont2a); check (*cont2a, true, 34); } } int main() { std::cout << "TileMutableDataContainer_test\n"; TileCablingSvc::init_idhelpers(); test1(); return 0; }
a549211e9568839f2e632131f42e4218b0bbaa95
01f1e62321c809233f845ea3d446869c2c9997b6
/2020-11-26/magic.cpp
70b54a919acd2f58e5d3470ffab6149bd27c4239
[ "MIT" ]
permissive
pufe/programa
1ed3faf00bac0b5f89009bf7f5e1120409edf73c
7f79566597446e9e39222e6c15fa636c3dd472bb
refs/heads/master
2023-02-04T21:57:12.181499
2020-12-22T21:53:38
2020-12-22T21:53:38
319,476,590
2
0
null
null
null
null
UTF-8
C++
false
false
1,478
cpp
magic.cpp
#include <bits/stdc++.h> using namespace std; typedef vector<vector<int> > matrix; matrix referenceMagicSquare() { return matrix { {8, 3, 4}, {1, 5, 9}, {6, 7, 2} }; } int calculateCost(matrix a, matrix b) { int total = 0; for(int i=0; i<3; ++i) for(int j=0; j<3; ++j) total+=abs(a[i][j]-b[i][j]); return total; } matrix flip(matrix a) { matrix r(3); for(int i=0; i<3; ++i) { r[i].resize(3); for(int j=0; j<3; ++j) { r[i][j] = a[2-i][j]; } } return r; } matrix rotate(matrix a) { matrix r(3); for(int i=0; i<3; ++i) { r[i].resize(3); for(int j=0; j<3; ++j) { r[i][j] = a[j][2-i]; } } return r; } // Complete the formingMagicSquare function below. int formingMagicSquare(matrix s) { matrix magic = referenceMagicSquare(); int cost = 1024; for(int i=0; i<4; ++i) { for(int j=0; j<2; ++j) { cost = min(cost, calculateCost(s, magic)); magic = flip(magic); } magic = rotate(magic); } return cost; } int main() { ofstream fout(getenv("OUTPUT_PATH")); matrix s(3); for (int i = 0; i < 3; i++) { s[i].resize(3); for (int j = 0; j < 3; j++) { cin >> s[i][j]; } cin.ignore(numeric_limits<streamsize>::max(), '\n'); } int result = formingMagicSquare(s); fout << result << "\n"; fout.close(); return 0; }
a7b53f098651b592a62a955adda7f5ba341a90ec
0ec609ad68a2eae91069d5a9817e4a02c537c021
/Modules/Core/Common/test/otbImageRegionNonUniformMultidimensionalSplitter.cxx
b119267e07b561cf04c999c4114810c51c528bc3
[ "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "AGPL-3.0-only", "GPL-3.0-only", "MIT", "LGPL-3.0-only", "Zlib", "BSD-3-Clause", "CECILL-B", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Pandinosaurus/OTB
895ff78d0dab62c68f3ef903d383b82de29fd29d
d74ab47d4308591db4ed5a5ea3b820cef73a39fe
refs/heads/develop
2023-07-20T12:31:53.392294
2023-07-19T08:37:29
2023-07-19T08:37:29
122,958,025
2
0
Apache-2.0
2023-07-20T05:45:27
2018-02-26T11:06:04
GLSL
UTF-8
C++
false
false
2,242
cxx
otbImageRegionNonUniformMultidimensionalSplitter.cxx
/* * Copyright (C) 2005-2022 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbImageRegionNonUniformMultidimensionalSplitter.h" #include <fstream> int otbImageRegionNonUniformMultidimensionalSplitter(int itkNotUsed(argc), char* argv[]) { const int Dimension = 2; typedef otb::ImageRegionNonUniformMultidimensionalSplitter<Dimension> FilterType; typedef FilterType::IndexType IndexType; typedef FilterType::SizeType SizeType; typedef FilterType::RegionType RegionType; IndexType index; index[0] = atoi(argv[1]); index[1] = atoi(argv[2]); SizeType size; size[0] = atoi(argv[3]); size[1] = atoi(argv[4]); unsigned int nbSplitTheoric(atoi(argv[5])); unsigned int nbAsked(atoi(argv[6])); const char* outfname(argv[7]); RegionType region; region.SetSize(size); region.SetIndex(index); FilterType::Pointer filter = FilterType::New(); unsigned int nb = filter->GetNumberOfSplits(region, nbSplitTheoric); RegionType region2 = filter->GetSplit(nbAsked, nb, region); std::ofstream outfile(outfname); outfile << "Input region: " << region << std::endl; outfile << "Input NumberOfSplits: " << nbSplitTheoric << std::endl; outfile << "Output GetNumberOfSplits: " << nb << std::endl; outfile << "Output GetSplit(" << nbAsked << "," << nb << ", input region): " << std::endl; outfile << " " << region2 << std::endl; outfile.close(); return EXIT_SUCCESS; }
496be3e428a4eba0681365d474d72b5e0249997d
54e7b4f25d3461154778f24aa10082d754e5f764
/src/win32com/ControllerSettings.cpp
635fb8c9cd0988564d7c566f7518d1e3bb872cc6
[]
no_license
tomlogic/pinmame
2e9624d64374f8f59657b3e054ab3cfdb361e039
26333ff367a04a698336ac6d97b23bb92cb587c8
refs/heads/master
2021-06-11T05:22:51.798432
2018-03-12T03:25:20
2019-11-18T03:51:21
20,775,729
5
4
null
null
null
null
UTF-8
C++
false
false
11,076
cpp
ControllerSettings.cpp
// ControllerSettings.cpp : Implementation of CControllerSettings #include "stdafx.h" #if _MSC_VER >= 1700 #ifdef inline #undef inline #endif #endif #include "VPinMAME_h.h" #include "ControllerSettings.h" #include "VPinMAMEConfig.h" #include "VPinMAMEAboutDlg.h" #include "ControllerRegKeys.h" #include <atlwin.h> #include <shlobj.h> #include "DisplayInfoList.h" // from ControllerRun.cpp extern BOOL IsEmulationRunning(); // from VPinMAMEConfig.c extern int fAllowWriteAccess; // we need this to adjust the game window if a game is running #include "Controller.h" extern "C" HWND win_video_window; ///////////////////////////////////////////////////////////////////////////// // CControllerSettingsDlg class CControllerSettingsDlg : public CDialogImpl<CControllerSettingsDlg> { public: BEGIN_MSG_MAP(CControllerSettingsDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) MESSAGE_HANDLER(WM_DESTROY, OnDestroy) COMMAND_CODE_RANGE_HANDLER(IDC_ROMDIRS, IDC_IMGDIR, EN_CHANGE, OnEditCtrlChanged) COMMAND_HANDLER(IDC_ALLOWWRITEACCESS, BN_CLICKED, OnEditCtrlChanged) COMMAND_HANDLER(IDC_FULLSCREEN, BN_CLICKED, OnEditCtrlChanged) COMMAND_HANDLER(IDC_DISPLAYLIST, CBN_SELCHANGE, OnEditCtrlChanged) COMMAND_ID_HANDLER(IDOK, OnOK) COMMAND_ID_HANDLER(IDCANCEL, OnCancel) COMMAND_ID_HANDLER(IDABOUT, OnAbout) COMMAND_ID_HANDLER(IDRESETTODEFAULT, OnResetToDefault) COMMAND_RANGE_HANDLER(IDDIRBUTTONROM, IDDIRBUTTONIMG, OnBrowseForDir) END_MSG_MAP() enum { IDD = IDD_CONTROLLERSETTINGSDLG }; private: bool m_fChanged; CControllerSettings* pControllerSettings; CWindow displayList; private: // helper functions //============================================================ // ShowDisplays //============================================================ // Uses the displays collection to fill in the IDC_DISPLAYLIST combo box. void ShowDisplays() { // Get the current display name (for selection) char* szDisplayName = (char*) get_option("screen"); CDisplayInfoList displays = CDisplayInfoList(); // Add each display to the combo box for (size_t i=0; i < displays.Count(); i++) { // Get the display at the index CDisplayInfo* display = displays.Item(i); // Add to the list // displayList.SendMessage(CB_ADDSTRING, 0, (LPARAM)display->GetDriverDescription()); UINT_PTR index = displayList.SendMessage(CB_ADDSTRING, 0, (LPARAM) display->GetFriendlyName()); char* szItemData = new char[256]; if ( display->GetIsDefault() ) lstrcpy(szItemData, ""); else lstrcpy(szItemData, display->GetDriverName()); displayList.SendMessage(CB_SETITEMDATA, (WPARAM) index, (LPARAM) szItemData); if ( lstrcmpi(szItemData, szDisplayName)==0 ) displayList.SendMessage(CB_SETCURSEL, (WPARAM) index, (LPARAM) 0); } if ( displayList.SendMessage(CB_GETCURSEL, (WPARAM) 0, (LPARAM) 0)<0 ) displayList.SendMessage(CB_SETCURSEL, (WPARAM) 0, (LPARAM) 0); } void CleanupDisplayComboBox() { UINT_PTR count = displayList.SendMessage(CB_GETCOUNT, 0, 0); for(UINT_PTR i=0; i<count; i++) { char* szItemData = (char*) displayList.SendMessage(CB_GETITEMDATA, (WPARAM) i, (LPARAM) NULL); displayList.SendMessage(CB_SETITEMDATA, (WPARAM) i, (LPARAM) NULL); delete szItemData; } } //============================================================ // SetControlValues //============================================================ // Sets the values from the configuration data into the dialog controls void SetControlValues() { /******************************************/ /*POPULATE CONTROLS FROM OPTIONS IN MEMORY*/ /******************************************/ VARIANT vValue; VariantInit(&vValue); // Path Values SetDlgItemText(IDC_ROMDIRS, (char*) get_option("rompath")); SetDlgItemText(IDC_CFGDIR, (char*) get_option("cfg_directory")); SetDlgItemText(IDC_NVRAMDIR, (char*) get_option("nvram_directory")); SetDlgItemText(IDC_SAMPLEDIRS, (char*) get_option("samplepath")); SetDlgItemText(IDC_MEMCARDDIRS, (char*)get_option("memcard_directory")); SetDlgItemText(IDC_IMGDIR, (char*) get_option("snapshot_directory")); // Set check boxes pControllerSettings->get_Value(CComBSTR("window"), &vValue); CheckDlgButton(IDC_FULLSCREEN, (vValue.boolVal==VARIANT_TRUE)?BST_UNCHECKED:BST_CHECKED); // NOTE: Inverted VariantClear(&vValue); char szRegKey[256]; lstrcpy(szRegKey, REG_BASEKEY); CheckDlgButton(IDC_ALLOWWRITEACCESS, ReadRegistry(szRegKey, REG_DWALLOWWRITEACCESS, REG_DWALLOWWRITEACCESSDEF)); } //============================================================ // GetControlValues //============================================================ // Gets the values from the dialog controls and stores them into the configuration data void GetControlValues() { char szPath[4096]; GetDlgItemText(IDC_ROMDIRS, szPath, sizeof(szPath)); pControllerSettings->put_Value(CComBSTR("rompath"), CComVariant(szPath)); GetDlgItemText(IDC_CFGDIR, szPath, sizeof(szPath)); pControllerSettings->put_Value(CComBSTR("cfg_directory"), CComVariant(szPath)); GetDlgItemText(IDC_NVRAMDIR, szPath, sizeof(szPath)); pControllerSettings->put_Value(CComBSTR("nvram_directory"), CComVariant(szPath)); GetDlgItemText(IDC_SAMPLEDIRS, szPath, sizeof(szPath)); pControllerSettings->put_Value(CComBSTR("samplepath"), CComVariant(szPath)); GetDlgItemText(IDC_MEMCARDDIRS, szPath, sizeof(szPath)); pControllerSettings->put_Value(CComBSTR("memcard_directory"), CComVariant(szPath)); GetDlgItemText(IDC_IMGDIR, szPath, sizeof(szPath)); pControllerSettings->put_Value(CComBSTR("snapshot_directory"), CComVariant(szPath)); UINT_PTR index = displayList.SendMessage(CB_GETCURSEL, (WPARAM) 0, (LPARAM) 0); char* szItemData = (char*) displayList.SendMessage(CB_GETITEMDATA, (WPARAM) index, (LPARAM) NULL); pControllerSettings->put_Value(CComBSTR("screen"), CComVariant(szItemData)); pControllerSettings->put_Value(CComBSTR("window"), CComVariant((BOOL) !IsDlgButtonChecked(IDC_FULLSCREEN))); // NOTE: Inverted fAllowWriteAccess = IsDlgButtonChecked(IDC_ALLOWWRITEACCESS); char szRegKey[256]; lstrcpy(szRegKey, REG_BASEKEY); WriteRegistry(szRegKey, REG_DWALLOWWRITEACCESS, fAllowWriteAccess); } /***************************************************************/ /*LAUNCH A GETDIRECTORY() WINDOW AND CAPTURE SELECTED DIRECTORY*/ /***************************************************************/ BOOL BrowseForDirectory(char* pResult) { BOOL bResult = FALSE; LPMALLOC piMalloc; BROWSEINFO Info; LPITEMIDLIST pItemIDList = NULL; char buf[MAX_PATH]; if (!SUCCEEDED(SHGetMalloc(&piMalloc))) return FALSE; Info.hwndOwner = m_hWnd; Info.pidlRoot = NULL; Info.pszDisplayName = buf; Info.lpszTitle = (LPCSTR)"Directory name:"; Info.ulFlags = BIF_RETURNONLYFSDIRS; Info.lpfn = NULL; Info.lParam = (LPARAM) NULL; pItemIDList = SHBrowseForFolder(&Info); if (pItemIDList != NULL) { if (SHGetPathFromIDList(pItemIDList, buf) == TRUE) { strncpy(pResult, buf, MAX_PATH); bResult = TRUE; } piMalloc->Free(pItemIDList); } else { bResult = FALSE; } piMalloc->Release(); return bResult; } void SetChanged(bool fChanged) { m_fChanged = fChanged; } // message handlers LRESULT OnInitDialog(UINT, WPARAM, LPARAM lParam, BOOL&) { CenterWindow(); pControllerSettings = (CControllerSettings*) lParam; // Get the display list control (combo box) displayList = CWindow(GetDlgItem(IDC_DISPLAYLIST)); // Show displays ShowDisplays(); /*Init Dialog*/ SetControlValues(); SetChanged(false); return 1; } LRESULT OnDestroy(UINT, WPARAM, LPARAM lParam, BOOL&) { CleanupDisplayComboBox(); return 1; } LRESULT OnEditCtrlChanged(WORD, UINT, HWND, BOOL&) { SetChanged(true); return 0; } LRESULT OnOK(WORD, UINT, HWND, BOOL&) { if ( m_fChanged ) { // get settings from the controls GetControlValues(); // emulation is running? if ( IsEmulationRunning() ) MessageBox("Your changes will not take effect until you restart Visual PinMAME!","Notice!",MB_OK | MB_ICONINFORMATION); } EndDialog(IDOK); return 0; } LRESULT OnCancel(WORD, UINT, HWND, BOOL&) { EndDialog(IDCANCEL); return 0; } LRESULT OnAbout(WORD, UINT, HWND, BOOL&) { ShowAboutDlg(m_hWnd); return 0; } LRESULT OnResetToDefault(WORD, UINT, HWND, BOOL&) { /* Delete controller (global) settings for the registry and reload them */ DeleteGlobalSettings(); LoadGlobalSettings(); SetControlValues(); SetChanged(false); return 0; } LRESULT OnBrowseForDir(WORD, UINT uCtrlId, HWND, BOOL&) { char szDir[MAX_PATH]; if ( !BrowseForDirectory(szDir) ) return 0; switch ( uCtrlId ) { case IDDIRBUTTONROM: SetDlgItemText(IDC_ROMDIRS, szDir); break; case IDDIRBUTTONCFG: SetDlgItemText(IDC_CFGDIR, szDir); break; case IDDIRBUTTONNVRAM: SetDlgItemText(IDC_NVRAMDIR, szDir); break; case IDDIRBUTTONSAMPLE: SetDlgItemText(IDC_SAMPLEDIRS, szDir); break; case IDDIRBUTTONMEMCARD: SetDlgItemText(IDC_MEMCARDDIRS, szDir); break; case IDDIRBUTTONIMG: SetDlgItemText(IDC_IMGDIR, szDir); break; } return 0; } }; ///////////////////////////////////////////////////////////////////////////// // CControllerSettings STDMETHODIMP CControllerSettings::InterfaceSupportsErrorInfo(REFIID riid) { static const IID* arr[] = { &IID_IControllerSettings }; for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; } CControllerSettings::CControllerSettings() { } STDMETHODIMP CControllerSettings::ShowSettingsDlg(LONG_PTR hParentWnd) { CControllerSettingsDlg ControllerSettingsDlg; ControllerSettingsDlg.DoModal((HWND) hParentWnd, (LPARAM) this); return S_OK; } STDMETHODIMP CControllerSettings::Clear() { DeleteGlobalSettings(); return S_OK; } STDMETHODIMP CControllerSettings::get_Value(BSTR sName, VARIANT *pVal) { char szName[4096]; WideCharToMultiByte(CP_ACP, 0, sName, -1, szName, sizeof szName, NULL, NULL); return GetSetting(NULL, szName, pVal)?S_OK:S_FALSE; } STDMETHODIMP CControllerSettings::put_Value(BSTR sName, VARIANT newVal) { char szName[4096]; WideCharToMultiByte(CP_ACP, 0, sName, -1, szName, sizeof szName, NULL, NULL); HRESULT hr = PutSetting(NULL, szName, newVal)?S_OK:S_FALSE; if ( SUCCEEDED(hr) ) { VariantChangeType(&newVal, &newVal, 0, VT_BSTR); char szValue[4096]; WideCharToMultiByte(CP_ACP, 0, newVal.bstrVal, -1, szValue, sizeof szName, NULL, NULL); set_option(szName, szValue, 0); if ( IsEmulationRunning() && SettingAffectsRunningGame(szName) ) PostMessage(win_video_window, RegisterWindowMessage(VPINMAMEADJUSTWINDOWMSG), 0, 0); } return hr; } STDMETHODIMP CControllerSettings::get_InstallDir(BSTR *pVal) { char szInstallDir[MAX_PATH]; GetInstallDir(szInstallDir, sizeof szInstallDir); *pVal = CComBSTR(szInstallDir).Detach(); return S_OK; }
829a4faa9149a6e291b24f3f16f6b92598ac1b50
2d695a43bd68fb161131dbb25050f559fe1e2082
/fine_grain_amcl/src/main.cpp
b76619cd4beb0bdd320a9beaaba63cc7ecdccf20
[]
no_license
mryellow/ros-catslam
ca8c16007d68e15114ea321ee39f52c324b1b3b0
4da0e0075d21be28a7c7e876e5186420ef42fa4a
refs/heads/master
2020-05-17T13:45:40.463378
2012-05-03T01:13:28
2012-05-03T01:13:28
33,471,152
0
0
null
null
null
null
UTF-8
C++
false
false
1,467
cpp
main.cpp
#include "ros/ros.h" #include "geometry_msgs/PoseWithCovarianceStamped.h" #include "geometry_msgs/PoseStamped.h" #include <tf/transform_listener.h> double px,py,pz,rx,ry,rz,rw; int main(int argc, char **argv) { ros::init(argc,argv,"fine_grain_amcl"); ros::NodeHandle n; ros::Publisher raw_pub= n.advertise<geometry_msgs::PointStamped>("fine_grain_amcl",1); ros::Rate loop_rate(10); int count = 0; tf::TransformListener listener; while(ros::ok()) { tf::StampedTransform transform; try{ listener.lookupTransform("/map", "/base_link", ros::Time(0), transform); } catch(tf::TransformException ex) { ROS_ERROR("%s",ex.what()); } //ROS_INFO("Robot at %f,%f",transform.getOrigin().x(),transform.getOrigin().y() ); geometry_msgs::PoseStamped msg; msg.header.stamp = ros::Time::now(); msg.header.frame_id = "/map"; msg.pose.position.x = transform.getOrigin().x(); msg.pose.position.y = transform.getOrigin().y(); msg.pose.position.z = transform.getOrigin().z(); msg.pose.orientation.x = transform.getRotation().x(); msg.pose.orientation.y = transform.getRotation().y(); msg.pose.orientation.z = transform.getRotation().z(); msg.pose.orientation.w = transform.getRotation().w(); raw_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } return 0; }
60c11bd28de9fb5a9f2340df3d6ba0c069afb610
187ce9d4df99208c3db0e44f3db6a3df4ce34717
/C++/36.valid-sudoku.cpp
15b04e304483499ccd5d84eaa7ce1dc3bfc1e906
[]
no_license
zhoujf620/LeetCode-Practice
5098359fbebe07ffa0d13fe40236cecf80c12507
8babc83cefc6722b9845f61ef5d15edc99648cb6
refs/heads/master
2022-09-26T21:49:59.248276
2022-09-21T14:33:03
2022-09-21T14:33:03
222,195,315
0
0
null
null
null
null
UTF-8
C++
false
false
748
cpp
36.valid-sudoku.cpp
/* * @lc app=leetcode.cn id=36 lang=cpp * * [36] Valid Sudoku */ #include<vector> using namespace std; // @lc code=start class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { vector<short> row(9, 0), col(9, 0), block(9, 0); for (int i=0; i<9; i++){ for (int j=0; j<9; j++){ if(board[i][j] != '.') { int idx = 1<<(board[i][j]-'0'); if (row[i]&idx || col[j]&idx || block[i/3*3 + j/3]&idx) return false; row[i] |= idx; col[j] |= idx; block[i/3*3 + j/3] |= idx; } } } return true; } }; // @lc code=end
54f2ae86eeeabc19d0341c318388ee09e7c8a172
bca5bfe5c60f8f33950439d7c09864efa3dddfd5
/mycalendarscreen.cpp
fbe599d50c1e3a3dd4bd0c2d10f432e419c6f224
[]
no_license
AlexTheTRex/PerfectPlan
f0035eda0d1b4c3f5c2b4e5adaa1f214122257d4
4ede9aa1619ab617ec055f787fda518a15989541
refs/heads/master
2021-09-21T00:21:34.091540
2017-11-02T18:53:38
2017-11-02T18:53:38
109,305,743
0
0
null
null
null
null
UTF-8
C++
false
false
1,538
cpp
mycalendarscreen.cpp
#include "mycalendarscreen.h" MyCalendarScreen::MyCalendarScreen(MyAccountScreen* account) : QWidget() { this->accountscreen_ = account; this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::Window); this->cancelbutton_ = new QPushButton("Annuler"); this->okbutton_ = new QPushButton("Ajouter"); this->buttonslayout_ = new QHBoxLayout; this->buttonslayout_->addWidget(this->okbutton_); this->buttonslayout_->addWidget(this->cancelbutton_); this->biglayout_ = new QVBoxLayout; this->calendar_ = new QCalendarWidget; this->calendar_->setLocale(QLocale::French); this->biglayout_->addWidget(this->calendar_); this->biglayout_->addLayout(buttonslayout_); this->setLayout(this->biglayout_); QObject::connect(this->cancelbutton_, SIGNAL(clicked()), this, SLOT(Cancel())); QObject::connect(this->okbutton_, SIGNAL(clicked()), this, SLOT(Add())); } void MyCalendarScreen::Cancel(){ this->close(); this->accountscreen_->setEnabled(true); delete this; } void MyCalendarScreen::Add(){ QDate date = this->calendar_->selectedDate(); this->accountscreen_->mainscreen_->engine_->AddVacationDay(this->accountscreen_->user_->GetId(), date); MyAccountScreen* oldaccountscreen = this->accountscreen_; this->accountscreen_ = new MyAccountScreen(oldaccountscreen->user_, oldaccountscreen->mainscreen_); this->close(); this->accountscreen_->showMaximized(); oldaccountscreen->close(); delete oldaccountscreen; delete this; }
8a111a129e5511a966ad94f3eb3b4cbe9337d6a9
5e2f3f3938c2ecc46806e245e172e2445063792f
/src/win32/gpucc_compiler_fxc_win32.cc
853cb25ff242a12040e83bd15aa7765b69856938
[]
no_license
russellklenk/gpucc
32db8f597212e87b9186ffcdfc671f627133c5aa
992e5b9fe6e10d06aac98dc0edc434aa20303e86
refs/heads/master
2020-05-15T18:19:50.212524
2019-05-09T22:20:44
2019-05-09T22:20:44
182,423,143
5
0
null
null
null
null
UTF-8
C++
false
false
10,922
cc
gpucc_compiler_fxc_win32.cc
#include "gpucc.h" #include "gpucc_internal.h" #include "win32/gpucc_compiler_fxc_win32.h" GPUCC_API(struct GPUCC_PROGRAM_BYTECODE*) gpuccCreateProgramBytecodeFxc ( struct GPUCC_PROGRAM_COMPILER *compiler ) { GPUCC_BYTECODE_FXC_WIN32 *code = nullptr; if ((code = (GPUCC_BYTECODE_FXC_WIN32*) malloc(sizeof(GPUCC_BYTECODE_FXC_WIN32))) == nullptr) { GPUCC_RESULT r = gpuccMakeResult(GPUCC_RESULT_CODE_OUT_OF_HOST_MEMORY); gpuccDebugPrintf(L"GpuCC: Failed to allocate %Iu bytes to create FXC bytecode.\n", sizeof(GPUCC_BYTECODE_FXC_WIN32)); gpuccSetLastResult(r); return nullptr; } memset(code, 0, sizeof(GPUCC_BYTECODE_FXC_WIN32)); /* TODO: Increment ref count on compiler object? */ code->CommonFields.Compiler = compiler; code->CommonFields.CompileResult = gpuccMakeResult(GPUCC_RESULT_CODE_EMPTY_BYTECODE_CONTAINER); code->CommonFields.EntryPoint = nullptr; /* Set on compile */ code->CommonFields.SourcePath = nullptr; /* Set on compile */ code->CommonFields.LogBuffer = nullptr; /* Set on compile */ code->CommonFields.LogBufferSize = 0; /* Set on compile */ code->CommonFields.BytecodeSize = 0; /* Set on compile */ code->CommonFields.BytecodeBuffer = nullptr; /* Set on compile */ code->CodeBuffer = nullptr; /* Set on compile */ code->ErrorLog = nullptr; /* Set on compile */ return (struct GPUCC_PROGRAM_BYTECODE*) code; } GPUCC_API(void) gpuccDeleteProgramBytecodeFxc ( struct GPUCC_PROGRAM_BYTECODE *bytecode ) { GPUCC_BYTECODE_FXC_WIN32 *code = gpuccBytecodeFxc_(bytecode); if (code->ErrorLog != nullptr) { ID3DBlob *log = code->ErrorLog; code->CommonFields.LogBufferSize = 0; code->CommonFields.LogBuffer = nullptr; code->ErrorLog = nullptr; log->Release(); } if (code->CodeBuffer != nullptr) { ID3DBlob *buf = code->CodeBuffer; code->CommonFields.BytecodeBuffer = nullptr; code->CommonFields.BytecodeSize = 0; code->CodeBuffer = nullptr; buf->Release(); } if (code->CommonFields.EntryPoint != nullptr) { free(code->CommonFields.EntryPoint); code->CommonFields.EntryPoint = nullptr; code->CommonFields.SourcePath = nullptr; } /* TODO: Decrement ref count on compiler object? */ } GPUCC_API(struct GPUCC_RESULT) gpuccCompileBytecodeFxc ( struct GPUCC_PROGRAM_BYTECODE *container, char const *source_code, uint64_t source_size, char const *source_path, char const *entry_point ) { GPUCC_COMPILER_FXC_WIN32 *compiler_ = gpuccCompilerFxc_(gpuccQueryBytecodeCompiler_(container)); GPUCC_BYTECODE_FXC_WIN32 *container_ = gpuccBytecodeFxc_(container); FXCCOMPILERAPI_DISPATCH *dispatch = compiler_->DispatchTable; GPUCC_RESULT result = gpuccMakeResult(GPUCC_RESULT_CODE_SUCCESS); ID3DBlob *code = nullptr; ID3DBlob *log = nullptr; HRESULT res = S_OK; DWORD flags1 = compiler_->FxcCompileFlags; DWORD flags2 = 0; res = dispatch->D3DCompile ( source_code, source_size, source_path, compiler_->DefineArray, nullptr, /* ID3DInclude* pInclude */ entry_point, compiler_->ShaderModel, flags1, flags2, &code, &log ); if (FAILED(res)) { result = gpuccMakeResult(GPUCC_RESULT_CODE_COMPILE_FAILED); } if (code != nullptr) { container_->CommonFields.BytecodeSize =(uint64_t) code->GetBufferSize(); container_->CommonFields.BytecodeBuffer =(uint8_t*) code->GetBufferPointer(); } else { container_->CommonFields.BytecodeSize = 0; container_->CommonFields.BytecodeBuffer = nullptr; } container_->CodeBuffer = code; if (log != nullptr) { container_->CommonFields.LogBufferSize =(uint64_t) log->GetBufferSize(); container_->CommonFields.LogBuffer =(char *) log->GetBufferPointer(); } else { container_->CommonFields.LogBufferSize = 0; container_->CommonFields.LogBuffer = nullptr; } container_->ErrorLog = log; return result; } static void gpuccCleanupCompilerFxc ( struct GPUCC_PROGRAM_COMPILER *compiler ) { UNREFERENCED_PARAMETER(compiler); } GPUCC_API(struct GPUCC_PROGRAM_COMPILER*) gpuccCreateCompilerFxc ( struct GPUCC_PROGRAM_COMPILER_INIT *config ) { // Assume that config has been validated by gpuccCreateCompiler. GPUCC_PROCESS_CONTEXT_WIN32 *pctx = gpuccGetProcessContext_(); GPUCC_COMPILER_FXC_WIN32 *fxc = nullptr; D3D_SHADER_MACRO *macros = nullptr; uint8_t *base = nullptr; uint8_t *ptr = nullptr; size_t nbneed = 0; int version_mj = 0; int version_mi = 0; char shader_type[3] ={0, 0, 0}; DWORD flags1 = 0; /* Validate the target profile. */ if (config->TargetProfile == nullptr) { GPUCC_RESULT r = gpuccMakeResult(GPUCC_RESULT_CODE_INVALID_TARGET_PROFILE); gpuccDebugPrintf(L"GpuCC: A target profile, for example, \"cs_5_0\", is required by the FXC compiler.\n"); gpuccSetLastResult(r); return nullptr; } if (gpuccExtractDirect3DShaderModel(config->TargetProfile, shader_type, &version_mj, &version_mi) != 0) { /* The TargetProfile string doesn't match the expected format. */ GPUCC_RESULT r = gpuccMakeResult(GPUCC_RESULT_CODE_INVALID_TARGET_PROFILE); gpuccDebugPrintf(L"GpuCC: Invalid target profile \"%S\" for the FXC compiler.\n", config->TargetProfile); gpuccSetLastResult(r); return nullptr; } if (_stricmp(shader_type, "cs") != 0 && _stricmp(shader_type, "vs") != 0 && _stricmp(shader_type, "ps") != 0 && _stricmp(shader_type, "gs") != 0) { /* The target profile specifies an unexpected shader type. */ GPUCC_RESULT r = gpuccMakeResult(GPUCC_RESULT_CODE_INVALID_TARGET_PROFILE); gpuccDebugPrintf(L"GpuCC: Invalid target profile \"%S\". Unexpected shader type \'%s\'.\n", config->TargetProfile, shader_type); gpuccSetLastResult(r); return nullptr; } if (version_mj < 4) { /* Legacy D3D9 shader models are not supported. */ GPUCC_RESULT r = gpuccMakeResult(GPUCC_RESULT_CODE_INVALID_TARGET_PROFILE); gpuccDebugPrintf(L"GpuCC: Invalid target profile \"%S\". Legacy shader models are not supported.\n", config->TargetProfile); gpuccSetLastResult(r); return nullptr; } if (version_mj > 5) { /* Shader Model 6 and later requires using the newer dxc compiler. */ GPUCC_RESULT r = gpuccMakeResult(GPUCC_RESULT_CODE_INVALID_TARGET_PROFILE); gpuccDebugPrintf(L"GpuCC: Invalid target profile \"%S\". Shader model 6+ require the newer dxc compiler and DXIL bytecode format.\n", config->TargetProfile); gpuccSetLastResult(r); return nullptr; } /* Determine the D3DCOMPILE flags. */ if (config->CompilerFlags & GPUCC_COMPILER_FLAG_DEBUG) { flags1 |= D3DCOMPILE_DEBUG; } if (config->CompilerFlags & GPUCC_COMPILER_FLAG_DISABLE_OPTIMIZATIONS) { flags1 |= D3DCOMPILE_SKIP_OPTIMIZATION; } if (config->CompilerFlags & GPUCC_COMPILER_FLAG_WARNINGS_AS_ERRORS) { flags1 |= D3DCOMPILE_WARNINGS_ARE_ERRORS; } if (config->CompilerFlags & GPUCC_COMPILER_FLAG_ROW_MAJOR_MATRICES) { flags1 |= D3DCOMPILE_PACK_MATRIX_ROW_MAJOR; } else { flags1 |= D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR; } if (config->CompilerFlags & GPUCC_COMPILER_FLAG_ENABLE_16BIT_TYPES) { gpuccDebugPrintf(L"GpuCC: Shader model targets pre-6.2 do not support native 16-bit types. Native support will be disabled.\n"); } if (config->CompilerFlags & GPUCC_COMPILER_FLAG_AVOID_FLOW_CONTROL) { flags1 |= D3DCOMPILE_AVOID_FLOW_CONTROL; } if (config->CompilerFlags & GPUCC_COMPILER_FLAG_ENABLE_IEEE_STRICT) { flags1 |= D3DCOMPILE_IEEE_STRICTNESS; } /* Determine the amount of memory required. */ nbneed += sizeof(GPUCC_COMPILER_FXC_WIN32); nbneed += sizeof(D3D_SHADER_MACRO) * (config->DefineCount + 1); nbneed += strlen(config->TargetProfile) + 1; for (uint32_t i = 0, n = config->DefineCount; i < n; ++i) { nbneed += strlen(config->DefineSymbols[i]) + 1; nbneed += strlen(config->DefineValues [i]) + 1; } /* Allocate as a single block. */ if ((base = (uint8_t*) malloc(nbneed)) == nullptr) { GPUCC_RESULT r = gpuccMakeResult(GPUCC_RESULT_CODE_OUT_OF_HOST_MEMORY); gpuccDebugPrintf(L"GpuCC: Failed to allocate %Iu bytes to create FXC compiler.\n", nbneed); gpuccSetLastResult(r); return nullptr; } fxc =(GPUCC_COMPILER_FXC_WIN32*) base; ptr = base + sizeof(GPUCC_COMPILER_FXC_WIN32); /* The array of D3D_SHADER_MACRO structures immediately follows the * compiler record. The entries are initialized when interning the * strings below. */ macros =(D3D_SHADER_MACRO *) ptr; ptr += sizeof(D3D_SHADER_MACRO) * (config->DefineCount + 1); /* Copy string data into the memory block. */ fxc->ShaderModel = gpuccPutStringUtf8(ptr, config->TargetProfile); for (uint32_t i = 0 , n = config->DefineCount; i < n; ++i) { macros[i].Name = gpuccPutStringUtf8(ptr, config->DefineSymbols[i]); macros[i].Definition = gpuccPutStringUtf8(ptr, config->DefineValues [i]); } /* The macro array is always terminated with a null entry. */ macros[config->DefineCount] = D3D_SHADER_MACRO { nullptr, nullptr }; /* Finish initializing the compiler structure. */ fxc->CommonFields.CompilerType = GPUCC_COMPILER_TYPE_FXC; fxc->CommonFields.BytecodeType = GPUCC_BYTECODE_TYPE_DXBC; fxc->CommonFields.CreateBytecode = gpuccCreateProgramBytecodeFxc; fxc->CommonFields.DeleteBytecode = gpuccDeleteProgramBytecodeFxc; fxc->CommonFields.CompileBytecode = gpuccCompileBytecodeFxc; fxc->CommonFields.CleanupCompiler = gpuccCleanupCompilerFxc; fxc->DispatchTable =&pctx->FxcCompiler_Dispatch; fxc->DefineArray = macros; fxc->DefineCount = config->DefineCount; fxc->TargetRuntime = config->TargetRuntime; fxc->FxcCompileFlags = flags1; return (struct GPUCC_PROGRAM_COMPILER*) fxc; }
ce674f2c5724ce9030dd4b51b1b3197a6ce0220c
fdecb4cfcf13c8113fd741b2976b2daf208a9e26
/src/logger_decls.h
9a9642bd275233f333bf0714e1e3c299409f8b4e
[ "MIT" ]
permissive
zionlang/zion
cb1a3a50ff51775e042c89933571fe1d19017f15
5b4df370766e342fd4efffff34cd8966990f9ac4
refs/heads/master
2023-01-04T21:56:43.501770
2023-01-02T17:07:56
2023-01-02T22:48:50
184,154,262
49
2
NOASSERTION
2020-08-27T04:35:04
2019-04-29T22:42:36
C++
UTF-8
C++
false
false
965
h
logger_decls.h
#pragma once #include <stdio.h> #include "location.h" enum LogLevel { log_info = 1, log_warning = 2, log_error = 4, log_panic = 8, }; struct Location; void log_enable(int log_level); void logv(LogLevel level, const char *format, va_list args); void logv_location(LogLevel level, const Location &location, const char *format, va_list args); void log(const char *format, ...); void log(LogLevel level, const char *format, ...); void log_location(LogLevel level, const Location &location, const char *format, ...); void log_location(const Location &location, const char *format, ...); void panic_(const char *filename, int line, std::string msg); void log_stack(LogLevel level); void log_dump(); void write_fp(FILE *fp, const char *format, ...); bool check_errno(const char *tag); void print_stacktrace(FILE *p_out, unsigned int p_max_frames);
c8643dd8838ed7ddefe96e28a06c01846dc990b8
efc7993e946c4423356a2bf8f41d4ee4bd19dd89
/src/common.h
e2a6eeefea0db9a6cb6244eec21b365954f42ad4
[]
no_license
romgille/IG4I22_212_giller
eb17f110b24a24c2a382bfd77770587149fa6507
d2fe9a9e9e2c74ce9adaf5bd1ca3cd13e9abf28e
refs/heads/master
2021-04-03T10:27:39.676819
2018-03-26T09:15:46
2018-03-26T09:15:46
124,429,010
0
0
null
null
null
null
UTF-8
C++
false
false
917
h
common.h
// Some helper functions #pragma once #include <boost/program_options.hpp> #include <opencv2/opencv.hpp> #include <string> #include <initializer_list> /** Read an image from a file. options: - forceFloat: ensures that the loaded image is in float format. If original image was a byte image, its values are divided by 255. - forceGrayScale: ensures that the loaded image contains a single channel */ cv::Mat imreadHelper(std::string filename, bool forceFloat=true, bool forceGrayScale=true); /** Write an image to disk. */ void imwriteHelper(cv::Mat image, std::string filename); /** Display an image in a window with the given name as title. */ void showimage(cv::Mat image, const char * name=NULL); /** Helper function for argument parsing. */ boost::program_options::variables_map parseArgs(int argc, char ** argv, std::initializer_list<std::string> arglist);
2c2c1bb2036a82dad24b27149e9a762865150b95
64e25c9d67db2ce4b5abe1a980a070fb59a2f938
/clang/test/CMFE/cmlangspec/5_1_3_a.cpp
3595a2604a1fb8dc86bd50cec2df1e872858ad92
[ "NCSA", "MIT" ]
permissive
intel/cm-compiler
22d8b56baefc26d5576572f5aab6b3ecb3033300
9b2e628b788344088d8fcfd97d406db576f608af
refs/heads/cmc_monorepo_80
2023-08-28T13:09:41.523730
2023-08-04T23:23:23
2023-08-04T23:23:23
111,158,121
141
60
null
2023-05-01T21:17:30
2017-11-17T22:50:46
C++
UTF-8
C++
false
false
657
cpp
5_1_3_a.cpp
/*========================== begin_copyright_notice ============================ Copyright (C) 2016-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ // expected-no-diagnostics #include <cm/cm.h> #include <cm/cmtl.h> #define WIDTH 4 _GENX_MAIN_ void test(SurfaceIndex ibuf) { // SurfaceIndex ibuf passed in as parameter // WIDTH previously defined vector<int, WIDTH> block; int x = get_thread_origin_x() * WIDTH; // Read block from input surface cmtl::ReadLinear(ibuf, x, block.select_all()); } // RUN: %cmc -emit-llvm -march=SKL -Xclang -verify -- %s
0c02d47808e08b2db027954056cde8d851407e25
f9ca0e466af1ef6aa186225455382d8ee8689b07
/Biblioteca/frmCad_Editora.cpp
61a58ea6baa79957c4bfe8cf37713fd8dd9b43be
[]
no_license
YugoVtr/Sibi_Biblioteca
ea56478396f0598708d6030f0cb29f08a95c100e
91401fe8fb670ef8625f5c43db054f472268b32a
refs/heads/master
2020-12-02T22:36:35.575633
2017-07-03T22:51:19
2017-07-03T22:51:19
96,155,971
0
1
null
2017-07-04T13:06:59
2017-07-03T22:49:54
C++
UTF-8
C++
false
false
1,970
cpp
frmCad_Editora.cpp
#include "frmCad_Editora.h" #include "ui_frmCad_Editora.h" frmCad_Editora::frmCad_Editora(QWidget *parent) : QDialog(parent), ui(new Ui::frmCad_Editora) { ui->setupUi(this); this->setGeometry(QStyle::alignedRect(Qt::LeftToRight,Qt::AlignCenter,this->size(),qApp->desktop()->availableGeometry())); } frmCad_Editora::~frmCad_Editora() { delete ui; } void frmCad_Editora::on_concluirPushButton_clicked() { try{ QString arq = "../Arquivos/arquivoEditora.txt"; Biblioteca::PersistenciaEditora persistir(arq); int codigo = Vitor::Codigo().gerarCodigo(); if(persistir.consultar(codigo)!="0") throw QString("Editora ja existente,Cadastro Editora"); QString nome = ui->nomeLineEdit->text(); QString cidade = ui->cidadeLineEdit->text(); QString estado = ui->estadoComboBox->currentText(); Biblioteca::Editora aux(codigo,nome,cidade,estado); persistir.incluir(aux); QMessageBox::information(this,"Cadastrar","Cadastrado com sucesso"); this->close(); } catch(QString &erro) { QMessageBox::about(this,"Erro",erro); } } //void frmCad_Editora::on_editarPushButton_clicked() //{ // try{ // QString arq = "../Arquivos/arquivoEditora.txt"; // Biblioteca::EditoraPersistencia persistir(arq); // int codigo = ui->codigoLineEdit->text().toInt(); // if(persistir.consultar(codigo)=="0") // throw QString("Editora nao existe, Cadastro Editora Editar"); // QString nome = ui->nomeLineEdit->text(); // QString cidade = ui->cidadeLineEdit->text(); // QString estado = ui->estadoComboBox->currentText(); // Biblioteca::Editora aux(codigo,nome,cidade,estado); // persistir.alterar(aux); // QMessageBox::information(this,"Editar","Editado com sucesso"); // this->close(); // } catch(QString &erro) { // QMessageBox::about(this,"Erro",erro); // } //}
57d5517156008b4db4067f6e7d16fb9cd58c7c48
f1d93db4e369b68473bdde689377c1ce139cca78
/limit-break/dynacol.cpp
3b5a25de988d87f31f083db27e84ffbd7b012457
[ "MIT" ]
permissive
michael-fadely/sadx-limit-break
f066e22404500552cab2f2d83d31ad6146eb170b
66fd107bcacd77d009f9f689d1c12f3051487c98
refs/heads/master
2022-01-14T16:51:05.307975
2019-06-07T01:24:27
2019-06-07T01:24:27
65,354,128
1
2
MIT
2019-05-31T19:11:46
2016-08-10T05:49:09
C++
UTF-8
C++
false
false
11,969
cpp
dynacol.cpp
#include "stdafx.h" #pragma region "ObjectArray" struct UsedObject { bool used; NJS_OBJECT* object; }; std::deque<UsedObject> object_array; NJS_OBJECT* __cdecl ObjectArray_GetFreeObject_r() { const auto pred = [](const auto& e) -> bool { return e.used == false; }; const auto it = std::find_if(object_array.begin(), object_array.end(), pred); if (it != object_array.end()) { it->used = true; *it->object = {}; return it->object; } const auto object = new NJS_OBJECT {}; const UsedObject element { true, object }; object_array.push_back(element); PrintDebug("object_array expanded to: %u\n", object_array.size()); return object; } int __cdecl ObjectArray_Remove_r(NJS_OBJECT* a1) { int result = 0; for (auto& element : object_array) { if (element.object == a1) { element.used = false; return result; } ++result; } return -1; } #pragma endregion FunctionPointer(/*NJS_OBJECT_LIST*/ void*, sub_456B40, (NJS_OBJECT* a1), 0x456B40); DataPointer(int, LandTable_CollisionMeshCount, 0x03B36D3C); //DataPointer(int, LandTableLoadedA, 0x0091545C); DataPointer(int, LandTableLoadedB, 0x00915460); constexpr auto ColFlags_WaterNoAlpha = 0x400000; static std::vector<DynamicCOL> dynacol_a; static std::vector<DynamicCOL> dynacol_b; void __cdecl DynamicCOL_RunA() { DynamicCOL* dynacol_landtable = DynamicCOLArray_LandTable; if (!Camera_Data1) { return; } NJS_VECTOR v[2] {}; v[0] = Camera_Data1->Position; int player_count = 1; if (EntityData1Ptrs[0]) { v[0] = EntityData1Ptrs[0]->Position; if (EntityData1Ptrs[1]) { ++player_count; v[1] = EntityData1Ptrs[1]->Position; } } else if (EntityData1Ptrs[1]) { v[0] = EntityData1Ptrs[1]->Position; } DynamicCOLCount_B = 0; DynamicCOLCount_B_Again = 0; //dynacol_b.clear(); njPushMatrix(nullptr); if (!DynamicCOLCount || dynacol_a.empty()) { goto WHAT_FUCK; // NOLINT } DynamicCOL* v5 = &dynacol_a.back(); size_t dynacol_a_i = 0; while (true) { NJS_OBJECT* model = v5->Model; if (!(v5->Entity->Data1->Status & Status_Ball)) { goto CONTINUE; // NOLINT } float px; float py; float pz; if (v5->Flags & ColFlags_UseRotation) { njUnitMatrix(nullptr); Angle rz = model->ang[2]; if (rz) { njRotateZ(nullptr, (unsigned __int16)rz); } Angle rx = model->ang[0]; if (rx) { njRotateX(nullptr, (unsigned __int16)rx); } Angle ry = model->ang[1]; if (ry) { njRotateY(nullptr, (unsigned __int16)ry); } NJS_VECTOR point {}; // [esp+2Ch] [ebp-24h] njCalcPoint(nullptr, &model->basicdxmodel->center, &point); px = point.x + model->pos[0]; py = point.y + model->pos[1]; pz = point.z + model->pos[2]; } else { NJS_MODEL_SADX* v7 = model->basicdxmodel; const float v8 = v7->center.x; const auto center = &v7->center; px = v8 + model->pos[0]; py = center->y + model->pos[1]; pz = center->z + model->pos[2]; } int v15 = player_count; float v16 = LandTable_MinimumRadius; if (player_count <= 0) { goto CONTINUE; // NOLINT } NJS_VECTOR* v17 = &v[0]; while (true) { const float dx = v17->x - px; const float dy = v17->y - py; const float dz = v17->z - pz; auto dxmodel = model->getbasicdxmodel(); if ((v16 + dxmodel->r) * (v16 + dxmodel->r) > dz * dz + dy * dy + dx * dx) { break; } v16 = 40.0f; --v15; ++v17; if (v15 <= 0) { goto CONTINUE; // NOLINT } } *dynacol_landtable = *v5; //dynacol_b.push_back(*v5); dynacol_b.resize(DynamicCOLCount_B + 1); dynacol_b[DynamicCOLCount_B] = *v5; ++dynacol_landtable; ++DynamicCOLCount_B; ++DynamicCOLCount_B_Again; /*if (static_cast<size_t>(DynamicCOLCount_B_Again) >= dynacol_b.size()) { break; }*/ if (DynamicCOLCount_B >= DynamicCOLArray_LandTable_Length) { njPopMatrix(1u); return; } CONTINUE: --v5; if (++dynacol_a_i >= dynacol_a.size()) { goto WHAT_FUCK; // NOLINT } } /* PrintDebug("overflow tears 0\n"); */ WHAT_FUCK: njPopMatrix(1u); LandTable_CollisionMeshCount = 0; COL* v35 = ColList2; if (LandTableLoadedB != 1 || !CurrentLandTable) { return; } for (int i = 0; i < CurrentLandTable->COLCount; ++i) { auto v21 = &CurrentLandTable->Col[i]; if (!(v21->Flags & (ColFlags_WaterNoAlpha | ColFlags_Water | ColFlags_Solid))) { continue; } int v23 = player_count; float v36 = LandTable_MinimumRadius; if (player_count <= 0) { continue; } auto v24 = &v[0]; while (true) { const float dx = v21->Center.x - v24->x; const float dy = v21->Center.y - v24->y; const float dz = v21->Center.z - v24->z; const float distance = dz * dz + dy * dy + dx * dx; if (squareroot(distance) - v36 < v21->Radius) { break; } --v23; ++v24; v36 = 40.0f; if (v23 <= 0) { goto LABEL_38; } } memcpy(v35, v21, sizeof(COL)); dynacol_landtable->Flags = v21->Flags; dynacol_landtable->Entity = nullptr; ++v35; dynacol_landtable->Model = v21->Model; ++dynacol_landtable; ++DynamicCOLCount_B; ++LandTable_CollisionMeshCount; if (/*static_cast<size_tLandTable_CollisionMeshCount) >= dynacol_b.size() || */DynamicCOLCount_B >= DynamicCOLArray_LandTable_Length) { return; } LABEL_38: continue; } } void __cdecl DynamicCOL_RunB() { short v1 = 0; DynamicCOL* v2 = DynamicCOLArray_LandTable; DynamicCOLCount_B = 0; DynamicCOLCount_B_Again = 0; dynacol_b.clear(); size_t landtable_i = 0; if (DynamicCOLCount && !dynacol_a.empty()) { DynamicCOL* v0 = &dynacol_a.back(); while (true) { //DynamicCOL* v3 = (DynamicCOL*)((char*)DynamicCOLArray_B + (char*)v2 - (char*)DynamicCOLArray_LandTable); dynacol_b.push_back(*v0); //*(NJS_OBJECT * *)((char*)& DynamicCOLArray_LandTable[0].Model + (char*)v2 // - (char*)DynamicCOLArray_LandTable) = v0->Model; //*(ObjectMaster * *)((char*)& DynamicCOLArray_LandTable[0].Entity // + (char*)v2 // - (char*)DynamicCOLArray_LandTable) = v0->Entity; DynamicCOLArray_LandTable[landtable_i].Model = v0->Model; DynamicCOLArray_LandTable[landtable_i].Entity = v0->Entity; v2->Flags = v0->Flags; ++v2; ++v1; ++DynamicCOLCount_B_Again; /*if (static_cast<size_t>(DynamicCOLCount_B_Again) >= dynacol_b.size()) { break; }*/ if (v1 < DynamicCOLArray_LandTable_Length) { --v0; if (landtable_i < dynacol_a.size()) { continue; } } DynamicCOLCount_B = v1; goto WHAT_FUCK; // NOLINT } /* DynamicCOLCount_B = v1; PrintDebug("overflow tears 1\n"); v1 = DynamicCOLCount_B; */ } WHAT_FUCK: LandTable_CollisionMeshCount = 0; COL* v6 = ColList2; if (LandTableLoadedB == 1 && CurrentLandTable) { COL* v7 = CurrentLandTable->Col; for (int i = CurrentLandTable->COLCount; i > 0; --i) { if (v7->Flags & (ColFlags_WaterNoAlpha | ColFlags_Water | ColFlags_Solid)) { memcpy(v6, v7, sizeof(COL)); v2->Flags = v7->Flags; v2->Entity = nullptr; ++v6; v2->Model = v7->Model; ++v2; ++v1; DynamicCOLCount_B = v1; ++LandTable_CollisionMeshCount; if (static_cast<size_t>(LandTable_CollisionMeshCount) >= dynacol_b.size() || v1 >= DynamicCOLArray_LandTable_Length) { return; } } ++v7; } } } void __cdecl sub_43ACD0_r(float x, float y, float z, float radius) { DynamicCOL* v5 = DynamicCOLArray_LandTable; DynamicCOLCount_B = 0; njPushMatrix(nullptr); //DynamicCOL* v4 = (DynamicCOL*)((char*)& DynamicCOLArray_LandTable[DynamicCOLCount_B_Again + 1023] + 8); if (DynamicCOLCount_B_Again < 1) { LABEL_14: njPopMatrix(1u); if (LandTableLoadedB == 1 && CurrentLandTable) { for (int i = 0; i < LandTable_CollisionMeshCount; ++i) { COL* col = &ColList2[i]; if (!(col->Flags & (ColFlags_WaterNoAlpha | ColFlags_Water | ColFlags_Solid))) { continue; } const float dy = col->Center.y - y; const float dz = col->Center.z - z; const float distance = dz * dz + dy * dy + (col->Center.x - x) * (col->Center.x - x); if (squareroot(distance) - radius < col->Radius) { NJS_OBJECT* v28 = col->Model; v5->Flags = col->Flags; v5->Entity = nullptr; v5->Model = v28; ++v5; ++DynamicCOLCount_B; if (DynamicCOLCount_B >= DynamicCOLArray_LandTable_Length) { break; } } } } return; } DynamicCOL* v4 = &dynacol_b.back(); size_t i = 0; float v14 = 0.0f; float v15 = 0.0f; while (true) { NJS_OBJECT* v6 = v4->Model; float v8; // st5 if (v4->Flags & ColFlags_UseRotation) { njUnitMatrix(nullptr); Angle rz = v6->ang[2]; if (rz) { njRotateZ(nullptr, (unsigned __int16)rz); } Angle rx = v6->ang[0]; if (rx) { njRotateX(nullptr, (unsigned __int16)rx); } Angle ry = v6->ang[1]; if (ry) { njRotateY(nullptr, (unsigned __int16)ry); } NJS_VECTOR point; // [esp+10h] [ebp-Ch] njCalcPoint(nullptr, &v6->basicdxmodel->center, &point); v14 = x - (point.x + v6->pos[0]); v15 = y - (point.y + v6->pos[1]); v8 = point.z; } else { //auto v7 = (float*)v6->basicdxmodel; //float v9 = x - (v7[6] + v6->pos[0]); //float v10 = y - (v7[7] + v6->pos[1]); const auto& center = v6->basicdxmodel->center; v14 = center.x; // HACK v15 = center.y; // HACK v8 = center.z; } // lol ida //if (!(v19 | v20)) const float v16 = z - (v8 + v6->pos[2]); const float v17 = radius + v6->basicdxmodel->r + 30.0f; // ghidra v8 = (x - v14) * (x - v14) + (y - v15) * (y - v15) + v16 * v16; const auto length = v17 * v17; // ghidra if (length <= v8) { ObjectMaster* v21 = v4->Entity; v5->Flags = v4->Flags; v5->Model = v6; v5->Entity = v21; ++v5; ++DynamicCOLCount_B; if (DynamicCOLCount_B >= DynamicCOLArray_LandTable_Length) { break; } } if (++i >= dynacol_b.size()) { goto LABEL_14; // NOLINT } --v4; } njPopMatrix(1u); } void __cdecl DynamicCOL_Add_r(uint32_t flags, ObjectMaster* entity, NJS_OBJECT* model) { char v6 = 0; // c0 if (!v6) { if ((model->ang[0] | model->ang[1] | model->ang[2]) & 0xFFF0) { flags |= ColFlags_UseRotation; } } DynamicCOL dynacol {}; dynacol.Flags = flags; dynacol.Model = model; dynacol.Entity = entity; entity->Data1->Status |= Status_Ground; dynacol_a.push_back(dynacol); ++DynamicCOLCount; } void __cdecl DynamicCOL_Remove_r(ObjectMaster* entity, NJS_OBJECT* model) { auto pred = [entity, model](const auto& a) -> bool { return a.Entity == entity && a.Model == model; }; const auto it = std::remove_if(dynacol_a.begin(), dynacol_a.end(), pred); if (it != dynacol_a.end()) { sub_456B40(model); dynacol_a.erase(it); DynamicCOLCount -= DynamicCOLCount - static_cast<Uint16>(dynacol_a.size()); } } void __cdecl sub_43A210_r(); static Trampoline sub_43A210_t(0x0043A210, 0x0043A217, sub_43A210_r); void __cdecl sub_43A210_r() { auto original = reinterpret_cast<decltype(sub_43A210_r)*>(sub_43A210_t.Target()); original(); dynacol_a.clear(); dynacol_b.clear(); } void __cdecl LandTableObj_Delete_r(ObjectMaster* obj); static Trampoline LandTableObj_Delete_t(0x0043A500, 0x0043A507, LandTableObj_Delete_r); void __cdecl LandTableObj_Delete_r(ObjectMaster* obj) { auto original = reinterpret_cast<decltype(LandTableObj_Delete_r)*>(LandTableObj_Delete_t.Target()); original(obj); dynacol_a.clear(); dynacol_b.clear(); } void dynacol_init() { WriteJump(ObjectArray_GetFreeObject, ObjectArray_GetFreeObject_r); WriteJump(ObjectArray_Remove, ObjectArray_Remove_r); WriteJump(DynamicCOL_Add, DynamicCOL_Add_r); WriteJump(DynamicCOL_Remove, DynamicCOL_Remove_r); WriteJump(reinterpret_cast<void*>(0x0043AEF0), DynamicCOL_RunA); WriteJump(reinterpret_cast<void*>(0x0043B580), DynamicCOL_RunB); WriteJump(reinterpret_cast<void*>(0x43ACD0), sub_43ACD0_r); }
3aceece304a3e6d23622656a91328f26ee7decfd
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/components/omnibox/browser/actions/omnibox_action_in_suggest.h
9f603caaa6d56c94d881ecc84240023244944e86
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
1,688
h
omnibox_action_in_suggest.h
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_OMNIBOX_BROWSER_ACTIONS_OMNIBOX_ACTION_IN_SUGGEST_H_ #define COMPONENTS_OMNIBOX_BROWSER_ACTIONS_OMNIBOX_ACTION_IN_SUGGEST_H_ #include <optional> #include "components/omnibox/browser/actions/omnibox_action.h" #include "components/omnibox/browser/autocomplete_result.h" #include "components/search_engines/template_url.h" #include "components/strings/grit/components_strings.h" #include "third_party/omnibox_proto/entity_info.pb.h" class OmniboxActionInSuggest : public OmniboxAction { public: OmniboxActionInSuggest( omnibox::ActionInfo action_info, absl::optional<TemplateURLRef::SearchTermsArgs> search_terms_args); #if BUILDFLAG(IS_ANDROID) base::android::ScopedJavaLocalRef<jobject> GetOrCreateJavaObject( JNIEnv* env) const override; #endif void RecordActionShown(size_t position, bool executed) const override; void Execute(ExecutionContext& context) const override; OmniboxActionId ActionId() const override; omnibox::ActionInfo::ActionType Type() const; // Downcasts the given OmniboxAction to an OmniboxActionInSuggest if the // supplied instance represents one, otherwise returns nullptr. static const OmniboxActionInSuggest* FromAction(const OmniboxAction* action); static OmniboxActionInSuggest* FromAction(OmniboxAction* action); omnibox::ActionInfo action_info{}; absl::optional<TemplateURLRef::SearchTermsArgs> search_terms_args{}; private: ~OmniboxActionInSuggest() override; }; #endif // COMPONENTS_OMNIBOX_BROWSER_ACTIONS_OMNIBOX_ACTION_IN_SUGGEST_H_
3966dc43563c3ed8b1f05eb538cf7937a44ae8c4
0803bc22723b75b8080d8b4f0e57b4db540d508a
/Source/LuaMachine/Private/LuaState.cpp
bedf2adbbdcd5c764143acf115b1d86f3e790cee
[ "MIT" ]
permissive
rdeioris/LuaMachine
58910d9906eb921319c0942a02bc3d3e30b4ae8f
94c584b94671ce2e40e875ca77f25f746633e6c4
refs/heads/master
2023-08-11T03:37:05.961916
2023-06-24T15:38:32
2023-06-24T15:38:32
152,728,104
468
122
MIT
2023-07-21T08:38:58
2018-10-12T09:36:19
C++
UTF-8
C++
false
false
71,906
cpp
LuaState.cpp
// Copyright 2018-2022 - Roberto De Ioris #include "LuaState.h" #include "LuaComponent.h" #include "LuaUserDataObject.h" #include "LuaMachine.h" #include "LuaBlueprintPackage.h" #include "LuaBlueprintFunctionLibrary.h" #if ENGINE_MAJOR_VERSION >= 5 && ENGINE_MINOR_VERSION > 0 #include "AssetRegistry/AssetRegistryModule.h" #else #include "AssetRegistryModule.h" #endif #include "GameFramework/Actor.h" #include "Runtime/Core/Public/Misc/FileHelper.h" #include "Runtime/Core/Public/Misc/Paths.h" #include "Runtime/Core/Public/Serialization/BufferArchive.h" #include "Runtime/CoreUObject/Public/UObject/TextProperty.h" LUAMACHINE_API DEFINE_LOG_CATEGORY(LogLuaMachine); ULuaState::ULuaState() { L = nullptr; bLuaOpenLibs = true; bDisabled = false; bLogError = true; bAddProjectContentDirToPackagePath = true; bPersistent = false; bEnableLineHook = false; bEnableCallHook = false; bEnableReturnHook = false; bEnableCountHook = false; bRawLuaFunctionCall = false; FCoreUObjectDelegates::GetPostGarbageCollect().AddUObject(this, &ULuaState::GCLuaDelegatesCheck); } ULuaState* ULuaState::GetLuaState(UWorld* InWorld) { CurrentWorld = InWorld; if (L != nullptr) { return this; } if (bDisabled) { return nullptr; } L = luaL_newstate(); if (bLuaOpenLibs) { luaL_openlibs(L); } // load "package" for allowing minimal setup luaL_requiref(L, "package", luaopen_package, 1); lua_pop(L, 1); if (!bLuaOpenLibs) { if (LuaLibsLoader.bLoadBase) { luaL_requiref(L, "_G", luaopen_base, 1); lua_pop(L, 1); } if (LuaLibsLoader.bLoadCoroutine) { luaL_requiref(L, "coroutine", luaopen_coroutine, 1); lua_pop(L, 1); } if (LuaLibsLoader.bLoadTable) { luaL_requiref(L, "table", luaopen_table, 1); lua_pop(L, 1); } if (LuaLibsLoader.bLoadIO) { luaL_requiref(L, "io", luaopen_io, 1); lua_pop(L, 1); } if (LuaLibsLoader.bLoadOS) { luaL_requiref(L, "os", luaopen_os, 1); lua_pop(L, 1); } if (LuaLibsLoader.bLoadString) { luaL_requiref(L, "string", luaopen_string, 1); lua_pop(L, 1); } if (LuaLibsLoader.bLoadMath) { luaL_requiref(L, "math", luaopen_math, 1); lua_pop(L, 1); } if (LuaLibsLoader.bLoadUTF8) { luaL_requiref(L, "utf8", luaopen_utf8, 1); lua_pop(L, 1); } if (LuaLibsLoader.bLoadDebug) { luaL_requiref(L, "debug", luaopen_debug, 1); lua_pop(L, 1); } } ULuaState** LuaExtraSpacePtr = (ULuaState**)lua_getextraspace(L); *LuaExtraSpacePtr = this; // get the global table lua_pushglobaltable(L); // override print PushCFunction(ULuaState::TableFunction_print); SetField(-2, "print"); GetField(-1, "package"); if (!OverridePackagePath.IsEmpty()) { OverridePackagePath.ReplaceInline(*FString("$(CONTENT_DIR)"), *FPaths::ProjectContentDir()); lua_pushstring(L, TCHAR_TO_ANSI(*OverridePackagePath)); SetField(-2, "path"); } if (bAddProjectContentDirToPackagePath) { GetField(-1, "path"); const char* CurrentLuaPath = lua_tostring(L, -1); FString NewPackagePath = FString(CurrentLuaPath) + ";" + FPaths::ProjectContentDir() + "/?.lua"; Pop(); lua_pushstring(L, TCHAR_TO_ANSI(*NewPackagePath)); SetField(-2, "path"); } for (FString SubDir : AppendProjectContentDirSubDir) { GetField(-1, "path"); const char* CurrentLuaPath = lua_tostring(L, -1); FString NewPackagePath = FString(CurrentLuaPath) + ";" + FPaths::ProjectContentDir() / SubDir + "/?.lua"; Pop(); lua_pushstring(L, TCHAR_TO_ANSI(*NewPackagePath)); SetField(-2, "path"); } if (!OverridePackageCPath.IsEmpty()) { OverridePackageCPath.ReplaceInline(*FString("$(CONTENT_DIR)"), *FPaths::ProjectContentDir()); static const FString libExtension = #if PLATFORM_MAC || PLATFORM_IOS FString("dylib"); #elif PLATFORM_LINUX || PLATFORM_ANDROID FString("so"); #elif PLATFORM_WINDOWS FString("dll"); #else FString(""); #endif OverridePackageCPath.ReplaceInline(*FString("$(LIB_EXT)"), *libExtension); lua_pushstring(L, TCHAR_TO_ANSI(*OverridePackageCPath)); SetField(-2, "cpath"); } // manage RequireTable GetField(-1, "preload"); for (TPair<FString, ULuaCode*>& Pair : RequireTable) { PushCFunction(ULuaState::TableFunction_package_preload); SetField(-2, TCHAR_TO_ANSI(*Pair.Key)); } // pop package.prelod Pop(1); // manage searchers GetField(-1, "searchers"); PushCFunction(ULuaState::TableFunction_package_loader); constexpr int PackageLoadersFirstAvailableIndex = 5; lua_seti(L, -2, PackageLoadersFirstAvailableIndex); // pop package.searchers (and package) Pop(2); for (TPair<FString, FLuaValue>& Pair : Table) { FromLuaValue(Pair.Value, this, L); SetField(-2, TCHAR_TO_ANSI(*Pair.Key)); } for (TPair<FString, TSubclassOf<ULuaBlueprintPackage>>& Pair : LuaBlueprintPackagesTable) { if (Pair.Value) { NewTable(); ULuaBlueprintPackage* LuaBlueprintPackage = NewObject<ULuaBlueprintPackage>(this, Pair.Value); if (LuaBlueprintPackage) { for (auto LuaPair : LuaBlueprintPackage->Table) { FromLuaValue(LuaPair.Value, LuaBlueprintPackage); SetField(-2, TCHAR_TO_ANSI(*LuaPair.Key)); } // this avoid the package to be GC'd LuaBlueprintPackages.Add(Pair.Key, LuaBlueprintPackage); LuaBlueprintPackage->SelfTable = ToLuaValue(-1); LuaBlueprintPackage->Init(); LuaBlueprintPackage->ReceiveInit(); } } else { PushNil(); } SetField(-2, TCHAR_TO_ANSI(*Pair.Key)); } // pop global table Pop(); // This allows subclasses to do any last minute initialization on lua state before // we load code ReceiveLuaStatePreInitialized(); int DebugMask = 0; // install hooks if (bEnableLineHook) { DebugMask |= LUA_MASKLINE; } if (bEnableCallHook) { DebugMask |= LUA_MASKCALL; } if (bEnableReturnHook) { DebugMask |= LUA_MASKRET; } if (bEnableCountHook) { DebugMask |= LUA_MASKCOUNT; } if (DebugMask != 0) { lua_sethook(L, Debug_Hook, DebugMask, HookInstructionCount); } if (LuaCodeAsset) { if (!RunCodeAsset(LuaCodeAsset)) { if (bLogError) LogError(LastError); ReceiveLuaError(LastError); bDisabled = true; return nullptr; } } if (!LuaFilename.IsEmpty()) { if (!RunFile(LuaFilename, true)) { if (bLogError) LogError(LastError); ReceiveLuaError(LastError); bDisabled = true; return nullptr; } } if (UserDataMetaTableFromCodeAsset) { if (!RunCodeAsset(UserDataMetaTableFromCodeAsset, 1)) { if (bLogError) LogError(LastError); ReceiveLuaError(LastError); bDisabled = true; return nullptr; } UserDataMetaTable = ToLuaValue(-1); Pop(); } LuaStateInit(); ReceiveLuaStateInitialized(); #if WITH_EDITOR if (!(GetFlags() & RF_ClassDefaultObject)) { LuaConsole.LuaState = this; IModularFeatures::Get().RegisterModularFeature(IConsoleCommandExecutor::ModularFeatureName(), &LuaConsole); } #endif return this; } FLuaValue ULuaState::GetLuaBlueprintPackageTable(const FString& PackageName) { if (!LuaBlueprintPackages.Contains(PackageName)) { return FLuaValue(); } return LuaBlueprintPackages[PackageName]->SelfTable; } bool ULuaState::RunCodeAsset(ULuaCode* CodeAsset, int NRet) { if (CodeAsset->bCooked && CodeAsset->bCookAsBytecode) { #if PLATFORM_ANDROID // fix size_t of the bytecode if (CodeAsset->ByteCode.Num() >= 14) CodeAsset->ByteCode[13] = sizeof(size_t); #endif return RunCode(CodeAsset->ByteCode, CodeAsset->GetPathName(), NRet); } return RunCode(CodeAsset->Code.ToString(), CodeAsset->GetPathName(), NRet); } bool ULuaState::RunFile(const FString& Filename, bool bIgnoreNonExistent, int NRet, bool bNonContentDirectory) { TArray<uint8> Code; FString AbsoluteFilename = FPaths::Combine(FPaths::ProjectContentDir(), Filename); if (bNonContentDirectory) { AbsoluteFilename = Filename; } if (!FPaths::FileExists(AbsoluteFilename)) { if (bIgnoreNonExistent) return true; LastError = FString::Printf(TEXT("Unable to open file %s"), *Filename); FLuaValue LuaLastError = FLuaValue(LastError); FromLuaValue(LuaLastError); return false; } if (FFileHelper::LoadFileToArray(Code, *AbsoluteFilename)) { if (RunCode(Code, AbsoluteFilename, NRet)) { return true; } return false; } LastError = FString::Printf(TEXT("Unable to open file %s"), *Filename); FLuaValue LuaLastError = FLuaValue(LastError); FromLuaValue(LuaLastError); return false; } bool ULuaState::RunCode(const FString& Code, const FString& CodePath, int NRet) { TArray<uint8> Bytes; Bytes.Append((uint8*)TCHAR_TO_UTF8(*Code), FCStringAnsi::Strlen(TCHAR_TO_UTF8(*Code))); return RunCode(Bytes, CodePath, NRet); } bool ULuaState::RunCode(const TArray<uint8>& Code, const FString& CodePath, int NRet) { FString FullCodePath = FString("@") + CodePath; if (luaL_loadbuffer(L, (const char*)Code.GetData(), Code.Num(), TCHAR_TO_ANSI(*FullCodePath))) { LastError = FString::Printf(TEXT("Lua loading error: %s"), ANSI_TO_TCHAR(lua_tostring(L, -1))); return false; } else { if (lua_pcall(L, 0, NRet, 0)) { LastError = FString::Printf(TEXT("Lua execution error: %s"), ANSI_TO_TCHAR(lua_tostring(L, -1))); return false; } } return true; } int ULuaState::ToByteCode_Writer(lua_State* L, const void* Ptr, size_t Size, void* UserData) { TArray<uint8>* Output = (TArray<uint8>*)UserData; Output->Append((uint8*)Ptr, Size); return 0; } TArray<uint8> ULuaState::ToByteCode(const FString& Code, const FString& CodePath, FString& ErrorString) { const TCHAR* CodeRaw = *Code; FString FullCodePath = FString("@") + CodePath; TArray<uint8> Output; lua_State* L = luaL_newstate(); if (luaL_loadbuffer(L, TCHAR_TO_UTF8(CodeRaw), FCStringAnsi::Strlen(TCHAR_TO_UTF8(CodeRaw)), TCHAR_TO_ANSI(*FullCodePath))) { ErrorString = ANSI_TO_TCHAR(lua_tostring(L, -1)); Output.Empty(); lua_close(L); return Output; } if (lua_dump(L, ULuaState::ToByteCode_Writer, &Output, 1)) { ErrorString = ANSI_TO_TCHAR(lua_tostring(L, -1)); Output.Empty(); lua_close(L); return Output; } lua_close(L); return Output; } void ULuaState::FromLuaValue(FLuaValue& LuaValue, UObject* CallContext, lua_State* State) { if (!State) { State = this->L; } switch (LuaValue.Type) { case ELuaValueType::Bool: lua_pushboolean(State, LuaValue.Bool ? 1 : 0); break; case ELuaValueType::Integer: lua_pushinteger(State, LuaValue.Integer); break; case ELuaValueType::Number: lua_pushnumber(State, LuaValue.Number); break; case ELuaValueType::String: { TArray<uint8> Bytes = LuaValue.ToBytes(); lua_pushlstring(State, (const char*)Bytes.GetData(), Bytes.Num()); } break; case ELuaValueType::Table: if (LuaValue.LuaRef == LUA_NOREF) { lua_newtable(State); lua_pushvalue(State, -1); // hold references in the main state LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX); LuaValue.LuaState = this; break; } if (this != LuaValue.LuaState) { lua_pushnil(State); break; } lua_rawgeti(this->L, LUA_REGISTRYINDEX, LuaValue.LuaRef); if (this->L != State) lua_xmove(this->L, State, 1); break; case ELuaValueType::Thread: if (LuaValue.LuaRef == LUA_NOREF) { lua_newthread(State); lua_pushvalue(State, -1); LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX); LuaValue.LuaState = this; break; } if (this != LuaValue.LuaState) { lua_pushnil(State); break; } lua_rawgeti(this->L, LUA_REGISTRYINDEX, LuaValue.LuaRef); if (this->L != State) lua_xmove(this->L, State, 1); break; case ELuaValueType::Function: if (this != LuaValue.LuaState || LuaValue.LuaRef == LUA_NOREF) { lua_pushnil(State); break; } lua_rawgeti(this->L, LUA_REGISTRYINDEX, LuaValue.LuaRef); if (this->L != State) lua_xmove(this->L, State, 1); break; case ELuaValueType::UObject: { if (!LuaValue.Object) { lua_pushnil(State); break; } NewUObject(LuaValue.Object, State); if (ULuaComponent* LuaComponent = Cast<ULuaComponent>(LuaValue.Object)) { if (!LuaComponent->LuaState) { UE_LOG(LogLuaMachine, Warning, TEXT("%s has no associated LuaState"), *LuaComponent->GetFullName()); } // ensure we are in the same LuaState else if (LuaComponent->LuaState == GetClass()) { SetupAndAssignUserDataMetatable(LuaComponent, LuaComponent->Metatable, State); } } else if (ULuaUserDataObject* LuaUserDataObject = Cast<ULuaUserDataObject>(LuaValue.Object)) { if (!LuaUserDataObject->GetLuaState()) { UE_LOG(LogLuaMachine, Warning, TEXT("%s has no associated LuaState"), *LuaUserDataObject->GetFullName()); } // ensure we are in the same LuaState else if (LuaUserDataObject->GetLuaState() == GetClass()) { SetupAndAssignUserDataMetatable(LuaUserDataObject, LuaUserDataObject->Metatable, State); } } else { if (UserDataMetaTable.Type == ELuaValueType::Table) { FromLuaValue(UserDataMetaTable, nullptr, State); } else { lua_newtable(State); // allow comparison between userdata/UObject/UFunction lua_pushcfunction(State, ULuaState::MetaTableFunctionUserData__eq); lua_setfield(State, -2, "__eq"); } lua_setmetatable(State, -2); } } break; case ELuaValueType::UFunction: // if no context is assigned to the function, own it ! if (!LuaValue.LuaState.IsValid()) { LuaValue.LuaState = this; } if (this != LuaValue.LuaState) { lua_pushnil(State); break; } // first time we should have a CallContext, then we cache it in the Object field if (!CallContext) { CallContext = LuaValue.Object; } if (CallContext) { UObject* FunctionOwner = CallContext; if (ULuaComponent* LuaComponent = Cast<ULuaComponent>(CallContext)) { FunctionOwner = LuaComponent->GetOwner(); } if (FunctionOwner) { UFunction* Function = FunctionOwner->FindFunction(LuaValue.FunctionName); if (Function) { // cache it for context-less calls LuaValue.Object = CallContext; FLuaUserData* LuaCallContext = (FLuaUserData*)lua_newuserdata(State, sizeof(FLuaUserData)); LuaCallContext->Type = ELuaValueType::UFunction; LuaCallContext->Context = CallContext; LuaCallContext->Function = Function; lua_newtable(State); lua_pushcfunction(State, bRawLuaFunctionCall ? ULuaState::MetaTableFunction__rawcall : ULuaState::MetaTableFunction__call); lua_setfield(State, -2, "__call"); lua_setmetatable(State, -2); return; } } } // no function found lua_pushnil(State); break; case ELuaValueType::MulticastDelegate: // if no context is assigned to the function, own it ! if (!LuaValue.LuaState.IsValid()) { LuaValue.LuaState = this; } if (this != LuaValue.LuaState) { lua_pushnil(State); break; } { FLuaUserData* LuaCallContext = (FLuaUserData*)lua_newuserdata(State, sizeof(FLuaUserData)); LuaCallContext->Type = ELuaValueType::MulticastDelegate; LuaCallContext->Function = reinterpret_cast<UFunction*>(LuaValue.Object); LuaCallContext->MulticastScriptDelegate = LuaValue.MulticastScriptDelegate; lua_newtable(State); lua_pushcfunction(State, bRawLuaFunctionCall ? ULuaState::MetaTableFunction__rawbroadcast : ULuaState::MetaTableFunction__rawbroadcast); lua_setfield(State, -2, "__call"); lua_setmetatable(State, -2); return; } break; default: lua_pushnil(State); } } FLuaValue ULuaState::ToLuaValue(int Index, lua_State* State) { if (!State) { State = this->L; } FLuaValue LuaValue; if (lua_isboolean(State, Index)) { LuaValue = FLuaValue(lua_toboolean(State, Index) != 0); } else if (lua_type(State, Index) == LUA_TSTRING) { size_t StringLength = 0; const char* String = lua_tolstring(State, Index, &StringLength); LuaValue = FLuaValue(String, StringLength); } else if (lua_isinteger(State, Index)) { LuaValue = FLuaValue(static_cast<int32>(lua_tointeger(State, Index))); } else if (lua_type(State, Index) == LUA_TNUMBER) { LuaValue = FLuaValue(static_cast<double>(lua_tonumber(State, Index))); } else if (lua_istable(State, Index)) { lua_pushvalue(State, Index); if (State != this->L) lua_xmove(State, this->L, 1); LuaValue.Type = ELuaValueType::Table; LuaValue.LuaState = this; LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX); } else if (lua_isthread(State, Index)) { lua_pushvalue(State, Index); if (State != this->L) lua_xmove(State, this->L, 1); LuaValue.Type = ELuaValueType::Thread; LuaValue.LuaState = this; LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX); } else if (lua_isfunction(State, Index)) { lua_pushvalue(State, Index); if (State != this->L) lua_xmove(State, this->L, 1); LuaValue.Type = ELuaValueType::Function; LuaValue.LuaState = this; LuaValue.LuaRef = luaL_ref(this->L, LUA_REGISTRYINDEX); } else if (lua_isuserdata(State, Index)) { FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(State, Index); switch (UserData->Type) { case(ELuaValueType::UObject): if (UserData->Context.IsValid()) { LuaValue.Type = UserData->Type; LuaValue.Object = UserData->Context.Get(); LuaValue.LuaState = this; } break; case(ELuaValueType::UFunction): if (UserData->Context.IsValid() && UserData->Function.IsValid()) { LuaValue.Type = UserData->Type; LuaValue.FunctionName = UserData->Function->GetFName(); LuaValue.Object = UserData->Context.Get(); LuaValue.LuaState = this; } break; } } return LuaValue; } int32 ULuaState::GetTop() { return lua_gettop(L); } int ULuaState::MetaTableFunctionUserData__index(lua_State* L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(L, 1); if (!UserData->Context.IsValid()) { return luaL_error(L, "invalid UObject for UserData %p", UserData); } TMap<FString, FLuaValue>* TablePtr = nullptr; UObject* Context = UserData->Context.Get(); ULuaUserDataObject* LuaUserDataObject = nullptr; ULuaComponent* LuaComponent = nullptr; FString Key = ANSI_TO_TCHAR(lua_tostring(L, 2)); LuaComponent = Cast<ULuaComponent>(Context); if (LuaComponent) { TablePtr = &LuaComponent->Table; } else { LuaUserDataObject = Cast<ULuaUserDataObject>(Context); if (LuaUserDataObject) { TablePtr = &LuaUserDataObject->Table; } } if (TablePtr) { FLuaValue* LuaValue = TablePtr->Find(Key); if (LuaValue) { LuaState->FromLuaValue(*LuaValue, Context, L); return 1; } } if (LuaComponent) { FLuaValue MetaIndexReturnValue = LuaComponent->ReceiveLuaMetaIndex(Key); LuaState->FromLuaValue(MetaIndexReturnValue, Context, L); return 1; } if (LuaUserDataObject) { FLuaValue MetaIndexReturnValue = LuaUserDataObject->ReceiveLuaMetaIndex(Key); LuaState->FromLuaValue(MetaIndexReturnValue, MetaIndexReturnValue.Object ? MetaIndexReturnValue.Object : Context, L); return 1; } lua_pushnil(L); return 1; } int ULuaState::MetaTableFunctionUserData__newindex(lua_State* L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(L, 1); if (!UserData->Context.IsValid()) { return luaL_error(L, "invalid UObject for UserData %p", UserData); } TMap<FString, FLuaValue>* TablePtr = nullptr; UObject* Context = UserData->Context.Get(); ULuaComponent* LuaComponent = Cast<ULuaComponent>(Context); if (LuaComponent) { TablePtr = &LuaComponent->Table; } else if (ULuaUserDataObject* LuaUserDataObject = Cast<ULuaUserDataObject>(Context)) { TablePtr = &LuaUserDataObject->Table; } if (TablePtr) { FString Key = ANSI_TO_TCHAR(lua_tostring(L, 2)); FLuaValue* LuaValue = TablePtr->Find(Key); if (LuaValue) { *LuaValue = LuaState->ToLuaValue(3, L); } else { if (LuaComponent) { if (LuaComponent->ReceiveLuaMetaNewIndex(LuaState->ToLuaValue(2, L), LuaState->ToLuaValue(3, L))) { return 0; } } TablePtr->Add(Key, LuaState->ToLuaValue(3, L)); } } return 0; } FLuaDebug ULuaState::LuaGetInfo(int32 Level) { lua_Debug ar; if (lua_getstack(L, Level, &ar) != 1) return FLuaDebug(); lua_getinfo(L, "lSn", &ar); FLuaDebug LuaDebug; LuaDebug.CurrentLine = ar.currentline; LuaDebug.Source = ANSI_TO_TCHAR(ar.source); LuaDebug.Name = ANSI_TO_TCHAR(ar.name); LuaDebug.NameWhat = ANSI_TO_TCHAR(ar.namewhat); LuaDebug.What = ANSI_TO_TCHAR(ar.what); return LuaDebug; } TMap<FString, FLuaValue> ULuaState::LuaGetLocals(int32 Level) { TMap<FString, FLuaValue> ReturnValue; lua_Debug ar; if (lua_getstack(L, Level, &ar) != 1) return ReturnValue; int Index = 1; const char* name = lua_getlocal(L, &ar, Index); while (name) { FLuaValue LuaValue = ToLuaValue(-1); ReturnValue.Add(ANSI_TO_TCHAR(name), LuaValue); Pop(); name = lua_getlocal(L, &ar, ++Index); } return ReturnValue; } void ULuaState::Debug_Hook(lua_State* L, lua_Debug* ar) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); FLuaDebug LuaDebug; lua_getinfo(L, "lSn", ar); LuaDebug.CurrentLine = ar->currentline; LuaDebug.Source = ANSI_TO_TCHAR(ar->source); LuaDebug.Name = ANSI_TO_TCHAR(ar->name); LuaDebug.NameWhat = ANSI_TO_TCHAR(ar->namewhat); LuaDebug.What = ANSI_TO_TCHAR(ar->what); switch (ar->event) { case LUA_HOOKLINE: LuaState->ReceiveLuaLineHook(LuaDebug); break; case LUA_HOOKCALL: LuaState->ReceiveLuaCallHook(LuaDebug); break; case LUA_HOOKRET: LuaState->ReceiveLuaReturnHook(LuaDebug); break; case LUA_HOOKCOUNT: LuaState->ReceiveLuaCountHook(LuaDebug); break; default: break; } } int ULuaState::MetaTableFunctionUserData__eq(lua_State* L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(L, 1); if (!UserData->Context.IsValid()) { return luaL_error(L, "invalid UObject for UserData %p", UserData); } FLuaUserData* UserData2 = (FLuaUserData*)lua_touserdata(L, 2); if (!UserData2->Context.IsValid()) { return luaL_error(L, "invalid UObject for UserData %p", UserData2); } if (UserData->Type == UserData2->Type && UserData->Context.Get() == UserData2->Context.Get()) { if (UserData->Type == ELuaValueType::UFunction) { if (!UserData->Function.IsValid()) { return luaL_error(L, "invalid UFunction for UserData %p", UserData); } if (!UserData2->Function.IsValid()) { return luaL_error(L, "invalid UFunction for UserData %p", UserData2); } if (UserData->Function.Get() == UserData2->Function.Get()) { lua_pushboolean(L, 1); return 1; } } else if (UserData->Type == ELuaValueType::UObject) { lua_pushboolean(L, 1); return 1; } } lua_pushboolean(L, 0); return 1; } int ULuaState::MetaTableFunctionUserData__gc(lua_State* L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); FLuaUserData* UserData = (FLuaUserData*)lua_touserdata(L, 1); if (!UserData->Context.IsValid()) { return luaL_error(L, "invalid UObject for UserData %p", UserData); } ULuaUserDataObject* LuaUserDataObject = Cast<ULuaUserDataObject>(UserData->Context.Get()); if (LuaUserDataObject) { LuaState->TrackedLuaUserDataObjects.Remove(LuaUserDataObject); LuaUserDataObject->ReceiveLuaGC(); } lua_pushnil(L); return 1; } int ULuaState::MetaTableFunction__call(lua_State* L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); FLuaUserData* LuaCallContext = (FLuaUserData*)lua_touserdata(L, 1); if (!LuaCallContext->Context.IsValid() || !LuaCallContext->Function.IsValid()) { return luaL_error(L, "invalid lua UFunction for UserData %p", LuaCallContext); } int NArgs = lua_gettop(L); UObject* CallScope = LuaCallContext->Context.Get(); bool bImplicitSelf = false; int StackPointer = 2; if (ULuaComponent* LuaComponent = Cast<ULuaComponent>(CallScope)) { CallScope = LuaComponent->GetOwner(); if (NArgs > 0) { FLuaValue LuaFirstArgument = LuaState->ToLuaValue(StackPointer, L); if (LuaFirstArgument.Type == ELuaValueType::UObject && LuaFirstArgument.Object == LuaComponent) { bImplicitSelf = LuaComponent->bImplicitSelf; } } } else if (ULuaUserDataObject* LuaUserDataObject = Cast<ULuaUserDataObject>(CallScope)) { if (NArgs > 0) { FLuaValue LuaFirstArgument = LuaState->ToLuaValue(StackPointer, L); if (LuaFirstArgument.Type == ELuaValueType::UObject && LuaFirstArgument.Object == LuaUserDataObject) { bImplicitSelf = LuaUserDataObject->bImplicitSelf; } } } FScopeCycleCounterUObject ObjectScope(CallScope); FScopeCycleCounterUObject FunctionScope(LuaCallContext->Function.Get()); void* Parameters = FMemory_Alloca(LuaCallContext->Function->ParmsSize); FMemory::Memzero(Parameters, LuaCallContext->Function->ParmsSize); #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) { FProperty* Prop = *It; #else for (TFieldIterator<UProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) { UProperty* Prop = *It; #endif if (!Prop->HasAnyPropertyFlags(CPF_ZeroConstructor)) { Prop->InitializeValue_InContainer(Parameters); } } if (bImplicitSelf) { NArgs--; StackPointer++; } // arguments #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> FArgs(LuaCallContext->Function.Get()); FArgs && ((FArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm); ++FArgs) { FProperty* Prop = *FArgs; FStructProperty* LuaProp = CastField<FStructProperty>(Prop); #else for (TFieldIterator<UProperty> FArgs(LuaCallContext->Function.Get()); FArgs && ((FArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm); ++FArgs) { UProperty* Prop = *FArgs; UStructProperty* LuaProp = Cast<UStructProperty>(Prop); #endif if (!LuaProp) { #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FArrayProperty* ArrayProp = CastField<FArrayProperty>(Prop); if (ArrayProp) { LuaProp = CastField<FStructProperty>(ArrayProp->Inner); #else UArrayProperty* ArrayProp = Cast<UArrayProperty>(Prop); if (ArrayProp) { LuaProp = Cast<UStructProperty>(ArrayProp->Inner); #endif if (!LuaProp) { break; } if (LuaProp->Struct != FLuaValue::StaticStruct()) { break; } // start filling the array with the rest of arguments int ArgsToProcess = NArgs - StackPointer + 1; if (ArgsToProcess < 1) { break; } FScriptArrayHelper_InContainer ArrayHelper(ArrayProp, LuaProp->ContainerPtrToValuePtr<uint8>(Parameters)); ArrayHelper.AddValues(ArgsToProcess); for (int i = StackPointer; i < StackPointer + ArgsToProcess; i++) { FLuaValue LuaValue = LuaState->ToLuaValue(i, L); *LuaProp->ContainerPtrToValuePtr<FLuaValue>(ArrayHelper.GetRawPtr(i - StackPointer)) = LuaValue; } } break; } if (LuaProp->Struct != FLuaValue::StaticStruct()) { break; } FLuaValue LuaValue = LuaState->ToLuaValue(StackPointer++, L); *LuaProp->ContainerPtrToValuePtr<FLuaValue>(Parameters) = LuaValue; } LuaState->InceptionLevel++; CallScope->ProcessEvent(LuaCallContext->Function.Get(), Parameters); check(LuaState->InceptionLevel > 0); LuaState->InceptionLevel--; if (LuaState->InceptionLevel == 0) { FString Error; while (LuaState->InceptionErrors.Dequeue(Error)) { ULuaComponent* LuaComponent = Cast<ULuaComponent>(LuaCallContext->Context); if (LuaComponent) { if (LuaComponent->bLogError) { LuaState->LogError(Error); } LuaComponent->OnLuaError.Broadcast(Error); } else { if (LuaState->bLogError) { LuaState->LogError(Error); } LuaState->ReceiveLuaError(Error); } } } int ReturnedValues = 0; // get return value #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> FArgs(LuaCallContext->Function.Get()); FArgs; ++FArgs) { FProperty* Prop = *FArgs; #else for (TFieldIterator<UProperty> FArgs(LuaCallContext->Function.Get()); FArgs; ++FArgs) { UProperty* Prop = *FArgs; #endif if (!Prop->HasAnyPropertyFlags(CPF_ReturnParm | CPF_OutParm)) { continue; } // avoid input args (at all costs !) if (Prop->HasAnyPropertyFlags(CPF_ConstParm | CPF_ReferenceParm)) { continue; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FStructProperty* LuaProp = CastField<FStructProperty>(Prop); if (!LuaProp) { FArrayProperty* ArrayProp = CastField<FArrayProperty>(Prop); if (ArrayProp) { LuaProp = CastField<FStructProperty>(ArrayProp->Inner); #else UStructProperty* LuaProp = Cast<UStructProperty>(Prop); if (!LuaProp) { UArrayProperty* ArrayProp = Cast<UArrayProperty>(Prop); if (ArrayProp) { LuaProp = Cast<UStructProperty>(ArrayProp->Inner); #endif if (!LuaProp) break; if (LuaProp->Struct != FLuaValue::StaticStruct()) break; FScriptArrayHelper_InContainer ArrayHelper(ArrayProp, LuaProp->ContainerPtrToValuePtr<uint8>(Parameters)); for (int i = 0; i < ArrayHelper.Num(); i++) { FLuaValue* LuaValue = LuaProp->ContainerPtrToValuePtr<FLuaValue>(ArrayHelper.GetRawPtr(i)); ReturnedValues++; LuaState->FromLuaValue(*LuaValue, nullptr, L); } } break; } if (LuaProp->Struct != FLuaValue::StaticStruct()) break; FLuaValue* LuaValue = LuaProp->ContainerPtrToValuePtr<FLuaValue>(Parameters); if (LuaValue) { ReturnedValues++; LuaState->FromLuaValue(*LuaValue, nullptr, L); } } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) #else for (TFieldIterator<UProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) #endif { It->DestroyValue_InContainer(Parameters); } if (ReturnedValues > 0) return ReturnedValues; lua_pushnil(L); return 1; } int ULuaState::MetaTableFunction__rawcall(lua_State * L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); FLuaUserData* LuaCallContext = (FLuaUserData*)lua_touserdata(L, 1); if (!LuaCallContext->Context.IsValid() || !LuaCallContext->Function.IsValid()) { return luaL_error(L, "invalid lua UFunction for UserData %p", LuaCallContext); } int NArgs = lua_gettop(L); UObject* CallScope = LuaCallContext->Context.Get(); bool bImplicitSelf = false; int StackPointer = 2; if (ULuaComponent* LuaComponent = Cast<ULuaComponent>(CallScope)) { CallScope = LuaComponent->GetOwner(); if (NArgs > 0) { FLuaValue LuaFirstArgument = LuaState->ToLuaValue(StackPointer, L); if (LuaFirstArgument.Type == ELuaValueType::UObject && LuaFirstArgument.Object == LuaComponent) { bImplicitSelf = LuaComponent->bImplicitSelf; } } } else if (ULuaUserDataObject* LuaUserDataObject = Cast<ULuaUserDataObject>(CallScope)) { if (NArgs > 0) { FLuaValue LuaFirstArgument = LuaState->ToLuaValue(StackPointer, L); if (LuaFirstArgument.Type == ELuaValueType::UObject && LuaFirstArgument.Object == LuaUserDataObject) { bImplicitSelf = LuaUserDataObject->bImplicitSelf; } } } FScopeCycleCounterUObject ObjectScope(CallScope); FScopeCycleCounterUObject FunctionScope(LuaCallContext->Function.Get()); void* Parameters = FMemory_Alloca(LuaCallContext->Function->ParmsSize); FMemory::Memzero(Parameters, LuaCallContext->Function->ParmsSize); #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) { FProperty* Prop = *It; #else for (TFieldIterator<UProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) { UProperty* Prop = *It; #endif if (!Prop->HasAnyPropertyFlags(CPF_ZeroConstructor)) { Prop->InitializeValue_InContainer(Parameters); } } if (bImplicitSelf) { NArgs--; StackPointer++; } // arguments #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> FArgs(LuaCallContext->Function.Get()); FArgs && ((FArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm); ++FArgs) { FProperty* Prop = *FArgs; #else for (TFieldIterator<UProperty> FArgs(LuaCallContext->Function.Get()); FArgs && ((FArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm); ++FArgs) { UProperty* Prop = *FArgs; #endif bool bPropertySet = false; LuaState->ToProperty(Parameters, Prop, LuaState->ToLuaValue(StackPointer++, L), bPropertySet, 0); } LuaState->InceptionLevel++; CallScope->ProcessEvent(LuaCallContext->Function.Get(), Parameters); check(LuaState->InceptionLevel > 0); LuaState->InceptionLevel--; if (LuaState->InceptionLevel == 0) { FString Error; while (LuaState->InceptionErrors.Dequeue(Error)) { ULuaComponent* LuaComponent = Cast<ULuaComponent>(LuaCallContext->Context); if (LuaComponent) { if (LuaComponent->bLogError) { LuaState->LogError(Error); } LuaComponent->OnLuaError.Broadcast(Error); } else { if (LuaState->bLogError) { LuaState->LogError(Error); } LuaState->ReceiveLuaError(Error); } } } int ReturnedValues = 0; // get return value #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> FArgs(LuaCallContext->Function.Get()); FArgs; ++FArgs) { FProperty* Prop = *FArgs; #else for (TFieldIterator<UProperty> FArgs(LuaCallContext->Function.Get()); FArgs; ++FArgs) { UProperty* Prop = *FArgs; #endif if (!Prop->HasAnyPropertyFlags(CPF_ReturnParm | CPF_OutParm)) { continue; } // avoid input args (at all costs !) if (Prop->HasAnyPropertyFlags(CPF_ConstParm | CPF_ReferenceParm)) { continue; } bool bPropertyGet = false; FLuaValue LuaValue = LuaState->FromProperty(Parameters, Prop, bPropertyGet, 0); ReturnedValues++; LuaState->FromLuaValue(LuaValue, nullptr, L); } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) #else for (TFieldIterator<UProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) #endif { It->DestroyValue_InContainer(Parameters); } if (ReturnedValues > 0) { return ReturnedValues; } lua_pushnil(L); return 1; } int ULuaState::MetaTableFunction__rawbroadcast(lua_State * L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); FLuaUserData* LuaCallContext = (FLuaUserData*)lua_touserdata(L, 1); if (!LuaCallContext->MulticastScriptDelegate || !LuaCallContext->Function.IsValid()) { return luaL_error(L, "invalid lua Multicast Delegate for UserData %p", LuaCallContext); } int NArgs = lua_gettop(L); int StackPointer = 2; FScopeCycleCounterUObject FunctionScope(LuaCallContext->Function.Get()); void* Parameters = FMemory_Alloca(LuaCallContext->Function->ParmsSize); FMemory::Memzero(Parameters, LuaCallContext->Function->ParmsSize); for (TFieldIterator<FProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) { FProperty* Prop = *It; if (!Prop->HasAnyPropertyFlags(CPF_ZeroConstructor)) { Prop->InitializeValue_InContainer(Parameters); } } // arguments for (TFieldIterator<FProperty> FArgs(LuaCallContext->Function.Get()); FArgs && ((FArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm); ++FArgs) { FProperty* Prop = *FArgs; bool bPropertySet = false; LuaState->ToProperty(Parameters, Prop, LuaState->ToLuaValue(StackPointer++, L), bPropertySet, 0); } LuaState->InceptionLevel++; LuaCallContext->MulticastScriptDelegate->ProcessMulticastDelegate<UObject>(Parameters); check(LuaState->InceptionLevel > 0); LuaState->InceptionLevel--; if (LuaState->InceptionLevel == 0) { FString Error; while (LuaState->InceptionErrors.Dequeue(Error)) { if (LuaState->bLogError) { LuaState->LogError(Error); } LuaState->ReceiveLuaError(Error); } } // no return values in multicast delegates for (TFieldIterator<FProperty> It(LuaCallContext->Function.Get()); (It && It->HasAnyPropertyFlags(CPF_Parm)); ++It) { It->DestroyValue_InContainer(Parameters); } lua_pushnil(L); return 1; } int ULuaState::TableFunction_print(lua_State * L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); TArray<FString> Messages; int n = lua_gettop(L); lua_getglobal(L, "tostring"); for (int i = 1; i <= n; i++) { lua_pushvalue(L, -1); lua_pushvalue(L, i); lua_call(L, 1, 1); const char* s = lua_tostring(L, -1); if (!s) return luaL_error(L, "'tostring must return a string to 'print'"); FString Value = ANSI_TO_TCHAR(s); lua_pop(L, 1); Messages.Add(Value); } LuaState->Log(FString::Join(Messages, TEXT("\t"))); return 0; } int ULuaState::TableFunction_package_loader_codeasset(lua_State * L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); // use the second (sanitized by the loader) argument FString Key = ANSI_TO_TCHAR(lua_tostring(L, 2)); FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(TEXT("AssetRegistry")); #if ENGINE_MAJOR_VERSION >= 5 && ENGINE_MINOR_VERSION > 0 FAssetData AssetData = AssetRegistryModule.Get().GetAssetByObjectPath(Key); if (AssetData.IsValid() && AssetData.AssetClassPath.ToString() == "LuaCode") #else FAssetData AssetData = AssetRegistryModule.Get().GetAssetByObjectPath(*Key); if (AssetData.IsValid() && AssetData.AssetClass == "LuaCode") #endif { ULuaCode* LuaCode = Cast<ULuaCode>(AssetData.GetAsset()); if (LuaCode) { if (!LuaState->RunCodeAsset(LuaCode, 1)) { return luaL_error(L, "%s", lua_tostring(L, -1)); } return 1; } } return luaL_error(L, "unable to load asset '%s'", TCHAR_TO_UTF8(*Key)); } int ULuaState::TableFunction_package_loader_asset(lua_State * L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); // use the second (sanitized by the loader) argument const FString Key = ANSI_TO_TCHAR(lua_tostring(L, 2)); if (LuaState->RunFile(Key, true, 1)) { return 1; } return luaL_error(L, "%s", lua_tostring(L, -1)); } int ULuaState::TableFunction_package_loader(lua_State * L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); FString Key = ANSI_TO_TCHAR(lua_tostring(L, 1)); // check for code assets if (FPackageName::IsValidObjectPath(Key)) { // fix asset name (if required) int32 LastSlashIndex = -1; Key.FindLastChar('/', LastSlashIndex); const FString LastPart = Key.RightChop(LastSlashIndex + 1); if (!LastPart.Contains(".")) { Key = FString::Printf(TEXT("%s.%s"), *Key, *LastPart); } lua_pushcfunction(L, ULuaState::TableFunction_package_loader_codeasset); lua_pushstring(L, TCHAR_TO_UTF8(*Key)); return 2; } else { // TODO: make it smarter by checking for file extension... if (!Key.EndsWith(".lua")) { Key += ".lua"; } // search in root content... FString AbsoluteFilename = FPaths::Combine(FPaths::ProjectContentDir(), Key); if (FPaths::FileExists(AbsoluteFilename)) { lua_pushcfunction(L, ULuaState::TableFunction_package_loader_asset); lua_pushstring(L, TCHAR_TO_UTF8(*Key)); return 2; } else { // or search in additional paths for (FString AdditionalPath : LuaState->AppendProjectContentDirSubDir) { AbsoluteFilename = FPaths::Combine(FPaths::ProjectContentDir(), AdditionalPath, Key); if (FPaths::FileExists(AbsoluteFilename)) { lua_pushcfunction(L, ULuaState::TableFunction_package_loader_asset); lua_pushstring(L, TCHAR_TO_UTF8(*(AdditionalPath / Key))); return 2; } } } } // use UTF8 as the package name can contains non-ASCII chars lua_pushstring(L, TCHAR_TO_UTF8(*FString::Printf(TEXT("\n\tno asset '%s'"), *Key))); return 1; } int ULuaState::TableFunction_package_preload(lua_State * L) { ULuaState* LuaState = ULuaState::GetFromExtraSpace(L); if (LuaState->L != L) return luaL_error(L, "you cannot call package.preload from a thread/coroutine (error while loading %s)", lua_tostring(L, 1)); FString Key = ANSI_TO_TCHAR(lua_tostring(L, 1)); // check for code assets ULuaCode** LuaCodePtr = LuaState->RequireTable.Find(Key); if (!LuaCodePtr) { if (LuaState->bAddProjectContentDirToPackagePath && LuaState->RunFile(Key + ".lua", true, 1)) { return 1; } return luaL_error(L, "%s", lua_tostring(L, -1)); // now search in additional paths for (FString AdditionalPath : LuaState->AppendProjectContentDirSubDir) { if (LuaState->RunFile(AdditionalPath / Key + ".lua", true, 1)) { return 1; } return luaL_error(L, "%s", lua_tostring(L, -1)); } return luaL_error(L, "unable to find package %s", TCHAR_TO_ANSI(*Key)); } ULuaCode* LuaCode = *LuaCodePtr; if (!LuaCode) { return luaL_error(L, "LuaCodeAsset not set for package %s", TCHAR_TO_ANSI(*Key)); } if (!LuaState->RunCodeAsset(LuaCode, 1)) { return luaL_error(L, "%s", lua_tostring(L, -1)); } return 1; } void ULuaState::ReceiveLuaError_Implementation(const FString & Message) { } void ULuaState::ReceiveLuaCallHook_Implementation(const FLuaDebug & LuaDebug) { } void ULuaState::ReceiveLuaReturnHook_Implementation(const FLuaDebug & LuaDebug) { } void ULuaState::ReceiveLuaLineHook_Implementation(const FLuaDebug & LuaDebug) { } void ULuaState::ReceiveLuaCountHook(const FLuaDebug & LuaDebug) { } void ULuaState::ReceiveLuaLevelRemovedFromWorld_Implementation(ULevel * Level, UWorld * World) { } void ULuaState::ReceiveLuaLevelAddedToWorld_Implementation(ULevel * Level, UWorld * World) { } void ULuaState::ReceiveLuaStatePreInitialized_Implementation() { } void ULuaState::ReceiveLuaStateInitialized_Implementation() { } void ULuaState::NewTable() { lua_newtable(L); } void ULuaState::SetMetaTable(int Index) { lua_setmetatable(L, Index); } void ULuaState::GetMetaTable(int Index) { lua_getmetatable(L, Index); } void ULuaState::SetField(int Index, const char* FieldName) { lua_setfield(L, Index, FieldName); } void ULuaState::GetField(int Index, const char* FieldName) { lua_getfield(L, Index, FieldName); } void ULuaState::RawGetI(int Index, int N) { lua_rawgeti(L, Index, N); } void ULuaState::RawSetI(int Index, int N) { lua_rawseti(L, Index, N); } void ULuaState::PushGlobalTable() { lua_pushglobaltable(L); } void ULuaState::PushRegistryTable() { lua_pushvalue(L, LUA_REGISTRYINDEX); } int32 ULuaState::GetFieldFromTree(const FString & Tree, bool bGlobal) { TArray<FString> Parts; Tree.ParseIntoArray(Parts, TEXT(".")); if (Parts.Num() == 0) { LastError = FString::Printf(TEXT("invalid Lua key: \"%s\""), *Tree); if (bLogError) LogError(LastError); ReceiveLuaError(LastError); PushNil(); return 1; } int32 AdditionalPop = bGlobal ? 1 : 0; if (bGlobal) { PushGlobalTable(); } int32 i; for (i = 0; i < Parts.Num(); i++) { GetField(-1, TCHAR_TO_ANSI(*Parts[i])); if (lua_isnil(L, -1)) { if (i == Parts.Num() - 1) { return i + 1 + AdditionalPop; } LastError = FString::Printf(TEXT("Lua key \"%s\" is nil"), *Parts[i]); if (bLogError) LogError(LastError); ReceiveLuaError(LastError); return i + 1 + AdditionalPop; } } return i + AdditionalPop; } void ULuaState::SetFieldFromTree(const FString & Tree, FLuaValue & Value, bool bGlobal, UObject * CallContext) { TArray<FString> Parts; Tree.ParseIntoArray(Parts, TEXT(".")); int32 ItemsToPop = GetFieldFromTree(Tree, bGlobal); // invalid key if (ItemsToPop != (Parts.Num() + (bGlobal ? 1 : 0))) { Pop(ItemsToPop); return; } Pop(); FromLuaValue(Value, CallContext); SetField(-2, TCHAR_TO_ANSI(*Parts.Last())); Pop(ItemsToPop - 1); } void ULuaState::NewUObject(UObject * Object, lua_State * State) { if (!State) { State = this->L; } FLuaUserData* UserData = (FLuaUserData*)lua_newuserdata(State, sizeof(FLuaUserData)); UserData->Type = ELuaValueType::UObject; UserData->Context = Object; UserData->Function = nullptr; } void ULuaState::GetGlobal(const char* Name) { lua_getglobal(L, Name); } void ULuaState::SetGlobal(const char* Name) { lua_setglobal(L, Name); } void ULuaState::PushValue(int Index) { lua_pushvalue(L, Index); } bool ULuaState::PCall(int NArgs, FLuaValue & Value, int NRet) { bool bSuccess = Call(NArgs, Value, NRet); if (!bSuccess) { if (InceptionLevel > 0) { InceptionErrors.Enqueue(LastError); } else { if (bLogError) LogError(LastError); ReceiveLuaError(LastError); } } return bSuccess; } bool ULuaState::Call(int NArgs, FLuaValue & Value, int NRet) { if (lua_pcall(L, NArgs, NRet, 0)) { LastError = FString::Printf(TEXT("Lua error: %s"), ANSI_TO_TCHAR(lua_tostring(L, -1))); return false; } if (NRet > 0) { Value = ToLuaValue(-1); } return true; } void ULuaState::Pop(int32 Amount) { lua_pop(L, Amount); } void ULuaState::PushNil() { lua_pushnil(L); } void ULuaState::PushCFunction(lua_CFunction Function) { lua_pushcfunction(L, Function); } void* ULuaState::NewUserData(size_t DataSize) { return lua_newuserdata(L, DataSize); } void ULuaState::Unref(int Ref) { luaL_unref(L, LUA_REGISTRYINDEX, Ref); } void ULuaState::UnrefChecked(int Ref) { // in case of moved value (like when compiling a blueprint), L should be nullptr if (!L) return; Unref(Ref); } int ULuaState::NewRef() { return luaL_ref(L, LUA_REGISTRYINDEX); } void ULuaState::GetRef(int Ref) { lua_rawgeti(L, LUA_REGISTRYINDEX, Ref); } int ULuaState::Next(int Index) { return lua_next(L, Index); } bool ULuaState::Yield(int Index, int NArgs) { lua_State* Coroutine = lua_tothread(L, Index); if (!Coroutine) return false; if (lua_status(Coroutine) == LUA_OK && lua_gettop(Coroutine) == 0) { lua_pushboolean(L, 0); lua_pushstring(L, "Lua error: cannot yield a dead coroutine"); return false; } lua_xmove(L, Coroutine, NArgs); int Ret = lua_yield(Coroutine, NArgs); if (Ret != LUA_OK) { lua_pushboolean(L, 0); lua_xmove(Coroutine, L, 1); return false; } int NRet = lua_gettop(Coroutine); lua_pushboolean(L, 1); lua_xmove(Coroutine, L, NRet); return true; } bool ULuaState::Resume(int Index, int NArgs) { lua_State* Coroutine = lua_tothread(L, Index); if (!Coroutine) return false; if (lua_status(Coroutine) == LUA_OK && lua_gettop(Coroutine) == 0) { lua_pushboolean(L, 0); lua_pushstring(L, "Lua error: cannot resume dead coroutine"); return false; } lua_xmove(L, Coroutine, NArgs); int Ret = lua_resume(Coroutine, L, NArgs); if (Ret != LUA_OK && Ret != LUA_YIELD) { lua_pushboolean(L, 0); lua_xmove(Coroutine, L, 1); return false; } int NRet = lua_gettop(Coroutine); lua_pushboolean(L, 1); lua_xmove(Coroutine, L, NRet); return true; } int ULuaState::GC(int What, int Data) { return lua_gc(L, What, Data); } void ULuaState::Len(int Index) { lua_len(L, Index); } int32 ULuaState::ILen(int Index) { return luaL_len(L, Index); } int32 ULuaState::ToInteger(int Index) { return lua_tointeger(L, Index); } FLuaValue ULuaState::CreateLuaTable() { FLuaValue NewTable; NewTable.Type = ELuaValueType::Table; NewTable.LuaState = this; FromLuaValue(NewTable); Pop(); return NewTable; } FLuaValue ULuaState::CreateLuaLazyTable() { FLuaValue NewTable; NewTable.Type = ELuaValueType::Table; NewTable.LuaState = this; return NewTable; } FLuaValue ULuaState::CreateLuaThread(FLuaValue Value) { FLuaValue NewThread; NewThread.Type = ELuaValueType::Thread; NewThread.LuaState = this; FromLuaValue(NewThread); lua_State* NewLuaThread = lua_tothread(L, -1); FromLuaValue(Value, nullptr, NewLuaThread); Pop(); return NewThread; } ELuaThreadStatus ULuaState::GetLuaThreadStatus(FLuaValue Value) { if (Value.Type != ELuaValueType::Thread || Value.LuaState != this) return ELuaThreadStatus::Invalid; FromLuaValue(Value); lua_State* LuaThread = lua_tothread(L, -1); int ReturnValue = lua_status(LuaThread); Pop(); if (ReturnValue == 0) return ELuaThreadStatus::Ok; if (ReturnValue == LUA_YIELD) return ELuaThreadStatus::Suspended; return ELuaThreadStatus::Error; } int32 ULuaState::GetLuaThreadStackTop(FLuaValue Value) { if (Value.Type != ELuaValueType::Thread || Value.LuaState != this) return MIN_int32; FromLuaValue(Value); lua_State* LuaThread = lua_tothread(L, -1); int ReturnValue = lua_gettop(LuaThread); Pop(); return ReturnValue; } TSharedRef<FLuaSmartReference> ULuaState::AddLuaSmartReference(FLuaValue Value) { TSharedRef<FLuaSmartReference> Ref = MakeShared<FLuaSmartReference>(); Ref->LuaState = this; Ref->Value = Value; LuaSmartReferences.Add(Ref); return Ref; } void ULuaState::RemoveLuaSmartReference(TSharedRef<FLuaSmartReference> Ref) { LuaSmartReferences.Remove(Ref); } ULuaState::~ULuaState() { FCoreUObjectDelegates::GetPostGarbageCollect().Remove(GCLuaDelegatesHandle); #if WITH_EDITOR if (LuaConsole.LuaState) { IModularFeatures::Get().UnregisterModularFeature(IConsoleCommandExecutor::ModularFeatureName(), &LuaConsole); } #endif FLuaMachineModule::Get().UnregisterLuaState(this); if (L) { lua_close(L); L = nullptr; } } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 #define LUAVALUE_PROP_CAST(Type, Type2) F##Type* __##Type##__ = CastField<F##Type>(Property);\ if (__##Type##__)\ {\ return FLuaValue((Type2)__##Type##__->GetPropertyValue_InContainer(Buffer, Index));\ } #define LUAVALUE_PROP_CAST_TOSTRING(Type) F##Type* __##Type##__ = CastField<F##Type>(Property);\ if (__##Type##__)\ {\ return FLuaValue(__##Type##__->GetPropertyValue_InContainer(Buffer, Index).ToString());\ } #define LUAVALUE_PROP_SET(Type, Value) F##Type* __##Type##__ = CastField<F##Type>(Property);\ if (__##Type##__)\ {\ __##Type##__->SetPropertyValue_InContainer(Buffer, Value, Index);\ return;\ } #else #define LUAVALUE_PROP_CAST(Type, Type2) U##Type* __##Type##__ = Cast<U##Type>(Property);\ if (__##Type##__)\ {\ return FLuaValue((Type2)__##Type##__->GetPropertyValue_InContainer(Buffer, Index));\ } #define LUAVALUE_PROP_CAST_TOSTRING(Type) U##Type* __##Type##__ = Cast<U##Type>(Property);\ if (__##Type##__)\ {\ return FLuaValue(__##Type##__->GetPropertyValue_InContainer(Buffer, Index).ToString());\ } #define LUAVALUE_PROP_SET(Type, Value) U##Type* __##Type##__ = Cast<U##Type>(Property);\ if (__##Type##__)\ {\ __##Type##__->SetPropertyValue_InContainer(Buffer, Value, Index);\ return;\ } #endif #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FLuaValue ULuaState::FromUProperty(void* Buffer, FProperty * Property, bool& bSuccess, int32 Index) { return FromFProperty(Buffer, Property, bSuccess, Index); } void ULuaState::ToUProperty(void* Buffer, FProperty * Property, FLuaValue Value, bool& bSuccess, int32 Index) { ToFProperty(Buffer, Property, Value, bSuccess, Index); } #endif #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FLuaValue ULuaState::FromFProperty(void* Buffer, FProperty * Property, bool& bSuccess, int32 Index) #else FLuaValue ULuaState::FromUProperty(void* Buffer, UProperty * Property, bool& bSuccess, int32 Index) #endif { bSuccess = true; LUAVALUE_PROP_CAST(BoolProperty, bool); LUAVALUE_PROP_CAST(DoubleProperty, double); LUAVALUE_PROP_CAST(FloatProperty, float); LUAVALUE_PROP_CAST(IntProperty, int32); LUAVALUE_PROP_CAST(UInt32Property, int32); LUAVALUE_PROP_CAST(Int16Property, int32); LUAVALUE_PROP_CAST(Int8Property, int32); LUAVALUE_PROP_CAST(ByteProperty, int32); LUAVALUE_PROP_CAST(UInt16Property, int32); LUAVALUE_PROP_CAST(StrProperty, FString); LUAVALUE_PROP_CAST_TOSTRING(NameProperty); LUAVALUE_PROP_CAST_TOSTRING(TextProperty); LUAVALUE_PROP_CAST(ClassProperty, UObject*); LUAVALUE_PROP_CAST(ObjectProperty, UObject*); #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FEnumProperty* EnumProperty = CastField<FEnumProperty>(Property); if (EnumProperty) { const uint8* EnumValue = EnumProperty->ContainerPtrToValuePtr<const uint8>(Buffer, Index); return FLuaValue((int32)*EnumValue); } #endif #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FObjectPropertyBase* ObjectPropertyBase = CastField<FObjectPropertyBase>(Property); #else UObjectPropertyBase* ObjectPropertyBase = Cast<UObjectPropertyBase>(Property); #endif if (ObjectPropertyBase) { return FLuaValue(ObjectPropertyBase->GetObjectPropertyValue_InContainer(Buffer, Index)); } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FWeakObjectProperty* WeakObjectProperty = CastField<FWeakObjectProperty>(Property); #else UWeakObjectProperty* WeakObjectProperty = Cast<UWeakObjectProperty>(Property); #endif if (WeakObjectProperty) { const FWeakObjectPtr& WeakPtr = WeakObjectProperty->GetPropertyValue_InContainer(Buffer, Index); return FLuaValue(WeakPtr.Get()); } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FMulticastDelegateProperty* MulticastProperty = CastField<FMulticastDelegateProperty>(Property)) #else if (UMulticastDelegateProperty* MulticastProperty = Cast<UMulticastDelegateProperty>(Property)) #endif { FLuaValue MulticastValue; MulticastValue.Type = ELuaValueType::MulticastDelegate; MulticastValue.Object = MulticastProperty->SignatureFunction; MulticastValue.MulticastScriptDelegate = reinterpret_cast<FMulticastScriptDelegate*>(MulticastProperty->ContainerPtrToValuePtr<uint8>(Buffer)); return MulticastValue; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FDelegateProperty* DelegateProperty = CastField<FDelegateProperty>(Property)) #else if (UDelegateProperty* DelegateProperty = Cast<UDelegateProperty>(Property)) #endif { const FScriptDelegate& ScriptDelegate = DelegateProperty->GetPropertyValue_InContainer(Buffer, Index); return FLuaValue::FunctionOfObject((UObject*)ScriptDelegate.GetUObject(), ScriptDelegate.GetFunctionName()); } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FArrayProperty* ArrayProperty = CastField<FArrayProperty>(Property)) #else if (UArrayProperty* ArrayProperty = Cast<UArrayProperty>(Property)) #endif { FLuaValue NewLuaArray = CreateLuaTable(); FScriptArrayHelper_InContainer Helper(ArrayProperty, Buffer, Index); for (int32 ArrayIndex = 0; ArrayIndex < Helper.Num(); ArrayIndex++) { uint8* ArrayItemPtr = Helper.GetRawPtr(ArrayIndex); bool bArrayItemSuccess = false; NewLuaArray.SetFieldByIndex(ArrayIndex + 1, FromProperty(ArrayItemPtr, ArrayProperty->Inner, bArrayItemSuccess, 0)); } return NewLuaArray; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FMapProperty* MapProperty = CastField<FMapProperty>(Property)) #else if (UMapProperty* MapProperty = Cast<UMapProperty>(Property)) #endif { FLuaValue NewLuaTable = CreateLuaTable(); FScriptMapHelper_InContainer Helper(MapProperty, Buffer, Index); for (int32 MapIndex = 0; MapIndex < Helper.Num(); MapIndex++) { uint8* ArrayKeyPtr = Helper.GetKeyPtr(MapIndex); uint8* ArrayValuePtr = Helper.GetValuePtr(MapIndex); bool bArrayItemSuccess = false; NewLuaTable.SetField( FromProperty(ArrayKeyPtr, MapProperty->KeyProp, bArrayItemSuccess, 0).ToString(), FromProperty(ArrayValuePtr, MapProperty->ValueProp, bArrayItemSuccess, 0)); } return NewLuaTable; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FSetProperty* SetProperty = CastField<FSetProperty>(Property)) #else if (USetProperty* SetProperty = Cast<USetProperty>(Property)) #endif { FLuaValue NewLuaArray = CreateLuaTable(); FScriptSetHelper_InContainer Helper(SetProperty, Buffer, Index); for (int32 SetIndex = 0; SetIndex < Helper.Num(); SetIndex++) { uint8* ArrayItemPtr = Helper.GetElementPtr(SetIndex); bool bArrayItemSuccess = false; NewLuaArray.SetFieldByIndex(SetIndex + 1, FromProperty(ArrayItemPtr, SetProperty->ElementProp, bArrayItemSuccess, 0)); } return NewLuaArray; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FStructProperty* StructProperty = CastField<FStructProperty>(Property)) #else if (UStructProperty* StructProperty = Cast<UStructProperty>(Property)) #endif { // fast path if (StructProperty->Struct == FLuaValue::StaticStruct()) { FLuaValue* LuaValuePtr = StructProperty->ContainerPtrToValuePtr<FLuaValue>(Buffer); // trick for allowing lazy tables creation FromLuaValue(*LuaValuePtr); Pop(); return *LuaValuePtr; } const uint8* StructContainer = StructProperty->ContainerPtrToValuePtr<const uint8>(Buffer, Index); return StructToLuaTable(StructProperty->Struct, StructContainer); } bSuccess = false; return FLuaValue(); } FLuaValue ULuaState::StructToLuaTable(UScriptStruct * InScriptStruct, const uint8 * StructData) { FLuaValue NewLuaTable = CreateLuaTable(); #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> It(InScriptStruct); It; ++It) #else for (TFieldIterator<UProperty> It(InScriptStruct); It; ++It) #endif { #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FProperty* FieldProp = *It; #else UProperty* FieldProp = *It; #endif FString PropName = FieldProp->GetName(); bool bTableItemSuccess = false; NewLuaTable.SetField(PropName, FromProperty((void*)StructData, FieldProp, bTableItemSuccess, 0)); } return NewLuaTable; } FLuaValue ULuaState::StructToLuaTable(UScriptStruct * InScriptStruct, const TArray<uint8>&StructData) { return StructToLuaTable(InScriptStruct, StructData.GetData()); } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 void ULuaState::ToFProperty(void* Buffer, FProperty * Property, FLuaValue Value, bool& bSuccess, int32 Index) #else void ULuaState::ToUProperty(void* Buffer, UProperty * Property, FLuaValue Value, bool& bSuccess, int32 Index) #endif { bSuccess = true; LUAVALUE_PROP_SET(BoolProperty, Value.ToBool()); LUAVALUE_PROP_SET(DoubleProperty, Value.ToFloat()); LUAVALUE_PROP_SET(FloatProperty, Value.ToFloat()); LUAVALUE_PROP_SET(IntProperty, Value.ToInteger()); LUAVALUE_PROP_SET(UInt32Property, Value.ToInteger()); LUAVALUE_PROP_SET(Int16Property, Value.ToInteger()); LUAVALUE_PROP_SET(Int8Property, Value.ToInteger()); LUAVALUE_PROP_SET(ByteProperty, Value.ToInteger()); LUAVALUE_PROP_SET(UInt16Property, Value.ToInteger()); LUAVALUE_PROP_SET(StrProperty, Value.ToString()); LUAVALUE_PROP_SET(NameProperty, Value.ToName()); LUAVALUE_PROP_SET(TextProperty, FText::FromString(Value.ToString())); LUAVALUE_PROP_SET(ClassProperty, Value.Object); LUAVALUE_PROP_SET(ObjectProperty, Value.Object); #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FEnumProperty* EnumProperty = CastField<FEnumProperty>(Property); if (EnumProperty) { uint8* EnumValue = EnumProperty->ContainerPtrToValuePtr<uint8>(Buffer, Index); *EnumValue = Value.ToInteger(); return; } #endif #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FObjectPropertyBase* ObjectPropertyBase = CastField<FObjectPropertyBase>(Property); #else UObjectPropertyBase* ObjectPropertyBase = Cast<UObjectPropertyBase>(Property); #endif if (ObjectPropertyBase) { ObjectPropertyBase->SetObjectPropertyValue_InContainer(Buffer, Value.Object, Index); } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FWeakObjectProperty* WeakObjectProperty = CastField<FWeakObjectProperty>(Property); #else UWeakObjectProperty* WeakObjectProperty = Cast<UWeakObjectProperty>(Property); #endif if (WeakObjectProperty) { FWeakObjectPtr WeakPtr(Value.Object); WeakObjectProperty->SetPropertyValue_InContainer(Buffer, WeakPtr, Index); return; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FMulticastDelegateProperty* MulticastProperty = CastField<FMulticastDelegateProperty>(Property)) #else if (UMulticastDelegateProperty* MulticastProperty = Cast<UMulticastDelegateProperty>(Property)) #endif { if (Value.IsNil()) { UObject* Object = static_cast<UObject*>(Buffer); UnregisterLuaDelegatesOfObject(Object); MulticastProperty->ClearDelegate(Object); return; } ULuaDelegate* LuaDelegate = NewObject<ULuaDelegate>(); LuaDelegate->SetupLuaDelegate(MulticastProperty->SignatureFunction, this, Value); RegisterLuaDelegate((UObject*)Buffer, LuaDelegate); FScriptDelegate Delegate; Delegate.BindUFunction(LuaDelegate, FName("LuaDelegateFunction")); MulticastProperty->AddDelegate(Delegate, (UObject*)Buffer); return; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FDelegateProperty* DelegateProperty = CastField<FDelegateProperty>(Property)) #else if (UDelegateProperty* DelegateProperty = Cast<UDelegateProperty>(Property)) #endif { if (Value.IsNil()) { UObject* Object = static_cast<UObject*>(Buffer); UnregisterLuaDelegatesOfObject(Object); DelegateProperty->SetPropertyValue_InContainer(Buffer, FScriptDelegate(), Index); return; } ULuaDelegate* LuaDelegate = NewObject<ULuaDelegate>(); LuaDelegate->SetupLuaDelegate(DelegateProperty->SignatureFunction, this, Value); RegisterLuaDelegate((UObject*)Buffer, LuaDelegate); FScriptDelegate Delegate; Delegate.BindUFunction(LuaDelegate, FName("LuaDelegateFunction")); DelegateProperty->SetPropertyValue_InContainer(Buffer, Delegate, Index); return; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FStructProperty* StructProperty = CastField<FStructProperty>(Property)) #else if (UStructProperty* StructProperty = Cast<UStructProperty>(Property)) #endif { // fast path if (StructProperty->Struct == FLuaValue::StaticStruct()) { FLuaValue* LuaValuePtr = StructProperty->ContainerPtrToValuePtr<FLuaValue>(Buffer); *LuaValuePtr = Value; return; } const uint8* StructContainer = StructProperty->ContainerPtrToValuePtr<const uint8>(Buffer, Index); LuaTableToStruct(Value, StructProperty->Struct, (uint8*)StructContainer); return; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FArrayProperty* ArrayProperty = CastField<FArrayProperty>(Property)) #else if (UArrayProperty* ArrayProperty = Cast<UArrayProperty>(Property)) #endif { FScriptArrayHelper_InContainer Helper(ArrayProperty, Buffer, Index); TArray<FLuaValue> ArrayValues = ULuaBlueprintFunctionLibrary::LuaTableGetValues(Value); Helper.Resize(ArrayValues.Num()); for (int32 ArrayIndex = 0; ArrayIndex < Helper.Num(); ArrayIndex++) { uint8* ArrayItemPtr = Helper.GetRawPtr(ArrayIndex); bool bArrayItemSuccess = false; ToProperty(ArrayItemPtr, ArrayProperty->Inner, ArrayValues[ArrayIndex], bArrayItemSuccess, 0); } return; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FMapProperty* MapProperty = CastField<FMapProperty>(Property)) #else if (UMapProperty* MapProperty = Cast<UMapProperty>(Property)) #endif { FScriptMapHelper_InContainer Helper(MapProperty, Buffer, Index); Helper.EmptyValues(); TArray<FLuaValue> TableKeys = ULuaBlueprintFunctionLibrary::LuaTableGetKeys(Value); for (FLuaValue TableKey : TableKeys) { int32 NewIndex = Helper.AddUninitializedValue(); uint8* KeyBuffer = Helper.GetKeyPtr(NewIndex); uint8* ValueBuffer = Helper.GetValuePtr(NewIndex); bool bTableItemSuccess = false; ToProperty(KeyBuffer, Helper.GetKeyProperty(), TableKey, bTableItemSuccess, 0); ToProperty(ValueBuffer, Helper.GetValueProperty(), TableKey, bTableItemSuccess, 0); } return; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 if (FSetProperty* SetProperty = CastField<FSetProperty>(Property)) #else if (USetProperty* SetProperty = Cast<USetProperty>(Property)) #endif { FScriptSetHelper_InContainer Helper(SetProperty, Buffer, Index); TArray<FLuaValue> ArrayValues = ULuaBlueprintFunctionLibrary::LuaTableGetValues(Value); Helper.EmptyElements(ArrayValues.Num()); for (int32 ArrayIndex = 0; ArrayIndex < Helper.Num(); ArrayIndex++) { uint8* SetItemPtr = Helper.GetElementPtr(ArrayIndex); bool bArrayItemSuccess = false; ToProperty(SetItemPtr, SetProperty->ElementProp, ArrayValues[ArrayIndex], bArrayItemSuccess, 0); } return; } bSuccess = false; } void ULuaState::LuaTableToStruct(FLuaValue & LuaValue, UScriptStruct * InScriptStruct, uint8 * StructData) { TArray<FLuaValue> TableKeys = ULuaBlueprintFunctionLibrary::LuaTableGetKeys(LuaValue); for (FLuaValue TableKey : TableKeys) { #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FProperty* StructProp = InScriptStruct->FindPropertyByName(TableKey.ToName()); #else UProperty* StructProp = InScriptStruct->FindPropertyByName(TableKey.ToName()); #endif if (StructProp) { bool bStructValueSuccess = false; ToProperty((void*)StructData, StructProp, LuaValue.GetField(TableKey.ToString()), bStructValueSuccess, 0); } } } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 void ULuaState::ToProperty(void* Buffer, FProperty * Property, FLuaValue Value, bool& bSuccess, int32 Index) { ToFProperty(Buffer, Property, Value, bSuccess, Index); } FLuaValue ULuaState::FromProperty(void* Buffer, FProperty * Property, bool& bSuccess, int32 Index) { return FromFProperty(Buffer, Property, bSuccess, Index); } #else void ULuaState::ToProperty(void* Buffer, UProperty * Property, FLuaValue Value, bool& bSuccess, int32 Index) { ToUProperty(Buffer, Property, Value, bSuccess, Index); } FLuaValue ULuaState::FromProperty(void* Buffer, UProperty * Property, bool& bSuccess, int32 Index) { return FromUProperty(Buffer, Property, bSuccess, Index); } #endif FLuaValue ULuaState::GetLuaValueFromProperty(UObject * InObject, const FString & PropertyName) { if (!InObject) { return FLuaValue(); } UClass* Class = InObject->GetClass(); #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FProperty* Property = nullptr; #else UProperty* Property = nullptr; #endif Property = Class->FindPropertyByName(*PropertyName); if (Property) { bool bSuccess = false; return FromProperty(InObject, Property, bSuccess); } return FLuaValue(); } bool ULuaState::SetPropertyFromLuaValue(UObject * InObject, const FString & PropertyName, FLuaValue Value) { if (!InObject) { return false; } UClass* Class = InObject->GetClass(); #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 FProperty* Property = nullptr; #else UProperty* Property = nullptr; #endif Property = Class->FindPropertyByName(*PropertyName); if (Property) { bool bSuccess = false; ToProperty(InObject, Property, Value, bSuccess); return bSuccess; } return false; } void ULuaState::SetUserDataMetaTable(FLuaValue MetaTable) { UserDataMetaTable = MetaTable; } void ULuaState::SetupAndAssignUserDataMetatable(UObject * Context, TMap<FString, FLuaValue>&Metatable, lua_State * State) { if (!State) { State = this->L; } lua_newtable(State); lua_pushcfunction(State, ULuaState::MetaTableFunctionUserData__index); lua_setfield(State, -2, "__index"); lua_pushcfunction(State, ULuaState::MetaTableFunctionUserData__newindex); lua_setfield(State, -2, "__newindex"); lua_pushcfunction(State, ULuaState::MetaTableFunctionUserData__eq); lua_setfield(State, -2, "__eq"); if (Context->IsA<ULuaUserDataObject>()) { lua_pushcfunction(State, ULuaState::MetaTableFunctionUserData__gc); lua_setfield(State, -2, "__gc"); } for (TPair<FString, FLuaValue>& Pair : Metatable) { // first check for UFunction if (Pair.Value.Type == ELuaValueType::UFunction) { UObject* FunctionOwner = Context; if (ULuaComponent* LuaComponent = Cast<ULuaComponent>(Context)) { FunctionOwner = LuaComponent->GetOwner(); } if (FunctionOwner) { UFunction* Function = FunctionOwner->FindFunction(Pair.Value.FunctionName); if (Function) { FLuaUserData* LuaCallContext = (FLuaUserData*)lua_newuserdata(State, sizeof(FLuaUserData)); LuaCallContext->Type = ELuaValueType::UFunction; LuaCallContext->Context = Context; LuaCallContext->Function = Function; lua_newtable(State); lua_pushcfunction(State, bRawLuaFunctionCall ? ULuaState::MetaTableFunction__rawcall : ULuaState::MetaTableFunction__call); lua_setfield(State, -2, "__call"); lua_setmetatable(State, -2); } else { lua_pushnil(State); } } } else { FromLuaValue(Pair.Value, nullptr, State); } lua_setfield(State, -2, TCHAR_TO_ANSI(*Pair.Key)); } lua_setmetatable(State, -2); } FLuaValue ULuaState::NewLuaUserDataObject(TSubclassOf<ULuaUserDataObject> LuaUserDataObjectClass, bool bTrackObject) { ULuaUserDataObject* LuaUserDataObject = NewObject<ULuaUserDataObject>(this, LuaUserDataObjectClass); if (LuaUserDataObject) { if (bTrackObject) { TrackedLuaUserDataObjects.Add(LuaUserDataObject); } LuaUserDataObject->ReceiveLuaUserDataTableInit(); return FLuaValue(LuaUserDataObject); } return FLuaValue(); } void ULuaState::SetLuaUserDataField(FLuaValue UserData, const FString & Key, FLuaValue Value) { if (UserData.Type != ELuaValueType::UObject || !UserData.Object) return; if (ULuaComponent* LuaComponent = Cast<ULuaComponent>(UserData.Object)) { LuaComponent->LuaSetField(Key, Value); return; } if (ULuaUserDataObject* LuaUserDataObject = Cast<ULuaUserDataObject>(UserData.Object)) { LuaUserDataObject->LuaSetField(Key, Value); return; } } FLuaValue ULuaState::GetLuaUserDataField(FLuaValue UserData, const FString & Key) { if (UserData.Type != ELuaValueType::UObject || !UserData.Object) return FLuaValue(); if (ULuaComponent* LuaComponent = Cast<ULuaComponent>(UserData.Object)) { return LuaComponent->LuaGetField(Key); } if (ULuaUserDataObject* LuaUserDataObject = Cast<ULuaUserDataObject>(UserData.Object)) { return LuaUserDataObject->LuaGetField(Key); } return FLuaValue(); } const void* ULuaState::ToPointer(int Index) { return lua_topointer(L, Index); } void ULuaState::LuaStateInit() { } void ULuaState::GCLuaDelegatesCheck() { TSet<TWeakObjectPtr<UObject>> DeadObjects; for (TPair<TWeakObjectPtr<UObject>, FLuaDelegateGroup>& Pair : LuaDelegatesMap) { if (!Pair.Key.IsValid()) { DeadObjects.Add(Pair.Key); } } for (TWeakObjectPtr<UObject>& WeakObjectPtr : DeadObjects) { LuaDelegatesMap.Remove(WeakObjectPtr); } } void ULuaState::RegisterLuaDelegate(UObject * InObject, ULuaDelegate * InLuaDelegate) { FLuaDelegateGroup* LuaDelegateGroup = LuaDelegatesMap.Find(InObject); if (LuaDelegateGroup) { LuaDelegateGroup->LuaDelegates.Add(InLuaDelegate); } else { FLuaDelegateGroup NewLuaDelegateGroup; NewLuaDelegateGroup.LuaDelegates.Add(InLuaDelegate); LuaDelegatesMap.Add(InObject, NewLuaDelegateGroup); } } void ULuaState::UnregisterLuaDelegatesOfObject(UObject* InObject) { LuaDelegatesMap.Remove(InObject); } TArray<FString> ULuaState::GetPropertiesNames(UObject * InObject) { TArray<FString> Names; if (!InObject) { return Names; } UClass* Class = InObject->GetClass(); if (!Class) { return Names; } #if ENGINE_MAJOR_VERSION > 4 || ENGINE_MINOR_VERSION >= 25 for (TFieldIterator<FProperty> It(Class); It; ++It) #else for (TFieldIterator<UProperty> It(Class); It; ++It) #endif { Names.Add((*It)->GetName()); } return Names; } TArray<FString> ULuaState::GetFunctionsNames(UObject * InObject) { TArray<FString> Names; if (!InObject) { return Names; } UClass* Class = InObject->GetClass(); if (!Class) { return Names; } for (TFieldIterator<UFunction> It(Class); It; ++It) { Names.Add((*It)->GetName()); } return Names; } void ULuaState::AddLuaValueToLuaState(const FString & Name, FLuaValue LuaValue) { SetFieldFromTree(Name, LuaValue, true); } FLuaValue ULuaState::RunString(const FString & CodeString, FString CodePath) { FLuaValue ReturnValue; if (CodePath.IsEmpty()) { CodePath = CodeString; } if (!RunCode(CodeString, CodePath, 1)) { if (bLogError) LogError(LastError); ReceiveLuaError(LastError); } else { ReturnValue = ToLuaValue(-1); } Pop(); return ReturnValue; }
9ef2f339c7a3f175d1197d212333f569fd2cad7b
c9fd44fa1cd68926f5bb4a4deaf7dc5b6ec59418
/QmlCppExample/valueobject.h
e045e4502a25874130bb347aa07611c3304ed4d8
[]
no_license
jryannel/ubuntu-qtquick-webinar
a18e4ba7c62151ad5edc812e2441374f7142f292
4433f75b2cb245a5399a81fc30719baffe8e73fc
refs/heads/master
2016-09-05T09:51:58.873335
2011-04-15T15:01:52
2011-04-15T15:01:52
1,619,384
0
0
null
null
null
null
UTF-8
C++
false
false
388
h
valueobject.h
#ifndef VALUEOBJECT_H #define VALUEOBJECT_H #include <QtGui> class ValueObject : public QObject { Q_OBJECT Q_PROPERTY(QColor value READ value WRITE setValue NOTIFY valueChanged) public: ValueObject(QObject *parent=0); void setValue(const QColor& value); QColor value() const; signals: void valueChanged(); private: QColor _value; }; #endif // VALUEOBJECT_H
51225db2cbf1acd41dfcb76601bad789c9186b44
683368f51482729f1cdd6ee9a7c3024230772933
/Homeworks/07. semester/Containers/Containers.Phone/item.hpp
2a4e58a9571a2ccce7bbb12eb2bf8cbe09e182fa
[]
no_license
vajanko/Algorithms
679f150b49c493c045c44c6f69aafc65ea192eb7
cfbbaece13df5935ac91e467682df053fa058436
refs/heads/master
2020-12-24T21:00:28.953028
2016-04-25T14:14:26
2016-04-25T14:14:26
57,046,795
0
0
null
null
null
null
UTF-8
C++
false
false
504
hpp
item.hpp
#pragma once #include<string> #include<iostream> struct item { typedef unsigned long long num_type; typedef std::string text_type; text_type surname; text_type name; num_type number; text_type direction; friend std::ostream & operator<<(std::ostream &stream, const item& item); friend std::istream & operator>>(std::istream &istream, item& item); bool operator<(const item &item); void parse(std::istream& str); void print(std::ostream& stream) const; std::string to_string() const; };
1532ed30d7c3e537d1aca0007b12f254937de4bd
fe81cb4ae381c48b65eabf419a38fc7fdcc79fda
/Lilla spelprojektet/Code/Camera.cpp
b7517fa3db5c09d1c793679969802c5175b7ae4e
[]
no_license
Noise-filter/Lilla_spelprojektet
02252e94af9406a30ca6123dba025e56aaeacb44
12187b3128113c43e3dec4483c6dc6ffd784ed8a
refs/heads/master
2020-04-14T12:56:05.697488
2013-06-05T11:03:15
2013-06-05T11:03:15
9,350,331
0
0
null
null
null
null
UTF-8
C++
false
false
3,483
cpp
Camera.cpp
#include "Camera.h" Camera::Camera() { this->m_position = Vec3(0, 50, 0); this->mRight = Vec3(1, 0, 0); this->mUp = Vec3(0, 1, 0); this->mLook = Vec3(0, 0, 1); } Camera::~Camera() { } void Camera::SetPosition(const Vec3& v) { this->m_position = v; } Vec3 Camera::GetPosition()const { return this->m_position; } Vec3 Camera::GetRight()const { return this->mRight; } Vec3 Camera::GetUp()const { return this->mUp; } Vec3 Camera::GetLook()const { return this->mLook; } float Camera::GetNearZ()const { return this->mNearZ; } float Camera::GetFarZ()const { return this->mFarZ; } float Camera::GetAspect()const { return this->mAspect; } Vec3 Camera::CrossMatrix(const Vec3& vector, const D3DXMATRIX& matrix) { Vec3 vec; vec.x = matrix._11*vector.x + matrix._12*vector.y + matrix._13*vector.z; vec.y = matrix._21*vector.x + matrix._22*vector.y + matrix._23*vector.z; vec.z = matrix._31*vector.x + matrix._32*vector.y + matrix._33*vector.z; return vec; } void Camera::SetLens(float fovY, float aspect, float zn, float zf) { this->mFovY = fovY; this->mAspect = aspect; this->mNearZ = zn; this->mFarZ = zf; float yScale = tan((PI*0.5f) - (mFovY*0.5f)); float xScale = yScale/this->mAspect; mProj = D3DXMATRIX(xScale, 0, 0, 0, 0, yScale, 0, 0, 0, 0, zf/(zf-zn), 1, 0, 0, -zn*zf/(zf-zn), 0); } void Camera::LookAt(Vec3 pos, Vec3 target, Vec3 worldUp) { Vec3 L; D3DXVec3Subtract(&L, &target, &pos); D3DXVec3Normalize(&L, &L); Vec3 R; D3DXVec3Cross(&R, &worldUp, &L); D3DXVec3Normalize(&R, &R); Vec3 U; D3DXVec3Cross(&U, &L, &R); this->m_position = pos; this->mLook = L; this->mRight = R; this->mUp = U; } D3DXMATRIX Camera::View()const { return this->mView; } D3DXMATRIX Camera::Proj()const { return this->mProj; } D3DXMATRIX Camera::ViewsProj()const { D3DXMATRIX M; D3DXMatrixMultiply(&M, &this->mView, &this->mProj); return M; } void Camera::Walk(float dist) { this->m_position += dist*Vec3(1,0,0); } void Camera::Strafe(float dist) { this->m_position += dist*this->mRight; } void Camera::Pitch(float angle) { float radians = angle * 0.0174532925f; D3DXMATRIX R; D3DXMatrixRotationAxis(&R, &-mRight, radians); this->mUp = CrossMatrix(this->mUp, R); this->mLook = CrossMatrix(this->mLook, R); } void Camera::Yaw(float angle) { float radians = angle * 0.0174532925f; D3DXMATRIX R; Vec3 up(0,1,0); D3DXMatrixRotationAxis(&R, &-up, radians); this->mRight = CrossMatrix(this->mRight, R); this->mUp = CrossMatrix(mUp, R); this->mLook = CrossMatrix(this->mLook, R); } void Camera::UpdateViewMatrix() { D3DXVec3Normalize(&this->mLook, &this->mLook); D3DXVec3Cross(&this->mUp, &this->mLook, &this->mRight); D3DXVec3Normalize(&this->mUp, &this->mUp); D3DXVec3Cross(&this->mRight, &this->mUp, &this->mLook); float x = -D3DXVec3Dot(&this->m_position, &mRight); float y = -D3DXVec3Dot(&this->m_position, &mUp); float z = -D3DXVec3Dot(&this->m_position, &mLook); this->mView(0, 0) = this->mRight.x; this->mView(1, 0) = this->mRight.y; this->mView(2, 0) = this->mRight.z; this->mView(3, 0) = x; this->mView(0, 1) = this->mUp.x; this->mView(1, 1) = this->mUp.y; this->mView(2, 1) = this->mUp.z; this->mView(3, 1) = y; this->mView(0, 2) = this->mLook.x; this->mView(1, 2) = this->mLook.y; this->mView(2, 2) = this->mLook.z; this->mView(3, 2) = z; this->mView(0, 3) = 0.0f; this->mView(1, 3) = 0.0f; this->mView(2, 3) = 0.0f; this->mView(3, 3) = 1.0f; }
d69850a696e1c8f961678a697f851fbf40886ac6
2489f20116dfa10e4514b636cbf92a6036edc21a
/tojcode/2028.cpp
af8b649d90cdbb322a37b170a649d4c1c3359f08
[]
no_license
menguan/toj_code
7db20eaffce976932a3bc8880287f0111a621a40
f41bd77ee333c58d5fcb26d1848a101c311d1790
refs/heads/master
2020-03-25T04:08:41.881068
2018-08-03T05:02:38
2018-08-03T05:02:38
143,379,558
1
0
null
null
null
null
UTF-8
C++
false
false
1,423
cpp
2028.cpp
#include<stdio.h> #include<string.h> #include<ctype.h> #include<iostream> #include<string> #include<cstdlib> int main() { int m,n,i,j,num[20],max,t=1,a,k,len; char word[20][20],excuse[20][71],ch[71]; while(scanf("%d%d",&m,&n)!=EOF) { getchar(); for(i=0; i<m; i++) { scanf("%s",word[i]); getchar(); } memset(num,0,sizeof(num)); max=0; for(i=0; i<n; i++) { gets(excuse[i]); len=strlen(excuse[i]); for(j=0; j<len; j++) { a=0; while(isalpha(excuse[i][j])) { ch[a++]=tolower(excuse[i][j]); j++; } if(a>0) { ch[a]='\0'; for(k=0; k<m; k++) { if(strcmp(ch,word[k])==0) { num[i]++;break; } } } } max=max>num[i]?max:num[i]; } printf("Excuse Set #%d\n",t++); for(i=0; i<n; i++) { if(num[i]==max) { printf("%s\n",excuse[i]); } } printf("\n"); } return 0; }
74a0a302d5123832da2d19b4269797723ba41984
f0f07044710c3b4ceb18d9439ce5cc3f8438f495
/src/synth/voice.cpp
898d164e10dad006c72627dfec51da3bf518f3ee
[]
no_license
botio/ps-01
80b36278edd8ff76eeb070b407c49e1d599bc9a6
4ed2147468f0c87063df036fe2dc40b0c33e4fde
refs/heads/master
2022-03-26T04:34:33.294313
2019-12-07T14:09:13
2019-12-07T14:09:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
cpp
voice.cpp
#include "voice.h" Voice::Voice() {} void Voice::setWaveform(Waveform waveform) { oscillator.setWaveform(waveform); } void Voice::setFrequency(float frequency) { oscillator.setFrequency(frequency); } void Voice::setPulseWidth(uint16_t pulseWidth) { oscillator.setPulseWidth(pulseWidth); } void Voice::setADSR(uint16_t attack, uint16_t decay, uint8_t sustain, uint16_t release) { adsr.setAttack(attack); adsr.setDecay(decay); adsr.setSustain(sustain); adsr.setRelease(release); } void Voice::setGate(bool gate) { adsr.setGate(gate); } void Voice::setChannel(Channel channel) { _channel = channel; } bool Voice::isAudibleInChannel(Channel channel) { return (_channel == CH_BOTH) || (_channel == channel); } int16_t Voice::getSample() { int16_t sample = oscillator.getSample(); sample = adsr.apply(sample); return sample; } void Voice::clock() { _clock++; oscillator.clock(); adsr.clock(); } void Voice::debug() { // oscillator.debug(); }
5ca442e65c905697789fd3d84bc8ba609864a145
4a5faf8daf58caed9c4f5ccce301d1376a436292
/traces_analyzer/source/plugin_frame.cpp
c0e2743f5d8cce3e6ebfaa8edefca15fe0703863
[]
no_license
aicpp/utils
faa4cef84e5d60223cffa67711aa9d77de4be6f5
29aaff51b7635aad513491b44f34b0e27f6aa05a
refs/heads/master
2020-08-02T14:27:03.326614
2019-10-13T16:48:36
2019-10-13T16:48:36
211,388,372
1
0
null
2019-09-27T19:28:44
2019-09-27T19:28:44
null
WINDOWS-1251
C++
false
false
12,198
cpp
plugin_frame.cpp
#include "resource.h" #include "plugin_frame.h" #include "registry.h" #include "scintilla.h" #include "helpers/check.h" #include "npp/scintilla.h" #include "npp/menu_cmd_id.h" #include "afxvisualmanagerofficexp.h" #include <afxpriv.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // User windows message #define WM_UPDATE_TOOLBAR WM_USER + 100 BEGIN_MESSAGE_MAP(PluginFrame, CFrameWndEx) ON_WM_CREATE() ON_WM_CLOSE() ON_WM_WINDOWPOSCHANGED() ON_MESSAGE(WM_UPDATE_TOOLBAR, &PluginFrame::OnUpdateToolbar) ON_UPDATE_COMMAND_UI(ID_TRACES_PARSERS, &PluginFrame::OnUpdateTracesParserComboBox) ON_UPDATE_COMMAND_UI(ID_PROCESS_START_STOP, &PluginFrame::OnUpdateProcessStartButton) ON_COMMAND(ID_FILE_NEW, &PluginFrame::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &PluginFrame::OnFileOpen) ON_COMMAND(ID_FILE_SAVE, &PluginFrame::OnFileSave) ON_COMMAND(ID_PROCESS_START_STOP, &PluginFrame::OnToolbarProcesStart) END_MESSAGE_MAP() PluginFrame::PluginFrame(PluginInfo const& info) : m_info(info), m_notepad(info.npp), m_startProcessButtonState(StartProcessButtonState::Start) { // Путь потом будем брать из настроек if (!m_tracesParserProvider.Create(m_notepad.GetPluginsConfigDir())) MessageBox(TEXT("Failed to load traces templates"), m_info.name.c_str(), MB_OK | MB_ICONERROR); CWinApp* const application = AfxGetApp(); CRect windowRect(0, 0, static_cast<int>(application->GetProfileInt(REG_SECTION_FRAME, REG_ENTRY_FRAME_LAST_PLACE_WIDTH, CW_USEDEFAULT)), static_cast<int>(application->GetProfileInt(REG_SECTION_FRAME, REG_ENTRY_FRAME_LAST_PLACE_HEIGHT, CW_USEDEFAULT))); windowRect.OffsetRect( static_cast<int>(application->GetProfileInt(REG_SECTION_FRAME, REG_ENTRY_FRAME_LAST_PLACE_LEFT, CW_USEDEFAULT)), static_cast<int>(application->GetProfileInt(REG_SECTION_FRAME, REG_ENTRY_FRAME_LAST_PLACE_TOP, CW_USEDEFAULT))); WIN_CHECK(Create(NULL, m_info.name.c_str(), WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, windowRect, NULL, MAKEINTRESOURCE(IDR_MAINFRAME))); CMFCToolBar::GetImages()->Load(IDB_PROCESS_START, 0, TRUE); CMFCToolBar::GetImages()->Load(IDB_PROCESS_CANCEL, 0, TRUE); } PluginFrame::~PluginFrame() { CMFCToolBar::GetImages()->CleanUp(); } void PluginFrame::OnStartProcess() { m_startProcessButtonState = StartProcessButtonState::Cancel; PostMessage(WM_UPDATE_TOOLBAR, 0, 0); } void PluginFrame::OnFinishProcess() { m_startProcessButtonState = StartProcessButtonState::Start; PostMessage(WM_UPDATE_TOOLBAR, 0, 0); } LRESULT PluginFrame::OnUpdateToolbar(WPARAM wParam, LPARAM lParam) { m_toolbar.OnUpdateCmdUI(this, TRUE); return 0; } int PluginFrame::OnCreate(LPCREATESTRUCT createStruct) { if (CFrameWndEx::OnCreate(createStruct) == -1) return -1; //CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOfficeXP)); RedrawWindow(nullptr, nullptr, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE); HICON const smallIcon = reinterpret_cast<HICON>(::GetClassLongPtrW(m_info.npp, GCLP_HICONSM)); HICON const bigIcon = reinterpret_cast<HICON>(::GetClassLongPtrW(m_info.npp, GCLP_HICON)); ASSERT(smallIcon && bigIcon); SetIcon(smallIcon, false); SetIcon(bigIcon, true); if (!m_toolbar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC)) return -1; ResetToolbar(); m_toolbar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_toolbar); CDockingManager::SetDockingMode(DT_SMART); EnableAutoHidePanes(CBRS_ALIGN_ANY); return 0; } void PluginFrame::OnClose() { if (SaveModifiedScheme()) { m_schemeContext.reset(nullptr); CFrameWndEx::OnClose(); } } void PluginFrame::OnWindowPosChanged(WINDOWPOS* wndPos) { CFrameWndEx::OnWindowPosChanged(wndPos); CWinApp* pApp = AfxGetApp(); pApp->WriteProfileInt(REG_SECTION_FRAME, REG_ENTRY_FRAME_LAST_PLACE_LEFT, wndPos->x); pApp->WriteProfileInt(REG_SECTION_FRAME, REG_ENTRY_FRAME_LAST_PLACE_TOP, wndPos->y); pApp->WriteProfileInt(REG_SECTION_FRAME, REG_ENTRY_FRAME_LAST_PLACE_WIDTH, wndPos->cx); pApp->WriteProfileInt(REG_SECTION_FRAME, REG_ENTRY_FRAME_LAST_PLACE_HEIGHT, wndPos->cy); } void PluginFrame::OnUpdateTracesParserComboBox(CCmdUI *pCmdUI) { if (pCmdUI->m_nID) { CMFCToolBarComboBoxButton* tracesParserComboBox = dynamic_cast<CMFCToolBarComboBoxButton*>(m_toolbar.GetButton(m_toolbar.CommandToIndex(pCmdUI->m_nID))); bool const enable = !!tracesParserComboBox->GetCount(); if (!enable) tracesParserComboBox->SetText(TEXT("No parsers")); pCmdUI->Enable(enable); } } void PluginFrame::OnUpdateProcessStartButton(CCmdUI *pCmdUI) { CMFCToolBarButton* processStartButton = m_toolbar.GetButton(m_toolbar.CommandToIndex(ID_PROCESS_START_STOP)); int imageIndex = 0; if (m_startProcessButtonState == StartProcessButtonState::Start) imageIndex = 0; else if (m_startProcessButtonState == StartProcessButtonState::Cancel) imageIndex = 1; else ASSERT(false); if (processStartButton->GetImage() != imageIndex) { processStartButton->SetImage(imageIndex); m_toolbar.InvalidateButton(m_toolbar.CommandToIndex(ID_PROCESS_START_STOP)); } CMFCToolBarComboBoxButton* tracesParserComboBox = dynamic_cast<CMFCToolBarComboBoxButton*>(m_toolbar.GetButton(m_toolbar.CommandToIndex(ID_TRACES_PARSERS))); pCmdUI->Enable(!!tracesParserComboBox->GetCount()); } void PluginFrame::OnToolbarProcesStart() { if (!m_schemeContext) { MessageBox(TEXT("Analysis scheme not loaded"), m_info.name.c_str(), MB_OK | MB_ICONERROR); return; } switch (m_startProcessButtonState) { case StartProcessButtonState::Start: { CMFCToolBarComboBoxButton* tracesParserComboBox = dynamic_cast<CMFCToolBarComboBoxButton*>(m_toolbar.GetButton(m_toolbar.CommandToIndex(ID_TRACES_PARSERS))); if (tracesParserComboBox->GetCount() == 0) { MessageBox(TEXT("Parsers are not loaded"), m_info.name.c_str(), MB_OK | MB_ICONERROR); return; } DWORD_PTR const parserIndex = tracesParserComboBox->GetItemData(tracesParserComboBox->GetCurSel()); TracesParser const tracesParser = m_tracesParserProvider.GetParser(static_cast<size_t>(parserIndex)); HWND const scintillaHandle = m_notepad.GetCurrentScintilla() ? m_info.scintillaSecond : m_info.scintillaMain; Scintilla const scintilla(scintillaHandle); bool result = m_schemeContext->StartAnalysis(m_notepad, scintilla, tracesParser, this); if (!result) MessageBox(TEXT("The analysis process is already in progress"), m_info.name.c_str(), MB_OK | MB_ICONINFORMATION); break; } case StartProcessButtonState::Cancel: { m_schemeContext->CancelAnalysis(); break; } default: ASSERT(false); } } void PluginFrame::OnFileNew() { MessageBox(TEXT("Feature not available yet"), m_info.name.c_str(), MB_OK | MB_ICONINFORMATION); return; if (SaveModifiedScheme()) { m_schemeContext.reset(new SchemeContext(this)); UpdateCaption(); } } void PluginFrame::OnFileOpen() { if (SaveModifiedScheme()) { CFileDialog dialog( TRUE, SCHEME_FILE_EXTENSTION, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, SCHEME_DEFAULT_FILE_NAME_FILTER); //if (dialog.DoModal() == IDOK) { std::unique_ptr<SchemeContext> newSchemeContext(new SchemeContext(this)); if (newSchemeContext->Create(TEXT("D:\\scheme.xml") /*dialog.GetPathName().GetBuffer()*/)) { m_schemeContext = std::move(newSchemeContext); UpdateCaption(); } else MessageBox(TEXT("Failed to open analyzes scheme"), m_info.name.c_str(), MB_OK | MB_ICONERROR); } } if (!m_schemeContext) DestroyWindow(); } void PluginFrame::OnFileSave() { SaveScheme(); } bool PluginFrame::SaveModifiedScheme() { if (m_schemeContext) { Scheme const& scheme = m_schemeContext->GetScheme(); if (scheme.IsModified()) { tstring const displayFileName = scheme.GetDisplayFileName(); tstring messageText(TEXT("You want to save changes to the file \"")); messageText += displayFileName.empty() ? SCHEME_DEFAULT_FILE_NAME : displayFileName; messageText += TEXT("\"?"); switch (MessageBox(messageText.c_str(), m_info.name.c_str(), MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON1)) { case IDYES: { if (!SaveScheme()) return false; break; } case IDNO: { break; } case IDCANCEL: default: { return false; } } } } return true; } bool PluginFrame::SaveScheme() { MessageBox(TEXT("Feature not available yet"), m_info.name.c_str(), MB_OK | MB_ICONINFORMATION); return false; if (m_schemeContext) { Scheme& scheme = m_schemeContext->GetScheme(); tstring const fileName = scheme.GetFileName(); bool result = false; if (fileName.empty()) { CFileDialog dialog( FALSE, SCHEME_FILE_EXTENSTION, SCHEME_DEFAULT_FILE_NAME, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, SCHEME_DEFAULT_FILE_NAME_FILTER); if (dialog.DoModal() == IDOK) result = scheme.Save(dialog.GetPathName().GetBuffer()); else return false; } else result = scheme.Save(); if (!result) MessageBox(TEXT("Failed to save analyzes scheme"), m_info.name.c_str(), MB_OK | MB_ICONERROR); return result; } else { return false; } } void PluginFrame::ResetToolbar() { m_toolbar.RemoveAllButtons(); m_toolbar.SetSizes(CSize(22, 22), CSize(16, 16)); // ID_TRACES_PARSERS m_toolbar.InsertButton( CMFCToolBarComboBoxButton(ID_TRACES_PARSERS, -1, CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP, 200)); CMFCToolBarComboBoxButton* tracesParserComboBox = dynamic_cast<CMFCToolBarComboBoxButton*>(m_toolbar.GetButton(m_toolbar.CommandToIndex(ID_TRACES_PARSERS))); tracesParserComboBox->EnableWindow(true); tracesParserComboBox->SetCenterVert(); tracesParserComboBox->SetDropDownHeight(25); tracesParserComboBox->SetFlatMode(); size_t const parsersCount = m_tracesParserProvider.GetCountParsers(); if (parsersCount) { for (size_t i = 0; i < parsersCount; ++i) { tstring const parserName = ToTString(m_tracesParserProvider.GetParser(i).GetName()); if (parserName.empty()) continue; tracesParserComboBox->AddItem(parserName.c_str(), static_cast<DWORD_PTR>(i)); } } tracesParserComboBox->SelectItem(0); // ID_PROCESS_START_STOP m_toolbar.InsertButton( CMFCToolBarButton(ID_PROCESS_START_STOP, 0)); } void PluginFrame::UpdateCaption() { tstring caption; if (m_schemeContext) { tstring schemeName = m_schemeContext->GetScheme().GetDisplayFileName(); if (schemeName.empty()) schemeName = SCHEME_DEFAULT_FILE_NAME; caption += schemeName; caption += TEXT(" - "); } caption += m_info.name; SetWindowText(caption.c_str()); }
103a79ca47fdd1e7814abdffada0ec1d83fb37a5
83f70d8409f28fcf08c17063ada3da8bc0485130
/echantillons_sensors/joystick/joystick.ino
fbb081ab948d3fd0144c1000ca73bfb46cef418b
[]
no_license
n1n3n1n3/kikicode-arduino
28fb06fa914166d02e62284d60d298ed8523bd7e
e7e72dabc874f9b7ef3da8a0b22696f8039113d0
refs/heads/master
2022-11-15T10:48:25.577045
2020-07-10T17:16:36
2020-07-10T17:16:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,299
ino
joystick.ino
/* Ks0008 keyestudio Joystick Module _________________________________ | SETUP | |Sensor pin :: Particle pin | | + :: 3.3v | | - :: GND | | B :: D0 | | X :: A0 | | Y :: A1 | |_________________________________| SPECIFICATIONS: digital button + xy analog map maps x and on from 0 to 4095 src: https://wiki.keyestudio.com/Ks0008_keyestudio_Joystick_Module */ #define JoyStick_X A4 //x #define JoyStick_Y A5 //y #define JoyStick_Z 4 //key #define LED 13 int x,y,z; void setup() { // pinMode(JoyStick_Z, INPUT); Serial.begin(9600); // 9600 bps } void loop() { x=analogRead(JoyStick_X); y=analogRead(JoyStick_Y); z=digitalRead(JoyStick_Z); Serial.print("x: "); Serial.print(x ,DEC); Serial.print(", y:"); Serial.print(y ,DEC); Serial.print(", z:"); Serial.println(z ,DEC); readJoystick(); delay(1000); } void readJoystick(){ if (x <= 400){ Serial.print("bas "); } else if (x >= 600){ Serial.print("haut "); } else { Serial.print("centre "); } if (y <= 400){ Serial.println("gauche "); } else if (y >= 600){ Serial.println("droite "); } else Serial.println("centre "); }
84357f234647e63773b8ade68b7c4e7231aa2f10
482ec3480e8418dda62f85a5359e70c89256f1a8
/cpp/CPP_NEW/packet_parser/include/Processor.hpp
d5c512373e1ed004adb47de5ad0a49956da501b3
[]
no_license
rajatgirotra/study
84d319968f31f78798a56362546f21d22abd7ae7
acbb6d21a8182feabcb3329e17c76ac3af375255
refs/heads/master
2023-09-01T20:48:31.137541
2023-08-29T01:41:17
2023-08-29T01:41:17
85,041,241
6
1
null
2023-05-01T19:25:38
2017-03-15T07:17:24
C++
UTF-8
C++
false
false
1,830
hpp
Processor.hpp
#pragma once #include "InputFormat.hpp" #include <array> #include <cstdint> #include <queue> #include <cassert> #include <memory> #include <fstream> class OrderManager; class Processor { // should be sufficient to hold messages that straddle multiple UDP packets. std::array<char, (1<<16) + 100> m_buffer{}; std::uint32_t m_bytesAvailable {0}; // number of bytes that can be consumed from the buffer. std::priority_queue<Packet, std::vector<Packet>, std::greater<Packet>> m_outOfSeqPkts {}; std::uint32_t m_nextExpectedSeqNo {1}; std::unique_ptr<OrderManager> m_orderManager; std::ofstream m_outFile; public: Processor(); ~Processor(); std::uint32_t nextExpectedSeqNo() const noexcept { return m_nextExpectedSeqNo; } void nextExpectedSeqNo(std::uint32_t val) noexcept { m_nextExpectedSeqNo = val; } void queue(Packet&& pkt) { m_outOfSeqPkts.push(std::move(pkt)); } // return true if the sequence number of first out of sequence packet is same as next expected seq no bool hasNext() const noexcept { return !m_outOfSeqPkts.empty() && m_outOfSeqPkts.top().m_seqNo == m_nextExpectedSeqNo; } Packet getNext() noexcept; void processPacket(const Packet& pkt); private: std::uint32_t doProcess(char* payload, std::size_t payloadLen); void processAddOrderMessage(char* payload, std::size_t payloadLen); void processExecuteOrderMessage(char* payload, std::size_t payloadLen); void processCancelOrderMessage(char* payload, std::size_t payloadLen); void processReplaceOrderMessage(char* payload, std::size_t payloadLen); template <std::size_t N> void write(const std::array<char, N>&); }; template<std::size_t N> inline void Processor::write(const std::array<char, N>& buffer) { m_outFile.write(buffer.data(), buffer.size()); }
bd8a6b9e7ca3526f34f4e38aca48d2eeb8349573
6a0ae86bca2d2ece6c92efd5594c0e3b1777ead7
/EDBRCommon/plugins/PTWeightAnalyzer.cc
8677899d4f8afe8e4bdf6084ed783a7549d59717
[]
no_license
wangmengmeng/ExoDiBosonResonances
c4b5d277f744e1b1986df9317ac60b46d202a29f
bf5d2e79f59ad25c7a11e7f97552e2bf6a283428
refs/heads/master
2016-09-06T14:54:53.245508
2014-06-05T15:02:37
2014-06-05T15:02:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
cc
PTWeightAnalyzer.cc
#include "ExoDiBosonResonances/EDBRCommon/plugins/PTWeightAnalyzer.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "FWCore/Common/interface/TriggerNames.h" #include "DataFormats/Common/interface/TriggerResults.h" PTWeightAnalyzer::PTWeightAnalyzer(const edm::ParameterSet& iConfig):weightTag_(iConfig.getParameter<edm::InputTag>("src")), selectorPath_(iConfig.getParameter<std::string>("selectorPath")), h_(0){ edm::Service<TFileService> fs; h_ = fs->make<TH1F>( "events" , "events", 4, -.5, 3.5 ); h_->GetXaxis()->SetBinLabel(1,"Total"); h_->GetXaxis()->SetBinLabel(2,"weighted"); h_->GetXaxis()->SetBinLabel(3,"Selected"); h_->GetXaxis()->SetBinLabel(4,"Weighted"); } void PTWeightAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup&){ edm::Handle<double> weightHandle; iEvent.getByLabel(weightTag_, weightHandle); edm::Handle<edm::TriggerResults> triggerResults; iEvent.getByLabel(edm::InputTag("TriggerResults"), triggerResults); bool selectedEvent = false; const edm::TriggerNames & trigNames = iEvent.triggerNames(*triggerResults); unsigned int pathIndex = trigNames.triggerIndex(selectorPath_); bool pathFound = (pathIndex<trigNames.size()); // pathIndex >= 0, since pathIndex is unsigned if (pathFound) { if (triggerResults->accept(pathIndex)) selectedEvent = true; } h_->Fill(0.,1.); h_->Fill(1.,*weightHandle); if(selectedEvent){ h_->Fill(2.,1.); h_->Fill(3.,*weightHandle); } }
fa7df31430f6ad09c9b148d1272f0e958412b100
f130e28299dadd1e18ef3533620e3e548328e24f
/BrowsifyAPI.h
57b112af83633b0ee529a8ad4111918645fd8fc5
[]
no_license
nessup/Browsify-npapi
b1ee030924735d88f506757a4e2a17f53cd783e5
7ad9b42514a1e1a88e9977447323e4ba15f3d41f
refs/heads/master
2021-04-24T17:53:42.588235
2012-08-26T20:28:18
2012-08-26T20:28:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,156
h
BrowsifyAPI.h
/**********************************************************\ Auto-generated BrowsifyAPI.h \**********************************************************/ #include <string> #include <sstream> #include <boost/weak_ptr.hpp> #include "JSAPIAuto.h" #include "BrowserHost.h" #include "BrowsifyPlugin.h" #ifndef H_BrowsifyAPI #define H_BrowsifyAPI class SpotifyController; class BrowsifyAPI : public FB::JSAPIAuto { public: BrowsifyAPI(const BrowsifyPluginPtr& plugin, const FB::BrowserHostPtr& host); ~BrowsifyAPI(); BrowsifyPluginPtr getPlugin(); void playOrPause(); void goToPreviousTrack(); void goToNextTrack(); bool isShuffling(); void setShuffling(bool shuffling); bool isRepeating(); void setRepeating(bool repeating); // Read only property bool isSpotifyPlaying(); // Read-only property ${PROPERTY.ident} std::string get_version(); private: typedef boost::shared_ptr<SpotifyController> SpotifyControllerPtr; BrowsifyPluginWeakPtr m_plugin; FB::BrowserHostPtr m_host; SpotifyControllerPtr m_player; std::string m_testString; }; #endif // H_BrowsifyAPI
df5f9e752f4faf9c1e97943f98df1f55058b4cd1
e6a41679bc053afcc847577f3428410e7b907637
/towers/FlameRingTower.cpp
d2941be9af7e6e4e92a5947222f3364d7d4a29d4
[]
no_license
ivancea/TowerDefense
d61acccee6ed82ba3cf675c0b7be359df3bafcf9
f4e3be26cea5342407b9e708cc433dd801b418df
refs/heads/master
2021-09-18T16:39:00.668766
2021-09-01T22:21:58
2021-09-01T22:21:58
50,257,135
2
0
null
null
null
null
UTF-8
C++
false
false
1,162
cpp
FlameRingTower.cpp
#include "FlameRingTower.hpp" #include "entities/FlameRing.hpp" int FlameRingTower::id = -1; FlameRingTower::FlameRingTower(){ _id = id; _ticksForShoot = 30; _ticksBetweenShoots = 30; _minRange = 5; _maxRange = 80; _ringVelocity = 2.5; _ringActualRange = _minRange; _ringSize = 30; _damage = 0.15; } TowerEvent FlameRingTower::tick(){ if(_ticksForShoot <= 0){ Game::entities.emplace_back( std::make_unique<FlameRing>( Game::getRealPosition(_position), _ringSize, _damage, _ringVelocity, _maxRange, _minRange ) ); _ticksForShoot = _ticksBetweenShoots; }else --_ticksForShoot; return TowerEvent::None; } void FlameRingTower::draw(sf::RenderWindow* window, Vec2d point) const{ int t = Game::pixelsPerSquare/2-2; glColor3ub(255,0,0); glBegin(GL_POLYGON); for(float i=0; i<PI*2.01; i+=PI/360) glVertex2i(point.x+sin(i)*t, point.y+cos(i)*t); glEnd(); } std::unique_ptr<Tower> FlameRingTower::clone() const { return std::make_unique<FlameRingTower>(); }
a471463bc351bab26605f5ddf6ca722c44a2a37b
9f087cfdb02d3f1de0091876fad0504934bef17c
/CustomWindow/Base/DelayReqBase.h
2f7712393713de250cf87e04b4e79a988ff9ebb2
[]
no_license
kknet/qt_client
0ac41592856048510f7c470521845b89f0078a41
6c71db967369f07bd37cfbe52690565e2be9924d
refs/heads/master
2022-04-04T17:24:41.731274
2018-11-08T03:51:11
2018-11-08T03:51:11
null
0
0
null
null
null
null
GB18030
C++
false
false
1,514
h
DelayReqBase.h
#pragma once #include "ThreadInterface.h" #include "Def.h" #include <vector> struct ReqPara { int nFailTry; // 失败后尝试的次数(未启用) int nFailWaitTime; // 失败后下一次等待的间隔时间(未启用) int nCurReqCount; // 当前尝试的次数(未启用) DWORD dLastReqTick; // 上一次请求的时间(未启用) DWORD dIniWait; // 第一次运行时等待的时间(未启用) EReqType eReqType; // 请求类型 vector<string> vPara; // 函数参数 ReqPara() { nFailTry = 2; nFailWaitTime = 0; nCurReqCount = 0; #ifdef _WIN32 dLastReqTick = ::GetTickCount64(); #else //macx??? dLastReqTick = ::mach_absolute_time(); #endif dIniWait = 0; } }; class CReqHandlerBase : public CThreadInferface { public: CReqHandlerBase(void); public: ~CReqHandlerBase(void); // 添加请求 void AddReq( const ReqPara &stReq ); // 设置延期时间 void SetDelayTime( int nTime ); protected: /* 判断添加的一笔请求是否无效(重复或者不需要),父类实现 */ virtual bool IsUseless( ReqPara &stReqInQue, const ReqPara &stReqAdd ); /* 发送所有的请求,父类实现 */ virtual void SendReq( const deque<ReqPara> &deqReq ); protected: int ThreadEntry(); int End(); void OnStart() { }; void OnStop() { }; protected: std::deque<ReqPara> m_deqReq; CCondMutex m_deqCondMutex; int m_nDelayTime; // 延期的时间,毫秒为单位 };
8a562654986056dcf6a841c3728f3e4920e1417e
ca7a7e11bc3253cead10f134424755de71f16fae
/src/Resources/Model.h
da35e1d3d8895e4d6773c154f76f5fa9d785b38e
[]
no_license
sohailshafii/VulkanGame
1335f718dc2fe8b2308423ee7c55cb3b9a7b43ba
abb09546932e7bac8f3a51400ded0242cec5f36c
refs/heads/master
2021-12-11T04:30:11.296531
2021-12-10T06:30:11
2021-12-10T06:30:11
165,705,107
0
0
null
null
null
null
UTF-8
C++
false
false
7,700
h
Model.h
#pragma once // NOTE: these two lines are necessary for hashing!!!! #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/hash.hpp> #include <vector> #include <array> #include <set> #include <unordered_map> #include <glm/glm.hpp> #include "vulkan/vulkan.h" #include "Vertex.h" #include "Math/NoiseGenerator.h" class Model { public: enum class TopologyType : char { TriangleList = 0, TriangleStrip }; struct ModelVert { ModelVert() : position(glm::vec3(0.0f, 0.0f, 0.0f)), normal(glm::vec3(0.0f, 0.0f, 0.0f)), color(glm::vec3(0.0f, 0.0f, 0.0f)), texCoord(glm::vec2(0.0f, 0.0f)) { } ModelVert(const glm::vec3& position) : position(position), normal(glm::vec3(0.0f, 0.0f, 0.0f)), color(glm::vec3(0.0f, 0.0f, 0.0f)), texCoord(glm::vec2(0.0f, 0.0f)) { } ModelVert(const glm::vec3& position, const glm::vec3& normal) : position(position), normal(normal), color(glm::vec3(0.0f, 0.0f, 0.0f)), texCoord(glm::vec2(0.0f, 0.0f)) { } ModelVert(const glm::vec3& position, const glm::vec3& normal, const glm::vec3& color) : position(position), normal(normal), color(color), texCoord(glm::vec2(0.0f, 0.0f)) { } ModelVert(const glm::vec3& position, const glm::vec3& normal, const glm::vec3& color, const glm::vec2& texCoord) : position(position), normal(normal), color(color), texCoord(texCoord) { } bool operator==(const ModelVert& other) const { return position == other.position && normal == other.normal && color == other.color && texCoord == other.texCoord; } glm::vec3 position; glm::vec3 normal; glm::vec3 color; glm::vec2 texCoord; }; struct TriangleEdgeSet { // first edge goes to point 1, second to point 2 uint32_t pointIndex1; uint32_t pointIndex2; TriangleEdgeSet(uint32_t index1, uint32_t index2) : pointIndex1(index1), pointIndex2(index2) { } bool operator<(TriangleEdgeSet const& b) const { bool comp1 = pointIndex1 < b.pointIndex1; return comp1 || (comp1 && pointIndex2 < b.pointIndex2); } }; Model() : modelTopology(TopologyType::TriangleList) {} Model(const std::string& modelPath); Model(const std::vector<ModelVert>& vertices, const std::vector<uint32_t>& indices, TopologyType modelTopology); ~Model(); static std::shared_ptr<Model> CreateQuad(glm::vec3 const& quadOrigin, glm::vec3 const& side1Vec, glm::vec3 const& side2Vec, bool isTriangleStrip); static std::shared_ptr<Model> CreateBox(glm::vec3 const& boxCenter, glm::vec3 const& right, glm::vec3 const& up, glm::vec3 const& forward); static void AddVerticesAndAppendIndices(std::vector<ModelVert> const & originalVerts, std::vector<ModelVert>& destinationVerts, std::vector<uint32_t>& indices, uint32_t indexOffset); static std::shared_ptr<Model> CreatePlane(const glm::vec3& lowerLeft, const glm::vec3& side1Vec, const glm::vec3& side2Vec, uint32_t numSide1Points, uint32_t numSide2Points, NoiseGeneratorType noiseGeneratorType, uint32_t numNoiseLayers = 0); static std::shared_ptr<Model> CreateIcosahedron(float radius, uint32_t numSubdivisions); const std::vector<VertexPos> BuildAndReturnVertsPos() { auto vertsToBuild = std::vector<VertexPos>(); for (auto &modelVert : vertices) { vertsToBuild.push_back(VertexPos(modelVert.position)); } return vertsToBuild; } const std::vector<VertexPosColor> BuildAndReturnVertsPosColor() { auto vertsToBuild = std::vector<VertexPosColor>(); for (auto &modelVert : vertices) { vertsToBuild.push_back(VertexPosColor(modelVert.position, modelVert.color)); } return vertsToBuild; } const std::vector<VertexPosTex> BuildAndReturnVertsPosTex() { auto vertsToBuild = std::vector<VertexPosTex>(); for (auto &modelVert : vertices) { vertsToBuild.push_back(VertexPosTex(modelVert.position, modelVert.texCoord)); } return vertsToBuild; } const std::vector<VertexPosNormalTexCoord> BuildAndReturnVertsPosNormalTexCoord() { auto vertsToBuild = std::vector<VertexPosNormalTexCoord>(); for (auto &modelVert : vertices) { vertsToBuild.push_back(VertexPosNormalTexCoord(modelVert.position, modelVert.normal, modelVert.texCoord)); } return vertsToBuild; } const std::vector<VertexPosColorTexCoord> BuildAndReturnVertsPosColorTexCoord() { auto vertsToBuild = std::vector<VertexPosColorTexCoord>(); for (auto &modelVert : vertices) { vertsToBuild.push_back(VertexPosColorTexCoord(modelVert.position, modelVert.color, modelVert.texCoord)); } return vertsToBuild; } const std::vector<VertexPosNormalColorTexCoord> BuildAndReturnVertsPosNormalColorTexCoord() { auto vertsToBuild = std::vector<VertexPosNormalColorTexCoord>(); for (auto &modelVert : vertices) { vertsToBuild.push_back(VertexPosNormalColorTexCoord(modelVert.position, modelVert.normal, modelVert.color, modelVert.texCoord)); } return vertsToBuild; } const std::vector<uint32_t>& GetIndices() { return indices; } std::vector<ModelVert>& GetVertices() { return vertices; } void AppendVertsAndIndices(std::vector<ModelVert> const & newVertices, std::vector<uint32_t> const & newIndices) { // since the vertices have been appended to the end, their indices are // effectively offsetted by the current size of the array // so if there are N vertices, are adding M verts to it, // the indices of M verts start at N, not at 0 as before uint32_t offsetFromCurrentVerts = (uint32_t)vertices.size(); vertices.reserve(vertices.size() + newVertices.size()); vertices.insert(vertices.end(), newVertices.begin(), newVertices.end()); indices.reserve(indices.size() + newIndices.size()); for (size_t i = 0; i < newIndices.size(); i++) { indices.push_back(newIndices[i] + offsetFromCurrentVerts); } } TopologyType GetTopologyType() const { return modelTopology; } private: std::vector<ModelVert> vertices; std::vector<uint32_t> indices; TopologyType modelTopology; static void GeneratePlaneNoiseAndDerivatives(float** noiseValues, glm::vec3** normals, const glm::vec3& lowerLeft, const glm::vec3& side1Vec, const glm::vec3& side2Vec, uint32_t numSide1Points, uint32_t numSide2Points, NoiseGeneratorType noiseGeneratorType, uint32_t numNoiseLayers); static void AddIcosahedronIndices(std::vector<uint32_t>& indices, uint32_t index1, uint32_t index2, uint32_t index3, std::unordered_map<uint32_t,std::set<TriangleEdgeSet>> & vertexNeighbors); static void SubdivideIcosahedron(std::vector<ModelVert>& vertices, std::vector<uint32_t>& indices, uint32_t numSubdivisions, float radius, std::unordered_map<uint32_t, std::set<TriangleEdgeSet>> & vertexNeighbors); static void ComputeHalfVertex(ModelVert const& v1, ModelVert const& v2, ModelVert& halfVertex, float radius); static void CalculateNormalVectors(std::vector<ModelVert>& vertices, std::unordered_map<uint32_t, std::set<TriangleEdgeSet>>& vertexNeighbors); static glm::vec3 ComputeNormal(uint32_t vertexIndex, std::vector<ModelVert>& vertices, std::unordered_map<uint32_t,std::set<TriangleEdgeSet>> & vertexNeighbors); }; namespace std { template<> struct hash<Model::ModelVert> { size_t operator()(Model::ModelVert const& vertex) const { return (((hash<glm::vec3>()(vertex.position) ^ (hash<glm::vec3>()(vertex.normal) << 1)) >> 1) ^ (hash<glm::vec3>()(vertex.color) << 1) >> 1) ^ (hash<glm::vec2>()(vertex.texCoord) << 1); } }; }
d6f12cc79668ae673e5d8a944ea16025f928e1a1
1d04f970fcab1b0ae8d63390b5223be000beb6ce
/src/MainFrm.h
90632eeb060fdf8df8450a3d17f86e706e6dbeb9
[]
no_license
alexf2/ReliabilityAnalyst
36a480da1964685c9b0aa667cfa4ff86f101b214
56e818a1c83fd49e10564f7349243b1a33025709
refs/heads/master
2021-05-04T23:54:22.512021
2018-02-02T22:09:23
2018-02-02T22:09:23
119,436,304
0
0
null
null
null
null
UTF-8
C++
false
false
3,795
h
MainFrm.h
// MainFrm.h : interface of the TMainFrame class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MAINFRM_H__FE33C088_CBA2_11D1_9887_00504E02C39D__INCLUDED_) #define AFX_MAINFRM_H__FE33C088_CBA2_11D1_9887_00504E02C39D__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "..\\RUDAKOW\\SERVIS\\mymenu.hpp" #include "opt.hpp" #include "globlmsg.hpp" #include "drtool.hpp" using namespace std; #include <memory> #include <list> struct TBtnDescr { UINT uCmd; bool bRight, bPush; }; class TSaveCfgData: public TClassFunc<fstream&, auto_ptr<TMCildOpt>&> { public: TSaveCfgData( fstream& rS ): TClassFunc<fstream&, auto_ptr<TMCildOpt>&>( rS ) { } void operator()( auto_ptr<TMCildOpt>& rArg ) { m_data << *rArg; } }; typedef auto_ptr<TMCildOpt> TMCildOpt_AP; class TMainFrame : public CMDIFrameWnd { DECLARE_DYNAMIC(TMainFrame) public: TMainFrame(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(TMainFrame) virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: virtual ~TMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif void OnUserWnd( CCmdUI* pCmdUI ); void OnAlways( CCmdUI* pCmdUI ); void OnLocalToolUpd( CCmdUI* pCmdUI ); void OnLocalToolTextureUpd( CCmdUI* pCmdUI ); void OnVievSaveOptUpd( CCmdUI* pCmdUI ); void OnVievSaveDesktopUpd( CCmdUI* pCmdUI ); void OnAbout(); void OnAppWindow(); void OnNext(); void OnPriv(); void OnCloseAll(); void SaveCfg( CString& ); void LoadCfg( CString& ); void DefaultPos(); void My_ShowControlBar( int iId, int iFl ); void StoreCfg(); const TMFrOpt& GetOpt() const { return m_opt; } TMCildOpt* GetOptPtr( LPCSTR ); void CheckBrig( bool bFl ) { m_pKeyBrigIt->SetCheckMy( bFl ); } bool IsActive() const { return m_bActive; } TDrToolsManeger m_gdiMgr; protected: // control bar embedded members CStatusBar m_wndStatusBar; auto_ptr<TMSStyleTooolBar> m_apTool; TMSItem *m_pKeyBrigIt; // Generated message map functions protected: void RefreshChildLocalTool(); //{{AFX_MSG(TMainFrame) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnDestroy(); afx_msg void OnClose(); afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); afx_msg void OnPaletteChanged(CWnd* pFocusWnd); afx_msg BOOL OnQueryNewPalette(); afx_msg void OnSysColorChange(); afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized); //}}AFX_MSG LONG OnGLOpenDoc( UINT ui, LONG ll ); afx_msg void OnLocalTool(); afx_msg void OnLocalTexture(); afx_msg void OnVievSaveOpt(); afx_msg void OnVievSaveDesktop(); DECLARE_MESSAGE_MAP() private: TMFrOpt m_opt; bool m_bActive; list<TMCildOpt_AP> m_lstChOpt; bool m_bFirstShow; }; class TCreData: public TClassFunc<TMainFrame*, auto_ptr<TMCildOpt>&> { public: TCreData( TMainFrame* pF ): TClassFunc<TMainFrame*, auto_ptr<TMCildOpt>&>( pF ) { } void operator()( auto_ptr<TMCildOpt>& rArg ) { m_data->PostMessage( globl_iMsgOpenDoc, 0, (LPARAM)rArg.get() ); } }; class TFindOptData { public: TFindOptData( LPCSTR lp ): m_lp( lp ) {}; int operator()( auto_ptr<TMCildOpt>& rArg ) { return !_stricmp( m_lp, (LPCSTR)rArg->m_csPath ); } protected: LPCSTR m_lp; }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MAINFRM_H__FE33C088_CBA2_11D1_9887_00504E02C39D__INCLUDED_)
37968a3b679684b6c19119141f350c136e625537
8cd61aa3ae0f2ea26cc343d27c0841493707b973
/src-antonio1/rvg-lua-xform.h
6670582a6b790a1c1ef9d294775876b98c7c0ee1
[]
no_license
antoniospg/2DCG-2021
f9d603de87c13a7d9ea1d54de52bded6abfad41f
3b49a2cca01c9b87a130e3cfd46708e9803b6524
refs/heads/main
2023-03-02T12:12:24.418989
2021-02-08T13:04:55
2021-02-08T13:04:55
337,068,685
0
0
null
null
null
null
UTF-8
C++
false
false
1,634
h
rvg-lua-xform.h
#ifndef RVG_LUA_XFORM_H #define RVG_LUA_XFORM_H #include "rvg-lua.h" #include "rvg-xform.h" // There are many types of xform: identity, rotation, scaling, translation, // linear, affinity, projectivity. // They are represented by userdata with different metatables in Lua. // We want library functions to be able to accept objects of all these types as // if they were all a single type. // To do so, we declare explicit specializations of function that obtain a xform // from an entry in the stack template <> rvg::xform rvg_lua_check<rvg::xform>(lua_State *L, int idx, int ctxidx); template <> rvg::xform *rvg_lua_check_pointer<rvg::xform>(lua_State *L, int idx, int ctxidx); // And we make sure no other module tries to instantiate them from the templates in // rvg-lua.h, because their explicit specializations are defined in rvg-lua-xform.cpp extern template rvg::xform rvg_lua_check<rvg::xform>(lua_State *L, int idx, int ctxidx); extern template rvg::xform *rvg_lua_check_pointer<rvg::xform>(lua_State *L, int idx, int ctxidx); int rvg_lua_xform_init(lua_State *L, int ctxidx); int rvg_lua_xform_export(lua_State *L, int ctxidx); rvg::xform rvg_lua_xform_identity(lua_State *L, int base); rvg::xform rvg_lua_xform_rotation(lua_State *L, int base); rvg::xform rvg_lua_xform_scaling(lua_State *L, int base); rvg::xform rvg_lua_xform_translation(lua_State *L, int base); rvg::xform rvg_lua_xform_linearity(lua_State *L, int base); rvg::xform rvg_lua_xform_affinity(lua_State *L, int base); rvg::xform rvg_lua_xform_projectivity(lua_State *L, int base); rvg::xform rvg_lua_xform_windowviewport(lua_State *L, int base); #endif
9222ec3516b0394f76771235069bc926f9925884
fe1edb72f6d3828309dfcd8b452c53d0e9ee5ad9
/game.cc
d081ead73a5852965c79b8473b1508fe77b6b4aa
[]
no_license
gc-archer/cc3k
3993326a1a708380a34b2a138245a059345aaff6
ed5687f91c1ee233bb5711e1269b19e1f4d3cf8c
refs/heads/master
2020-05-05T06:50:48.149804
2018-09-03T01:40:46
2018-09-03T01:40:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,171
cc
game.cc
#ifndef GAME_CC #define GAME_CC #include <iostream> #include <string> #include "game.h" #include "pc.h" #include "npc.h" #include "dungeon.h" #include "slap.h" #include "tile.h" #include "floor.h" using namespace std; // constructor and destructor Game::Game(std::istream &input, string race) : input{input} { curFloor = 1; // constructs the dungeons gameDungeon = make_unique<Dungeon> (5, this, input); // put args of the constructor of dungeon in the parenthesis) gameDungeon->constructFloor(race); } Game::~Game() {} void Game::pcMove(int dir) { std::shared_ptr<Floor> f = gameDungeon->getFloor(curFloor); std::shared_ptr<PC> pc = f->getPlayer(); pc->move(dir); } void Game::pcUse(int dir) { std::shared_ptr<Floor> f = gameDungeon->getFloor(curFloor); std::shared_ptr<PC> pc = f->getPlayer(); pc->useItem(dir); } void Game::pcAtk(int dir) { std::shared_ptr<Floor> f = gameDungeon->getFloor(curFloor); std::shared_ptr<PC> pc = f->getPlayer(); pc->attackDir(dir); } void Game::switchFloor(int floor){ curFloor = floor; } // accessors and mutators int Game::getCurFloor(){ return curFloor; } // other methods void Game::displayFloor(int floor) { cout << *(gameDungeon->getFloor(floor)); } void Game::nextTurn() { std::shared_ptr<Floor> f = gameDungeon->getFloor(curFloor); std::shared_ptr<PC> pc = f->getPlayer(); Display *D = pc->getDisplay(); for (int j=0; j<=78; ++j) { for (int i=0; i<=24; ++i) { std::shared_ptr<Tile> t = f->getTile(i, j); if (t->getNPC()) { std::shared_ptr<NPC> npc = t->getNPC(); if (npc->pcInRange()) { npc->attack(*pc); D->setHP(*pc); } else npc->move(*D); npc->justAttacked(); npc->notify(*pc); } } } if (pc->getHP() <= 0) throw Slap("You died. Game over... "); } void Game::freezeEnemy(bool canMove) { std::shared_ptr<Floor> f = gameDungeon->getFloor(curFloor); std::shared_ptr<PC> pc = f->getPlayer(); for (int j=0; j<=78; ++j) { for (int i=0; i<=24; ++i) { std::shared_ptr<Tile> t = f->getTile(i, j); if (t->getNPC()) { std::shared_ptr<NPC> npc = t->getNPC(); npc->freeze(canMove); } } } } void Game::descend() { ++curFloor; } #endif
f035891931b80f8e1133466da5539c5a961b87f5
a9bb7dea956f9524d52d34afc8a0e5f31fac2006
/lib/lib.cpp
ebe8af4b65ccbc46bde327d2f4571086c7eaa839
[]
no_license
XzoRit/hackerrank
8142884bbabf0ea136de5b3902f5b1ac5d059047
275724eb46353ad88716a67762b9239d8e351ba4
refs/heads/master
2021-10-21T09:11:08.573878
2021-10-13T09:26:53
2021-10-13T09:27:35
191,216,494
0
0
null
null
null
null
UTF-8
C++
false
false
118
cpp
lib.cpp
#include <lib/lib.hpp> namespace xzr { namespace lib { inline namespace v1 { } } // namespace lib } // namespace xzr
2d2216c611cd1db731373d97500fc39f7ce75c61
20a59a738c1d8521dc95c380190b48d7bc3bb0bb
/uigraphics/AknIcon/SvgtFbsRasterizer/inc/SvgtFbsRasterizer.h
d1a8859e0424eb2be4304f3c4106be480c6f68a8
[]
no_license
SymbianSource/oss.FCL.sf.mw.uiresources
376c0cf0bccf470008ae066aeae1e3538f9701c6
b78660bec78835802edd6575b96897d4aba58376
refs/heads/master
2021-01-13T13:17:08.423030
2010-10-19T08:42:43
2010-10-19T08:42:43
72,681,263
2
0
null
null
null
null
UTF-8
C++
false
false
5,229
h
SvgtFbsRasterizer.h
/* * Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: CSvgtFbsRasterizer class. * */ #ifndef SVGTFBSRASTERIZER_H #define SVGTFBSRASTERIZER_H #include "SvgtRegisteredBitmap.h" #include "svgtgraphicsinterface.h" #include <graphics/fbsrasterizer.h> #include <graphics/fbsrasterizerclearcache.h> #include "SvgtRasterizerCacheLimitHandler.h" #include <e32base.h> #include <VG/openvg.h> const TUid KUidNvgProprietaryFormat = { 968435518 }; const TInt KMaxRecentBmpCacheSize = 0x40000; class CRasterizerCacheItem; class CRasterizedBitmapCache; class MVGImageBinder; class CSvgtRegisteredBitmap; class CNvgEngine; class TAknIconHeader; TBool operator==(const CFbsRasterizer::TBitmapDesc& aBitmapDesc1, const CFbsRasterizer::TBitmapDesc& aBitmapDesc2); class CSvgtRasterizerOOMPropertyMonitor; /** Example implementation of a rasterizer that is used to generate pixel data for extended bitmaps of example type KUidExtendedBitmapExample. */ NONSHARABLE_CLASS (CSvgtFbsRasterizer) : public CFbsRasterizer, public MFbsRasterizerClearCache, public MSvgtRasterizerCacheLimitHandler { public: IMPORT_C static CFbsRasterizer* New(); ~CSvgtFbsRasterizer(); // From CFbsRasterizer void BeginBitmap(TInt64 aBitmapId, const TBitmapDesc& aBitmapDesc, const TRegion* aRegionOfInterest); void EndBitmap(TInt64 aBitmapId); const TUint32* ScanLine(TInt64 aBitmapId, const TPoint& aPixel, TInt aLength); TInt GetInterface(TUid aInterfaceId, TAny*& aInterface); private: CSvgtFbsRasterizer(); CSvgtRegisteredBitmap* RegisteredBitmap(TInt64 aBitmapId); CSvgtRegisteredBitmap* RecentBitmap(TInt64 aBitmapId); void DoBeginBitmapL(TInt64 aBitmapId, const TBitmapDesc& aBitmapDesc, const TRegion* aRegionOfInterest); CSvgtRegisteredBitmap* DoCreateAndRegisterBitmapL(TInt64 aBitmapId, const TBitmapDesc& aBitmapDesc, CFbsBitmap * aPixmap); void InitializeRasterizer(); CRasterizerCacheItem* FetchFromCache( TInt64 aBitmapId ); /* * RenderL retrieves data from the Extended Bitmap and passes the data to nvgdecoder */ void RenderL( const TBitmapDesc& aBitmapDesc, CSvgtRegisteredBitmap& aBitmap ); /* * Rendering of Bitmap */ void RenderBitmapL(CSvgtRegisteredBitmap& aPixMap, CFbsBitmap * aMask, const TBitmapDesc& aBitmapDesc, TPtr8& aDataPtr8, TAknIconHeader& aIconHeader); /* * Rendering of mask */ void RenderMaskL(CSvgtRegisteredBitmap& aPixMap, CFbsBitmap * aMask, const TBitmapDesc& aBitmapDesc, TPtr8& aDataPtr8, TAknIconHeader& aIconHeader); /** * UpdateMatrices() * locally stores the current environment parameters like paint,path handles,position matrices etc., * so as to revert back (after operations done by nvgdecoder) so that the original position of the icons are intact */ void UpdateMatrices(); /**RestoreMatrices() reverts back the position matrices,path and paint handles which are locally stored using UpdateCurrentMatrices so that the original positions of the icons are intact */ void RestoreMatrices(); /** * ApplyMarginL applies MarginCorrection to icons which donot comply to the S60 width-height/aspect ratio restrictions */ TSize ApplyMarginL(VGImage aVgImage, TSize aSize); /** * Map OpenVg Error codes to symbian error codes */ TInt MapOpenVgErrorCodeToSymbian(TInt aErrorCode); /* * Returns cache limit (if) specific to process */ TInt GetCacheLimit(TUid aProcessUID) const; //From MFbsRasterizerClearCache virtual void ClearCache(); //from MSvgtRasterizerCacheLimitHandler virtual void ChangeCacheLimit( TBool aChangeCacheLimit ); private: //Data members /** List of currently registered extended bitmaps, the key is the bitmap id. */ TDblQue<CSvgtRegisteredBitmap> iRegisteredBmps; /** List of recently used extended bitmaps, the key is the bitmap id. */ TDblQue<CSvgtRegisteredBitmap> iRecentBmps; /** Total size in bytes of the pre-rendered buffers for all the recently used extended bitmaps. */ TInt iTotalRecentBmpSize; /** An idle-time active object to clean up the recently used extended bitmaps. */ CSvgtGraphicsInterface * iGraphicsInterface; CSvgtRasterizerOOMPropertyMonitor* iMonitor; TBool iIsRasterizerValidState; TBool iMatricesUpdated; CNvgEngine* iNvgEngine; VGPaint iUserStrokePaint; VGPaint iUserFillPaint; VGint iMatrixMode; TReal32 iImageMatrix[9]; TReal32 iPathMatrix[9]; TReal32 iFillPaintMatrix[9]; TReal32 iStrokePaintMatrix[9]; TInt iCacheLimit; }; #endif // SVGTFBSRASTERIZER_H
2ee2ded98a05aaa1e0ee321fb9bd878fabb46118
4518cf4df68153381f078ed98ce154e161877909
/include/TrackNode.hh
dc5d076acfcebb9bfa49b04f6462686edd005aec
[]
no_license
ANNIEsoft/RATEventLib
b878bbddd2424f6009646f15395e74756ed00774
164904ce6f10eaa773f4c18b823a028246893140
refs/heads/master
2020-04-20T03:30:10.138776
2019-12-12T21:24:22
2019-12-12T21:24:22
168,600,127
0
0
null
null
null
null
UTF-8
C++
false
false
2,553
hh
TrackNode.hh
#ifndef __RAT_TrackNode__ #define __RAT_TrackNode__ #include <MCTrackStep.hh> namespace RAT { class TrackNode : public DS::MCTrackStep { public: TrackNode() { trackStart = true; prev = next = 0; }; virtual ~TrackNode() { if (next) delete next; for (unsigned i=0; i < child.size(); i++) if (child[i]) delete child[i]; }; /** True if this is the first step in the track */ virtual bool IsTrackStart() const { return trackStart; }; virtual void SetTrackStart(bool state=true) { trackStart = state; }; /** True if this is the last step in the track */ virtual bool IsTrackEnd() const { return next == 0; }; /** ID number for this track. * * Guaranteed to be unique for all tracks within this event, numbered * starting from 1. */ virtual int GetTrackID() const { return trackID; }; virtual void SetTrackID(int _trackID) { trackID = _trackID; }; /** ID number for this step */ virtual int GetStepID() const { return stepID; }; virtual void SetStepID(int _stepID) { stepID = _stepID; }; /** Particle type as defined in MCParticle::pdgcode. */ virtual int GetPDGCode() const { return pdgcode; }; virtual void SetPDGCode(int _pdgcode) { pdgcode = _pdgcode; }; /** Name of particle. * * Often this is more accurate than the pdgcode, which is used inconsistently. */ virtual const std::string& GetParticleName() const { return particleName; }; virtual void SetParticleName(const std::string &_particleName) { particleName = _particleName; } // Step information inherited from DS::MCTrackStep virtual TrackNode *GetPrev() const { return prev; }; virtual void SetPrev(TrackNode *_prev) { prev = _prev; }; virtual TrackNode *GetNext() const { return next; }; virtual void SetNext(TrackNode *_next) { next = _next; }; std::vector<TrackNode*> child; // Any additional tracks connected to this one // Not using TClonesArray because this object does not go into a TTree ever! // Util methods void AddNext(TrackNode *n) { n->prev = this;n->trackStart = false;next = n; }; void AddChild(TrackNode *c) {c->prev = this;c->trackStart = true;child.push_back(c);}; virtual TrackNode &operator= (const DS::MCTrackStep &rhs) { *dynamic_cast<DS::MCTrackStep *>(this) = rhs; return *this; }; ClassDef(TrackNode,2); protected: bool trackStart; int trackID; int stepID; int pdgcode; std::string particleName; TrackNode *prev; TrackNode *next; // Next node for this same particle }; } // namespace RAT #endif
c817552d0bf1aa1c8a54ac0d6ab8a7ea832e5dee
11351870905c52454934b23b27ace5e3306c4107
/PACNW15/l.cpp
692558865d2f972f5b109cd5f6b763084c01ed0d
[]
no_license
IvanAli/ACMICPC2017Training
65cbe9a47788ab38026134dfe41ef7132801d8c5
0a274f41d9b4300fdfbc9160cd171c5edf265cbc
refs/heads/master
2021-08-29T15:42:24.789100
2017-12-14T05:49:03
2017-12-14T05:49:03
114,207,562
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
cpp
l.cpp
#include <bits/stdc++.h> #define EPS 1e-9 using namespace std; int n; long double W; int main() { cin>>n>>W; string pal; long double pi, vi; long double lastsafe = 0.; long double lastprize = 0.; long double acum = 1.; long double maxi = -1.; for(int i = 0; i < n; ++i) { cin>>pal>>pi>>vi; if(pal == "unsafe") { long double tmp; if(fabs(lastsafe-lastprize)>EPS) tmp = acum*(pi*log(1.+vi/W)+(1.-pi)*log(1.+lastsafe/W)+log(1.+lastprize/W)); else tmp = acum*(pi*log(1.+vi/W)+(1.-pi)*log(1.+lastsafe/W)); maxi = max(maxi,tmp); acum *= pi; } else { if(i == n-1) { long double tmp; if(fabs(lastsafe-lastprize)>EPS) tmp = acum*(pi*log(1.+vi/W)+(1.-pi)*log(1.+lastsafe/W)+log(1.+lastprize/W)); else tmp = acum*(pi*log(1.+vi/W)+(1.-pi)*log(1.+lastsafe/W)); maxi = max(maxi,tmp); acum *= pi; } lastsafe = vi; acum *= pi; } lastprize = vi; } long double res = (exp(maxi)-1.)*W; cout<<"$"<<fixed<<setprecision(2)<<res<<endl; return 0; }
06e15b52defe7728f1c5483c7818b9078b99f0bd
ea3e4778b792e8f393b35ee9f16473b2e5690808
/CPSC_2150/5_poly/Poly.h
922aff2f0e4cb09211fbb79a2973d19da1599c63
[]
no_license
shakirali2244/associates
0e856b71fd75803569b629b18aff18c3911f4b9c
3d87399b00b1914d9814e6d21af08dc2b219206f
refs/heads/master
2021-01-20T18:53:08.683021
2017-07-31T11:46:36
2017-07-31T11:46:36
42,191,554
0
0
null
null
null
null
UTF-8
C++
false
false
2,003
h
Poly.h
#include <iostream> using namespace std; struct Term { int coeff; int deg_x; int deg_y; Term* next; }; class Poly{ public: // constructor //precondition: // - //postcondition: // init head to nullptr Poly(); // Creates a new node for linked list //precondition: // coeff, x, and y cannot be null reference //postcondition: // returns a new dynamically allocated Node for list Term* cons(int coeff, int x, int y, Term* next); // Adds a new term to the front of the Linked list //precondition: // - //postcondition: // head is changed to the newer term Term* add(int coeff, int x, int y); // gets the size of the array //precondition: // - //postcondition: // number of terms is returned as an int int getSize(Term* in); // getter for head for friend functions //precondition: // - //postcondition: // head is returned Term* getHead(); //Helper for calling merge sort //precondition: // - //postcondition: // Current polynomial is modified to a sorted one void sortHelper(); // Merge Sort //precondition: // - //postcondition: // divides the lists into individual terms and calls merge returns final head Term* mergeSort(Term* in); //Merge the list //precondition: // left and right CANNOT BE NULL //postcondition: // merges the list and returns the head Term* merge(Term* left, Term* right); // Differentiates the current instance wrt x //precondition: // - //postcondition: // polynomial is changed to the differentiate void diffX(); // Differentiates the current instance wrt y //precondition: // - //postcondition: // polynomial is changed to the differentiate void diffY(); //overload << operator //precondition: // out is not a null reference //postcondition: // prints the polynomial with endl at the end friend ostream& operator << (ostream& out,const Poly A); //+ operator //precondition: // - //postcondition: // adds the polynomials friend Poly operator +(Poly A, Poly B); private: Term* head; };
b8746d3c9be43b8d8dd51e1c5751378ad64d4da7
9ff597117eb1ed9e6557f61599d215ebfb8f6727
/#1142 Maximal Clique.cpp
26884c45ae49e5a712057bf25b861a1768c62633
[ "MIT" ]
permissive
ZachVec/PAT-Advanced
ce9a3926feb8c4c86e92308324d0c51052835739
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
refs/heads/master
2023-03-22T05:39:19.994065
2021-03-13T10:08:48
2021-03-13T10:08:48
343,035,957
2
0
null
null
null
null
UTF-8
C++
false
false
1,094
cpp
#1142 Maximal Clique.cpp
#include <iostream> #include <unordered_set> #include <vector> using namespace std; int main() { size_t nv, ne, nq; if(scanf("%zu%zu", &nv, &ne) != 2) return 0; vector<vector<bool>> isAdj(nv + 1, vector<bool>(nv + 1, false)); for(size_t i = 0, u, v; i < ne && scanf("%zu%zu", &u, &v); ++i) isAdj[u][v] = isAdj[v][u] = true; if(!scanf("%zu", &nq)) return 0; unordered_set<size_t> clique; for(size_t i = 0, k; i < nq && scanf("%zu", &k); ++i) { bool inSetAdj = true, outSetAdj = false; clique.clear(); for(size_t j = 0, u; j < k && scanf("%zu", &u); ++j) { for(const size_t &v : clique) inSetAdj = inSetAdj && isAdj[u][v]; clique.emplace(u); } if(!inSetAdj) { printf("Not a Clique\n"); continue; } for(size_t u = 1; u <= nv && !outSetAdj; ++u) { if(clique.count(u)) continue; outSetAdj = true; for(const size_t &v : clique) outSetAdj = outSetAdj && isAdj[u][v]; } printf("%s\n", outSetAdj ? "Not Maximal" : "Yes"); } return 0; }
cbe92287135f942f133b46774e0a0762c42bceb5
661bb25db192b744bd10d6c3ca702a7e307c602d
/TribesAscendSDK/HeaderDump/Engine.K2Connector.h
137759692d5f8785143c2ef596023fc8fed09274
[]
no_license
Orvid/TASDK
9582682f0f60a6f6fce5caea3cdd978f401565b3
6057c26b8185b08bc47c58ddecefe0f14becf566
refs/heads/master
2020-12-25T01:06:16.876697
2013-08-02T16:26:25
2013-08-02T16:26:25
11,539,096
0
1
null
null
null
null
UTF-8
C++
false
false
1,001
h
Engine.K2Connector.h
#pragma once namespace UnrealScript { class K2Connector; } #include "Core.Object.h" #include "Engine.K2Connector.EK2ConnectorDirection.h" #include "Engine.K2Connector.EK2ConnectorType.h" #include "Engine.K2NodeBase.h" #define ADD_STRUCT(x, y, offset) \ x get_##y() { return *(x*)(this + offset); } \ void set_##y(x val) { *(x*)(this + offset) = val; } \ __declspec(property(get=get_##y, put=set_##y)) x y; #define ADD_OBJECT(x, y, offset) \ class x* get_##y() { return *(class x**)(this + offset); } \ void set_##y(x* val) { *(class x**)(this + offset) = val; } \ __declspec(property(get=get_##y, put=set_##y)) class x* y; namespace UnrealScript { class K2Connector : public Object { public: typedef K2Connector__EK2ConnectorType EK2ConnectorType; typedef K2Connector__EK2ConnectorDirection EK2ConnectorDirection; ADD_STRUCT(K2Connector__EK2ConnectorType, Type, 76) ADD_STRUCT(ScriptString*, ConnName, 64) ADD_OBJECT(K2NodeBase, OwningNode, 60) }; } #undef ADD_STRUCT #undef ADD_OBJECT
48212f292590f13b396f0bdec2df8bbdf640bd54
db84bf6382c21920c3649b184f20ea48f54c3048
/munichteststand/src/GECorradoDetector.cc
68d9c4716b19585afe87c641a4418f1b5ad874a4
[]
no_license
liebercanis/MaGeLAr
85c540e3b4c5a48edea9bc0520c9d1a1dcbae73c
aa30b01f3c9c0f5de0f040d05681d358860a31b3
refs/heads/master
2020-09-20T12:48:38.106634
2020-03-06T18:43:19
2020-03-06T18:43:19
224,483,424
2
0
null
null
null
null
UTF-8
C++
false
false
87,604
cc
GECorradoDetector.cc
//---------------------------------------------------------------------------// //bb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nu// // // // // // MaGe Simulation // // // // This code implementation is the intellectual property of the // // MAJORANA and Gerda Collaborations. It is based on Geant4, an // // intellectual property of the RD44 GEANT4 collaboration. // // // // ********************* // // // // Neither the authors of this software system, nor their employing // // institutes, nor the agencies providing financial support for this // // work make any representation or warranty, express or implied, // // regarding this software system or assume any liability for its use. // // By copying, distributing or modifying the Program (or any work based // // on on the Program) you indicate your acceptance of this statement, // // and all its terms. // // // //bb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nu// //---------------------------------------------------------------------------// // // $Id: GECorradoDetector.cc,v 1.5 2009-05-18 16:08:53 dusan Exp $ // // CLASS IMPLEMENTATION: GECorradoDetector.cc // //---------------------------------------------------------------------------// /** * SPECIAL NOTES: */ // //---------------------------------------------------------------------------// /** * AUTHOR: Luciano Pandola * CONTACT: * FIRST SUBMISSION: * * REVISION: * * 03-06-2007, Added in MaGe, Luciano * 03-07-2007, Changed to avoid problem with materials defined on-the-fly, Luciano * 06-01-2007, Implemented correct geometry of Corrado (originally by Werner), Dusan * 14-05-2009, Added more geometry options, added hole-size parameters, Dusan and Marc */ //---------------------------------------------------------------------------// // //#include "globals.hh" #include "G4Box.hh" #include "G4Sphere.hh" #include "G4EllipticalCone.hh" #include "G4LogicalVolume.hh" #include "G4Material.hh" #include "G4VisAttributes.hh" #include "G4Material.hh" #include "G4UnionSolid.hh" #include "G4SubtractionSolid.hh" #include "G4Box.hh" #include "G4Trap.hh" #include "G4Trd.hh" #include "G4Tubs.hh" #include "G4Cons.hh" #include "G4ThreeVector.hh" #include "G4VisAttributes.hh" #include "G4Colour.hh" #include "G4PVPlacement.hh" #include "G4SDManager.hh" #include "G4GeometryManager.hh" #include "gerdageometry/GEGeometrySD.hh" #include "geometry/MGGeometryGlobals.hh" #include "io/MGLogger.hh" //---------------------------------------------------------------------------// #include "munichteststand/GECorradoDetector.hh" #include "munichteststand/GECorradoDetectorMessenger.hh" using namespace CLHEP; //---------------------------------------------------------------------------// GECorradoDetector::GECorradoDetector() : MGGeometryDetector("") { //set defaults sample_geom="none"; //box height is also liquid level in the standard box box_height=1.1*cm; //box width is also diference between standard box and sample positions box_width=0.*cm; box_thickness=0.1*cm; // default: standard dose tube_innrad=0*cm; tube_outrad=3.65*cm; tube_length=2.8*cm; tube_angle=twopi; sample_mat_name="NitrogenGas"; s_x=0.*cm; s_y=0.*cm; s_z=0.*cm; //dead layer: fitted values for 3mm Al window - final d_front=0.1683617694*cm; d_side=0.1581820697*cm; coll_x=0; coll_y=0; coll_z=7.62*cm; //hole: fitted values - final hole_radius=0.82414*cm; hole_length=4.12414*cm; theMessenger = new GECorradoDetectorMessenger(this); } //---------------------------------------------------------------------------// GECorradoDetector::~GECorradoDetector() { delete theMessenger; } //---------------------------------------------------------------------------// void GECorradoDetector::ConstructDetector() { // Retrieve materials from the Table G4Material* Vacuum = G4Material::GetMaterial("Vacuum"); G4Material* Brass = G4Material::GetMaterial("Brass"); G4Material* Bronze = G4Material::GetMaterial("Bronze"); G4Material* ProportionalGas = G4Material::GetMaterial("ProportionalGas"); G4Material* N2Gas = G4Material::GetMaterial("NitrogenGas"); G4Material* Ge = G4Material::GetMaterial("NaturalGe"); G4Material* GeLi = G4Material::GetMaterial("Germanium/Lithium"); G4Material* GeB = G4Material::GetMaterial("Germanium/Boron"); G4Material* Pb = G4Material::GetMaterial("MetalLead"); G4Material* Fe = G4Material::GetMaterial("MetalIron"); G4Material* Cu = G4Material::GetMaterial("MetalCopper"); G4Material* Al = G4Material::GetMaterial("MetalAluminium"); G4Material* Vespel = G4Material::GetMaterial("Vespel"); G4Material* Teflon = G4Material::GetMaterial("Teflon"); G4Material* Acrylic = G4Material::GetMaterial("Acrylic"); G4Material* PE = G4Material::GetMaterial("PE"); //G4Material* PVC = G4Material::GetMaterial("PVC"); // Visualization attributes G4VisAttributes * Brasscolour= new G4VisAttributes( G4Colour(226/255. ,163/255. ,29/255. )); //orange-brown G4VisAttributes * Sample_Colour = new G4VisAttributes( G4Colour(255/255. ,0/255. ,12/255. )); //red Sample_Colour -> SetForceSolid(true); G4VisAttributes * Vacuumcolour = new G4VisAttributes( G4Colour(175/255. ,164/255. ,255/255. )); //sky-blue G4VisAttributes * ProportionalGascolour= new G4VisAttributes( G4Colour(154/255. ,237/255. ,193/255. )); //blue-green G4VisAttributes * Pbcolour = new G4VisAttributes( G4Colour(171/255. ,171/255. ,195/255. )); //gray G4VisAttributes * Cucolour= new G4VisAttributes( G4Colour(255/255. ,71/255. ,33/255. )); //red G4VisAttributes * Gecolour= new G4VisAttributes( G4Colour(133/255. ,133/255. ,133/255. )); //dark grey //Gecolour -> SetForceSolid(true); G4VisAttributes * GeLicolour= new G4VisAttributes( G4Colour(187/255. ,28/255. ,0/255. )); //almost black (->'dead'...) G4VisAttributes * Fecolour = new G4VisAttributes( G4Colour(175/255. ,157/255. ,189/255. )); //redish-blue gray G4VisAttributes * N2Gascolour = new G4VisAttributes( G4Colour(150/255. ,150/255. ,255/255. )); //light blue G4VisAttributes * Alcolour= new G4VisAttributes( G4Colour(210/255. ,213/255. ,210/255. )); //light gray G4VisAttributes * Vespelcolour= new G4VisAttributes( G4Colour(224/255. ,224/255. ,190/255. )); //yellow-gray G4VisAttributes * Collimatorcolour= new G4VisAttributes( G4Colour(0/255. ,0/255. ,190/255. )); //indigo Collimatorcolour -> SetForceSolid(true); G4VisAttributes * Bronzecolour = new G4VisAttributes(G4Colour(149/255., 175/255., 69/255.)); //dark yellowish-green G4VisAttributes * Tefloncolour= new G4VisAttributes(G4Colour(119/255.,101/255., 0.)); //brown G4VisAttributes* GeBcolour= new G4VisAttributes (G4Colour(140/255., 113/255., 139/255.)); //another kind of grey... G4VisAttributes * Acryliccolour= new G4VisAttributes( G4Colour(231/255. ,217/255. ,240/255. )); //light blue-grey //------------------------------------------------------ volumes //-------------------------------1. Experimental hall (world volume) G4double expHall_x = 2.0*m; G4double expHall_y = 2.0*m; G4double expHall_z = 2.0*m; G4Box* experimentalHall_box = new G4Box("expHall_box", expHall_x, expHall_y, expHall_z); G4LogicalVolume* experimentalHall_log = new G4LogicalVolume(experimentalHall_box, N2Gas, "expHall_log", 0, 0, 0); experimentalHall_log -> SetVisAttributes(G4VisAttributes::Invisible); //-----------------2. MUON-VETOS and STEEL-STRUCTURE ON THE BOTTOM OF THE SHIELDING // STATUS: READY FOR FIRST TESTING //-----------------Muon-Vetos //---------------- Frontside G4Box* MuonVetoFrontSide_box = new G4Box("MuonVetoFrontSide_box", 42.65*cm, 35.00*cm, 2.5*cm); G4LogicalVolume* MuonVetoFrontSide_log = new G4LogicalVolume(MuonVetoFrontSide_box, Brass, "MuonVetoFrontSide_log", 0, 0, 0); MuonVetoFrontSide_log -> SetVisAttributes(Brasscolour); new G4PVPlacement(0, G4ThreeVector(0., 10.00*cm, 46.0*cm-5.6*cm), MuonVetoFrontSide_log, "MuonVetoFrontSide", experimentalHall_log, false, 0); //moved whole setup 5.6cm to place the front cap of detector at the coordinate origin //---------------- Proportional Gas P10 inside the Frontside G4Box* P10FrontSide_box = new G4Box("P10FrontSide_box", 41.15*cm, 33.5*cm, 2.0*cm); G4LogicalVolume* P10FrontSide_log = new G4LogicalVolume(P10FrontSide_box, ProportionalGas, "P10FrontSide_log", 0, 0, 0); P10FrontSide_log -> SetVisAttributes(ProportionalGascolour); new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), P10FrontSide_log, "P10FrontSide", MuonVetoFrontSide_log, false, 0); //----------------- Topside G4Box* MuonVetoTopSide_box = new G4Box("MuonVetoTopSide_box", 42.5*cm, 2.5*cm, 57.0*cm); G4LogicalVolume* MuonVetoTopSide_log = new G4LogicalVolume(MuonVetoTopSide_box, Brass, "MuonVetoTopSide_log", 0, 0, 0); MuonVetoTopSide_log -> SetVisAttributes(Brasscolour); new G4PVPlacement(0, G4ThreeVector(0., 38.0*cm, -14.5*cm-5.6*cm), MuonVetoTopSide_log, "MuonVetoTopSide", experimentalHall_log, false, 0); //moved whole setup 5.6cm to place the front cap of detector at the coordinate origin //----------------- Proportional Gas P10 inside the Topside G4Box* P10TopSide_box = new G4Box("P10TopSide_box", 41.0*cm, 2.0*cm, 55.5*cm); G4LogicalVolume* P10TopSide_log = new G4LogicalVolume(P10TopSide_box, ProportionalGas, "P10TopSide_log", 0, 0, 0); P10TopSide_log -> SetVisAttributes(ProportionalGascolour); new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), P10TopSide_log, "P10TopSide", MuonVetoTopSide_log, false, 0); //------------------ Endside G4Box* MuonVetoEndSide_box = new G4Box("MuonVetoEndSide_box", 35.0*cm, 42.65*cm, 2.5*cm); G4LogicalVolume* MuonVetoEndSide_log = new G4LogicalVolume(MuonVetoEndSide_box, Brass, "MuonVetoEndSide_log", 0, 0, 0); MuonVetoEndSide_log -> SetVisAttributes(Brasscolour); new G4PVPlacement(0, G4ThreeVector( 0., -7.15*cm, -46.0*cm-5.6*cm), MuonVetoEndSide_log, "MuonVetoEndSide", experimentalHall_log, false, 0); //moved whole setup 5.6cm to place the front cap of detector at the coordinate origin //------------------ Proportional Gas P10 inside the Endside G4Box* P10EndSide_box = new G4Box("P10EndSide_box", 33.5*cm, 41.15*cm, 2.0*cm); G4LogicalVolume* P10EndSide_log = new G4LogicalVolume(P10EndSide_box, ProportionalGas, "P10EndSide_log", 0, 0, 0); P10EndSide_log -> SetVisAttributes(ProportionalGascolour); new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), P10EndSide_log, "P10EndSide", MuonVetoEndSide_log, false, 0); //------------------- Side A and side B (on the right and on the left seen from frontside) G4Box* MuonVetoSide_box = new G4Box("MuonVetoSide_box", 2.5*cm, 29.15*cm, 47.00*cm); G4LogicalVolume* MuonVetoSide_log = new G4LogicalVolume(MuonVetoSide_box, Brass, "MuonVetoSide_log", 0, 0, 0); MuonVetoSide_log -> SetVisAttributes(Brasscolour); new G4PVPlacement(0, G4ThreeVector(37.50*cm, 6.35*cm, -3.5*cm-5.6*cm), MuonVetoSide_log, "MuonVetoSideA", experimentalHall_log, false, 0); new G4PVPlacement(0, G4ThreeVector(-37.50*cm, 6.35*cm, -3.5*cm-5.6*cm), MuonVetoSide_log, "MuonVetoSideB", experimentalHall_log, false, 0); //moved whole setup 5.6cm to place the front cap of detector at the coordinate origin // ------------------ Proportional Gas P10 inside the side A and side B G4Box* P10Side_box = new G4Box("P10Side_box", 2.0*cm, 27.65*cm, 45.5*cm); G4LogicalVolume* P10Side_log = new G4LogicalVolume(P10Side_box, ProportionalGas, "P10Side_log", 0, 0, 0); P10Side_log -> SetVisAttributes(ProportionalGascolour); new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), P10Side_log, "P10SideA", MuonVetoSide_log, false, 0); //G4VPhysicalVolume* P10SideB_phys; //P10SideB_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), P10Side_log, "P10SideB", MuonVetoSide_log, false, 0); //-----------------3. SHIELDS(WITHOUT MUONVETOS)------------------------------------------------------------- // STATUS: Fixed Cooling fingers, Dusan // Copper in both doors still wrong and needs fixing! //----------------- Lead-Shield G4Box* PbShield_box = new G4Box("PbShield_box", 33.5*cm, 35.5*cm, 43.5*cm); G4LogicalVolume* PbShield_log = new G4LogicalVolume(PbShield_box, Pb, "PbShield_log", 0, 0, 0); PbShield_log -> SetVisAttributes(Pbcolour); new G4PVPlacement(0, G4ThreeVector(0.,0.,-5.6*cm), PbShield_log, "PbShield", experimentalHall_log, false, 0); //moved whole setup 5.6cm to place the front cap of detector at the coordinate origin //------------------ Coolingfinger CF filled with N2gas through the lead-shield G4Tubs* CFLeadShield_tubs = new G4Tubs("CFLeadShield_tubs", 0, 2.1*cm, 10.15*cm, 0, 2*M_PI); G4Tubs* CFLeadShieldGas_tubs = new G4Tubs("CFLeadShieldGas_tubs", 0, 1.95*cm, 10.15*cm, 0, 2*M_PI); G4LogicalVolume* CFLeadShield_log = new G4LogicalVolume(CFLeadShield_tubs, Cu, "CFLeadShield_log", 0, 0, 0); G4LogicalVolume* CFLeadShieldGas_log = new G4LogicalVolume(CFLeadShieldGas_tubs, N2Gas, "CFLeadShieldGas_log", 0, 0, 0); CFLeadShield_log -> SetVisAttributes(Cucolour); CFLeadShieldGas_log -> SetVisAttributes(N2Gascolour); G4RotationMatrix* HalfPi_rot_x = new G4RotationMatrix; HalfPi_rot_x ->rotateX(1.5*M_PI); new G4PVPlacement(HalfPi_rot_x, G4ThreeVector(0., -25.35*cm, -20.5*cm), CFLeadShield_log, "CFLeadShield", PbShield_log, false, 0); new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), CFLeadShieldGas_log, "CFLeadShieldGas", CFLeadShield_log, false, 0); //------------------- Part 6 of the coldness-transfer-cable G4Tubs* ColdTransfer6_tubs = new G4Tubs("ColdTransfer6_tubs", 0., 0.5*cm, 10.15*cm, 0, 2*M_PI); G4LogicalVolume* ColdTransfer6_log = new G4LogicalVolume(ColdTransfer6_tubs, Cu, "ColdTransfer5_log", 0, 0, 0); ColdTransfer6_log -> SetVisAttributes(Cucolour); new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), ColdTransfer6_log, "ColdTransfer6", CFLeadShieldGas_log, false, 0); //------------------- Copper-planes, on which the lead-blocks of the doors are fixed G4Box* CuPlane_box = new G4Box("CuPlane_box", 15.0*cm, 15.0*cm, 0.1*cm); G4LogicalVolume* CuPlane_log = new G4LogicalVolume(CuPlane_box, Cu, "CuPlane_log", 0, 0, 0); CuPlane_log -> SetVisAttributes(Cucolour); new G4PVPlacement(0, G4ThreeVector(0, 0, 38.4*cm), CuPlane_log, "CuPlaneFrontdoor1", PbShield_log, false, 0); new G4PVPlacement(0, G4ThreeVector(0, 0, 33.4*cm), CuPlane_log, "CuPlaneFrontdoor2", PbShield_log, false, 0); //G4VPhysicalVolume* CuPlaneFrontdoor3_phys; //CuPlaneFrontdoor3_phys = new G4PVPlacement(0, G4ThreeVector(0, 0, 30.4*cm), CuPlane_log, "CuPlaneFrontdoor3", PbShield_log, false, 0); new G4PVPlacement(0, G4ThreeVector(0, 0, -38.4*cm), CuPlane_log, "CuPlaneEnddoor1", PbShield_log, false, 0); new G4PVPlacement(0, G4ThreeVector(0, 0, -33.4*cm), CuPlane_log, "CuPlaneEnddoor2", PbShield_log, false, 0); //G4VPhysicalVolume* CuPlaneEnddoor3_phys; //CuPlaneEnddoor3_phys = new G4PVPlacement(0, G4ThreeVector(0, 0, -30.4*cm), CuPlane_log, "CuPlaneEnddoor3", PbShield_log, false, 0); //------------------- Main-Copper-Shield G4Box* CuShield_box = new G4Box("CuShield_box", 15.0*cm, 15.0*cm, 30.0*cm); G4LogicalVolume* CuShield_log = new G4LogicalVolume(CuShield_box, Cu, "CuShield_log", 0, 0, 0); CuShield_log -> SetVisAttributes(Cucolour); new G4PVPlacement(0, G4ThreeVector(0, 0, 0), CuShield_log, "CuShield", PbShield_log, false, 0); //-------------------- Coolingfinger CF filled with N2gas through the main copper shield G4Tubs* CFCopperShield_tubs = new G4Tubs("CFCopperShield_tubs", 0, 1.95*cm, 2.5*cm, 0, 2*M_PI); G4LogicalVolume* CFCopperShield_log = new G4LogicalVolume(CFCopperShield_tubs, N2Gas, "CFCopperShield_log", 0, 0, 0); CFCopperShield_log -> SetVisAttributes(N2Gascolour); /*G4VPhysicalVolume* CFCopperShield_phys; CFCopperShield_phys = */ new G4PVPlacement(HalfPi_rot_x, G4ThreeVector(0., -12.5*cm, -20.5*cm), CFCopperShield_log, "CFCopperShield", CuShield_log, false, 0); //--------------------- Part 4 of the coldness-transfer-cable G4Tubs* ColdTransfer4_tubs = new G4Tubs("ColdTransfer4_tubs", 0., 0.5*cm, 2.5*cm, 0, 2*M_PI); G4LogicalVolume* ColdTransfer4_log = new G4LogicalVolume(ColdTransfer4_tubs, Cu, "ColdTransfer4_log", 0, 0, 0); ColdTransfer4_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* ColdTransfer4_phys; ColdTransfer4_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), ColdTransfer4_log, "ColdTransfer4", CFCopperShield_log, false, 0); //--------------------- Copper-sheet above the Copper-Shield G4Box* CuSheetAbove_box = new G4Box("CuSheetAbove", 25*cm, 0.1*cm, 43.5*cm); G4LogicalVolume* CuSheetAbove_log = new G4LogicalVolume(CuSheetAbove_box, Cu, "CuSheetAbove_log", 0, 0, 0); CuSheetAbove_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* CuSheetAbove_phys; CuSheetAbove_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 15.1*cm, 0), CuSheetAbove_log, "CuSheetAbove", PbShield_log, false, 0); //--------------------- Copper-sheet beneath the Copper-Shield G4Box* CuSheetBeneath_box = new G4Box("CuSheetBeneath", 15.2*cm, 0.1*cm, 43.5*cm); G4LogicalVolume* CuSheetBeneath_log = new G4LogicalVolume(CuSheetBeneath_box, Cu, "CuSheetBeneath_log", 0, 0, 0); CuSheetBeneath_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* CuSheetBeneath_phys; CuSheetBeneath_phys = */ new G4PVPlacement(0, G4ThreeVector(0, -15.1*cm, 0), CuSheetBeneath_log, "CuSheetBeneath", PbShield_log, false, 0); //--------------------- Coolingfinger CF filled with N2gas through the copper-sheet beneath the main copper shield G4Tubs* CFCopperSheet_tubs = new G4Tubs("CFCopperSheet_tubs", 0, 1.95*cm, 0.1*cm, 0, 2*M_PI); G4LogicalVolume* CFCopperSheet_log = new G4LogicalVolume(CFCopperSheet_tubs, N2Gas, "CFCopperSheet_log", 0, 0, 0); CFCopperSheet_log -> SetVisAttributes(N2Gascolour); /* G4VPhysicalVolume* CFCopperSheet_phys; CFCopperSheet_phys = */ new G4PVPlacement(HalfPi_rot_x, G4ThreeVector(0., 0., -20.5*cm), CFCopperSheet_log, "CFCopperSheet", CuSheetBeneath_log, false, 0); //---------------------- Part 5 of the coldness-transfer-cable G4Tubs* ColdTransfer5_tubs = new G4Tubs("ColdTransfer5_tubs", 0., 0.5*cm, 0.1*cm, 0, 2*M_PI); G4LogicalVolume* ColdTransfer5_log = new G4LogicalVolume(ColdTransfer5_tubs, Cu, "ColdTransfer5_log", 0, 0, 0); ColdTransfer5_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* ColdTransfer5_phys; ColdTransfer5_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), ColdTransfer5_log, "ColdTransfer5", CFCopperSheet_log, false, 0); //---------------------- Copper-sheets on both left and right sides of the Copper-Shield G4Box* CuSheetLateral_box = new G4Box("CuSheetLateral", 0.1*cm, 15.0*cm, 43.5*cm); G4LogicalVolume* CuSheetLateral_log = new G4LogicalVolume(CuSheetLateral_box, Cu, "CuSheetLateral_log", 0, 0, 0); CuSheetLateral_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* CuSheetLateralLeft_phys; CuSheetLateralLeft_phys = */ new G4PVPlacement(0, G4ThreeVector(15.1*cm, 0., 0.), CuSheetLateral_log, "CuSheetLateralLeft", PbShield_log, false, 0); /*G4VPhysicalVolume* CuSheetLateralRight_phys; CuSheetLateralRight_phys = */ new G4PVPlacement(0, G4ThreeVector(-15.1*cm, 0., 0.), CuSheetLateral_log, "CuSheetLateralRight", PbShield_log, false, 0); //------------------------4. STRUCTURE OF THE N2-CHAMBER--------------------------------------------------------------------- // STATUS: Fixed Cooling fingers, Dusan //------------------- N2-Chamber G4Box* N2Chamber_box = new G4Box("N2Chamber_box", 10.0*cm, 10.0*cm, 25.0*cm); G4LogicalVolume* N2Chamber_log = new G4LogicalVolume(N2Chamber_box, N2Gas, "N2Chamber_log", 0, 0, 0); N2Chamber_log -> SetVisAttributes(N2Gascolour); /* G4VPhysicalVolume* N2Chamber_phys; N2Chamber_phys = */ new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), N2Chamber_log, "N2Chamber", CuShield_log, false, 0); //------------------ Copperwall in the N2-chamber G4VSolid* CopperWall_Full = new G4Box("CopperWall_Full", 10.00*cm, 9.75*cm, 2.50*cm); G4VSolid* CopperWall_Hole = new G4Tubs("CopperWall_Hole", 0, 2.1*cm, 3.00*cm, 0, 2*M_PI); G4VSolid* CopperWall_Solid = new G4SubtractionSolid("CopperWall_Solid", CopperWall_Full, CopperWall_Hole, 0, G4ThreeVector(0, 0.25*cm, 0)); G4LogicalVolume* CopperWall_log = new G4LogicalVolume(CopperWall_Solid, Cu, "CopperWall_log", 0, 0, 0); CopperWall_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* CopperWall_phys; CopperWall_phys =*/ new G4PVPlacement(0, G4ThreeVector(0, -0.25*cm, -13.5*cm), CopperWall_log, "CopperWall", N2Chamber_log, false, 0); //----------------- Additional Copper-pieces between the Copper-wall and the Enddoor within the N2-chamber // Part 1 and 2 G4Box* CopperPiece_box = new G4Box("CopperPiece_box", 0.86*cm, 10.0*cm, 4.5*cm); G4LogicalVolume* CopperPiece_log = new G4LogicalVolume(CopperPiece_box, Cu, "CopperPiece_log", 0, 0, 0); CopperPiece_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* Copperpiece1_phys; Copperpiece1_phys = */ new G4PVPlacement(0, G4ThreeVector(9.14*cm,0.,-20.5*cm), CopperPiece_log, "CopperPiece1", N2Chamber_log, false, 0); /*G4VPhysicalVolume* Copperpiece2_phys; Copperpiece2_phys =*/ new G4PVPlacement(0, G4ThreeVector(-9.14*cm,0.,-20.5*cm), CopperPiece_log, "CopperPiece2", N2Chamber_log, false, 0); //---------------- Cooling-Finger in the N2-chamber - horizontal part G4VSolid* CoolingFingerHorizontal_tubs = new G4Tubs("CoolingFingerHorizontal_tubs", 1.95*cm, 2.1*cm, 7.3*cm, 0, 2*M_PI); G4VSolid* CoolingFingerHorizontalCutOff_trd = new G4Trd("CoolingFingerHorizontalCutOff", 3.0*cm, 3.0*cm, 6.7*cm, 0.5*cm, 3.1*cm); G4VSolid* CoolingFingerHorizontal_Solid = new G4SubtractionSolid("CoolingFingerHorizontal_Solid", CoolingFingerHorizontal_tubs, CoolingFingerHorizontalCutOff_trd, 0, G4ThreeVector(0, -3.6*cm, -5.2*cm)); G4LogicalVolume* CoolingFingerHorizontal_log = new G4LogicalVolume(CoolingFingerHorizontal_Solid, Cu, "CoolingFingerHorizontal_log", 0, 0, 0); CoolingFingerHorizontal_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* CoolingFingerHorizontal_phys; CoolingFingerHorizontal_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., -15.3*cm), CoolingFingerHorizontal_log, "CoolingFingerHorizontal", N2Chamber_log, false, 0); //----------------- Part 2 of the coldness-transfer-cable G4VSolid* ColdTransfer2_tubs = new G4Tubs("ColdTransfer2_tubs", 0., 0.5*cm, 7.3*cm, 0, 2*M_PI); G4VSolid* ColdTransfer2CutOff_trd = new G4Trd("ColdTransfer2CutOff", 3.0*cm, 3.0*cm, 6.7*cm, 0.5*cm, 3.1*cm); G4VSolid* ColdTransfer2_solid = new G4SubtractionSolid("ColdTransfer2_solid", ColdTransfer2_tubs, ColdTransfer2CutOff_trd, 0, G4ThreeVector(0, -3.6*cm, -5.2*cm)); G4LogicalVolume* ColdTransfer2_log = new G4LogicalVolume(ColdTransfer2_solid, Cu, "ColdTransfer2_log", 0, 0, 0); ColdTransfer2_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* ColdTransfer2_phys; ColdTransfer2_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., -15.3*cm), ColdTransfer2_log, "ColdTransfer2", N2Chamber_log, false, 0); //------------------ Cooling-Finger in the N2-chamber - vertical part G4VSolid* CoolingFingerVertical_tubs = new G4Tubs("CoolingFingerHorizontal_tubs", 1.95*cm, 2.1*cm, 6.05*cm, 0, 2*M_PI); G4VSolid* CoolingFingerVerticalCutOff_trd = new G4Trd("CoolingFingerHorizontalCutOff", 3.0*cm, 3.0*cm, 6.7*cm, 0.5*cm, 3.1*cm); G4VSolid* CoolingFingerVertical_solid = new G4SubtractionSolid("CoolingFingerVertical_solid", CoolingFingerVertical_tubs, CoolingFingerVerticalCutOff_trd, 0, G4ThreeVector(0, 3.6*cm, -3.95*cm)); G4LogicalVolume* CoolingFingerVertical_log = new G4LogicalVolume(CoolingFingerVertical_solid, Cu, "CoolingFingerVertical_log", 0, 0, 0); CoolingFingerVertical_log -> SetVisAttributes(Cucolour); /*G4VPhysicalVolume* CoolingFingerVertical_phys; CoolingFingerVertical_phys = */ new G4PVPlacement(HalfPi_rot_x, G4ThreeVector(0., -3.95*cm, -20.5*cm), CoolingFingerVertical_log, "CoolingFingerVertical", N2Chamber_log, false, 0); //------------------- Part 3 of the coldness-transfer-cable G4VSolid* ColdTransfer3_tubs = new G4Tubs("ColdTransfer3_tubs", 0., 0.5*cm, 6.05*cm, 0, 2*M_PI); G4VSolid* ColdTransfer3CutOff_trd = new G4Trd("ColdTransfer3CutOff", 3.0*cm, 3.0*cm, 6.7*cm, 0.5*cm, 3.1*cm); G4VSolid* ColdTransfer3_solid = new G4SubtractionSolid("ColdTransfer3_solid", ColdTransfer3_tubs, ColdTransfer3CutOff_trd, 0, G4ThreeVector(0, 3.6*cm, -3.95*cm)); G4LogicalVolume* ColdTransfer3_log = new G4LogicalVolume(ColdTransfer3_solid, Cu, "ColdTransfer3_log", 0, 0, 0); ColdTransfer3_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* ColdTransfer3_phys; ColdTransfer3_phys = */ new G4PVPlacement(HalfPi_rot_x, G4ThreeVector(0., -3.95*cm, -20.5*cm), ColdTransfer3_log, "ColdTransfer3", N2Chamber_log, false, 0); //------------------- 5. OUTER DETECTOR HOUSING----------------------------------------------------------- // STATUS: Fixed screws , Dusan //------------------ Outer Detector Housing as fullfilled body ----- G4VSolid* DetOuterHousing_body = new G4Tubs("DetOuterHousing_body", 0., 4.6*cm, 6.8*cm, 0, 2*M_PI); G4VSolid* DetOuterHousing_hole = new G4Tubs("DetOuterHousins_hole", 4.25*cm, 5.0*cm, 6.8*cm, 0, 2*M_PI); G4VSolid* DetOuterHousing_solid = new G4SubtractionSolid("DetOuterHousing_solid", DetOuterHousing_body, DetOuterHousing_hole, 0, G4ThreeVector(0., 0., 2.5*cm)); G4LogicalVolume* DetOuterHousing_log = new G4LogicalVolume(DetOuterHousing_solid, Al, "DetOuterHousing_log", 0, 0, 0); DetOuterHousing_log -> SetVisAttributes(Alcolour); /* G4VPhysicalVolume* DetOuterHousing_phys; DetOuterHousing_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., -1.2*cm), DetOuterHousing_log, "DetOuterHousingAl", N2Chamber_log, false, 0); //------ ******* additional vacuum volume for different winow thickness : 3mm ******** G4Tubs* CapGap_tubs = new G4Tubs("CapGap_tubs", 0., 4.0*cm, 0.025*cm, 0, 2*M_PI); G4LogicalVolume* CapGap_log = new G4LogicalVolume(CapGap_tubs, Vacuum, "CapGap_log", 0, 0, 0); CapGap_log -> SetVisAttributes(Vacuumcolour); new G4PVPlacement(0, G4ThreeVector(0., 0., 6.475*cm), CapGap_log, "CapGapVac", DetOuterHousing_log, false, 0); //------------------ Vacuum inside the Outer Detector Housing G4Tubs* Vacuum_tubs = new G4Tubs("Vacuum_tubs", 0., 4.0*cm, 6.625*cm, 0, 2*M_PI); G4LogicalVolume* Vacuum_log = new G4LogicalVolume(Vacuum_tubs, Vacuum, "Vacuum_log", 0, 0, 0); Vacuum_log -> SetVisAttributes(Vacuumcolour); /* G4VPhysicalVolume* Vacuum_phys; Vacuum_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., -0.175*cm), Vacuum_log, "InHousingVac", DetOuterHousing_log, false, 0); //------------------ Closing Parts of the Outer Detector Housing //------------------ Part1 G4Tubs* DetOuterClosePart1_tubs = new G4Tubs("DetOuterClosePart1_tubs", 2.1*cm, 4.0*cm, 0.475*cm, 0, 2*M_PI); G4LogicalVolume* DetOuterClosePart1_log = new G4LogicalVolume(DetOuterClosePart1_tubs, Al, "DetOuterClosePart1_log", 0, 0, 0); DetOuterClosePart1_log -> SetVisAttributes(Alcolour); /*G4VPhysicalVolume* DetOuterClosePart1_phys; DetOuterClosePart1_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., -6.15*cm), DetOuterClosePart1_log, "DetOuterClosePart1Al", Vacuum_log, false, 0); //------------------- Part2 G4Tubs* DetOuterClosePart2_tubs = new G4Tubs("DetOuterClosePart2", 3.65*cm, 4.0*cm, 0.775*cm, 0, 2*M_PI); G4LogicalVolume* DetOuterClosePart2_log = new G4LogicalVolume(DetOuterClosePart2_tubs, Al, "DetOuterClosePart2_log", 0, 0, 0); DetOuterClosePart2_log -> SetVisAttributes(Alcolour); /*G4VPhysicalVolume* DetOuterClosePart2_phys; DetOuterClosePart2_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., -4.9*cm), DetOuterClosePart2_log, "DetOuterClosePart2Al", Vacuum_log, false, 0); //------------------- Part3: Copper-ring: belonging to the cooling finger and laying in Part1 G4Tubs* CopperRing_tubs = new G4Tubs("CopperRing_tubs", 1.95*cm, 2.1*cm, 0.475*cm, 0, 2*M_PI); G4LogicalVolume* CopperRing_log = new G4LogicalVolume(CopperRing_tubs, Cu, "CopperRing_log", 0, 0, 0); CopperRing_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* CopperRing_phys; CopperRing_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., -6.15*cm), CopperRing_log, "CopperRing", Vacuum_log, false, 0); //------------------- Old-Roman-ship-iron-screws on the backside of the Outer Detector Housing //------------------- Part of screws inside the Housing G4Tubs* FeScrewIn_tubs = new G4Tubs("FeScrewIn", 0, 0.125*cm, 1.0*cm, 0, 2*M_PI); G4LogicalVolume* FeScrewIn_log = new G4LogicalVolume(FeScrewIn_tubs, Fe, "FeScrewIn_log", 0, 0, 0); FeScrewIn_log -> SetVisAttributes(Fecolour); /*G4VPhysicalVolume* FeScrew1In_phys; FeScrew1In_phys = */ new G4PVPlacement(0, G4ThreeVector(4.125*cm, 0., -5.8*cm), FeScrewIn_log, "FeScrew1In", DetOuterHousing_log, false, 0); /* G4VPhysicalVolume* FeScrew2In_phys; FeScrew2In_phys = */ new G4PVPlacement(0, G4ThreeVector(2.9168*cm, 2.9168*cm, -5.8*cm), FeScrewIn_log, "FeScrew2In", DetOuterHousing_log, false, 0); /* G4VPhysicalVolume* FeScrew3In_phys; FeScrew3In_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 4.125*cm, -5.8*cm), FeScrewIn_log, "FeScrew3In", DetOuterHousing_log, false, 0); /* G4VPhysicalVolume* FeScrew4In_phys; FeScrew4In_phys = */ new G4PVPlacement(0, G4ThreeVector(-2.9168*cm, 2.9168*cm, -5.8*cm), FeScrewIn_log, "FeScrew4In", DetOuterHousing_log, false, 0); /* G4VPhysicalVolume* FeScrew5In_phys; FeScrew5In_phys = */ new G4PVPlacement(0, G4ThreeVector(- 4.125*cm, 0., -5.8*cm), FeScrewIn_log, "FeScrew5In", DetOuterHousing_log, false, 0); /* G4VPhysicalVolume* FeScrew6In_phys; FeScrew6In_phys = */ new G4PVPlacement(0, G4ThreeVector(-2.9168*cm, -2.9168*cm, -5.8*cm), FeScrewIn_log, "FeScrew6In", DetOuterHousing_log, false, 0); /*G4VPhysicalVolume* FeScrew7In_phys; FeScrew7In_phys = */ new G4PVPlacement(0, G4ThreeVector(0, -4.125*cm, -5.8*cm), FeScrewIn_log, "FeScrew7In", DetOuterHousing_log, false, 0); /* G4VPhysicalVolume* FeScrew8In_phys; FeScrew8In_phys = */ new G4PVPlacement(0, G4ThreeVector(2.9168*cm, -2.9168*cm , -5.8*cm), FeScrewIn_log, "FeScrew8In", DetOuterHousing_log, false, 0); //------------------- Part of screws outside the Housing G4Tubs* FeScrewOut_tubs = new G4Tubs("FeScrewOut", 0., 0.375*cm, 0.3*cm, 0, 2*M_PI); G4LogicalVolume* FeScrewOut_log = new G4LogicalVolume(FeScrewOut_tubs, Fe, "FeScrewOut_log", 0, 0, 0); FeScrewOut_log -> SetVisAttributes(Fecolour); /* G4VPhysicalVolume* FeScrew1Out_phys; FeScrew1Out_phys = */ new G4PVPlacement(0, G4ThreeVector(4.125*cm, 0., -8.3*cm), FeScrewOut_log, "FeScrew1Out", N2Chamber_log, false, 0); /* G4VPhysicalVolume* FeScrew2Out_phys; FeScrew2Out_phys = */ new G4PVPlacement(0, G4ThreeVector(2.9168*cm, 2.9168*cm, -8.3*cm), FeScrewOut_log, "FeScrew2Out", N2Chamber_log, false, 0); /* G4VPhysicalVolume* FeScrew3Out_phys; FeScrew3Out_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 4.125*cm, -8.3*cm), FeScrewOut_log, "FeScrew3Out", N2Chamber_log , false, 0); /* G4VPhysicalVolume* FeScrew4Out_phys; FeScrew4Out_phys = */ new G4PVPlacement(0, G4ThreeVector(-2.9168*cm, 2.9168*cm, -8.3*cm), FeScrewOut_log, "FeScrew4Out", N2Chamber_log , false, 0); /* G4VPhysicalVolume* FeScrew5Out_phys; FeScrew5Out_phys = */ new G4PVPlacement(0, G4ThreeVector(- 4.125*cm, 0., -8.3*cm), FeScrewOut_log, "FeScrew5Out", N2Chamber_log , false, 0); /* G4VPhysicalVolume* FeScrew6Out_phys; FeScrew6Out_phys = */ new G4PVPlacement(0, G4ThreeVector(-2.9168*cm, -2.9168*cm, -8.3*cm), FeScrewOut_log, "FeScrew6Out", N2Chamber_log , false, 0); /* G4VPhysicalVolume* FeScrew7Out_phys; FeScrew7Out_phys = */ new G4PVPlacement(0, G4ThreeVector(0, -4.125*cm, -8.3*cm), FeScrewOut_log, "FeScrew7Out", N2Chamber_log , false, 0); /* G4VPhysicalVolume* FeScrew8Out_phys; FeScrew8Out_phys = */ new G4PVPlacement(0, G4ThreeVector(2.9168*cm, -2.9168*cm , -8.3*cm), FeScrewOut_log, "FeScrew8Out", N2Chamber_log, false, 0); //------------------- 6. INNER PARTS BESIDE THE INNER DETECTOR HOUSING------------------------------- // STATUS: fixed cooling cable, overlapping volumes, Dusan //------------------- VespelFrontCover G4Tubs* VespelFrontCover_tubs = new G4Tubs("VespelFrontCover_tubs", 0, 3.7*cm, 0.15*cm, 0, 2*M_PI); G4LogicalVolume* VespelFrontCover_log = new G4LogicalVolume(VespelFrontCover_tubs, Vespel, "VespelFrontCover_log", 0, 0, 0); VespelFrontCover_log -> SetVisAttributes(Vespelcolour); /* G4VPhysicalVolume* VespelFrontCover_phys; VespelFrontCover_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, 6.115*cm), VespelFrontCover_log, "VespelFrontCover", Vacuum_log, false, 0); //------------------- VespelClosingPart G4Tubs* VespelClosingPart_tubs = new G4Tubs("VespelClosingPart_tubs", 3.47*cm, 3.7*cm, 0.5*cm, 0, 2*M_PI); G4LogicalVolume* VespelClosingPart_log = new G4LogicalVolume(VespelClosingPart_tubs, Vespel, "VespelClosingPart_log", 0, 0, 0); VespelClosingPart_log -> SetVisAttributes(Vespelcolour); /* G4VPhysicalVolume* VespelClosingPart_phys; VespelClosingPart_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, 5.465*cm), VespelClosingPart_log, "VespelClosingPart", Vacuum_log, false, 0); //------------------- Copper-screws pressing against the inner detector housing G4Box* ScrewInnerHousing_box = new G4Box("ScrewInnerHousing_box", 0.2*cm, 0.2*cm, 0.2*cm); G4LogicalVolume* ScrewInnerHousing_log = new G4LogicalVolume(ScrewInnerHousing_box, Cu, "ScrewInnerHousing_log", 0, 0, 0); ScrewInnerHousing_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* ScrewInnerHousing1a_phys; ScrewInnerHousing1a_phys = */ new G4PVPlacement(0, G4ThreeVector(0, -3.67*cm, 1.265*cm), ScrewInnerHousing_log, "ScrewInnerHousing1aCu", Vacuum_log, false, 0); /* G4VPhysicalVolume* ScrewInnerHousing1b_phys; ScrewInnerHousing1b_phys = */ new G4PVPlacement(0, G4ThreeVector(0, -3.67*cm, 3.765*cm), ScrewInnerHousing_log, "ScrewInnerHousing1bCu", Vacuum_log, false, 0); /* G4VPhysicalVolume* ScrewInnerHousing2a_phys; ScrewInnerHousing2a_phys = */ new G4PVPlacement(0, G4ThreeVector(3.67*cm, 0, 1.265*cm), ScrewInnerHousing_log, "ScrewInnerHousing2aCu", Vacuum_log, false, 0); /* G4VPhysicalVolume* ScrewInnerHousing2b_phys; ScrewInnerHousing2b_phys = */ new G4PVPlacement(0, G4ThreeVector(3.67*cm, 0, 3.765*cm), ScrewInnerHousing_log, "ScrewInnerHousing2bCu", Vacuum_log, false, 0); //-------------------- FET G4VSolid* Fet_box = new G4Box("Fet_box", 1.6*cm, 0.75*cm, 0.8*cm); G4VSolid* Fet_cavity = new G4Box("Fet_cavity", 1.4*cm, 0.55*cm, 0.6*cm); G4VSolid* Fet_solid = new G4SubtractionSolid("Fet_solid", Fet_box, Fet_cavity, 0, G4ThreeVector(0., 0., 0.)); G4LogicalVolume* Fet_log = new G4LogicalVolume(Fet_solid, Cu, "Fet_log", 0, 0, 0 ); Fet_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* Fet_phys; Fet_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 2.75*cm, -2.135*cm), Fet_log, "FetCu", Vacuum_log, false, 0); //-------------------- FET-holder //-------------------- Part1 G4VSolid* FetHolderPart1_body = new G4Box("FetHolderPart1_body", 1.6*cm, 1.7*cm, 0.1*cm); G4VSolid* FetHolderPart1_hole = new G4Tubs("FetHolderPart1_hole", 0., 1.25*cm , 0.2*cm, 0, 2*M_PI); G4VSolid* FetHolderPart1_solid = new G4SubtractionSolid("FetHolderPart1_solid", FetHolderPart1_body, FetHolderPart1_hole, 0, G4ThreeVector(0., -0.1*cm, 0.)); G4LogicalVolume* FetHolderPart1_log = new G4LogicalVolume(FetHolderPart1_solid, Cu, "FetHolderPart1_log", 0, 0, 0); FetHolderPart1_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* FetHolderPart1_phys; FetHolderPart1_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0.1*cm, -2.835*cm), FetHolderPart1_log, "FetHolderPart1Cu", Vacuum_log, false, 0); //------------------- Part2 G4Box* FetHolderPart2_box = new G4Box("FetHolderPart2_body", 1.6*cm, 0.1*cm, 0.9*cm); G4LogicalVolume* FetHolderPart2_log = new G4LogicalVolume(FetHolderPart2_box, Cu, "FetHolderPart2_log", 0, 0, 0); FetHolderPart2_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* FetHolderPart2_phys; FetHolderPart2_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 1.9*cm , -2.035*cm), FetHolderPart2_log, "FetHolderPart2Cu", Vacuum_log, false, 0); //------------------- Part3 G4Box* FetHolderPart3_box = new G4Box("FetHolderPart3_body", 1.6*cm, 0.75*cm, 0.1*cm); G4LogicalVolume* FetHolderPart3_log = new G4LogicalVolume(FetHolderPart3_box, Cu, "FetHolderPart3_log", 0, 0, 0); FetHolderPart3_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* FetHolderPart3_phys; FetHolderPart3_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 2.75*cm , -1.235*cm), FetHolderPart3_log, "FetHolderPart3Cu", Vacuum_log, false, 0); //------------------- Cooled big screw G4Tubs* CooledBigScrew_tubs = new G4Tubs("CooledBigScrew_tubs", 0, 1.25*cm, 1.25*cm, 0, 2*M_PI); G4LogicalVolume* CooledBigScrew_log = new G4LogicalVolume(CooledBigScrew_tubs, Al, "CooledBigScrew_log", 0, 0, 0); CooledBigScrew_log -> SetVisAttributes(Alcolour); /* G4VPhysicalVolume* CooledBigScrew_phys; CooledBigScrew_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -3.665*cm), CooledBigScrew_log, "CooledBigScrewAl", Vacuum_log, false, 0); //------------------- Cooled middle screw G4Tubs* CooledMiddleScrew_tubs = new G4Tubs("CooledMiddleScrew_tubs", 0, 0.98*cm, 0.25*cm, 0, 2*M_PI); G4LogicalVolume* CooledMiddleScrew_log = new G4LogicalVolume(CooledMiddleScrew_tubs, Cu, "CooledMiddleScrew_log", 0, 0, 0); CooledMiddleScrew_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* CooledMiddleScrew_phys; CooledMiddleScrew_phys = */ new G4PVPlacement(0, G4ThreeVector(0, -0.21*cm, -5.165*cm), CooledMiddleScrew_log, "CooledMiddleScrewCu", Vacuum_log, false, 0); //------------------- Cooled small screw G4Tubs* CooledSmallScrew_tubs = new G4Tubs("CooledSmallScrew_tubs", 0, 0.62*cm, 0.25*cm, 0, 2*M_PI); G4LogicalVolume* CooledSmallScrew_log = new G4LogicalVolume(CooledSmallScrew_tubs, Cu, "CooledSmallScrew_log", 0, 0, 0); CooledSmallScrew_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* CooledSmallScrew_phys; CooledSmallScrew_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -5.665*cm), CooledSmallScrew_log, "CooledSmallScrewCu", Vacuum_log, false, 0); //------------------- Part 1 of the coldness-transfer-cable G4Tubs* ColdTransfer1_tubs = new G4Tubs("ColdTransfer1_tubs", 0., 0.5*cm, 0.355*cm, 0, 2*M_PI); G4LogicalVolume* ColdTransfer1_log = new G4LogicalVolume(ColdTransfer1_tubs, Cu, "ColdTransfer1_log", 0, 0, 0); ColdTransfer1_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* ColdTransfer1_phys; ColdTransfer1_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -6.27*cm), ColdTransfer1_log, "ColdTransfer1Cu", Vacuum_log, false, 0); //------------------- Spider (original from Canberra) G4Tubs* Spider_tubs = new G4Tubs("Spider_tubs", 1.25*cm, 3.75*cm, 0.57*cm, 0, 2*M_PI); G4LogicalVolume* Spider_log = new G4LogicalVolume(Spider_tubs, Teflon, "Spider_log", 0, 0, 0); Spider_log -> SetVisAttributes(Tefloncolour); /* G4VPhysicalVolume* Spider_phys; Spider_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -3.505*cm), Spider_log, "SpiderTeflon", Vacuum_log, false, 0); //------------------- Alu-ring inside the spider G4Tubs* SpiderRing_tubs = new G4Tubs("SpiderRing_tubs", 1.25*cm, 1.45*cm, 0.67*cm, 0, 2*M_PI); G4LogicalVolume* SpiderRing_log = new G4LogicalVolume(SpiderRing_tubs, Al, "SpiderRing_log", 0, 0, 0); SpiderRing_log -> SetVisAttributes(Alcolour); /* G4VPhysicalVolume* SpiderRing_phys; SpiderRing_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), SpiderRing_log, "SpiderRingAl", Spider_log, false, 0); //------------------- 3 screws holding the spider G4Tubs* SpiderScrew_tubs = new G4Tubs("SpiderScrew_tubs", 0., 0.3*cm, 0.8*cm, 0, 2*M_PI); G4LogicalVolume* SpiderScrew_log = new G4LogicalVolume(SpiderScrew_tubs, Cu, "SpiderScrew_log", 0, 0, 0); SpiderScrew_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* SpiderScrew1_phys; SpiderScrew1_phys = */ new G4PVPlacement(0, G4ThreeVector(2.73*cm, 1.575*cm, -4.875*cm), SpiderScrew_log, "SpiderScrew1Cu", Vacuum_log, false, 0); /* G4VPhysicalVolume* SpiderScrew2_phys; SpiderScrew2_phys = */ new G4PVPlacement(0, G4ThreeVector(-2.73*cm, 1.575*cm, -4.875*cm), SpiderScrew_log, "SpiderScrew2Cu", Vacuum_log, false, 0); /* G4VPhysicalVolume* SpiderScrew3_phys; SpiderScrew3_phys = */ new G4PVPlacement(0, G4ThreeVector(0, -3.15*cm, -4.875*cm), SpiderScrew_log, "SpiderScrew3Cu", Vacuum_log, false, 0); //------------------- Parts of the 3 Spider-screws inside the spider-tube G4Tubs* SpiderScrewIn_tubs = new G4Tubs("SpiderScrewIn_tubs", 0., 0.3*cm, 0.57*cm, 0, 2*M_PI); G4LogicalVolume* SpiderScrewIn_log = new G4LogicalVolume(SpiderScrewIn_tubs, Cu, "SpiderScrewIn_log", 0, 0, 0); SpiderScrewIn_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* SpiderScrewIn1_phys; SpiderScrewIn1_phys = */ new G4PVPlacement(0, G4ThreeVector(2.73*cm, 1.575*cm, 0.), SpiderScrewIn_log, "SpiderScrewIn1Cu", Spider_log, false, 0); /* G4VPhysicalVolume* SpiderScrewIn2_phys; SpiderScrewIn2_phys = */ new G4PVPlacement(0, G4ThreeVector(-2.73*cm, 1.575*cm, 0.), SpiderScrewIn_log, "SpiderScrewIn2Cu", Spider_log, false, 0); /* G4VPhysicalVolume* SpiderScrewIn3_phys; SpiderScrewIn3_phys = */ new G4PVPlacement(0, G4ThreeVector(0, -3.15*cm, 0.), SpiderScrewIn_log, "SpiderScrewIn3Cu", Spider_log, false, 0); //------------------- 7. INNER DETECTOR HOUSING-------------------------------------------------- // STATUS: Fixed overlapping parts, Dusan //------------------- Inner detector housing as fullfilled body G4VSolid* DetInnerHousing_body = new G4Tubs("DetInnerHousing_tubs", 0, 3.47*cm, 4.19*cm, 0, 2*M_PI); G4VSolid* DetInnerHousing_hole1 = new G4Tubs("DetInnerHousing_hole1", 1.4*cm, 5.*cm, 1.80*cm, 0, 2*M_PI); G4VSolid* DetInnerHousing_hole2 = new G4Tubs("DetInnerHousing_hole2", 2.435*cm, 5.0*cm, 2.3*cm, 0, 2*M_PI); G4VSolid* DetInnerHousing_solid1 = new G4SubtractionSolid("DetInnerHousing_solid1", DetInnerHousing_body, DetInnerHousing_hole1, 0, G4ThreeVector(0, 0, -4.19*cm)); G4VSolid* DetInnerHousing_solid2 = new G4SubtractionSolid("DetInnerHousing_solid2", DetInnerHousing_solid1, DetInnerHousing_hole2, 0, G4ThreeVector(0, 0, -4.19*cm)); G4LogicalVolume* DetInnerHousing_log = new G4LogicalVolume(DetInnerHousing_solid2, Al, "DetInnerHousing_log", 0, 0, 0); DetInnerHousing_log -> SetVisAttributes(Alcolour); /* G4VPhysicalVolume* DetInnerHousing_phys; DetInnerHousing_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, 1.775*cm), DetInnerHousing_log, "DetInnerHousingAl", Vacuum_log, false, 0); //------------------- Teflon feedthrough (further parts in the detector housing) //------------------- Part1 G4Tubs* TeflonFeedthroughPart1_tubs = new G4Tubs("TeflonFeedthroughPart1_tubs", 0, 0.505*cm, 0.7*cm, 0, 2*M_PI); G4LogicalVolume* TeflonFeedthroughPart1_log = new G4LogicalVolume(TeflonFeedthroughPart1_tubs, Teflon, "TeflonFeedthroughPart1_log", 0, 0, 0); TeflonFeedthroughPart1_log -> SetVisAttributes(Tefloncolour); /* G4VPhysicalVolume* TeflonFeedthroughPart1_phys; TeflonFeedthroughPart1_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -2.89*cm), TeflonFeedthroughPart1_log, "TeflonFeedthroughPart1", DetInnerHousing_log, false, 0); //------------------- Vacuum inside Part1 G4Tubs* InsideFeedthroughPart1_tubs = new G4Tubs("InsideFeedthroughPart1_tubs", 0, 0.305*cm, 0.62*cm, 0, 2*M_PI); G4LogicalVolume* InsideFeedthroughPart1_log = new G4LogicalVolume(InsideFeedthroughPart1_tubs, Vacuum, "InsideFeedthroughPart1_log", 0, 0, 0); InsideFeedthroughPart1_log -> SetVisAttributes(Vacuumcolour); /* G4VPhysicalVolume* InsideFeedthroughPart1_phys; InsideFeedthroughPart1_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, 0.08*cm), InsideFeedthroughPart1_log, "InsideFeedthroughPart2Vac", TeflonFeedthroughPart1_log, false, 0); //------------------- Part 1 of contact rod belonging to the contact spring inside vacuum of Part 1 of the feedthrough G4Tubs* ContactRodPart1_tubs = new G4Tubs("ContactRodPart1_tubs", 0, 0.15*cm, 0.62*cm, 0, 2*M_PI); G4LogicalVolume* ContactRodPart1_log = new G4LogicalVolume(ContactRodPart1_tubs, Cu, "ContactRodPart1_log", 0, 0, 0); ContactRodPart1_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* ContactRodPart1_phys; ContactRodPart1_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), ContactRodPart1_log, "ContactRodPart1Cu", InsideFeedthroughPart1_log, false, 0); //------------------- Part2 G4Tubs* TeflonFeedthroughPart2_tubs = new G4Tubs("TeflonFeedthroughPart2_tubs", 0, 2.235*cm, 0.25*cm, 0, 2*M_PI); G4LogicalVolume* TeflonFeedthroughPart2_log = new G4LogicalVolume(TeflonFeedthroughPart2_tubs, Teflon, "TeflonFeedthroughPart2_log", 0, 0, 0); TeflonFeedthroughPart2_log -> SetVisAttributes(Tefloncolour); /* G4VPhysicalVolume* TeflonFeedthroughPart2_phys; TeflonFeedthroughPart2_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -1.94*cm), TeflonFeedthroughPart2_log, "TeflonFeedthroughPart2", DetInnerHousing_log, false, 0); //-------------------- Vacuum A inside Part2 G4Tubs* InsideFeedthroughPart2A_tubs = new G4Tubs("InsideFeedthroughPart2A_tubs", 0, 0.305*cm, 0.20*cm, 0, 2*M_PI); G4LogicalVolume* InsideFeedthroughPart2A_log = new G4LogicalVolume(InsideFeedthroughPart2A_tubs, Vacuum, "InsideFeedthroughPart2A_log", 0, 0, 0); InsideFeedthroughPart2A_log -> SetVisAttributes(Vacuumcolour); /* G4VPhysicalVolume* InsideFeedthroughPart2A_phys; InsideFeedthroughPart2A_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -0.05*cm), InsideFeedthroughPart2A_log, "InsideFeedthroughPart2AVac", TeflonFeedthroughPart2_log, false, 0); //-------------------- Part 2 of contact rod belonging to the contact spring G4Tubs* ContactRodPart2_tubs = new G4Tubs("ContactRodPart2_tubs", 0, 0.15*cm, 0.20*cm, 0, 2*M_PI); G4LogicalVolume* ContactRodPart2_log = new G4LogicalVolume(ContactRodPart2_tubs, Cu, "ContactRodPart2_log", 0, 0, 0); ContactRodPart2_log -> SetVisAttributes(Cucolour); /* G4VPhysicalVolume* ContactRodPart2_phys; ContactRodPart2_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), ContactRodPart2_log, "ContactrodPart2Cu", InsideFeedthroughPart2A_log, false, 0); //-------------------- Vacuum B inside Part2 G4Tubs* InsideFeedthroughPart2B_tubs = new G4Tubs("InsideFeedthroughPart2B_tubs", 0, 2.135*cm, 0.05*cm, 0, 2*M_PI); G4LogicalVolume* InsideFeedthroughPart2B_log = new G4LogicalVolume(InsideFeedthroughPart2B_tubs, Vacuum, "InsideFeedthroughPart2B_log", 0, 0, 0); InsideFeedthroughPart2B_log -> SetVisAttributes(Vacuumcolour); /* G4VPhysicalVolume* InsideFeedthroughPart2B_phys; InsideFeedthroughPart2B_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, 0.20*cm), InsideFeedthroughPart2B_log, "InsideFeedthroughPart2BVac", TeflonFeedthroughPart2_log, false, 0); //-------------------- Part 3 of the contact spring in vacuum B inside Part2 G4Cons* ContactSpringPart3_cons = new G4Cons("ContactSpringPart3_cons", 0.8*cm, 0.9*cm, 0.5*cm, 0.6*cm, 0.05*cm, 0, 2*M_PI); G4LogicalVolume* ContactSpringPart3_log = new G4LogicalVolume(ContactSpringPart3_cons, Bronze, "ContactSpringPart3", 0, 0, 0); ContactSpringPart3_log -> SetVisAttributes(Bronzecolour); /* G4VPhysicalVolume* ContactSpringPart3_phys; ContactSpringPart3_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., 0. ), ContactSpringPart3_log, "ContactSpringPart3Bronze", InsideFeedthroughPart2B_log, false, 0); //-------------------- 8. TEFLON VESSEL AND CRYSTAL----------------------------------------------- // STATUS: Fixed Chineese hat position,vacuum cavity in Teflon cup, crystal groove,B-dead layer (300nm) Dusan //-------------------- Teflon Crystal cup (fullfilled) G4Tubs* TeflonCrystalCup_tubs = new G4Tubs("TeflonCrystalCup_tubs", 0., 3.27*cm, 2.94*cm, 0, 2*M_PI); G4LogicalVolume* TeflonCrystalCup_log = new G4LogicalVolume(TeflonCrystalCup_tubs, Teflon, "TeflonCrystalCup_log", 0, 0, 0); TeflonCrystalCup_log -> SetVisAttributes(Tefloncolour); /* G4VPhysicalVolume* TeflonCrystalCup_phys; TeflonCrystalCup_phys = */ new G4PVPlacement(0,G4ThreeVector(0.,0.,1.25*cm), TeflonCrystalCup_log, "TeflonCrystalCup", DetInnerHousing_log, false, 0); //-------------------- Crystal: DI 646 from PGT G4Tubs* Crystal_tubs = new G4Tubs("Crystal_tubs", 0., 3.22*cm, 2.89*cm, 0, 2*M_PI); G4LogicalVolume* Crystal_log = new G4LogicalVolume(Crystal_tubs, Ge, "Crystal_log", 0, 0, 0); Crystal_log -> SetVisAttributes(Gecolour); /* G4VPhysicalVolume* Crystal_phys; Crystal_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, 0.05*cm), Crystal_log, "CrystalGe", TeflonCrystalCup_log, false, 0); //-------------------- Dead-layer around crystal G4Tubs* DeadLayerAroundCrystal_tubs = new G4Tubs("DeadLayerAroundCrystal_tubs", 3.22*cm-d_side, 3.22*cm, 2.89*cm, 0, 2*M_PI); G4LogicalVolume* DeadLayerAroundCrystal_log = new G4LogicalVolume(DeadLayerAroundCrystal_tubs, GeLi, "DeadLayerAroundCrystal_log", 0, 0, 0); DeadLayerAroundCrystal_log -> SetVisAttributes(GeLicolour); /* G4VPhysicalVolume* DeadLayerAroundCrystal_phys; DeadLayerAroundCrystal_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), DeadLayerAroundCrystal_log, "DeadLayerAroundCrystalGe(Li)", Crystal_log, false, 0); //--------------------- Deadlayer-frontside G4Tubs* DeadLayerFrontside_tubs = new G4Tubs("DeadLayerFrontside_tubs", 0., 3.22*cm-d_side, d_front/2, 0, 2*M_PI); G4LogicalVolume* DeadLayerFrontside_log = new G4LogicalVolume(DeadLayerFrontside_tubs, GeLi, "DeadLayerFrontside_log", 0, 0, 0); DeadLayerFrontside_log -> SetVisAttributes(GeLicolour); /* G4VPhysicalVolume* DeadLayerFrontside_phys; DeadLayerFrontside_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, 2.89*cm-d_front/2), DeadLayerFrontside_log, "DeadLayerFrontsideGe(Li)", Crystal_log, false, 0); //--------------------- Deadlayer-endside *************************** groove now moves with R-hole !!!!!! dR=1.25mm, Sgroove=3.25mm ************************** //--------------------- Part 1 (GeLi-diffused part) (thickness made equal to side DL) G4Tubs* DeadLayerEndside1_tubs = new G4Tubs("DeadLayerEndside1_tubs", hole_radius+0.5*cm, 3.22*cm-d_side, d_side/2, 0, 2*M_PI); G4LogicalVolume* DeadLayerEndside1_log = new G4LogicalVolume(DeadLayerEndside1_tubs, GeLi, "DeadLayerEndside1_log", 0, 0, 0); DeadLayerEndside1_log -> SetVisAttributes(GeLicolour); /* G4VPhysicalVolume* DeadLayerEndside1_phys; DeadLayerEndside1_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, d_side/2-2.89*cm), DeadLayerEndside1_log, "DeadLayerEndside1Ge(Li)", Crystal_log, false, 0); //--------------------- Part 2 (GeB-diffused part) G4Tubs* DeadLayerEndside2_tubs = new G4Tubs("DeadLayerEndside2_tubs", hole_radius+0.00015*mm, hole_radius+0.175*cm, 0.00015*mm, 0, 2*M_PI); G4LogicalVolume* DeadLayerEndside2_log = new G4LogicalVolume(DeadLayerEndside2_tubs, GeB, "DeadLayerEndside2_log", 0, 0, 0); DeadLayerEndside2_log -> SetVisAttributes(GeBcolour); /* G4VPhysicalVolume* DeadLayerEndside2_phys; DeadLayerEndside2_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -2.889985*cm), DeadLayerEndside2_log, "DeadLayerEndside2Ge(B)", Crystal_log, false, 0); //--------------------- Small Hole between Part 1 and 2 of the deadlayer-endside = crystal groove G4Tubs* HoleBetweenPart1And2_tubs = new G4Tubs("HoleBetweenPart1And2_tubs", hole_radius+0.175*cm, hole_radius+0.5*cm, 0.2*cm, 0, 2*M_PI); G4LogicalVolume* HoleBetweenPart1And2_log = new G4LogicalVolume(HoleBetweenPart1And2_tubs, Vacuum, "HoleBetweenPart1And2_log", 0, 0, 0); HoleBetweenPart1And2_log -> SetVisAttributes(Vacuumcolour); /* G4VPhysicalVolume* HoleBetweenPart1And2_phys; HoleBetweenPart1And2_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., -2.69*cm), HoleBetweenPart1And2_log, "HoleBetweenPart1And2Vac", Crystal_log, false, 0); //--------------------- Deadlayer around crystal-hole (fullfilled) G4Tubs* DeadLayerAroundHole_tubs = new G4Tubs("DeadLayerAroundHole_tubs", 0., hole_radius+0.00015*mm, hole_length/2+0.00015*mm, 0, 2*M_PI); G4LogicalVolume* DeadLayerAroundHole_log = new G4LogicalVolume(DeadLayerAroundHole_tubs, GeB, "DeadLayerAroundHole_log", 0, 0, 0); DeadLayerAroundHole_log -> SetVisAttributes(GeBcolour); /* G4VPhysicalVolume* DeadLayerAroundHole_phys; DeadLayerAroundHole_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, hole_length/2+0.00015*mm-2.89*cm), DeadLayerAroundHole_log, "DeadLayerAroundHoleGe(B)", Crystal_log, false, 0); //--------------------- Vacuum inside the crystal-hole G4Tubs* VacuumInCrystalHole_tubs = new G4Tubs("VacuumInCrystalHole_tubs", 0., hole_radius, hole_length/2, 0, 2*M_PI); G4LogicalVolume* VacuumInCrystalHole_log = new G4LogicalVolume(VacuumInCrystalHole_tubs, Vacuum, "VacuumInCrystalHole_log", 0, 0, 0); VacuumInCrystalHole_log -> SetVisAttributes(Vacuumcolour); /* G4VPhysicalVolume* VacuumInCrystalHole_phys; VacuumInCrystalHole_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -0.00015*mm), VacuumInCrystalHole_log, "VacuumInCrystalHole", DeadLayerAroundHole_log, false, 0); //--------------------- Part 1 of the contact-spring in the crystal-hole = chineese hat G4Cons* ContactSpringPart1_cons = new G4Cons("ContactSpringPart1_cons", 0.4*cm, 0.5*cm, 0.01*cm, 0.1*cm, 0.25*cm, 0, 2*M_PI); G4LogicalVolume* ContactSpringPart1_log = new G4LogicalVolume(ContactSpringPart1_cons, Bronze, "ContactSpringPart1", 0, 0, 0); ContactSpringPart1_log -> SetVisAttributes(Bronzecolour); /* G4VPhysicalVolume* ContactSpringPart1_phys; ContactSpringPart1_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., 0.25*cm-hole_length/2), ContactSpringPart1_log, "ContactSpringPart1Bronze", VacuumInCrystalHole_log, false, 0); //--------------------- Vacuum at cavitiy in the endside of the TeflonCrystalCup G4Tubs* VacuumInTeflonCrystalCup_tubs = new G4Tubs("VacuumInTeflonCrystalCu_tubs", 0., 1.97*cm, 0.05*cm, 0, 2*M_PI); G4LogicalVolume* VacuumInTeflonCrystalCup_log = new G4LogicalVolume(VacuumInTeflonCrystalCup_tubs, Vacuum, "VacuumInTeflonCrystalCup_log", 0, 0, 0); VacuumInTeflonCrystalCup_log -> SetVisAttributes(Vacuumcolour); /* G4VPhysicalVolume* VacuumInTeflonCrystalCup_phys ; VacuumInTeflonCrystalCup_phys = */ new G4PVPlacement(0, G4ThreeVector(0, 0, -2.89*cm), VacuumInTeflonCrystalCup_log, "VacuumInTeflonCrystalCup", TeflonCrystalCup_log, false, 0); //--------------------- Part 2 of the contact spring in the cavity of the TeflonCrystalCup G4Cons* ContactSpringPart2_cons = new G4Cons("ContactSpringPart2_cons", 0.5*cm, 0.6*cm, 0.4*cm, 0.5*cm, 0.05*cm, 0, 2*M_PI); G4LogicalVolume* ContactSpringPart2_log = new G4LogicalVolume(ContactSpringPart2_cons, Bronze, "ContactSpringPart2", 0, 0, 0); ContactSpringPart2_log -> SetVisAttributes(Bronzecolour); /* G4VPhysicalVolume* ContactSpringPart2_phys; ContactSpringPart2_phys = */ new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), ContactSpringPart2_log, "ContactSpringPart2Bronze", VacuumInTeflonCrystalCup_log , false, 0); // --------------------------------------------------------------------------------------- // --- The samples // --------------------------------------------------------------------------------------- G4VSolid* sample_shape=0; if (G4Material::GetMaterial(sample_mat_name)) sample_mat = G4Material::GetMaterial(sample_mat_name); else { MGLog(error) << "The material called " << sample_mat_name << " does not exist" << endlog; MGLog(error) << "Please check and run MaGe again!" << endlog; G4Exception("GECorradoDetector::ConstructDetector()","err001",FatalException,"Exit MaGe"); } if (sample_geom=="none") { //---- for point-like sources } else if (sample_geom=="box") { // Keep this geometry unchanged to avoid confusion with macro writing! // Use the sample geometry "custom" is for any non-standard samples that require coding. sample_shape = new G4Box("sample_box", box_width/2, box_height/2, box_thickness/2); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log",0 , 0, 0); sample_log -> SetVisAttributes(Sample_Colour); // the position of the middle of the BACK SIDE of the sample relative to the center of the front of detector cap! // e.g. at position 0 0 0, the sample is just in front of the cap, touching it new G4PVPlacement(0, G4ThreeVector(s_x, s_y, s_z+box_thickness/2+5.6*cm), sample_log, "sample", N2Chamber_log, false, 0); } else if (sample_geom=="tube") { // Keep this geometry unchanged to avoid confusion with macro writing! // Use the sample geometry "custom" is for any non-standard samples that require coding. sample_shape = new G4Tubs("sample_tube", tube_innrad, tube_outrad, tube_length/2, 0, tube_angle); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); // the position of the middle of the BACK SIDE of the sample relative to the center of the front of detector cap! // e.g. at position 0 0 0, the sample is just in front of the cap, touching it new G4PVPlacement(0, G4ThreeVector(s_x, s_y, s_z+tube_length/2+5.6*cm), sample_log, "sample", N2Chamber_log, false, 0); } else if (sample_geom=="sbox") { // Keep this geometry unchanged to avoid confusion with macro writing! // Use the sample geometry "custom" is for any non-standard samples that require coding. // --- standard cylindrical box // box cover (the thinner wall) is facing the detector!!!!!!! // z-position of the sample relative to the acrylic box can be adjusted by box_width parameter G4Tubs* detplasticcap_tubs = new G4Tubs("detplasticcap_tubs", 0.*cm, 3.81*cm, 0.05*cm, 0, 2*M_PI); G4LogicalVolume* detplasticcap_log = new G4LogicalVolume(detplasticcap_tubs, Acrylic, "detplasticcap_log", 0, 0, 0); detplasticcap_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, s_z+5.6*cm+0.05*cm), detplasticcap_log, "detplasticcap", N2Chamber_log, false, 0); G4Tubs* detplasticcap1_tubs = new G4Tubs("detplasticcap1_tubs", 0.*cm, 3.81*cm, 0.075*cm, 0, 2*M_PI); G4LogicalVolume* detplasticcap1_log = new G4LogicalVolume(detplasticcap1_tubs, Acrylic, "detplasticcap1_log", 0, 0, 0); detplasticcap1_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, s_z+5.6*cm+2.975*cm), detplasticcap1_log, "detplasticcap1", N2Chamber_log, false, 0); G4Tubs* detplasticshell_tubs = new G4Tubs("detplasticshell_tubs", 3.65*cm, 3.81*cm, 1.4*cm, 0, 2*M_PI); G4LogicalVolume* detplasticshell_log = new G4LogicalVolume(detplasticshell_tubs, Acrylic, "detplasticshell_log", 0, 0, 0); detplasticshell_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, s_z+5.6*cm+1.5*cm), detplasticshell_log, "detplasticshell", N2Chamber_log, false, 0); // cylinder sample inside the standard box (default - filling the volume) sample_shape = new G4Tubs("sample_tube", tube_innrad, tube_outrad, tube_length/2, 0, tube_angle); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); // the position of the middle of the BACK SIDE of the sample relative to the center of the front of detector cap! // e.g. at position 0 0 0, the sample is just in front of the cap, touching it new G4PVPlacement(0, G4ThreeVector(s_x, s_y, s_z+box_width+5.6*cm+1.5*cm), sample_log, "sample", N2Chamber_log, false, 0); } else if (sample_geom=="liquid") { // Keep this geometry unchanged to avoid confusion with macro writing! // Use the sample geometry "custom" is for any non-standard samples that require coding. // --- standard cylindrical box _with liquid sample_ // // box cover (the thinner wall) is facing the detector!!!!!!! G4Tubs* detplasticcap_tubs = new G4Tubs("detplasticcap_tubs", 0.*cm, 3.81*cm, 0.05*cm, 0, 2*M_PI); G4LogicalVolume* detplasticcap_log = new G4LogicalVolume(detplasticcap_tubs, Acrylic, "detplasticcap_log", 0, 0, 0); detplasticcap_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, s_z+5.6*cm+0.05*cm), detplasticcap_log, "detplasticcap", N2Chamber_log, false, 0); G4Tubs* detplasticcap1_tubs = new G4Tubs("detplasticcap1_tubs", 0.*cm, 3.81*cm, 0.075*cm, 0, 2*M_PI); G4LogicalVolume* detplasticcap1_log = new G4LogicalVolume(detplasticcap1_tubs, Acrylic, "detplasticcap1_log", 0, 0, 0); detplasticcap1_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, s_z+5.6*cm+2.975*cm), detplasticcap1_log, "detplasticcap1", N2Chamber_log, false, 0); G4Tubs* detplasticshell_tubs = new G4Tubs("detplasticshell_tubs", 3.65*cm, 3.81*cm, 1.4*cm, 0, 2*M_PI); G4LogicalVolume* detplasticshell_log = new G4LogicalVolume(detplasticshell_tubs, Acrylic, "detplasticshell_log", 0, 0, 0); detplasticshell_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, s_z+5.6*cm+1.5*cm), detplasticshell_log, "detplasticshell", N2Chamber_log, false, 0); // liquid filling the standard box up to level of "boxheight" G4VSolid* sample_body = new G4Tubs("sample_tube", tube_innrad, tube_outrad, tube_length/2, 0, tube_angle); G4VSolid* sample_hole = new G4Box("sample_hole", tube_outrad+0.1*cm, tube_outrad, tube_length/2+0.1*cm); sample_shape = new G4SubtractionSolid("sample_shape", sample_body, sample_hole, 0, G4ThreeVector(0., 2*tube_outrad-box_height,0.)); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); // the position of the middle of the BACK SIDE of the sample relative to the center of the front of detector cap! // e.g. at position 0 0 0, the sample is just in front of the cap, touching it new G4PVPlacement(0, G4ThreeVector(s_x, s_y, s_z+5.6*cm+1.5*cm), sample_log, "sample", N2Chamber_log, false, 0); } else if (sample_geom=="marinelli") { // Keep this geometry unchanged to avoid confusion with macro writing! // Use the sample geometry "custom" is for any non-standard samples that require coding. // "marinelli" shape (box with a hole) G4VSolid* sample_body = new G4Box("sample_box", box_width/2, box_height/2, box_thickness/2); G4VSolid* sample_hole = new G4Tubs("sample_tube", 0., tube_outrad, tube_length, 0, tube_angle); sample_shape = new G4SubtractionSolid("sample_shape", sample_body, sample_hole, 0, G4ThreeVector(0., tube_innrad, -box_thickness/2)); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); // the position of the middle of the BACK SIDE of the sample relative to the center of the front of detector cap! // e.g. at position 0 0 0, the sample is just in front of the cap, touching it new G4PVPlacement(0, G4ThreeVector(s_x, s_y, s_z+box_thickness/2+5.6*cm), sample_log, "sample", N2Chamber_log, false, 0); } else if (sample_geom=="roundmarinelli") { // Keep this geometry unchanged to avoid confusion with macro writing! // Use the sample geometry "custom" is for any non-standard samples that require coding. // box_height = liquid level measured from center // box_width = (external) length of the front part // box_thickness = wall thickness (also the difference between front and belt radius) // tube_innrad = radius of internal hole // tube_outrad = external radius of the belt part // tube_length = length of the belt part ( = depth of internal hole) // true marinelli shape (tube with a hole), including PE (?) contaniner of thickness "boxthickness" and hole depth "boxwidth" // G4VSolid* marinelli1_tube = new G4Tubs("marinelli1_tube", tube_innrad, tube_outrad, tube_length/2, 0, tube_angle); G4VSolid* marinelli2_tube = new G4Tubs("marinelli2_tube", 0, tube_outrad+box_thickness, box_width/2, 0, tube_angle); G4VSolid* marinelli_shape = new G4UnionSolid("marinelli_shape", marinelli1_tube, marinelli2_tube, 0, G4ThreeVector(0., 0.,tube_length/2+box_width/2)); // G4LogicalVolume* marinelli_log = new G4LogicalVolume(marinelli_shape, PE, "marinelli_log", 0, 0, 0); marinelli_log -> SetVisAttributes(Acryliccolour); // // the position of the middle of the BACK SIDE of the sample container relative to the center of the front of detector cap! // e.g. at position 0 0 0, the sample is just in front of the cap, touching it new G4PVPlacement(0, G4ThreeVector(s_x, s_y, s_z-tube_length/2+5.6*cm), marinelli_log, "MarinelliPEHousing", N2Chamber_log, false, 0); // G4VSolid* sample1_tube = new G4Tubs("sample1_tube", tube_innrad+box_thickness, tube_outrad-box_thickness, tube_length/2, 0, tube_angle); G4VSolid* sample2_tube = new G4Tubs("sample2_tube", 0, tube_outrad, box_width/2-box_thickness, 0, tube_angle); G4VSolid* sample_upper = new G4Box("sample_upper", 10.*cm, 10.*cm, 20.*cm); G4VSolid* sample_lower = new G4Box("sample_lower", 10.*cm, 10.*cm, 20.*cm); // G4VSolid* help1_shape = new G4UnionSolid("help1_shape", sample1_tube, sample2_tube, 0, G4ThreeVector(0., 0.,tube_length/2+box_width/2-box_thickness)); sample_shape = new G4SubtractionSolid("sample_shape", help1_shape, sample_upper, 0, G4ThreeVector(0., box_height+10.*cm,0.)); G4VSolid* N2blanket_shape= new G4SubtractionSolid("N2blanket_shape", help1_shape, sample_lower, 0, G4ThreeVector(0., box_height-10.*cm,0.)); G4LogicalVolume* N2blanket_log = new G4LogicalVolume(N2blanket_shape, N2Gas, "N2blanket_log", 0, 0, 0); N2blanket_log -> SetVisAttributes(N2Gascolour); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); // new G4PVPlacement(0, G4ThreeVector(0, 0, box_thickness), N2blanket_log, "N2blanket", marinelli_log, false, 0); new G4PVPlacement(0, G4ThreeVector(0, 0, box_thickness), sample_log, "sample", marinelli_log, false, 0); } else if (sample_geom=="custom") { // here define any other sample geometry - feel free to replace contents /* // ------------ NPL-C: small cylindrical box (cover side facing detector) , z-position can be adjusted by box_width parameter -------------- //--------------- double plastic wrap around the box (approximated by one disc) G4Tubs* detplastic_tubs = new G4Tubs("detplastic_tubs", 0.*cm, 4.*cm, 0.0125*cm, 0, 2*M_PI); G4LogicalVolume* detplastic_log = new G4LogicalVolume(detplastic_tubs, PE, "detplastic_log", 0, 0, 0); detplastic_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, box_width+5.6*cm+0.0125*cm), detplastic_log, "detplastic", N2Chamber_log, false, 0); G4Tubs* detplasticcap_tubs = new G4Tubs("detplasticcap_tubs", 0.*cm, 2.13*cm, 0.04*cm, 0, 2*M_PI); G4LogicalVolume* detplasticcap_log = new G4LogicalVolume(detplasticcap_tubs, Acrylic, "detplasticcap_log", 0, 0, 0); detplasticcap_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, box_width+5.6*cm+0.065*cm), detplasticcap_log, "detplasticcap", N2Chamber_log, false, 0); G4Tubs* detplasticshell_tubs = new G4Tubs("detplasticshell_tubs", 2.13*cm, 2.26*cm, 0.86*cm, 0, 2*M_PI); G4LogicalVolume* detplasticshell_log = new G4LogicalVolume(detplasticshell_tubs, Acrylic, "detplasticshell_log", 0, 0, 0); detplasticshell_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, box_width+5.6*cm+0.965*cm), detplasticshell_log, "detplasticshell", N2Chamber_log, false, 0); G4Tubs* detplasticcap1_tubs = new G4Tubs("detplasticcap1_tubs", 0.*cm, 2.26*cm, 0.055*cm, 0, 2*M_PI); G4LogicalVolume* detplasticcap1_log = new G4LogicalVolume(detplasticcap1_tubs, Acrylic, "detplasticcap1_log", 0, 0, 0); detplasticcap1_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, box_width+5.6*cm+1.88*cm), detplasticcap1_log, "detplasticcap1", N2Chamber_log, false, 0); // cylinder sample inside the standard box (filling the volume, no options) sample_shape = new G4Tubs("sample_tube", 0, 2.13*cm, 0.86*cm, 0, tube_angle); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); new G4PVPlacement(0, G4ThreeVector(0, 0, box_width+5.6*cm+0.965*cm), sample_log, "sample", N2Chamber_log, false, 0); */ //---------------------------------- 7 Flexible steel tubes (sample 205) ------------------------------- /* G4Tubs* flexsteel_tubs = new G4Tubs("flexsteel_tubs", 1*cm, 1.35*cm, 5*cm, 0, 2*M_PI); //sample_shape = new G4Tubs("sample_tube", tube_innrad, tube_outrad, tube_length/2, 0, tube_angle); G4VSolid* flexsteel_tubs2 = new G4UnionSolid("flexsteel_tubs2", flexsteel_tubs, flexsteel_tubs, 0, G4ThreeVector(2.7*cm,0.,0.)); G4VSolid* flexsteel_tubs3 = new G4UnionSolid("flexsteel_tubs3", flexsteel_tubs2, flexsteel_tubs, 0, G4ThreeVector(-2.7*cm,0.,0.)); G4RotationMatrix* halfPi_z_rot = new G4RotationMatrix; halfPi_z_rot -> rotateZ(0.5*M_PI); G4VSolid* flexsteel_tubs5 = new G4UnionSolid("flexsteel_tubs5", flexsteel_tubs3, flexsteel_tubs2, halfPi_z_rot, G4ThreeVector(5.6*cm,5.4*cm,0.)); G4VSolid* flexsteel_tubs7 = new G4UnionSolid("flexsteel_tubs7", flexsteel_tubs5, flexsteel_tubs2, halfPi_z_rot, G4ThreeVector(-5.6*cm,5.4*cm,0.)); G4LogicalVolume* sample_log = new G4LogicalVolume(flexsteel_tubs7, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); G4RotationMatrix* halfPi_x_rot = new G4RotationMatrix; halfPi_x_rot -> rotateX(0.5*M_PI); new G4PVPlacement(halfPi_x_rot, G4ThreeVector(s_x, s_y, s_z+1.35*cm+5.6*cm), sample_log, "sample", N2Chamber_log, false, 0); */ // ------------------------------------ SAMPLE 0220_1: Air Filter --------------------------------// //Cylindrical box encapsulating the CELLAR Air sample for measurement 0220_1 in February 2009 //Box directly attached to the front of the detector endcap //Geometry: Radius = 2.5 cm; Margin-Width = 0.025 cm; // Height = 0.5 cm; Margin Top/Bottom = 0.025 cm each /* G4Tubs* detplasticcap1_tubs = new G4Tubs("detplasticcap1_tubs", 0.*cm, 2.55*cm, 0.0125*cm, 0, 2*M_PI); G4LogicalVolume* detplasticcap1_log = new G4LogicalVolume(detplasticcap1_tubs, PVC, "detplasticcap1_log", 0, 0, 0); detplasticcap1_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, s_z+5.6*cm+0.0125*cm), detplasticcap1_log, "detplasticcap1", N2Chamber_log, false, 0); G4Tubs* detplasticshell_tubs = new G4Tubs("detplasticshell_tubs", 2.50*cm, 2.55*cm, 0.25*cm, 0, 2*M_PI); G4LogicalVolume* detplasticshell_log = new G4LogicalVolume(detplasticshell_tubs, PVC, "detplasticshell_log", 0, 0, 0); detplasticshell_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(0, G4ThreeVector(0, 0, s_z+5.6*cm+0.025*cm+0.25*cm), detplasticshell_log, "detplasticshell", N2Chamber_log, false, 0); // cylinder sample inside the standard box (default - filling the volume) sample_shape = new G4Tubs("sample_tube", 0.0*cm, 2.5*cm, 0.25*cm, 0, 2*M_PI); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); new G4PVPlacement(0, G4ThreeVector(s_x, s_y, s_z+5.6*cm+0.025*cm+0.25*cm), sample_log, "sample", N2Chamber_log, false, 0); */ /* // -------------------------------------- SAMPLE 0224/0225: Krypton tubes --------------------------- // G4Material* CovarGlass = G4Material::GetMaterial("covarglass"); //Peculiarly formed cobar glass tubes containing krypton gas sample //directly attached to the detector end cap //Measurement in March 2009 //--- ROTATIONS ---// G4RotationMatrix* Pi_x_rot = new G4RotationMatrix; Pi_x_rot -> rotateX(1.0*M_PI); G4RotationMatrix* halfPi_x_rot = new G4RotationMatrix; halfPi_x_rot -> rotateX(0.5*M_PI); G4RotationMatrix* halfPi_x_rot_2 = new G4RotationMatrix; halfPi_x_rot_2 -> rotateX(1.5*M_PI); //--- GLASS CASING (inside casing) ---// //Sample volume in top cone G4Cons* cone_top = new G4Cons("cone_top", .0*cm, .25*cm, .0*cm, .000001*cm, .600*cm, 0, 2.0*M_PI); //Sample volume in cylinder top G4Tubs* cylinder_top = new G4Tubs("cylinder_top", 0.25*cm, 0.70*cm, 0.06*cm, 0, 2*M_PI); //Sample volume in cylinder G4Tubs* cylinder = new G4Tubs("cylinder", 0.0*cm, 0.70*cm, 1.00*cm, 0, 2*M_PI); //Sample volume in bottom cone G4Cons* cone_bottom = new G4Cons("cone_bottom", .0*cm, .70*cm, .0*cm, .000001*cm, .500*cm, 0, 2*M_PI); //--- GROUP CASING ---// G4VSolid* help_shape_1 = new G4UnionSolid("help_shape_1", cylinder, cylinder_top, 0, G4ThreeVector(0., 0.,1.060*cm)); G4VSolid* help_shape_2 = new G4UnionSolid("help_shape_2", help_shape_1, cone_top, 0, G4ThreeVector(0., 0.,1.720*cm)); G4VSolid* casing_shape = new G4UnionSolid("casing_shape", help_shape_2, cone_bottom, Pi_x_rot, G4ThreeVector(0., 0.,-1.500*cm)); //--- PLACE CASING as physical Volume ---// G4LogicalVolume* casing_log = new G4LogicalVolume(casing_shape, CovarGlass, "casing_log", 0, 0, 0); casing_log -> SetVisAttributes(Acryliccolour); G4VPhysicalVolume* casing_phys; casing_phys = new G4PVPlacement(halfPi_x_rot, G4ThreeVector(0, 0, s_z+5.6*cm+0.7*cm), casing_log, "glasscasing", N2Chamber_log, false, 0); //--- SAMPLE VOLUME (inside casing) ---// //Sample volume in top cone G4Cons* cone_top_sample = new G4Cons("cone_top_sample", 0.0*cm, 0.19*cm, 0.0*cm, 0.0000001*cm, 0.45*cm, 0, 2.0*M_PI); //Sample volume in cylinder top G4Tubs* cylinder_top_sample = new G4Tubs("cylinder_top_sample", 0.0*cm, 0.20*cm, 0.06*cm, 0, 2*M_PI); //Sample volume in cylinder G4Tubs* cylinder_sample = new G4Tubs("cylinder_sample", 0.0*cm, 0.58*cm, 1.00*cm, 0, 2*M_PI); //Sample volume in bottom cone G4Cons* cone_bottom_sample = new G4Cons("cone_bottom_sample", .0*cm, .58*cm, .0*cm, .000001*cm, .415*cm, 0, 2*M_PI); //--- GROUP SAMPLE PARTS ---// G4VSolid* help_shape_3 = new G4UnionSolid("help_shape_3", cylinder_sample, cylinder_top_sample, 0, G4ThreeVector(0., 0.,1.060*cm)); G4VSolid* help_shape_4 = new G4UnionSolid("help_shape_4", help_shape_3, cone_top_sample, 0, G4ThreeVector(0., 0.,1.570*cm)); G4VSolid* sample_shape = new G4UnionSolid("sample_shape", help_shape_4, cone_bottom_sample, Pi_x_rot, G4ThreeVector(0., 0.,-1.415*cm)); //--- PLACE SAMPLE inside the glass casing ---// G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); new G4PVPlacement(0, G4ThreeVector(0, 0, 0), sample_log, "sample", casing_log, false, 0); */ //----------------------------------- SAMPLE 0225_1: SIMPLE CYLINDRICAL GEOMETRY (for efficiency test) -------------------------------------- // /* //--- ROTATIONS ---// G4RotationMatrix* Pi_x_rot = new G4RotationMatrix; Pi_x_rot -> rotateX(1.0*M_PI); G4RotationMatrix* halfPi_x_rot = new G4RotationMatrix; halfPi_x_rot -> rotateX(0.5*M_PI); G4RotationMatrix* halfPi_x_rot_2 = new G4RotationMatrix; halfPi_x_rot_2 -> rotateX(1.5*M_PI); //Sample volume in cylinder top G4Tubs* cylinder_top = new G4Tubs("cylinder_top", 0.0*cm, 0.70*cm, 0.06*cm, 0, 2*M_PI); //Sample volume in cylinder G4Tubs* cylinder = new G4Tubs("cylinder", 0.0*cm, 0.70*cm, 1.15*cm, 0, 2*M_PI); //Sample volume in cylinder bottom G4Tubs* cylinder_bottom = new G4Tubs("cylinder_bottom", 0.0*cm, 0.70*cm, 0.06*cm, 0, 2*M_PI); G4VSolid* help_shape_1 = new G4UnionSolid("help_shape_1", cylinder, cylinder_top, 0, G4ThreeVector(0., 0.,1.210*cm)); G4VSolid* casing_shape = new G4UnionSolid("casing_shape", help_shape_1, cylinder_bottom, 0, G4ThreeVector(0., 0.,-1.210*cm)); //--- PLACE CASING as physical Volume ---// G4LogicalVolume* casing_log = new G4LogicalVolume(casing_shape, CovarGlass, "casing_log", 0, 0, 0); casing_log -> SetVisAttributes(Acryliccolour); G4VPhysicalVolume* casing_phys; casing_phys = new G4PVPlacement(halfPi_x_rot, G4ThreeVector(0, 0, s_z+5.6*cm+0.7*cm), casing_log, "glasscasing", N2Chamber_log, false, 0); //Sample volume in cylinder G4Tubs* sample_shape = new G4Tubs("sample_shape", 0.0*cm, 0.58*cm, 1.15*cm, 0, 2*M_PI); //--- PLACE SAMPLE inside the glass casing ---// G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); new G4PVPlacement(0, G4ThreeVector(0, 0, 0), sample_log, "sample", casing_log, false, 0); // -------------------------------------- SAMPLE 0221-0223: Erbium sample (from MPIK-EBIT) --------------------------- // //Small pieces of erbium placed directly at the end cap of the detector //Simulated volume: small cylindrical piece of erbium G4Tubs* sample_shape = new G4Tubs("sample_shape", 0.0*cm, 0.3*cm, 0.075*cm, 0, 2*M_PI); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); new G4PVPlacement(0, G4ThreeVector(s_x, s_y, s_z+box_width+5.6*cm+0.2*cm), sample_log, "sample", N2Chamber_log, false, 0); // --------------------------------------- SAMPLE 0230: Krypton in cylindrical glass vessel ------------------------- // G4Material* DuranGlass = G4Material::GetMaterial("duranglass"); //--- GLASS CASING G4Tubs* cylinder = new G4Tubs("cylinder", 0.0*cm, 2.00*cm, 2.40*cm, 0, 2*M_PI); G4Cons* cone = new G4Cons("cone", .0*cm, 2.00*cm, .0*cm, 0.60*cm, 0.60*cm, 0, 2.0*M_PI); G4VSolid* casing_shape = new G4UnionSolid("casing_shape", cylinder, cone, 0, G4ThreeVector(0., 0.,3.00*cm)); //--- PLACE CASING as physical Volume ---// G4LogicalVolume* casing_log = new G4LogicalVolume(casing_shape, DuranGlass, "casing_log", 0, 0, 0); casing_log -> SetVisAttributes(Acryliccolour); G4VPhysicalVolume* casing_phys; casing_phys = new G4PVPlacement(0, G4ThreeVector(0, -6.30*cm, s_z+5.6*cm-3.00*cm), casing_log, "glasscasing", N2Chamber_log, false, 0); //--- SAMPLE VOLUME G4Tubs* cylinder_sample = new G4Tubs("cylinder_sample", 0.0*cm, 1.90*cm, 2.30*cm, 0, 2*M_PI); G4Cons* cone_sample = new G4Cons("cone_sample", .0*cm, 1.90*cm, .0*cm, 0.50*cm, 0.60*cm, 0, 2.0*M_PI); G4VSolid* sample_shape = new G4UnionSolid("sample_shape", cylinder_sample, cone_sample, 0, G4ThreeVector(0., 0.,2.90*cm)); //--- PLACE SAMPLE inside the glass casing ---// G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); new G4PVPlacement(0, G4ThreeVector(0, 0, 0), sample_log, "sample", casing_log, false, 0); //--- Copper underlay G4Box* underlay = new G4Box("underlay_shape", 1.5*cm, 0.85*cm, 7.50*cm); G4LogicalVolume* underlay_log = new G4LogicalVolume(underlay, Cu, "underlay_log", 0, 0, 0); underlay_log -> SetVisAttributes(Cucolour); new G4PVPlacement(0, G4ThreeVector(0, -9.15*cm, s_z+5.6*cm), underlay_log, "underlay", N2Chamber_log, false, 0); */ // ----------------------------------- SAMPLE 0229: Steal screw threads for DOUBLE CHOOZ --------------------- // G4RotationMatrix* Pi_y_rot = new G4RotationMatrix; Pi_y_rot -> rotateY(1.0*M_PI); G4RotationMatrix* halfPi_y_rot = new G4RotationMatrix; halfPi_y_rot -> rotateY(0.5*M_PI); //Sample Volume //Parts of single steel thread G4Tubs* cylinder_head = new G4Tubs("cylinder_head", 0.5*cm, 1.60*cm, 2.00*cm, 0, 2*M_PI); G4Tubs* cylinder_body = new G4Tubs("cylinder_body", 0.0*cm, 0.60*cm, 6.50*cm, 0, 2*M_PI); //Single steel thread G4VSolid* single_thread_1 = new G4UnionSolid("single_thread_1", cylinder_body, cylinder_head, 0, G4ThreeVector(0., 0.,8.50*cm)); G4VSolid* single_thread_2 = new G4UnionSolid("single_thread_2", cylinder_body, cylinder_head, 0, G4ThreeVector(0., 0.,8.50*cm)); //Double steel thread G4VSolid* double_thread = new G4UnionSolid("double_thread",single_thread_1,single_thread_2, Pi_y_rot, G4ThreeVector(2.40*cm, 0.,4.00*cm)); //Quadruple steel thread G4VSolid* quad_thread = new G4UnionSolid("quad_thread",double_thread,double_thread, 0, G4ThreeVector(2*2.40*cm, 0,0)); //Octuple steel thread G4VSolid* oct_thread = new G4UnionSolid("oct_thread",quad_thread,quad_thread, 0, G4ThreeVector(4*2.40*cm, 0,0)); //Dodekanuple steel thread G4VSolid* twelve_thread = new G4UnionSolid("twelve_thread",oct_thread,quad_thread, halfPi_y_rot, G4ThreeVector(10.5*cm, 0, 13.0*cm)); //PLACE twelve steel threads as sample volume G4LogicalVolume* twelve_thread_log = new G4LogicalVolume(twelve_thread, Fe, "twelve_thread_log", 0, 0, 0); twelve_thread_log -> SetVisAttributes(Fecolour); new G4PVPlacement(0, G4ThreeVector(-8.4*cm, -8.4*cm, -3.50*cm), twelve_thread_log, "sample", N2Chamber_log, false, 0); } else if (sample_geom=="collimator") { //----------------------- THE COLLIMATOR ----------------------------------------------- G4VSolid* Collimator_Body = new G4Box("Collimator_Body", 3.5*cm, 3.5*cm, 2.*cm); G4VSolid* Collimator_Hole = new G4Tubs("Collimator_Hole", 0., 0.079*cm, 2.*cm, 0, 2*M_PI); G4VSolid* Collimator = new G4SubtractionSolid("Collimator", Collimator_Body, Collimator_Hole, 0, G4ThreeVector(0, 0, 0)); G4LogicalVolume* Collimator_log = new G4LogicalVolume(Collimator, Pb, "Collimator_log", 0, 0, 0); new G4PVPlacement(0, G4ThreeVector(coll_x ,coll_y ,coll_z), Collimator_log, "CollimatorPb", N2Chamber_log, false, 0); Collimator_log -> SetVisAttributes(Collimatorcolour); } else if (sample_geom=="NPL-GL") { //----------------------------------- NPL bottle with fancy shape :-) ------------------------------------- //rotate 90deg up : G4RotationMatrix* halfPi_x_rot = new G4RotationMatrix; halfPi_x_rot -> rotateX(0.5*M_PI); //--------------- plastic wrap around the box (approximated by one shell) G4Tubs* detplastic_tubs = new G4Tubs("detplastic_tubs", 3.62*cm, 3.6325*cm, 8*cm, 0, 2*M_PI); G4LogicalVolume* detplastic_log = new G4LogicalVolume(detplastic_tubs, PE, "detplastic_log", 0, 0, 0); detplastic_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(halfPi_x_rot, G4ThreeVector(0, 0, box_width+5.6*cm+3.6325*cm), detplastic_log, "detplastic", N2Chamber_log, false, 0); // --------------------------- The NPL bottle G4Tubs* NPLbottle_tubs = new G4Tubs("NPLbottle_tubs", 0., 3.62*cm, 6.5*cm, 0, 2*M_PI); //bottom of the bottle G4VSolid* bottom_sphere = new G4Sphere("bottom_sphere", 0., 3.975*cm, 0.,twopi, 0.,twopi); G4VSolid* cut_box = new G4Box("cut_box", 10.*cm, 10.*cm, 10.*cm); G4VSolid* bottom_first = new G4SubtractionSolid("bottom_first", bottom_sphere, cut_box, 0, G4ThreeVector(0., 0.,8.358*cm)); G4VSolid* bottom_shape = new G4SubtractionSolid("bottom_shape", bottom_first, cut_box, 0, G4ThreeVector(0., 0.,-12.642*cm)); G4VSolid* bottom2_sphere = new G4Sphere("bottom2_sphere", 0., 7.25*cm, 0.,twopi, 0.,twopi); //G4VSolid* bottom2_shape = new G4SubtractionSolid("bottom2_shape", bottom2_sphere, cut_box, 0, G4ThreeVector(0., 0.,-3.2*cm)); G4VSolid* NPLbottom_shape = new G4SubtractionSolid("NPLbottom_shape", bottom_shape, bottom2_sphere, 0, G4ThreeVector(0., 0.,-9.442*cm)); G4VSolid* NPLbottle_shape = new G4UnionSolid("NPLbottle_shape", NPLbottle_tubs, NPLbottom_shape, 0, G4ThreeVector(0.,0.,-4.858*cm)); G4LogicalVolume* NPLbottle_log = new G4LogicalVolume(NPLbottle_shape, PE, "NPLbottle_log", 0, 0, 0); NPLbottle_log -> SetVisAttributes(Acryliccolour); new G4PVPlacement(halfPi_x_rot, G4ThreeVector(0., 0.2*cm, box_width+5.6*cm+3.6325*cm), NPLbottle_log, "NPLbottle", N2Chamber_log, false, 0); //contents : cylinder G4VSolid* sample_tubs = new G4Tubs("sample_tube", 0., tube_outrad, box_height/2, 0, 2*M_PI); //bottom G4VSolid* Sbottom_sphere = new G4Sphere("Sbottom_sphere", 0., 3.875*cm, 0.,twopi, 0.,twopi); G4VSolid* Sbottom_first = new G4SubtractionSolid("Sbottom_first", Sbottom_sphere, cut_box, 0, G4ThreeVector(0., 0.,8.358*cm)); G4VSolid* Sbottom_shape = new G4SubtractionSolid("Sbottom_shape", Sbottom_first, cut_box, 0, G4ThreeVector(0., 0.,-12.5*cm)); G4VSolid* Sbottom2_sphere = new G4Sphere("Sbottom2_sphere", 0., 7.4*cm, 0.,twopi, 0.,twopi); G4VSolid* sample_first = new G4SubtractionSolid("sample_first", Sbottom_shape, Sbottom2_sphere, 0, G4ThreeVector(0., 0.,-9.442*cm)); sample_shape = new G4UnionSolid("sample_shape", sample_tubs, sample_first, 0, G4ThreeVector(0.,0.,6.5*cm-box_height/2-4.858*cm)); G4LogicalVolume* sample_log = new G4LogicalVolume(sample_shape, sample_mat, "sample_log", 0, 0, 0); sample_log -> SetVisAttributes(Sample_Colour); new G4PVPlacement(0, G4ThreeVector(0, 0, box_height/2-6.5*cm), sample_log, "sample", NPLbottle_log, false, 0); } else { MGLog(error) << "The shape is not defined " << endlog; MGLog(fatal) << endlog; G4Exception("GECorradoDetector::ConstructDetector()","err002",FatalException,"Check the shape type"); } //------------------------------------------------ // Sensitive detectors //------------------------------------------------ G4SDManager* SDman = G4SDManager::GetSDMpointer(); G4String CrystalSDname = "/mydet/gerda/gecrystal"; GEGeometrySD* CrystalSD = new GEGeometrySD(CrystalSDname); SDman->AddNewDetector(CrystalSD); Crystal_log-> SetSensitiveDetector(CrystalSD); SetDetectorLogical(experimentalHall_log); SetDetectorName("ExperimentalHall"); } //---------------------------------------------------------------------------// //---------------------------------------------------------------------------//
d68c6d9cf8c1fd8105950bf41757592f18d2fac1
8ba74a9f4923d01116b321f9f4570b02c8deb6e3
/deps/trucov/parser.h
359949151b246c8c5ed1b2682da752aebdb9825f
[ "MIT" ]
permissive
havocp/hwf
07d16c8b3a7eaa4c3c41537870e9b7b83c49f44b
a99e9a0461983226717b278513cfd9f1e53ba0f1
refs/heads/master
2021-01-19T11:25:46.193890
2014-01-24T18:53:21
2014-01-24T18:53:21
1,119,517
1
0
null
2014-01-24T08:54:09
2010-11-28T16:24:19
JavaScript
UTF-8
C++
false
false
9,574
h
parser.h
/////////////////////////////////////////////////////////////////////////////// // COPYRIGHT (c) 2009 Schweitzer Engineering Laboratories, Pullman, WA /////////////////////////////////////////////////////////////////////////////// // 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. /////////////////////////////////////////////////////////////////////////////// /// @file parser.h /// /// @brief /// Prototype GCNO/GCDA Parser /// /// @remarks /// Defines class Parser /// /// Requirements Specification: < Null > /// /// Design Description: < Null > /// /////////////////////////////////////////////////////////////////////////////// #ifndef PARSER_H #define PARSER_H // SYSTEM INCLUDES #include <string> #include <fstream> #include <iostream> #include <iomanip> #include <exception> #include <algorithm> #include <cstring> #include <iterator> #include <vector> #include <map> // PROJECT INCLUDES #include <boost/version.hpp> #if BOOST_VERSION < NEW_SPIRIT_VERSION #include <boost/spirit/core.hpp> #include <boost/spirit/tree/ast.hpp> #include <boost/spirit/tree/parse_tree.hpp> #else #include <boost/spirit/include/classic_core.hpp> #include <boost/spirit/include/classic_ast.hpp> #include <boost/spirit/include/classic_parse_tree.hpp> #endif // LOCAL INCLUDES #include "parser_builder.h" #include "gcno_grammar.h" #include "gcda_grammar.h" #include "record.h" #include "config.h" // DEFINTIIONS /////////////////////////////////////////////////////////////////////////////// /// @class Parser /// /// @brief /// Parser gcno and gcda files /// /// @remarks /// Class takes a name of a string when constructed, and then parses that /// file when the parse method is called /////////////////////////////////////////////////////////////////////////////// class Parser { public: // PUBLIC METHODS /// Destructor /// /// @brief /// Clean up the instance memory ~Parser() { if (ptr_instance != NULL) { delete ptr_instance; } } /// @brief /// Returns the single instance of this singleton. /// /// @return Returns a reference to the singleton Parser object static Parser & get_instance() { // Create instance is non existant if ( Parser::ptr_instance == NULL ) { ptr_instance = new Parser(); } return *ptr_instance; } // end of get_instance() /////////////////////////////////////////////////////////////////////////// /// Constructor with input file /// /// @param a an integer argument /// /// @remarks /// Constructs the Parser object and opens the input file given /////////////////////////////////////////////////////////////////////////// Parser(const char * gcnoFile, const char * gcdaFile); /////////////////////////////////////////////////////////////////////////// /// /// @return success(0), failure(-1) /// /// @remarks /// Parses the entire input file /// Pre : infile points to a valid input file stream /// Post : Parse Tree is constructed and all data on the program and test /// coverage has been gathered/calculated. /// Throw: IOException //////////////////////////////////////////////////////////////////////////// int parse(); int parse( const std::string & gcnoFile, const std::string & gcdaFile, const std::string & dumpFile ); int parse( const std::string & gcnoFile, const std::string & gcdaFile ); bool parse_all(); double get_coverage_percentage() const { return m_coverage_percentage; } std::map<std::string, Source_file> & get_source_files(); std::map<unsigned int, Record> & get_records(); // PUBLIC VARAIBLES static const int TagLength = 4; #ifdef DEBUGFLAG bool gui_dump( std::ofstream & out ) { std::map<std::string, Source_file> & sources = get_source_files(); for ( std::map<std::string, Source_file>::iterator it_src = sources.begin(); it_src != sources.end(); ++it_src ) { out << it_src->second.m_source_path << "\n" << it_src->second.m_coverage_percentage * 100 << "%\n"; std::map<unsigned int, Record> & records = it_src->second.m_records; for ( std::map<unsigned int, Record>::iterator it_rec = records.begin(); it_rec != records.end(); ++it_rec ) { out << it_rec->second.m_name_demangled << "\n" << it_rec->second.m_report_path << "\n" << it_rec->second.m_graph_path << "\n" << it_rec->second.m_line_num << "\n"; double den = it_rec->second.get_function_arc_total(); if ( den == 0 ) { double percentage = it_rec->second.get_coverage_percentage(); out << percentage * 100 << "%\n"; } else { double num = it_rec->second.get_function_arc_taken(); double percentage = it_rec->second.get_coverage_percentage(); out << percentage * 100 << "%\n"; } } out << "@@@__END_OF_SOURCE__@@@" << "\n"; } out << "@@@__END_OF_EVERYTHING__@@@" << "\n"; } #endif private: // PRIVATE METHODS /// @brief /// Constructs the Parser object, and initializes private data fields. /// /// @remarks /// Private default constructor required for singleton. explicit Parser() { // void } /// @brief /// Constructs this object to be exactly the same as the source. /// /// @remarks /// Private copy constructor required for singleton. explicit Parser( const Parser & source ) { // void } /// @brief /// Assigns this objects state to be the same as the source object. /// /// @remarks /// Private copy constructor required for singleton. Parser & operator=( const Parser & source ) { return *this; } /// Populate each Block's m_from_arcs with incoming Arc pointers void assign_entry_arcs(); /// Assign each counted Arc a value void assign_arc_counts(); /// Calculate the traversal count of each uncounted Arc void normalize_arcs(); /// Populate the Lines data for all blocks without line information void normalize_lines(); /// Calculate whether each block is fake void normalize_fake_blocks(); /// Populate m_blocks_sorted with Blocks sorted by line # void sort_blocks(); /// Calculates the total coverage for each source and the entire project. void calculate_total_coverage(); /// Create a vector with the first source line of each function within /// a source file void order_by_line( std::vector<unsigned> & first_line, const std::map<Source_file::Source_key, Record> & records ); /// Find the last source line of a record int find_last_line( const std::vector<unsigned> & first_line, const Record & rec ); /// Mark a line number as inlined if it meets certain criteria void assign_inline_status( Lines_data & line_data, const std::string & source, Record & rec, const unsigned last_line ); /// Get a line from the current source file void assign_line_current( Lines_data & line_data, Record & rec, unsigned block_no ); /// Get a line from an outside source file void assign_line_inlined( std::map<std::string, Lines_data> & lines, Record & rec, unsigned block_no ); // PRIVATE VARAIBLES std::ifstream mGcnoFile; // Gcno file stream std::ifstream mGcdaFile; // Gcda file stream std::ofstream mDumpFile; bool mIsDump; std::string mMagic; // Magic std::string mVersion; // Version of the input file std::string mStamp; // Stamp of the file std::string m_gcno_name; std::string m_gcda_name; bool mIsGCNO; bool mIsLittleEndian; double m_coverage_percentage; /// Pointer to the singleton instance of Dot_creator. static Parser * ptr_instance; /// Map of all source files within the project std::map<std::string, Source_file> m_source_files; }; // end of class Parse /// Compares the last line numbers of two blocks to determine order const bool compare_line_nums( const Block & lhs, const Block & rhs ); /// Compares two Line structs to determine order const bool compare_lines( const Line & lhs, const Line & rhs ); #endif
5b9ed6caf34b8dc9200c8d9b411301fcae9600f2
274099a586f8ddf323abb1ed77b2c08ca35fad43
/include/glvu/glvu.hpp
3bd26ed68fb14c9339e3c98685945789b3a790cb
[]
no_license
yunteng/CubicaPlus
912ac8dede855d8b85d0f87b28cb7ec4e751c394
3b5d60b863e54c6c880cb853c96d09cc7ca1caae
refs/heads/master
2021-01-19T06:36:31.994916
2016-05-31T19:50:31
2016-05-31T19:50:31
60,118,935
2
1
null
null
null
null
UTF-8
C++
false
false
25,775
hpp
glvu.hpp
//------------------------------------------------------------------------------ // File : glvu.hpp //------------------------------------------------------------------------------ // GLVU : Copyright 1997 - 2002 // The University of North Carolina at Chapel Hill //------------------------------------------------------------------------------ // Permission to use, copy, modify, distribute and sell this software and its // documentation for any purpose is hereby granted without fee, provided that // the above copyright notice appear in all copies and that both that copyright // notice and this permission notice appear in supporting documentation. // Binaries may be compiled with this software without any royalties or // restrictions. // // The University of North Carolina at Chapel Hill makes no representations // about the suitability of this software for any purpose. It is provided // "as is" without express or implied warranty. //============================================================================ // glvu.hpp : OpenGL/GLUT -based viewer //============================================================================ #ifndef _GLVU_ #define _GLVU_ #include <stdlib.h> #include <time.h> // FOR TIMED PATH PLAYBACK (glvu_camview) #include <sys/timeb.h> // FOR FRAME TIMING (glvu_camview) #if __APPLE__ #include <GLUT/glut.h> #else #include <GL/freeglut.h> #include <GL/glu.h> #endif #include <glvuVec3f.h> #include <camera.h> #ifndef ABS #define ABS(x) (((x)<0)?(-(x)):x) // HANDY UNIVERSAL ABSOLUTE VALUE FUNC #endif #define INERTIA_MINMOVE 2 // AMOUNT (in pixels) TO MOVE TO INVOKE INERTIAL SYSTEM #define MAX_GLVUS 33 // MAX NUMBER OF WINDOWS PLUS 1 SUPPORTED IN ONE APP #define FPS_INTEGRATE_INTERVAL 1.0f // MINIMUM NUMBER OF SECONDS TO INTEGRATE FRAME-RATE OVER /** * @class GLVU * @brief A convenient OpenGL/GLUT based 3D viewer. * * GLVU is part of a collection of C++ libraries for creating OpenGL * applications based on the cross-platform GLUT library. There are * many sub-libraries that comprise GLVU, but the actual GLVU class is * the one that encapsulates all of the GLUT user interface * functionality. Most of the other libraries do not depend on GLUT, * or depend on it in trivial ways. Another class that is based on * the Qt toolkit, QGLVU, can also be used for more advanced user * interface capabilities. Note however that Qt comes with some * significant licensing restrictions, whereas GLUT does not. * * The viewer library was developed mainly for creating small research * applications, and as such implements much of the functionality * necessary in a small viewer for prototyping rendering algorithms. * Among these features are a flexible camera class [Camera], several * camera manipulation, or navigation, modes, frame rate calculation, * and the ability to record and play back camera paths. All of these * are features likely to be needed at one time or another by most * anyone that wants to look at 3D geometric scene data with OpenGL, * and each requires some effor to implement. In particular, * developing the mouse-based camera manipulation routines can be * quite time consuming, as how to construct a mapping from 2D to 3D * (6D, really) that is intuitive for the user is far from obvious. * * Another nice feature supported by GLVU is "inertia", or the ability * to start a model spinning and have it keep spinning even after the * user releases the mouse. GLVU can also support multiple windows * easily, and the inertia works independently in each via GLUT * timers. GLVU does not use the one global GLUT idle callback at * all, leaving that instead for the user to do with as desired. * * Since GLUT is really more of a windowing toolkit than a user * interface toolkit, users of the GLVUT-based version of GLVU may * find an external GLUT-based UI toolkit to be useful. For quick * prototyping, GLUI is recommended * (http://www.cs.unc.edu/~rademach/glui). For more sophisticated * interfaces, use Qt and QGLVU rather than this class. * * Part of the philosophy in the design of GLVU was to make it as easy * as possible for current GLUT users to start using it right away. * For this reason all of the GLUT callbacks are still accessible to * the GLVU programmer. GLVU also supports a more object-oriented * approach as well, by allowing you to subclass GLVU and override * handler methods. * * @see QGLVU, Camera */ class GLVU { public: /// The world navigation modes. See SetWorldNavMode() /** These are the different modes for manipulating the current * camera with mouse input. */ enum WorldNavMode{ NAV_MODE_TRACKBALL, NAV_MODE_HYPERBALL, NAV_MODE_DRIVE, NAV_MODE_TRANSLATE, NAV_MODE_LOOK }; /// Camera IDs. There are 4 predefined cameras in /// a GLVU that can be switched between. enum CameraID { CAMERA_1, CAMERA_2, CAMERA_3, CAMERA_4, CAMERA_NUM_CAMS }; /// A function type used by the 'inertia' handling system typedef void (*InertiaFunc)(int x, int y); GLVU(); virtual ~GLVU(); int Init(char *WindowTitle, unsigned int VisualMode, int WindowStartX, int WindowStartY, int WindowWidth, int WindowHeight); virtual int InitWin(int aPreviouslyCreatedGlutWindow); void BeginFrame(); void EndFrame(); // CAMVIEW int GetPlaybackOn() const; int GetRecordingOn() const; // CAMVIEW void SetAllCams(const glvuVec3f& WorldMin, const glvuVec3f& WorldMax, const glvuVec3f& Eye, const glvuVec3f& LookAtCntr, const glvuVec3f& viewup, float Yfov, float Aspect, float NearFactor, float FarFactor); void AllCamsPerspectiveChange(float Yfov, float Aspect, float Ndist, float Fdist); void AllCamsPerspectiveAspectChange(float Aspect); void AllCamsPerspectiveNearFarChange(float Ndist, float Fdist); void AllCamsResetToOrig(); float* GetModelviewMatrix(float* M); float* GetProjectionMatrix(float* M); void GetPixelRay(int sx, int sy, int ww, int wh, glvuVec3f *Start, glvuVec3f *Dir) const; void SelectCam(int WhichCam); int GetCurrentCamId() const; Camera* GetCurrentCam(); void SetCurrentCam(Camera *NewCam); Camera* GetCam(int WhichCam); int GetInOutMode() const; void SetInOutMode(int Bool); void ToggleInOutMode(); void SetOrigCam(Camera *Cam); const glvuVec3f& GetViewUp() const ; const glvuVec3f& GetWorldCenter() const ; void SetWorldCenter(const glvuVec3f& newCenter); float GetWorldRadius() const ; void SetWorldRadius(float newRadius) ; void SetViewUp(glvuVec3f viewup) ; void SetMoveSpeed(float speed) ; float GetMoveSpeed() const ; void TranslateX(int OldX, int NewX, int WW); void TranslateY(int OldY, int NewY, int WH); void DriveY(int OldY, int NewY, int WH); void LookX(int OldX, int NewX, int WW); void LookY(int OldY, int NewY, int WH); void TrackBallX(int OldX, int NewX, int WW); void TrackBallY(int OldY, int NewY, int WH); void HyperBall(int OldX, int OldY, int NewX, int NewY,int WW, int WH); void StartRecording(const char *FileName = "path0.dat"); void EndRecording(); FILE* GetPathFile() const; void StartPlayback(const char *FileName = "path0.dat"); void EndPlayback(); void StopRecordingPlayback(); void StartFPSClock() ; void StopFPSClock() ; void DrawFPS(int xpos = 5, int ypos = 5); float GetFPS() const ; void UpdateFPS(); // USE ONLY IF YOU DO NOT CALL GLVU::BeginFrame() // MENU int GetMainMenuID() const ; int GetWorldNavMode() const ; void SetWorldNavMode(int mode) ; int GetCamDisplayOn(int WhichCam) const ; int IsWorldNavMode() const ; // MOUSE bool GetLeftButtonDown() const ; bool GetMiddleButtonDown() const ; bool GetRightButtonDown() const ; bool GetAltDown() const; bool GetShiftDown() const; bool GetCtrlDown() const; int GetMouseDeltaX(int curx) const; int GetMouseDeltaY(int cury) const; int GetInertiaOn() const ; int GetInertiaEnabled() const ; void SetInertiaOn(int Bool); void SetInertiaEnabled(int Bool) ; int GetInertiaDelay() const ; void SetInertiaDelay(int msec) ; void SetInertiaFunc(InertiaFunc f) ; InertiaFunc GetInertiaFunc() const; // DEFAULT CALLBACK FUNCTIONS (MOSTLY JUST CALL THE CALLBACK METHODS) static void DefaultMouseFunc(int button, int state, int x, int y); static void DefaultMotionFunc(int x, int y); static void DefaultReshapeFunc(int WW, int WH); static void DefaultDisplayFunc(); static void DefaultKeyboardFunc(unsigned char Key, int x, int y); static void DefaultInertiaFunc(int x, int y); // CALLBACK METHODS virtual void Mouse(int button, int state, int x, int y); virtual void Motion(int x, int y); virtual void Reshape(int WW, int WH); virtual void Display() ; virtual void Keyboard(unsigned char Key, int x, int y); virtual void Inertia(int x, int y); // MISC int GetWindowID() const; void MakeCurrent(); static GLVU* GetCurrent(); static GLVU* GetGLVU(int WindowID); static GLVU* GetGLVU(); // deprecated static void PrintVisualInfo(); static void CheckForGLError( char *msg ); protected: // GL VIEWER STATE VARIABLES Camera *Cams; // ARRAY OF 4 VIEWER CAMS Camera *Cam; // PTR TO CURRENT CAM (DEFAULT IS CAM 0) Camera OrigCam; // THE ORIGINAL VIEW FOR RESETTING int RecordingOn, PlaybackOn; // CAMERA RECORDING/PLAYBACK FLAGS FILE *RecordPlaybackFP; // RECORDING/PLAYBACK FILE POINTER glvuVec3f WorldCenter; // WORLD BOUNDING-SPHERE CENTER float WorldRadius; // WORLD BOUNDING-SPHERE RADIUS glvuVec3f ViewUp; // THE WORLD UP-VECTOR int InsideLookingOutMode; // NAVIGATION MODE (IN->OUT OR OUT->IN) clock_t PlaybackTime; // FOR PATH PLAYBACK TIMING int NumCams; struct timeb lastFPSClock; int calcFPS; float lastFPS; int lastFPSCount; bool LeftButtonDown, MiddleButtonDown, RightButtonDown; mutable int OldX, OldY; int NewX, NewY; // CURRENT OLD AND NEW MOUSE POSITIONS float moveSpeed; bool CtrlPressed, AltPressed, ShiftPressed; int InertiaOn, InertiaEnabled; int InertiaDelay; int MainMenuID; // GLUT MAIN MENU ID int WorldNavMode; // WORLD NAVIGATION MODE int *CamDisplayOn; // DISPLAY FLAG FOR EACH CAMERA // MENU static void MainMenuHandler(int value); static void vuOptionsMenuHandler(int value); static void glOptionsMenuHandler(int value); static void PathPlaybackMenuHandler(int value); static void CamViewMenuHandler(int value); static void CamViewDisplayMenuHandler(int value); static void EscapeHandler(int value); // MOUSE int DoInertia(); InertiaFunc UserInertiaFunc; static GLVU *GLVUs[MAX_GLVUS]; // glut WindowID int WindowID; static void InertialTimerFunc(int value); static void PathPlaybackTimerFunc(int value); virtual void InitMenu(); }; //---------------------------------------------------------------------------- /// Return whether or not playback mode is currently active /** * When playback mode is active, the modelview matrices for viewing * are read from a previously recorded file instead of coming from the * user's mousing. * * @see GetRecordingOn, StartRecording, EndRecording, * StartPlayback, EndPlayback, GetModelviewMatrix */ inline int GLVU::GetPlaybackOn() const { return(PlaybackOn); } /// Return whether or not playback mode is currently active /** * When record mode is active, every camera view change made by the user * (through mouse manipulation) is written to a file. The resulting * path can be played back later using StartPlayback(). * * @see GetPlaybackOn, StartRecording, EndRecording, * StartPlayback, EndPlayback, GetModelviewMatrix */ inline int GLVU::GetRecordingOn() const { return(RecordingOn); } /// Return the file pointer being used for playback or recording /** * Return the file pointer being used for playback or recording. * This is 0 if neither path playback nor recording is currently active. * * @see GetPlaybackOn, StartRecording, EndRecording, * StartPlayback, EndPlayback, GetModelviewMatrix */ inline FILE* GLVU::GetPathFile() const { return RecordPlaybackFP; } /// Switch to the specified camera /** * Changes the camera from which the \c GLVU renders the scene. * * By default this method is bound to the 1,2,3, and 4 keys on the * keyboard. * * @param WhichCam can be one of the #CameraID enum values. * @see GetModelviewMatrix, BeginFrame, EndFrame */ inline void GLVU::SelectCam(int WhichCam) { Cam = &Cams[WhichCam]; } /// Return the index of the active camera. inline int GLVU::GetCurrentCamId() const { return (Cam - &Cams[0]); } /// Return a pointer to the active camera. inline Camera* GLVU::GetCurrentCam() { return(Cam); } /// Set the active camera. /** * @param NewCam the new camera to set. * * @note The new camera will not be owned by GLVU. This sets the * current camera \em temporarily to \p NewCam. * * @see SelectCam */ inline void GLVU::SetCurrentCam(Camera *NewCam) { Cam=NewCam; } /// Return a pointer to the specified camera /** * @param WhichCam can be one of the \c CameraID identifiers \c * CAMERA_1, \c CAMERA_2, \c CAMERA_3, or \c CAMERA_4, or just a * number between zero and 3. */ inline Camera* GLVU::GetCam(int WhichCam) { return(&Cams[WhichCam]); } /** * Returns a boolean specifying whether the navigation mode is "inside looking * out" (true) or "outside looking in" (false, the default). * @see SetInOutMode, ToggleInOutMode */ inline int GLVU::GetInOutMode() const { return(InsideLookingOutMode); } /** * Sets the navigation mode to either "inside looking out" (true) or * "outside looking in" (false, the default). * @see SetInOutMode, ToggleInOutMode. */ inline void GLVU::SetInOutMode(int Bool) { InsideLookingOutMode=Bool; } /** * Toggles the display mode between "inside looking out" * and "outside looking in". * @see SetInOutMode, GetInOutMode */ inline void GLVU::ToggleInOutMode() { if (InsideLookingOutMode) InsideLookingOutMode=0; else InsideLookingOutMode=1; } /** * Stores a copy of \p Cam so that Cameras can be reset to its parameters * at a later time using AllCamsResetToOrig(). Called from SetAllCams(). * @see AllCamsResetToOrig, SetAllCams */ inline void GLVU::SetOrigCam(Camera *Cam) { OrigCam.Copy(*Cam); } /** * Returns the global "up" vector, as set by SetViewUp() or SetAllCams(). * This has some effect on the operation of certain mouse navigation modes. * @see SetWorldNavMode */ inline const glvuVec3f& GLVU::GetViewUp() const { return(ViewUp); } /** * Returns the global "center" of the world, as set by SetWorldCenter() or * (indirectly) by SetAllCams(). */ inline const glvuVec3f& GLVU::GetWorldCenter() const { return WorldCenter; } /** * Sets the global "center" of the world. Also set (indirectly) by SetAllCams(). * @see GetWorldCenter, SetWorldNavMode */ inline void GLVU::SetWorldCenter(const glvuVec3f& center) { WorldCenter = center; } /** * Returns the global "radius" of the world, as set by SetWorldRadius() or * (indirectly) by SetAllCams(). */ inline float GLVU::GetWorldRadius() const { return WorldRadius; } /** * Sets the global "radius" of the world. * @see GetWorldRadius */ inline void GLVU::SetWorldRadius(float newRadius) { WorldRadius = newRadius; } /** * Sets the global "up" vector. * @see GetViewUp */ inline void GLVU::SetViewUp(glvuVec3f viewup) { ViewUp=viewup; } /** * Sets the gain factor used in translating mouse motion in pixels * into world units. * @see GetMoveSpeed, SetWorldNavMode */ inline void GLVU::SetMoveSpeed(float speed) { moveSpeed = speed; } /** * Gets the gain factor used in translating mouse motion in pixels * into world units. * @see SetMoveSpeed, SetWorldNavMode */ inline float GLVU::GetMoveSpeed() const { return moveSpeed; } /** * Starts the frame timer and resets the frame counter. You must call * this once after creating the GLVU if you would like to take * advantage of the built-in frame timing capabilities. * @see StopFPSClock, UpdateFPS, BeginFrame */ inline void GLVU::StartFPSClock() { calcFPS = 1; ftime(&lastFPSClock); lastFPSCount=0; } /** * Stops the frame rate timer. * @see StartFPSClock */ inline void GLVU::StopFPSClock() { calcFPS = 0; } /** * Returns the last calculated Frames Per Second measurement. * @see StartFPSClock, StopFPSClock, UpdateFPS */ inline float GLVU::GetFPS() const { return lastFPS; } /** * Returns the GLUT ID for the right-click menu automatically installed by GLVU. * This can be used with GLUT calls to modify the contents of the menu. * @see InitMenu */ inline int GLVU::GetMainMenuID() const { return(MainMenuID); } /** * Returns the current world navigation mode, (i.e. camera control mode). * Return value is one of the #WorldNavMode enum constants. * @see SetWorldNavMode */ inline int GLVU::GetWorldNavMode() const { return(WorldNavMode); } /** * Sets the current world navigation mode, (i.e. camera control mode). * @param mode One of the #WorldNavMode enum constants. * * - \c NAV_MODE_TRACKBALL: a simple trackball. This is primarily for * rotating the model, but by holding down CTRL you can move * in and out as well. The rotation generated by the * trackball mode depends only upon the relative motion of * the mouse, not the absolute location. The drawback is * that this mode has no good way to make a model upright. * The Hyperball is better for that. * * - \c NAV_MODE_HYPERBALL: an "SGI-style" trackball. The effect of * this trackball is different depending on where on the * screen you drag the mouse. On the edge of the screen, * rotation happens mostly in the screen plane, but near * the middle of the window, rotation happens perpendicular * to the screen plane. Hold down CTRL to move in and out. * * - \c NAV_MODE_DRIVE: Left / Right to steer, Up / Down to move fore and aft. * - \c NAV_MODE_TRANSLATE: translate the camera parallel to the view plane. * - \c NAV_MODE_LOOK: Rotation about a fixed eye position. * * The outside-looking-in rotational modes (\c NAV_MODE_TRACKBALL, * \c NAV_MODE_HYPERBALL) use the "world center" as the center of rotation. * See SetWorldCenter() and SetAllCams() for more information about the * world center and camera settings. * * GLVU uses the following default keyboard accelerators to switch between modes: * * - 'z' : \c NAV_MODE_TRACKBALL * - 'x' : \c NAV_MODE_DRIVE * - 'c' : \c NAV_MODE_TRANSLATE * - 'v' : \c NAV_MODE_LOOK * - 'h' : \c NAV_MODE_TRACKBALL * * @see GetWorldNavMode */ inline void GLVU::SetWorldNavMode(int mode) { WorldNavMode=mode; } /** * Returns the display status of the specified Camera. * Camera display refers to rendering of some lines that show the extents of a * camera's frustum. GLVU has some functionality to do this automically. * * @see EndFrame */ inline int GLVU::GetCamDisplayOn(int WhichCam) const { return(CamDisplayOn[WhichCam]); } /** * Returns true (nonzero) if the current world nav mode set is valid * false (0) otherwise. * * @see SetWorldNavMode */ inline int GLVU::IsWorldNavMode() const { return(WorldNavMode>=0 && WorldNavMode<=3); } /** * Returns true if the left button was down * last time the Mouse() or Motion() callback got called. */ inline bool GLVU::GetLeftButtonDown() const { return(LeftButtonDown); } /** * Returns true if the middle button was down * last time the Mouse() or Motion() callback got called. */ inline bool GLVU::GetMiddleButtonDown() const { return(MiddleButtonDown); } /** * Returns true if the right button was down * last time the Mouse() or Motion() callback got called. */ inline bool GLVU::GetRightButtonDown() const { return(RightButtonDown); } /** * Returns true if the Alt key was down * last time the Mouse() or Keyboard() callback got called. */ inline bool GLVU::GetAltDown() const { return (AltPressed); } /** * Returns true if the Shift key was down * last time the Mouse() or Keyboard() callback got called. */ inline bool GLVU::GetShiftDown() const { return (ShiftPressed); } /** * Returns true if the Control key was down * last time the Mouse() or Keyboard() callback got called. */ inline bool GLVU::GetCtrlDown() const { return (CtrlPressed); } /** * Returns the difference between the current x value, curx, passed in * and the last mouse X value GLVU got. */ inline int GLVU::GetMouseDeltaX(int curx) const { int dx = curx - OldX; OldX = curx; return dx; } /** * Returns the difference between the current y value, cury, passed in * and the last mouse Y value GLVU got (inverts normal screen coordinate * system so that upward mouse motion gives a positive delta). */ inline int GLVU::GetMouseDeltaY(int cury) const { int dy = OldY - cury; OldY = cury; return dy; } /** * Returns true (nonzero) if inertia is currently active. * Note that this is different from whether or not it is \em enabled. * @see SetInertiaEnabled */ inline int GLVU::GetInertiaOn() const { return(InertiaOn); } /// Return whether inertia is enabled /** * Returns TRUE (1) if inertia is enabled, FALSE (0) otherwise. * @see SetInertiaEnabled */ inline int GLVU::GetInertiaEnabled() const { return(InertiaEnabled); } /// Enable or disable the GLVU's inertia feature /** * @see GetInertiaEnabled */ inline void GLVU::SetInertiaEnabled(int Bool) { InertiaEnabled=Bool; } /// Return the number of milliseconds between inertia callbacks /** * Inertia callbacks are only made by GLVU when inertia is active and * enabled. But when triggered, inertia callbacks are made repeatedly * at regular intervals to animate the camera. * * @see SetInertiaDelay, GetInertiaOn, GetInertiaEnabled */ inline int GLVU::GetInertiaDelay() const { return(InertiaDelay); } /// Set the number of milliseconds to wait between inertia callbacks /** * Inertia callbacks are only made by GLVU when inertia is active and * enabled. But when triggered, inertia callbacks are made repeatedly * at regular intervals to animate the camera. * * The implementation relies on \c glutTimerFunc(). * * @see GetInertiaDelay, GetInertiaOn, GetInertiaEnabled */ inline void GLVU::SetInertiaDelay(int msec) { InertiaDelay=msec; } /// Set the function to use as an inertia callback /** * The default implemntation works fine. There's really no * reason to call this. */ inline void GLVU::SetInertiaFunc(GLVU::InertiaFunc f) { UserInertiaFunc=f; } /// Return the function being uses as the inertia callback /** * @see SetInertiaFunc */ inline GLVU::InertiaFunc GLVU::GetInertiaFunc() const { return UserInertiaFunc; } /// Return the GLUT window ID associated with this GLVU /** * Sometimes it is necessary to get the GLUT window ID for a GLVU * window, and when you do, you can call this method. If all you want * to do is make this the active GLUT window (i.e. call \c * glutSetWindow() on it) then you can call MakeCurrent() instead. * * @see MakeCurrent, GetGLVU(int), GetGLVU */ inline int GLVU::GetWindowID() const { return WindowID; } /// Make \c this the currently active GL context /** * Equivalent to \c glutSetWindow(GetWindowID()). * * @note This bites most people at some point or other in their \c * glutIdleFunc. Many new GLUT users aren't aware that the * glutIdleFunc is global -- one per application. All the other GLUT * callbacks are per window, but not the idle func. When your idle * func gets called there is no guarantee which glut window will be * current. If you do a \c glutPostRedisplay() that redisplay event * could be sent to a window other than the one you were intending * unless you call MakeCurrent() first. * * None of the other GLUT callbacks have this problem. They are all * per-window, and GLUT guarantees that that window will be current * when your callback is called. * * @see GetGLVU(void) */ inline void GLVU::MakeCurrent() { glutSetWindow(WindowID); } /// Returns the currently active GLVU window /** * See MakeCurrent() for a discussion of what it means to be the active * window, and why you should care. * * @see MakeCurrent, GetGLVU(int) */ inline GLVU* GLVU::GetCurrent() { return GLVUs[ glutGetWindow() ]; } /// Returns a pointer to the GLVU that corresponds to the specified GLUT window ID. /** * There's a one-to-one mapping between GLVUs and GLUT windows. This * does the reverse lookup to find the GLVU for a given GLUT window * ID. GetWindowID() does the forward lookup. * * @see MakeCurrent, GetCurrent, GetWindowID */ inline GLVU* GLVU::GetGLVU(int WindowID) { return GLVUs[ WindowID ]; } /// Returns the currently active GLVU window /** * @deprecated * * This does the same thing as GetCurrent(). You should use that instead. * * @see MakeCurrent */ inline GLVU* GLVU::GetGLVU(void) { return GLVUs[ glutGetWindow() ]; } #endif
34558bd99a919047f6c277232aaa35ce2f7ee8b2
e9de7cf850dfaea8ac440a513d9913b7cbde3a14
/TrannyDestroyer/Menu.cpp
316759357836392ba7a0422708ed588aa866af49
[]
no_license
KaylinOwO/TrannyDestroyer
d4a448b772bca82734d9ccbdd3ae6fa7f18123eb
fc4d6663101ca2ace3bd8431e4f7f342b5732f22
refs/heads/master
2022-06-12T05:07:39.220470
2020-05-08T07:21:27
2020-05-08T07:21:27
262,254,830
0
2
null
null
null
null
UTF-8
C++
false
false
7,990
cpp
Menu.cpp
#include "Menu.h" #include "Draw.h" #include "Esp.h" #include "Aimbot.h" #include "Misc.h" #include "Triggerbot.h" #include "Antiaim.h" #include "Crits.h" Menu g_Menu; #define keyDown GetAsyncKeyState #define keyPress(x) keyDown(x) & 1 CKey gKey; #define GROUP_WIDTH 180 #define TAB_WIDTH 150 #define MENU_TOPBAR 30 //#include "Editor.h" void Menu::CreateGUI() { Tabs.AddTab(new Tab("Aimbot", { &g_Aimbot.master, &g_Aimbot.aimkey, &g_Aimbot.autoshoot, &g_Aimbot.proj, &g_Aimbot.aim_option, &g_Aimbot.silent, &g_Aimbot.fov, &g_Aimbot.ignore_cloak, &g_Aimbot.scope, &g_Aimbot.showtarget, }, TAB_WIDTH)); Tabs.AddTab(new Tab("Triggerbot", { &g_Triggerbot.master, &g_Triggerbot.trigkey, &g_Triggerbot.scoped, &g_Triggerbot.ignore_cloak, &g_Triggerbot.ignore_disguise, &g_Triggerbot.hitbox, }, TAB_WIDTH)); /*Tabs.AddTab(new Tab("HvH", { &g_AntiAim.master, &g_AntiAim.yaw_bsendpacket, new Space(200), new Groupbox("AntiAim", { &g_AntiAim.pitch, &g_AntiAim.pitch_bsendpacket, &g_AntiAim.real_pitch, &g_AntiAim.fake_pitch, &g_AntiAim.yaw, &g_AntiAim.real_yaw, &g_AntiAim.fake_yaw, }, GROUP_WIDTH), }, TAB_WIDTH));*/ Tabs.AddTab(new Tab("Esp", { &g_Esp.master, &g_Esp.team, new Groupbox("Players", { &g_Esp.name, &g_Esp.szclass, &g_Esp.health, &g_Esp.box, &g_Esp.glow, }, GROUP_WIDTH), new Groupbox("Chams", { &g_Esp.chams_enabled, &g_Esp.chams_players, &g_Esp.chams_team, &g_Esp.chams_weapons, &g_Esp.chams_material, &g_Esp.chams_wep_material, new Space(5), &g_Esp.chams_hand, &g_Esp.chams_hand_color, }, GROUP_WIDTH), new Groupbox("Misc", { &g_Esp.misc_noscope, &g_Esp.misc_nozoom, &g_Esp.misc_drawvmodel, }, GROUP_WIDTH), new Groupbox("Colors", { &g_Esp.aim_color, &g_Esp.text_color, &g_Esp.red_clr, &g_Esp.blue_clr, &g_Esp.chams_wep_clr, }, GROUP_WIDTH), }, TAB_WIDTH)); Tabs.AddTab(new Tab("Misc", { &g_Misc.bhop, &g_Misc.autostrafe, &g_Misc.enginepred, //&g_Crits.melee_crits, &g_Crits.crit_key, }, TAB_WIDTH)); } #include "XorString.h" void Menu::Draw() { if (key == VK_INSERT || key == VK_F11) enabled = !enabled; g_Draw.DrawString(50, 110, Color(181, 181, 181, 5), XorStr("trannydestroyer uc build"), gFonts.verdana_bold); if (!enabled) return; static bool dragging = false; if (mb == e_mb::lclick && mouseOver(pos.x, pos.y, scale.x, MENU_TOPBAR)) dragging = true; else if (mb != e_mb::ldown) dragging = false; if (dragging && focus == 0) { pos.x += mouse.x - pmouse.x; pos.y += mouse.y - pmouse.y; } for (auto& window : Windows) { if (!dragging && !focus) window->HandleInput(); window->Draw(); } POINT _pos = pos, _scale = scale; _scale.y += MENU_TOPBAR; #pragma region Main window // Menu outline g_Draw.OutlineRect(pos.x - 1, pos.y - 1, _scale.x + 2, _scale.y + 2, Color(0)); int topbar = style->TopBar(_pos.x, _pos.y, _scale.x, "TrannyDestroyer - by yapht"); // Re-adjusting pos and scale for easy coding _pos.y += topbar, _scale.y -= topbar; // Tab region g_Draw.DrawRect(_pos.x, _pos.y, TAB_WIDTH, _scale.y, Color(22, 23, 24)); g_Draw.DrawLine(_pos.x + TAB_WIDTH - 1, _pos.y, _pos.x + TAB_WIDTH - 1, _pos.y + _scale.y, Color(0)); Tabs.SetPos(_pos.x, _pos.y + topbar); Tabs.SetWidth(TAB_WIDTH); Tabs.HandleInput(); Tabs.Draw(false); // Control region g_Draw.DrawRect(_pos.x + TAB_WIDTH, _pos.y, _scale.x - TAB_WIDTH, _scale.y, Color(36, 36, 42)); // Dividing line g_Draw.DrawLine(_pos.x, _pos.y, _pos.x + _scale.x, _pos.y, Color(0)); // Re-adjusting pos and scale again _pos.x += TAB_WIDTH + 3, _scale.x = scale.x - (_pos.x - pos.x); #pragma endregion if (Tabs.active) { int cx = _pos.x + 13, cy = _pos.y + 12; int maxWidth = 0; auto& controls = Tabs.active->GetChildren(); for (size_t i = 0; i < controls.size(); i++) { if (!controls[i]->IsVisible()) continue; if (cy + controls[i]->GetHeight() > scale.y + _pos.y - 12) cy = _pos.y + 12, cx += 13 + maxWidth + 10, maxWidth = 0; if (controls[i]->GetWidth() > maxWidth) maxWidth = controls[i]->GetWidth(); controls[i]->SetPos(cx, cy); bool over = mouseOver(cx, cy, controls[i]->GetWidth(), controls[i]->GetHeight()); bool getInput = !(controls[i]->flags & noinput) && over && !IsDialogOpen(); if (getInput) controls[i]->HandleInput(); cy += controls[i]->Draw(getInput) + SPACING; } } size_t last = dialogs.size() - 1; if (dialogs.size() > 1) { e_mb new_mb = mb; e_mw new_mw = mw; POINT new_mouse = mouse, new_pmouse = pmouse; // Enforce focus so that only the last dialog gets to use these variables mb = e_mb::null, mw = e_mw::null, mouse = pmouse = { 0, 0 }; for (size_t i = 0; i < last; i++) { if (dialogs[i] == nullptr) continue; dialogs[i]->Draw(dialogs[i]->data, i + 1); } mb = new_mb, mw = new_mw, mouse = new_mouse, pmouse = new_pmouse; dialogs[last]->Draw(dialogs[last]->data, last + 1); } else if (!last) dialogs[last]->Draw(dialogs[last]->data, last + 1); if (key == VK_ESCAPE && dialogs.size()) dialogs.pop_back(); } bool Menu::mouseOver(int x, int y, int w, int h) { return mouse.x >= x && mouse.x <= x + w && mouse.y >= y && mouse.y <= y + h; } bool Menu::mouseOver(CBounds region) { return mouse.x >= region.x && mouse.x <= region.x + region.w && mouse.y >= region.y && mouse.y <= region.y + region.h; } void Menu::GetInput() { int mx = 0, my = 0; g_Interfaces.Surface->GetCursorPosition(mx, my); pmouse = mouse; mouse = { mx, my }; if (keyDown(VK_LBUTTON)) { if (mb == e_mb::lclick || mb == e_mb::ldown) mb = e_mb::ldown; else mb = e_mb::lclick; } else if (keyDown(VK_RBUTTON)) { if (mb == e_mb::rclick || mb == e_mb::rdown) mb = e_mb::rdown; else mb = e_mb::rclick; } else mb = e_mb::null; } void Menu::EndInput() { // Reseting Window message variables so they won't stick mw = e_mw::null; key = NULL; } LRESULT __stdcall Hooked_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_MOUSEWHEEL: if ((int)wParam < 0) g_Menu.mw = e_mw::up; else g_Menu.mw = e_mw::down; break; case WM_KEYDOWN: case WM_SYSKEYDOWN: // Allows input to work with alt key if (wParam > 255) break; g_Menu.keys[wParam] = true, g_Menu.last_key = wParam = g_Menu.key = wParam; break; case WM_KEYUP: case WM_SYSKEYUP: // Avoid Mouse 3/4/5 here if (wParam > 255 && wParam < VK_MBUTTON && wParam > VK_XBUTTON2) break; g_Menu.keys[wParam] = false; if (g_Menu.last_key == wParam) g_Menu.last_key = NULL; break; case WM_MBUTTONDOWN: case WM_MBUTTONUP: g_Menu.keys[VK_MBUTTON] = uMsg == WM_MBUTTONDOWN; if (uMsg == WM_MBUTTONDOWN) g_Menu.last_key = g_Menu.key = VK_MBUTTON; else if (g_Menu.last_key == VK_MBUTTON) g_Menu.last_key = NULL; break; /*case WM_XBUTTONDOWN: case WM_XBUTTONUP: int param = GET_KEYSTATE_WPARAM(wParam); if (!(param & MK_XBUTTON1) && !(param & MK_XBUTTON2)) break; byte vk; if (param & MK_XBUTTON1) { vk = VK_XBUTTON1; gMenu.keys[vk] = uMsg == WM_XBUTTONDOWN; if (uMsg == WM_XBUTTONDOWN) gMenu.last_key = gMenu.key = vk; else if (gMenu.last_key == vk) gMenu.last_key = NULL; } if (param & MK_XBUTTON2) { vk = VK_XBUTTON2; gMenu.keys[vk] = uMsg == WM_XBUTTONDOWN; if (uMsg == WM_XBUTTONDOWN) gMenu.last_key = gMenu.key = vk; else if (gMenu.last_key == vk) gMenu.last_key = NULL; }*/ } if (g_Menu.enabled && g_Menu.keys[VK_ESCAPE]) return 0; // Don't let escape key affect the game while using our UI return CallWindowProc(g_Menu.windowProc, hWnd, uMsg, wParam, lParam); } void Menu::OpenDialog(Dialog& dlg) { dialogs.push_back(&dlg); focus = dialogs.size(); } void Menu::CloseDialog(size_t Index) { if (Index == 0) return; Index--; if (Index >= dialogs.size()) return; dialogs.erase(dialogs.begin() + Index); focus = dialogs.size(); }
0a1f4f47b74bd1fc594c48badb2e7c727f166f5d
9aad84216536481d5ed7d86a46874f7392aacd76
/GraphicsVMS.h
5a0d42bdffc078f9b1a8047a2a78345bb7b8331a
[]
no_license
VictorBarradas/IsometricForceExperiments
7e7c7f5d89ee9b0694c5a7aded8fb115dca8d4d5
f9c0c1ed724f6146fdb078248d8ec58471e20f6b
refs/heads/master
2021-01-01T04:12:04.713778
2016-05-23T22:28:20
2016-05-23T22:28:20
59,522,119
0
0
null
null
null
null
UTF-8
C++
false
false
430
h
GraphicsVMS.h
#pragma once #include <stdio.h> #include <string.h> #include "Graphics.h" #include "VMSErrorBasedPosMap.h" class GraphicsVMS : public Graphics { private: //VMSErrorBasedPosMap *vmsExperiment; VisuomotorScaling *vmsExperiment; int cursorZeroPosX; int cursorZeroPosY; char gStatusString[10][300]; public: GraphicsVMS(VisuomotorScaling*); void Display(); void Keyboard(unsigned char, int, int); void renderEnvironment(); };
c6e6d380e8185f66baf0efc403e035085b0c8df6
dd1e9e3796576da599f3981a7abaf2fcd9d6b89a
/BlitzSharp3D/blitz3d/md2rep.h
92dd4e106be57f2e596c3ad0d29ae8388d7a226e
[ "Zlib", "BSD-3-Clause" ]
permissive
blitzimagine/BlitzSharp3D
4ae674cfdd2aba09f6844dce10ad44796c92aad0
cbf25a5d4ad3e1081e819c0dfaeb3ce40cd57860
refs/heads/master
2023-04-13T08:50:40.440863
2022-06-08T13:41:12
2022-06-08T13:41:12
189,093,663
9
1
NOASSERTION
2021-09-04T22:52:21
2019-05-28T19:52:11
C
UTF-8
C++
false
false
1,054
h
md2rep.h
#ifndef MD2REP_H #define MD2REP_H #include "model.h" class MD2Rep { public: struct Vert { Vector coords, normal; }; MD2Rep(const string& f); virtual ~MD2Rep(); void render(Vert* verts, int frame); void render(Vert* verts, int frame, float time); void render(Vert* verts, int frame_a, int frame_b, float time); void render(Vert* verts, const Vert* verts_a, const Vert* verts_b, float time); void render(Model* model, int frame_a, int frame_b, float time); void render(Model* model, const Vert* verts_a, const Vert* verts_b, float time); void render(Model* model, const Vert* verts_a, int frame_b, float time); const Box& getBox()const { return box; } const int numFrames()const { return n_frames; } const int numVertices()const { return n_verts; } private: struct Vertex { unsigned char x, y, z, n; }; struct VertexUV { float u, v; }; struct Frame { Vector scale, trans; vector<Vertex> verts; }; Box box; gxMesh* mesh; int n_frames; int n_verts, n_tris; vector<Frame> frames; vector<VertexUV> uvs; }; #endif
87d31ab1e8af7c19b277719394acc5945c41763c
f5d5bd4bbc2582318d48955269a1d009546081c2
/vexception.h
6aa5f4a383a11a2a29840f62373a6a6032d5b034
[]
no_license
sm4ll-3gg/vector
411a81c35504c83954a033bfee33aef19729a30a
f49523a13a15561982a48fc143afeb06c6010b68
refs/heads/master
2021-06-06T17:57:52.259861
2016-10-31T21:57:01
2016-10-31T21:57:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
332
h
vexception.h
#ifndef VEXCEPTION_H #define VEXCEPTION_H #include <exception> #include <string> class VException : public std::exception { std::string name; public: VException(); VException(const std::string&); VException(const std::string&, std::exception&); const std::string& get_name() const; }; #endif // VEXCEPTION_H
dae21230ba0c2ef1b59b4bb6c7718d48e3dc0dd7
86e28d36a8b77ee7b6c6e1832215157ae4c6ca98
/copanies.h
e7fe155067a4de9d4eaa752a3a31a886c5b04611
[]
no_license
88roy88/yusuf
817265d0585b791c4cbe67248f8216401bd8320f
ab7f8bcda86d817e8801a13c771ef13a79b49db2
refs/heads/master
2020-04-19T02:17:33.937633
2016-09-09T21:10:01
2016-09-09T21:10:01
67,831,918
0
0
null
2016-09-09T20:59:53
2016-09-09T20:51:15
C++
UTF-8
C++
false
false
389
h
copanies.h
#pragma once #include <map> #include <string> #include "company.h" #include "help.h" using namespace help; class companies { public: static map<string, company*> comps; static void menu(); static void create(string name =""); static void erase(); static void printCompany(); static void printList(); //helper functions: static company::Type choseType(); };
375a5da5940a51e6d1bfcba5f6c193c343aead7b
9b50cd21aa1a8e84e13a10e9e9f7bc1847239018
/skeleton/RenderUtils.hpp
a9ac6566ce32ffbff752d2116b52652b3b4decf5
[]
no_license
GonzaPM7/ProyectoSIM
7c0dbce9c5e1b3443412102aef9833ef092ebaa2
f6791f1911c48a722d6da0b995619ff8d6a460f5
refs/heads/master
2020-09-26T17:55:09.134549
2019-12-12T18:57:38
2019-12-12T18:57:38
226,307,094
1
0
null
null
null
null
UTF-8
C++
false
false
1,430
hpp
RenderUtils.hpp
#ifndef __RENDER_UTILS_H__ #define __RENDER_UTILS_H__ #include "PxPhysicsAPI.h" #include "core.hpp" class RenderItem; void RegisterRenderItem(const RenderItem* _item); void DeregisterRenderItem(const RenderItem* _item); class RenderItem { public: RenderItem(physx::PxShape* _shape, const physx::PxTransform* _trans, const Vector4& _color) : shape(_shape), transform(_trans), actor(NULL), color(_color), references(1) { shape->acquireReference(); RegisterRenderItem(this); } RenderItem(physx::PxShape* _shape, const Vector4& _color) : shape(_shape), transform(NULL), actor(NULL), color(_color), references(1) { shape->acquireReference(); RegisterRenderItem(this); } RenderItem(physx::PxShape* _shape, const physx::PxRigidActor* _actor, const Vector4& _color) : shape(_shape), transform(NULL), actor(_actor), color(_color), references(1) { shape->acquireReference(); RegisterRenderItem(this); } RenderItem() : shape(NULL), transform(NULL), references(1) {} void addReference() { ++references; } void release() { --references; if (references == 0) { DeregisterRenderItem(this); shape->release(); delete this; } } public: physx::PxShape* shape; const physx::PxTransform* transform; const physx::PxRigidActor* actor; Vector4 color; unsigned references; }; double GetLastTime(); Camera* GetCamera(); physx::PxShape* CreateShape(const physx::PxGeometry& geo); #endif
dd506ed10db7a021edae4296cccb69ffb8247193
b302cb063485bb3fac9a3d9c9b730a90cf6d3806
/src/transitions/AbstractTransition.h
144a6842fcd996b8fa9d6ea6b563481cf77f95b9
[]
no_license
damiano-massarelli/harentz
5bb92ab97f6de37beefe229c38ef2210dbf47c3a
9f29fdbb641b38be0563531ac508d505bcdf16c7
refs/heads/master
2023-01-07T00:50:29.505897
2019-06-04T18:33:14
2019-06-04T18:33:14
152,626,561
2
0
null
2022-12-22T11:03:37
2018-10-11T17:00:36
C++
UTF-8
C++
false
false
1,039
h
AbstractTransition.h
#ifndef ABSTRACTTRANSITION_H #define ABSTRACTTRANSITION_H #include "EventListener.h" #include "EventListenerCrumb.h" #include <functional> #include <memory> class AbstractTransition { private: float m_elapsed{0.0f}; ///< total elapsed time from the creation of this transition float m_totalDuration{500.0f}; ///< total desired duration for this transition std::function<void()> m_onCompleteCallback; ///< this function is called when the transition is over bool m_cancelled{false}; ///< true if the user canceled it bool m_ended{false}; ///< true if the transition terminated on its own protected: AbstractTransition(float durationMS, std::function<void()> onComplete = nullptr); public: void onEnterFrame(float elapsed); // called by Transitions virtual void onUpdate(float f) const = 0; void cancel(); bool isCancelled() const; bool isEnded() const; virtual ~AbstractTransition(); }; #endif // ABSTRACTTRANSITION_H
378af20bf7ed169fe4621aaa0c433e5016928b60
2799ea2b1ebae6602e199731409cd7ee94055a8e
/TerrainGenerator/src/engine/utility/interfaces/INonmovable.h
a7aa4495e27a1010dceff5b5ec9d840a3faa3982
[ "MIT" ]
permissive
LucidSigma/vulkan-terrain-generator
ae37b777e478f93359a1c09c7602fa8f9097e07d
532530331d988dbd2c4e9ae382812d28fabbd5e8
refs/heads/master
2021-12-14T18:39:31.996322
2021-12-01T06:23:21
2021-12-01T06:23:21
253,969,092
3
0
null
null
null
null
UTF-8
C++
false
false
217
h
INonmovable.h
#pragma once class INonmovable { protected: INonmovable() = default; INonmovable(INonmovable&&) noexcept = delete; INonmovable& operator =(INonmovable&&) noexcept = delete; ~INonmovable() noexcept = default; };
3b680cbaaa6be11c3b481c953e194582da3980e5
70327430b2d38cbb921f3ad1c6f5b8943a270af6
/ClientSocket/ClientSocket/main.cpp
8b389d39dfe6c6b291dfc627120fc2a3cf372801
[]
no_license
zs1995/student
7884cb955b68571130a7962460c4060409f8230d
f698889e58ccd78e5358ed9a831edadd0acee846
refs/heads/master
2021-05-04T17:46:54.377582
2018-03-01T03:31:06
2018-03-01T03:31:06
120,276,766
3
0
null
null
null
null
UTF-8
C++
false
false
1,386
cpp
main.cpp
#include "udp.h" int main(int argc,char **argv) { WSADATA wsaData; SOCKET sockfd; int n,count1 = 0; char *recvline = NULL; struct sockaddr_in servaddr; struct hostent *host; recvline =(char *)malloc(100); if ( WSAStartup(MAKEWORD(2,2), &wsaData) != 0 ) { printf("Init Windows Socket Failed::%d",GetLastError()); return -1; } if((host = gethostbyname("192.168.10.102")) == NULL) { printf("gethostbyname error"); } memset(&servaddr,0,sizeof(sockaddr_in)); if((sockfd = socket(AF_INET,SOCK_STREAM,0))< 0) { printf("socket error"); } servaddr.sin_family = AF_INET; servaddr.sin_port = htons(18000); //servaddr.sin_addr.S_un.S_addr = INADDR_ANY; //servaddr.sin_addr.s_addr = inet_addr("192.168.10.102"); servaddr.sin_addr = *((struct in_addr*)host->h_addr); memset(servaddr.sin_zero, 0x00, 8); if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) < 0) { printf("connect error %d",GetLastError()); } n = send(sockfd,"hello",strlen("hello"),0); if ( n == SOCKET_ERROR ) { printf("Send Info Error::%d",GetLastError()); } char recvtmp[10] = {0}; while(true) { if((n = recv(sockfd,recvline+count1,2,0)) > 0) { count1 += n; memcpy(recvtmp,recvline,count1); printf("%s\n",recvtmp); } } getchar(); free(recvline); recvline = NULL; shutdown(sockfd,2); closesocket(sockfd); WSACleanup(); return 0; }
03d11488e4d0c7c3b16f7bf88818e4f9af3d3156
d1c86ad4b2e72afe43466ad2f8dedba2e64c1676
/ConsoleTest/ConsoleTest/src-linux/socketDef.h
f5fa4e0576057a0fd1e381d045d9abae00ea033d
[]
no_license
gydgzd/vs17
6183d688ec2e8af2334cd85e7844f2d278d9e833
0d34fc98aa6766562f00543b675a05c2a38805dc
refs/heads/master
2022-09-29T16:26:41.338370
2022-08-28T10:50:38
2022-08-28T10:50:38
163,606,943
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
h
socketDef.h
/* * socketDef.h * * Created on: May 7, 2019 * Author: gyd */ #ifndef SOCKETDEF_H_ #define SOCKETDEF_H_ #include <stdio.h> using namespace std; typedef unsigned char BYTE; #define MSGHEAD_LENGTH 8 #define MAXLENGTH 1024*64 struct MSGBODY { int type; // 0:int, 1:string, 2: byte(hex) int length; // length of msg BYTE msg[MAXLENGTH]; MSGBODY() { memset(this, 0, sizeof(MSGBODY)); type = 0; length = 0; } MSGBODY(const MSGBODY & msgbody) { memset(this, 0, sizeof(MSGBODY)); type = msgbody.type; length = msgbody.length; memcpy(msg,msgbody.msg,length); } }; /* * use to form a string clientIP:clientPort--> serverIP:serverPort */ struct CONNECTION { int socket_fd ; // int status ; // 0: closed; 1:connected int clientPort ; // test if ok int serverPort ; char clientIP[64] ; char serverIP[64] ; CONNECTION() { memset(this, 0, sizeof(CONNECTION)); socket_fd = 0; status = 0; clientPort = 0; serverPort = 0; } }; #endif /* SOCKETDEF_H_ */
630fc9c51035b53dd43b66e2ac4e386255601c8e
dfbed52d7ba6387e5324128aea52acfe5ecc1359
/_035_C-String(putback, peek, ignore).cpp
5fce168c578ebd9ad4d2d39ea4b64e97bbf41ef2
[]
no_license
joohongkeem/Cpp_Self_Study
55dac73f8532e9cafd6a0829c6e5f58b9ad62af5
936936807444848cfee6887608681d191d15bf30
refs/heads/master
2020-03-23T22:00:12.331117
2018-08-06T09:43:50
2018-08-06T09:43:50
142,146,758
0
0
null
null
null
null
UTF-8
C++
false
false
2,289
cpp
_035_C-String(putback, peek, ignore).cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; /* - 프로그램을 실행할 때 입력 스트림에 존재하는 다음 문자가 무엇인지를 파악할 필요가 생길 수 있다. But, 일단 입력 스트림의 다음 문자를 읽은 후, 경우에 따라서는 프로그래머가 원하지 않는 문자이기 때문에 이 문자를 읽기 전의 상태를 원하는 상황이 발생한다. 예를 들어, 프로그램에서 문자를 읽되 처음에 나오는 공백 입력을 원하지 않는 경우가 발생하는데, 문제는 공백 입력을 원치 않더라도 일단 입력 스트림에 존재하는 문자를 모두 읽어야 된다는 사실이다. 이런 경우 입력 스트림에는 공백이 더 이상 존재하지 않는다. 그리고 동일한 프로그램의 다른 부분에서 공백을 읽어서 처리해야 되는 경우가 발생할 수 있다. 이러한 상황을 해결할 수 있는 한 가지 방법은 'cin.putback() 멤버함수'를 사용하는 것이다. > cin.putback 함수는 1개의 char형 인자를 필요로 하며 함수가 실행되면 인자의 값이 입력 스트림에 삽입되어, 다음으로 입력될 문자가 된다. 여기서 인자는 char형 값을 처리할 수 있는 그 어떤 식이라도 무방하다. 또한 putback 멤버 함수를 사용하여 입력 스트림에 삽입되는 문자는 반드시 마지막으로 입력될 문자일 필요는 없으며, 그 어떤 위치에 놓인 문자라도 상관 없다. - cin.peek() 멤버 함수는 cin에 의하여 입력될 다음 문자를 리턴하지만, 입력 스트림에서 문자를 제거하지 않는다. 다시 말하면, peek 함수는 이름 그대로 다음에 읽어 들일 입력 문자를 살펴볼 뿐이다. (peek - 몰래 엿보다) - 만약에 '\n'과 같은 특정한 문자에 대하여 입력을 생략하고자 하면, cin.ignore() 멤버함수를 사용하면 된다. 예를 들어, cin.ignore(1000,'\n'); 의 코드는 최대 1000개의 문자를 읽을 때 까지, '\n'을 무시한다는 의미이다. >> 위의 함수들은 텍스트 파일 입력을 위해서, cin 객체 대신에 파일 입력 스트림으로 대치될 수 있다. */
373da8b3ad02b6c91c37fffb707d90a6df359785
6409abcf29dca7d6403a5a82f0ce2125a8b6d9c4
/source/MySQLLib/Database.cpp
529583e5484395ebb7c31f50c05f2004215971e3
[]
no_license
samlovejoyce/JDGC-BACKUP
c6c4c12774c4e4c390423a5ead0b7dd921a2e930
25c6b5edba0df8dabf3782eb066ca6d3628783ba
refs/heads/master
2020-04-05T10:41:17.942815
2019-01-29T06:35:51
2019-01-29T06:35:51
null
0
0
null
null
null
null
GB18030
C++
false
false
9,594
cpp
Database.cpp
#include <MySQLLib/Database.h> #include <MySQLLib/DatabaseException.h> #include <algorithm> #include <functional> #include <cctype> namespace MYSQLDB { bool Database::_embedded; Database::Database(const std::string & host, const std::string & user, const std::string & password, const std::string & database, unsigned int port, const char * unixSocket, unsigned long clientFlag) { _host = host; _user = user; _password = password; _database = database; _port = port; _unixSocket = unixSocket; _clientFlag = clientFlag; _initialCommand = ""; _isConnected = false; _autocommit = true; if ((_db = mysql_init(NULL) ) == NULL) throw DatabaseException("Error tryng to initialize MYSQL database", 0, "------", "insufficient memory"); } Database::Database() { _host = ""; _user = ""; _password = ""; _database = ""; _port = 0; _unixSocket = NULL; _clientFlag = 0; _initialCommand = ""; _isConnected = false; _autocommit = true; if ((_db = mysql_init(NULL)) == NULL) throw DatabaseException("Error tryng to initialize MYSQL database", 0, "------", "insufficient memory"); /* 嵌入式数据库 */ if (_embedded) { mysql_options(_db, MYSQL_READ_DEFAULT_GROUP, "embedded"); //mysql_options(_db, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL); } } Database::Database(const Database & db) { _host = db._host; _user = db._user; _password = db._password; _database = db._database; _port = db._port; _unixSocket = db._unixSocket; _clientFlag = db._clientFlag; _initialCommand = db._initialCommand; _isConnected = db._isConnected; _autocommit = db._autocommit; if ((_db = mysql_init(NULL)) == NULL) throw DatabaseException("Error tryng to initialize MYSQL database", 0, "------", "insufficient memory"); if (db._isConnected ) { try { connect(); } catch (DatabaseException &) { mysql_close(_db); throw; } } if (!db._autocommit) { try { autoCommit(_autocommit); } catch (DatabaseException* e) { mysql_close(_db); throw; } } } Database::~Database() { mysql_close(_db); } void Database::connect() { if (_host == "") { if (mysql_real_connect(_db, NULL, NULL, NULL, _database.c_str(), 0, NULL, 0) == NULL) throw DatabaseException(_db, "Error in Database::Connect"); } else { if (mysql_real_connect(_db, _host.c_str(), _user.c_str(), _password.c_str(), _database.c_str(), _port, _unixSocket, _clientFlag) == NULL) throw DatabaseException(_db, "Error in Database::Connect"); } _isConnected = true; if (mysql_set_character_set(_db, "utf8") != 0) { throw DatabaseException(_db, "Error in Database::Connect"); } } void Database::setInitialCommand(const std::string &initialCommand) { _initialCommand = initialCommand; } bool Database::autoCommit() const { return _autocommit; } void Database::autoCommit(bool value) { int ac = (value) ? 1 : 0; if (mysql_autocommit(_db, ac) != 0) throw DatabaseException(_db, "Error in Database::Autocommit"); } void Database::startTransaction() { if (mysql_query(_db, "START TRANSACTION") != 0) throw DatabaseException(_db, "Error in Dadabase::StartTransaction"); } void Database::commit() { if (mysql_query(_db, "COMMIT") != 0) throw DatabaseException(_db, "Error in Database::Commit"); } void Database::rollback() { if (mysql_query(_db, "ROLLBACK") != 0) throw DatabaseException(_db, "Error in Database::Rollback"); } bool Database::isConnected() { return _isConnected; } void Database::useDatabase(const std::string &dbName) { if (mysql_select_db(_db, dbName.c_str()) != 0) throw DatabaseException(_db, "Error in Database::UseDatabase"); } int Database::execute(const std::string &statement) { if (mysql_query(_db, statement.c_str()) != 0) throw DatabaseException(_db, "Error in Database::Execute"); MYSQL_RES *result = mysql_store_result(_db); if (result != NULL) { mysql_free_result(result); throw DatabaseException("Error in Database::Execute", 0, "-----", "statements passed to execute should never return results."); } return mysql_affected_rows(_db); } void Database::libraryInitialize(bool embedded) { _embedded = embedded; if (!embedded) { if (mysql_library_init(0, NULL, NULL) != 0) throw DatabaseException("Error in Database::LibraryInitialize", 0, "-----", "Failure to initialize the database library"); } else { static const char *server_args[] = { "this_program", "--basedir=/usr/local/mysql", "--datadir=/Users/ravidesai/mysql/data", "--plugin-dir=/Users/ravidesai/mysql/plugins", "--log-error=/Users/ravidesai/mysql/tmp/test.err", "--pid-file=/Users/ravidesai/mysql/tmp/test.pid", "--key_buffer_size=32M", "--log-bin=/Users/ravidesai/mysql/log/logbin" "--log-bin-trust-function-creators=1" "--log-bin-trust-routine-creators=1" }; static const char *server_groups[] = { "embedded", "server", "this_program_SERVER", (char *)NULL }; if (mysql_library_init(sizeof(server_args) / sizeof(char *), (char**)server_args, (char **)server_groups) != 0) { throw DatabaseException("Error in Database::Initialize", 0, "----", "Failure to initialize the database library"); } } } void Database::threadInitialize() { if (mysql_thread_init() != 0) throw DatabaseException("Error in Database::ThreadInitialize", 0, "-----", "Failure to initialize database thread"); } void Database::libraryFinalize() { mysql_library_end(); } void Database::threadFinalize() { mysql_thread_end(); } /************************************************************************/ /* string::trim */ /************************************************************************/ static inline std::string &ltrim(std::string &str) { str.erase(str.begin(), std::find_if(str.begin(), str.end(), std::not1(std::ptr_fun<int, int>(std::isspace) ))); return str; } static inline std::string &rtrim(std::string &str) { str.erase(std::find_if(str.rbegin(), str.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), str.end()); return str; } static inline std::string &trim(std::string &str) { return ltrim(rtrim(str)); } void Database::source(const std::string &fileName) { std::ifstream commands(fileName.c_str(), std::ios::in); if (!commands.is_open()) throw DatabaseException("Error in Database::Source", 0, "-----", (std::string("could not open file: ") + fileName ).c_str()); commands.exceptions(std::ios::badbit); try { std::string cmd; std::string collector; std::string delimiter; size_t delimpos; bool insideProcOrFunc = false; while (!commands.eof() ) { getline(commands, cmd); cmd = trim(cmd); /** 跳过mysql的注释语句 */ size_t dashDashPos = cmd.find("--"); if(dashDashPos != std::string::npos && dashDashPos == 0) continue; /** 查找数据库名称 */ delimpos = cmd.find("USE DATABASE "); if (delimpos != std::string::npos && delimpos == 0) { cmd.erase(0, 13); cmd = trim(cmd); useDatabase(cmd); continue; } /** 查找触发器 */ delimpos = cmd.find("DELIMITER "); if (delimpos != std::string::npos && delimpos == 0) { delimiter = cmd.erase(0, 10); delimiter = trim(delimiter); continue; } /** 查找存储过程 */ delimpos = cmd.find("CREATE PROC "); if (delimpos != std::string::npos && delimpos == 0) { insideProcOrFunc = true; } delimpos = cmd.find("CREATE FUNC "); if (delimpos != std::string::npos && delimpos == 0) { insideProcOrFunc = true; } if (insideProcOrFunc) { size_t poundPos = cmd.find("#"); if (poundPos != std::string::npos) { /** remove pound(#) comment */ cmd = cmd.erase(poundPos, cmd.length() - poundPos + 1); } } collector.append(" "); collector.append(cmd); delimpos = collector.rfind(delimiter.c_str()); if (delimpos != std::string::npos && delimpos + delimiter.length() >= collector.length()) { collector.replace(delimpos, delimiter.length(), ""); if (insideProcOrFunc) { size_t commentStart = collector.find("/*"); while (commentStart != std::string::npos ) { size_t commentEnd = collector.find("*/"); if (commentEnd == std::string::npos || commentEnd <= commentStart) { throw DatabaseException("Error in Database::Source", 0, "-----", "unmatched comment strings"); } collector = collector.replace(commentStart, commentEnd - commentStart + 2, ""); commentStart = collector.find("/*"); } } execute(collector); collector = ""; insideProcOrFunc = false; } } } catch (std::ifstream::failure &ex) { throw DatabaseException("Error while reading file in Database::Source", 0, "----", ex.what()); } } /************************************************************************/ /* */ /************************************************************************/ LibraryInitializer::LibraryInitializer(bool embedded) { Database::libraryInitialize(embedded); } LibraryInitializer::~LibraryInitializer() { Database::libraryFinalize(); } ThreadInitializer::ThreadInitializer() { Database::threadInitialize(); } ThreadInitializer::~ThreadInitializer() { Database::threadFinalize(); } }
9068188f6a1fa148d1351770b7b66aa6eede6029
c348efe40b4afac1de31e1cf93b800510f9d52f6
/Cal State San Bernardino (CSUSB)/CSE375 - Requirements of Analysis & Design/CSE375 Website/cse.csusb.edu/dick/cs375/tp1.cpp
c8d1db93a2e3d8d11428ade8998456881ef09b07
[]
no_license
acoustictime/CollegeCode
5b57dc45459c35694e3df002a587bacc4f99f81a
a8ec647fa4b5a6a90f34f1c8715dfea88cefe6c6
refs/heads/master
2020-03-28T19:22:04.384018
2018-09-16T18:37:22
2018-09-16T18:37:22
148,968,472
1
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
tp1.cpp
#include <iostream> #include <cassert> bool prime(int n) { return true; } int main(int argc, char* argv[]) {// test prime number function assert( prime(2) ); assert( prime(3) ); assert( not prime(4) ); assert( prime(5) ); assert( not prime(9) ); assert( not prime(42)); }//end main
5cdab3aefe67151528d20b749dc9578de155926b
da5c9b96d42cc280e3866c6fc242c7f85bc891f7
/Source/Alimer/IO/Console.cpp
99007cbe3263cf7eb2bcd45ad03c3fe75d524c19
[ "MIT", "Zlib" ]
permissive
parhelia512/alimer
641699a65f07f5810527b1ae3785ea5d43b751bf
b46c8b7bdbf11f2f6305a10d5372dbc61b595ab1
refs/heads/master
2020-03-15T04:22:04.540043
2018-05-02T18:46:15
2018-05-02T18:46:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,726
cpp
Console.cpp
// // Alimer is based on the Turso3D codebase. // Copyright (c) 2018 Amer Koleci and contributors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Console.h" #include "Base/String.h" #ifdef _WIN32 // This is needed for _fdopen on MinGW # undef __STRICT_ANSI__ # include "../PlatformIncl.h" # include <io.h> #else # include <unistd.h> #endif #include <cstdio> #include <fcntl.h> using namespace std; namespace Alimer { #ifdef _WIN32 static bool consoleOpened = false; inline std::wstring ToWide(const std::string& str) { int len; int slength = (int)str.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, nullptr, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } #endif static string currentLine; void ErrorExit(const string& message, int exitCode) { if (!message.empty()) PrintLine(message, true); exit(exitCode); } void OpenConsoleWindow() { #ifdef _WIN32 if (consoleOpened) return; AllocConsole(); HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); int hCrt = _open_osfhandle((size_t)hOut, _O_TEXT); FILE* outFile = _fdopen(hCrt, "w"); setvbuf(outFile, 0, _IONBF, 1); *stdout = *outFile; HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE); hCrt = _open_osfhandle((size_t)hIn, _O_TEXT); FILE* inFile = _fdopen(hCrt, "r"); setvbuf(inFile, 0, _IONBF, 128); *stdin = *inFile; consoleOpened = true; #endif } void PrintUnicode(const string& str, bool error) { #if !defined(ANDROID) && !defined(IOS) #ifdef _WIN32 HANDLE stream = GetStdHandle(error ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE); if (stream == INVALID_HANDLE_VALUE) return; wstring strW = ToWide(str); DWORD charsWritten; WriteConsoleW(stream, strW.c_str(), (DWORD)strW.length(), &charsWritten, 0); #else fprintf(error ? stderr : stdout, "%s", str.CString()); #endif #endif } void PrintUnicodeLine(const string& str, bool error) { PrintUnicode(str + '\n', error); } void PrintLine(const string& str, bool error) { #if !defined(ANDROID) && !defined(IOS) fprintf(error ? stderr : stdout, "%s\n", str.c_str()); #endif } string ReadLine() { string ret; #ifdef _WIN32 HANDLE input = GetStdHandle(STD_INPUT_HANDLE); HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE); if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE) { return ret; } // Use char-based input SetConsoleMode(input, ENABLE_PROCESSED_INPUT); INPUT_RECORD record; DWORD events = 0; DWORD readEvents = 0; if (!GetNumberOfConsoleInputEvents(input, &events)) return ret; while (events--) { ReadConsoleInputW(input, &record, 1, &readEvents); if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) { unsigned c = record.Event.KeyEvent.uChar.UnicodeChar; if (c) { if (c == '\b') { PrintUnicode("\b \b"); size_t length = currentLine.length(); if (length) currentLine = currentLine.substr(0, length - 1); } else if (c == '\r') { PrintUnicode("\n"); ret = currentLine; currentLine.clear(); return ret; } else { // We have disabled echo, so echo manually wchar_t out = (wchar_t)c; DWORD charsWritten; WriteConsoleW(output, &out, 1, &charsWritten, 0); str::AppendUTF8(currentLine, c); } } } } #else int flags = fcntl(STDIN_FILENO, F_GETFL); fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); for (;;) { int ch = fgetc(stdin); if (ch >= 0 && ch != '\n') ret += (char)ch; else break; } #endif return ret; } }
a698ca04fda2475398bfb3eb465d6a3b6cec65e2
87b61bd1fa1804472b1e4cfab2ed77015f4956a7
/test/tests/simulation/random_walker/SplitRandomWalkerTest.cpp
98c3f70fa16b7b8f482b86b3d048cfa98bc9fa6e
[]
no_license
PKua007/obstructed_tracer
c5c57374d0d21bf8ee82bea95990057beead37d6
25dd1fb70dceef437567111601454645e1df7bf8
refs/heads/master
2021-07-11T04:44:30.446441
2020-09-18T16:40:52
2020-09-18T16:40:52
199,272,872
0
0
null
null
null
null
UTF-8
C++
false
false
2,818
cpp
SplitRandomWalkerTest.cpp
/* * SplitRandomWalkerTest.cpp * * Created on: 22 gru 2019 * Author: pkua */ #include <catch2/catch.hpp> #include <catch2/trompeloeil.hpp> #include <sstream> #include "simulation/random_walker/SplitRandomWalker.h" #include "mocks/simulation/RandomWalkerMock.h" TEST_CASE("SplitRandomWalker: basics") { SECTION("correct number of trajectories") { auto randomWalker = std::unique_ptr<RandomWalkerMock>(new RandomWalkerMock); ALLOW_CALL_V(*randomWalker, getNumberOfTrajectories(), .RETURN(2)); ALLOW_CALL_V(*randomWalker, getNumberOfSteps(), .RETURN(3)); SplitRandomWalker splitRandomWalker(4, std::move(randomWalker)); REQUIRE(splitRandomWalker.getNumberOfTrajectories() == 2); } SECTION("correct total number of steps") { auto randomWalker = std::unique_ptr<RandomWalkerMock>(new RandomWalkerMock); ALLOW_CALL_V(*randomWalker, getNumberOfTrajectories(), .RETURN(2)); ALLOW_CALL_V(*randomWalker, getNumberOfSteps(), .RETURN(3)); SplitRandomWalker splitRandomWalker(4, std::move(randomWalker)); REQUIRE(splitRandomWalker.getNumberOfSteps() == 12); } } TEST_CASE("SplitRandomWalker: 2 splits, 1 trajectory") { Trajectory t1; t1.addPoint(Point{1, 2}); t1.addPoint(Point{3, 4}); Trajectory t2; t2.addPoint(Point{3, 4}); t2.addPoint(Point{5, 6}); std::vector<Tracer> initialTracers1 = {Tracer{Point{1, 2}, 0}}; std::vector<Tracer> initialTracers2 = {Tracer{Point{3, 4}, 0}}; auto randomWalker = std::unique_ptr<RandomWalkerMock>(new RandomWalkerMock); ALLOW_CALL_V(*randomWalker, getNumberOfTrajectories(), .RETURN(1)); ALLOW_CALL_V(*randomWalker, getNumberOfSteps(), .RETURN(1)); trompeloeil::sequence seq; using trompeloeil::_; // First split REQUIRE_CALL_V(*randomWalker, run(_, initialTracers1), .IN_SEQUENCE(seq)); REQUIRE_CALL_V(*randomWalker, getTrajectory(0), .IN_SEQUENCE(seq) .TIMES(AT_LEAST(1)) .LR_RETURN((t1))); // Second split REQUIRE_CALL_V(*randomWalker, run(_, initialTracers2), .IN_SEQUENCE(seq)); REQUIRE_CALL_V(*randomWalker, getTrajectory(0), .IN_SEQUENCE(seq) .TIMES(AT_LEAST(1)) .LR_RETURN((t2))); SplitRandomWalker splitRandomWalker(2, std::move(randomWalker)); std::ostringstream logger; splitRandomWalker.run(logger, initialTracers1); REQUIRE(splitRandomWalker.getNumberOfTrajectories() == 1); auto actualTrajectory = splitRandomWalker.getTrajectory(0); REQUIRE(actualTrajectory.getSize() == 3); REQUIRE(actualTrajectory[0] == Point{1, 2}); REQUIRE(actualTrajectory[1] == Point{3, 4}); REQUIRE(actualTrajectory[2] == Point{5, 6}); }
b14dd4836d374b261884641066724c1ee69390b5
0871c13ee23b5c2abcfb25fd68f5af6d6f3449e9
/ObjectManager.cpp
d801355e3ed3af2a81aef3a3a7bf293ca54841f8
[]
no_license
kokojae/SansEngine
494dc33fb2861cb9059c55ee430a5c91357538fe
e47180cc6b22d3b719f1eb74c85bd1175c26b239
refs/heads/master
2020-12-22T10:05:12.320476
2020-10-15T02:40:07
2020-10-15T02:40:07
236,747,051
0
0
null
null
null
null
UHC
C++
false
false
2,014
cpp
ObjectManager.cpp
#include "DXUT.h" #include "ObjectManager.h" #include "TextureInfo.h" #include "Camera.h" #include "SansEngine.h" ObjectManager::ObjectManager() { pSprite = NULL; } ObjectManager::~ObjectManager() { } void ObjectManager::Init() { D3DXCreateSprite(DXUTGetD3D9Device(), &pSprite); } void ObjectManager::Release() { if (pSprite != NULL) pSprite->Release(); } void ObjectManager::Load(LPCWSTR pFile, int width, int height, LPDIRECT3DTEXTURE9 * pTex) { D3DXCreateTextureFromFileEx(DXUTGetD3D9Device(), pFile, width, height, 0, false, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, NULL, NULL, NULL, pTex); } void ObjectManager::Draw(LPDIRECT3DTEXTURE9 pTex, TextureInfo info, D3DXVECTOR2 position) { pSprite->Begin(D3DXSPRITE_ALPHABLEND); D3DXMATRIX mat, center, pos, scale, rotation; D3DXMatrixTranslation(&center, -info.center.x, -info.center.y, 0); D3DXMatrixTranslation(&pos, (int)position.x, (int)position.y, 0); D3DXMatrixScaling(&scale, info.scale.x, info.scale.y, 1); D3DXMatrixRotationZ(&rotation, D3DXToRadian(info.rotation)); mat = center * scale * rotation * pos; pSprite->SetTransform(&mat); //도트겜일경우 사용 DXUTGetD3D9Device()->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); DXUTGetD3D9Device()->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); DXUTGetD3D9Device()->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT); RECT rect = RECT{ (LONG)(int)info.index * (LONG)info.size.x,0,(LONG)((int)info.index + 1) * (LONG)info.size.x,(LONG)info.size.y }; pSprite->Draw(pTex, &rect, NULL, NULL, info.uiColor); pSprite->End(); } bool ObjectManager::Collision(D3DXVECTOR2 vPos, RECT rRect, D3DXVECTOR2 vOpponentPos, RECT rOpponentRect) { if (vPos.x + rRect.left <= vOpponentPos.x + rOpponentRect.right && vPos.y + rRect.top <= vOpponentPos.y + rOpponentRect.bottom && vPos.x + rRect.right >= vOpponentPos.x + rOpponentRect.left && vPos.y + rRect.bottom >= vOpponentPos.y + rOpponentRect.top) return true; return false; }
83cbb8dbedf964e0dd2c3421159ccf6ebe09f86b
de50860fa8acd51fbf7ceef253a88dc2a2a0640f
/m2048/libs/protobuf/src/google/protobuf/compiler/js/js_field.cc
d49645d19570ee223315a96ff2a6b0a9063d978d
[ "LicenseRef-scancode-protobuf", "MIT" ]
permissive
hedonghuasir/2048_master
6555a2e6f4746569aaf1fa3506710fdd663a9353
991966ad399e2f8569dc727ad72bbafc8e774261
refs/heads/master
2021-06-28T01:46:56.107294
2020-04-28T03:49:30
2020-04-28T03:49:30
159,907,217
0
0
MIT
2020-10-13T11:05:53
2018-12-01T04:00:40
C++
UTF-8
C++
false
false
2,620
cc
js_field.cc
// // js_field.cpp // protobuf // // Created by zhao shuan on 8/3/15. // Copyright (c) 2015 hoolai. All rights reserved. // #include <google/protobuf/compiler/js/js_field.h> #include <google/protobuf/compiler/js/js_helpers.h> #include <google/protobuf/compiler/js/js_primitive_field.h> #include <google/protobuf/compiler/js/js_enum_field.h> #include <google/protobuf/compiler/js/js_message_field.h> #include <google/protobuf/compiler/js/js_string_field.h> #include <google/protobuf/stubs/common.h> namespace google { namespace protobuf { namespace compiler { namespace js { FieldGenerator::~FieldGenerator() {} void FieldGenerator::GenerateParsingCodeFromPacked(io::Printer* printer) const { // Reaching here indicates a bug. Cases are: // - This FieldGenerator should support packing, but this method should be // overridden. // - This FieldGenerator doesn't support packing, and this method should // never have been called. GOOGLE_LOG(FATAL) << "GenerateParsingCodeFromPacked() " << "called on field generator that does not support packing."; } FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor) : descriptor_(descriptor), field_generators_(new scoped_ptr<FieldGenerator>[descriptor->field_count()]) { for (int i = 0; i < descriptor->field_count(); i++) { FieldGenerator* generator = MakeGenerator(descriptor->field(i)); field_generators_[i].reset(generator); } } FieldGeneratorMap::~FieldGeneratorMap() { } const FieldGenerator& FieldGeneratorMap::get(const FieldDescriptor* field) const { return *field_generators_[field->index()]; } FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field) { if (field->is_repeated()) { switch (GetJSType(field)) { case JSTYPE_MESSAGE: return new RepeatedMessageFieldGenerator(field); case JSTYPE_STRING: return new RepeatedStringFieldGenerator(field); case JSTYPE_ENUM: return new RepeatedEnumFieldGenerator(field); default: return new RepeatedPrimitiveFieldGenerator(field); } } else { switch (GetJSType(field)) { case JSTYPE_MESSAGE: return new MessageFieldGenerator(field); case JSTYPE_STRING: return new StringFieldGenerator(field); case JSTYPE_ENUM: return new EnumFieldGenerator(field); default: return new PrimitiveFieldGenerator(field); } } } } } } }
7ecae4fcff3bcf90b9b56b13b9c718993d0c0997
a2637ebf462068a0fc3637246005bafd0b447f07
/CrimeEngine/include/Scenes/SceneManager.h
537dbe9d818db7e8ee3126c9f5975050d4bd132b
[ "MIT" ]
permissive
DavidtKate/Crime-Engine
08a063e80f4d0073f11365acb3e76d2244ff31d6
128529634011d41a1f7fc1a356245d7f7ef77cb3
refs/heads/main
2023-03-18T23:17:13.235494
2021-03-08T10:52:07
2021-03-08T10:52:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,070
h
SceneManager.h
#pragma once #include "Core/Core.h" #include "IScene.h" #include "Utils/IService.h" namespace cr { class RenderLayer; } namespace ce { class SceneManager : public IService { public: void OnCreate() override; void OnDestroy() override; void Update(float a_deltaTime) const; void PauseUpdate(float a_deltaTime) const; void Draw(cr::RenderLayer& a_renderLayer) const; template<typename T, typename = typename std::enable_if<std::is_base_of<IScene, T>::value, T>::type, typename ... Args> void AddScene(const std::string& a_sceneName, Args&& ... a_args); template<typename T, typename = typename std::enable_if<std::is_base_of<IScene, T>::value, T>::type> T* SwitchScene(const std::string& a_sceneName); void RemoveScene(const std::string& a_sceneName); IScene* GetCurrentScene() const { return m_currentScene; } private: std::unordered_map<std::string, std::unique_ptr<IScene>> m_scenes; IScene* m_currentScene { nullptr }; }; template <typename T, typename, typename ... Args> void SceneManager::AddScene(const std::string& a_sceneName, Args&&... a_args) { //Check if scene is already added. if(m_scenes.find(a_sceneName) != m_scenes.end()) { CE_CORE_ERROR("[SceneManagement] Scene({0}) has already been added!", a_sceneName); return; } auto scene = std::make_unique<T>(std::forward<Args>(a_args)...); scene->m_sceneName = a_sceneName; m_scenes.insert(std::make_pair(a_sceneName, std::move(scene))); } template <typename T, typename> T* SceneManager::SwitchScene(const std::string& a_sceneName) { const auto it = m_scenes.find(a_sceneName); CE_CORE_ASSERT_M(it != m_scenes.end(), "Couldn't switch to scene({0} as it has been added yet!", a_sceneName); if(m_currentScene != nullptr) { m_currentScene->OnDispose(); m_currentScene = nullptr; } m_currentScene = it->second.get(); if(!m_currentScene->OnSceneSwitched()) { CE_CORE_CRITICAL("[SceneManager] Couldn't initialize scene({0})!", a_sceneName); return nullptr; } return dynamic_cast<T*>(m_currentScene); } }
1ac66986500926b14ea5c062d8bbef6f9506a315
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/Trigger/TrigHypothesis/TrigHLTJetHypoUnitTests/TrigHLTJetHypoUnitTests/JetHypoExerciserCompareAlg.h
1da74dbe1090da21662415425ed48f5c563be00e
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
1,901
h
JetHypoExerciserCompareAlg.h
// -*- C++ -*- /* Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ #ifndef TRIGHLTJETHYPOUNITTESTS_JETHYPOEXERCISERCOMPAREALG_H #define TRIGHLTJETHYPOUNITTESTS_JETHYPOEXERCISERCOMPAREALG_H #include "TrigHLTJetHypo/ITrigJetHypoToolHelperMT.h" #include "TrigHLTJetHypoUnitTests/IHypoJetVectorGenerator.h" #include "GaudiKernel/ToolHandle.h" #include "AthenaBaseComps/AthAlgorithm.h" #include "Gaudi/Property.h" class JetHypoExerciserCompareAlg : public AthAlgorithm { public: JetHypoExerciserCompareAlg( const std::string& name, ISvcLocator* pSvcLocator ); virtual ~JetHypoExerciserCompareAlg(); StatusCode initialize(); StatusCode execute(); StatusCode finalize(); private: // ToolHandles as Properties ToolHandle<ITrigJetHypoToolHelperMT> m_helper0 {this, "JetHypoHelperTool0", "Tool0", "private IJetTrigHypoToolHelper0"}; ToolHandle<ITrigJetHypoToolHelperMT> m_helper1 {this, "JetHypoHelperTool1", "Tool1", "private IJetTrigHypoToolHelper1"}; ToolHandle<IHypoJetVectorGenerator> m_generator {this, "event_generator", {}, "Generates test vector"}; Gaudi::Property<bool> m_visitDebug {this, "visit_debug", false, "debug flag"}; Gaudi::Property<std::string> m_logname {this, "logname", "JetHypoExerciser.log", "debug info output fn"}; std::size_t m_ncall{0}; std::size_t m_agree_true{0}; std::size_t m_agree_false{0}; std::size_t m_differ{0}; std::size_t m_agree_jets{0}; std::size_t m_differ_jets{0}; StatusCode initialize_(const ToolHandle<ITrigJetHypoToolHelperMT>&, const std::string&); StatusCode execute_(ToolHandle<ITrigJetHypoToolHelperMT>&, HypoJetVector&, const std::string& collectorName, xAODJetCollector& jetCollector, const std::string& logname, bool& pass); }; #endif // !#define TRIGHLTJETHYPOUNITTESTS_JETHYPOEXERCISER_H
b2f3e63556316702c949e0d6c4781b999837bf79
7572598de10db5aad53619b97f336920f97edbff
/Code/EmbeddedDeformation/EmbeddedDeformation/Sample.h
f3f0e6d74b82c24fec11e50d152cae42260e6f61
[]
no_license
Yuanjrah/BetaShapeMachine
7eaf59859523c24ce4df1243aa21b9cdc06b6891
92f4c7903c723178049cd2abf8bcc556edafc8a9
refs/heads/master
2021-09-08T22:12:50.303283
2016-05-26T19:13:53
2016-05-26T19:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,033
h
Sample.h
#pragma once #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include<iostream> #include<vector> #include "TriMesh.h" using namespace std; using namespace trimesh; class Sample { public: Sample(void); ~Sample(void); Sample(vec3 pos, vec3 nor, float weg = 1.0f, int id = -1); vec3 position; vec3 normal; vec3 pca; vec3 angel; vec3 angel_with_up; ivec3 color; float weight; int face_id; int patch_id; vector<float> diff_feature; vector<float> sample_features; // just for check each feature vector<float> shape_context; vector<float> var_sc; // var for shape_context in each dim vector<float> angel_geo_dis; vector<float> var_agd; vector<float> spin_image; vector<float> var_si; vector<float> sample_pca; vector<float> curvature; vector<float> var_cur; vector<float> sdf; int is_sigular ; float dist_feature(Sample p1, int feature_type); float dist_with_normal(Sample p1); float dist_with_feature(Sample p1); float dis_curvature(Sample p1); float dis_shapeconetx(Sample p1); };
3bab64db27ff55e1392dc8895ea5f5fb7bb921f5
88d8d7b147e68bd4913fe05081cdb1574d933fca
/Source/Core/Messages/NetworkMessage.h
b41f757cdb9ad06724675d249bb601846397cd8f
[]
no_license
JimbobKR18/JFramework
d8acc577e81c6bbaf362a84061612d55f040f57a
17563250df026425d91622cf7119727af78dc9e0
refs/heads/master
2020-04-04T05:41:28.162914
2019-09-28T07:36:16
2019-09-28T07:36:16
5,645,960
0
0
null
null
null
null
UTF-8
C++
false
false
408
h
NetworkMessage.h
#ifndef __JFramework__NetworkMessage__ #define __JFramework__NetworkMessage__ class NetworkMessage : public Message { private: NetworkMessage() : Message() {} NetworkMessage(NetworkMessage const &aMessage) : Message(aMessage) {} public: NetworkMessage(HashString const &aContent) : Message() { SetDescription("Network"); SetContent(aContent); } virtual ~NetworkMessage() {} }; #endif
f295b0de90d7e0501dd6e6a65c21aff1b32bb410
59aaf30aaf64e16b43c6f1a3046f1c3c2b8f33e1
/file_sharing_system/int_to_iter.cpp
2c97b0707955ae69e8f0753dcf9c74317245f63a
[]
no_license
svinniepoopy/mini_architectures
67196a37c29e1ace52a7030e999ad66a0748fda4
a64c3f76ef671b378487bcc27c800326743fc22d
refs/heads/main
2023-04-15T06:25:23.365489
2021-04-12T09:26:47
2021-04-12T09:26:47
357,130,795
0
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
int_to_iter.cpp
#include <list> #include <unordered_map> int main() { std::unordered_map<int, std::list<int>::iterator> M; return 0; }
94790f3db90674ee5a3abec5e87a80dfe883f12d
d84e689d4b587263f62e353e1da559d906056473
/numarare4.cpp
c98525bd7f9d4b31b1cc982155b44c04a3884246
[]
no_license
cosminvoicu/LearnAlgoritms
2c4bc44d01edaae9a2851d39eef6d1e79068a215
1f71641d56d171c6d2943d33c770e15a86f10e52
refs/heads/master
2021-06-24T06:22:58.956608
2020-11-12T05:11:59
2020-11-12T05:11:59
156,120,051
0
0
null
null
null
null
UTF-8
C++
false
false
346
cpp
numarare4.cpp
#include<iostream> using namespace std; int gcd ( int a, int b) { if (!b) return a; return gcd ( b, a%b ); } int main() { int sir[201], n, contor=0; cin>>n; for ( int i = 1; i<=n; ++i ) { cin>>sir[i]; } for ( int i = 1; i<n; ++i ) { if ( gcd(sir[i],sir[n]) == 1 ) ++contor; } cout<<contor; return 0; }
54d32ab908be9427514c8bf981d825af2223c6a0
ac5442020a5247231ede042926530e500b16b501
/compilers/frontend/src/syntax/stmt/loop_stmt.cc
8967de8b5dcacbe37c78bada6a4ef28e2a67f7b4
[]
no_license
MuhammadNurYanhaona/ITandPCubeS
e8a42d8d50f56eb76954bdf2cb786377cb5a8ee5
8928c56587db8293f0ec02c7cb030cfb540ce2b4
refs/heads/master
2021-01-24T06:22:37.089569
2017-04-22T15:57:04
2017-04-22T15:57:04
15,794,818
1
1
null
null
null
null
UTF-8
C++
false
false
1,417
cc
loop_stmt.cc
#include "../ast.h" #include "../ast_stmt.h" #include "../ast_expr.h" #include "../ast_def.h" #include "../ast_task.h" #include "../../common/errors.h" #include "../../common/location.h" #include "../../semantics/scope.h" #include "../../semantics/symbol.h" #include "../../semantics/helper.h" #include "../../semantics/loop_index.h" #include "../../semantics/data_access.h" #include "../../static-analysis/reduction_info.h" #include "../../codegen-helper/extern_config.h" #include "../../../../common-libs/utils/list.h" #include "../../../../common-libs/utils/hashtable.h" #include <iostream> #include <sstream> #include <cstdlib> //------------------------------------------------------------ Loop Statement ----------------------------------------------------------/ LoopStmt::LoopStmt() : Stmt() { this->body = NULL; this->scope = NULL; this->indexScope = NULL; } LoopStmt::LoopStmt(Stmt *body, yyltype loc) : Stmt(loc) { Assert(body != NULL); this->body = body; this->body->SetParent(this); this->scope = NULL; } void LoopStmt::extractReductionInfo(List<ReductionMetadata*> *infoSet, PartitionHierarchy *lpsHierarchy, Space *executingLps) { body->extractReductionInfo(infoSet, lpsHierarchy, executingLps); } void LoopStmt::retrieveExternHeaderAndLibraries(IncludesAndLinksMap *includesAndLinksMap) { body->retrieveExternHeaderAndLibraries(includesAndLinksMap); }
3f55e8cd19f959d143179f998932aaf3eddac08c
3c21729775286440df2bd1a1b28b6e0596b223cb
/cpp/day02.cpp
e1f8a123a967798f3ffd18996d8737ae09221b65
[]
no_license
rnkjoshi/LCO_30_days_compiChallenge
65389736103dc2ed6473a77e9d4337733305c660
6558bcbb6839d8d26be655d53f92c901bbadb997
refs/heads/master
2022-11-05T20:23:59.907475
2020-06-15T18:06:13
2020-06-15T18:06:13
264,522,107
0
0
null
null
null
null
UTF-8
C++
false
false
587
cpp
day02.cpp
/* Print this pattern. ** ** **** **** ****** ****** ******** ******** */ #include<bits/stdc++.h> using namespace std; void patternPrint(int spaces,int asterics){ for(int i=0;i<spaces;i++) printf(" "); for(int i=0;i<asterics;i++) printf("*"); printf("\n"); } int main(){ int n; cin>>n; int counter=2; for(int i=0;i<n;i++){ patternPrint(n-i,counter); patternPrint(n-i,counter); counter+=2; } }
148585f2d3b1aa176c61fb72ba5aa0a0627bbd44
fbc1c378980fbfffb79b10803de99313df9c115f
/fe.h
cfbd50f8d92a5874fa6da057161667da0d71ed1f
[]
no_license
ShoiX/cpp-lib-sample
c6fe55ea15e13d93e809ab246ebc9f8b382370c4
cdd785d2a401815755622bb215ebc97ce7ff5ac6
refs/heads/master
2020-06-05T07:31:02.076516
2019-06-17T14:13:14
2019-06-17T14:13:14
192,360,930
0
0
null
null
null
null
UTF-8
C++
false
false
204
h
fe.h
// TODO: create a Makefile // to compile g++ -g fe.cpp main.cpp -o main #include <cmath> #include <iostream> unsigned int fast_exponentiation(unsigned int base, unsigned int exponent, unsigned int mod);
9e34e00081389817df542fa69694dd821416df5c
072ffc598dc09bb48b8bb97f81e39266c2a1c4d6
/FP/FP1/Practices/PC08.cpp
cfa2b42ad556863ce8fa17341ddcf2e37ec1714e
[]
no_license
korven48/Codigo_Uni
e6eeb66528a1f0508072de7d9183db26be6b24f1
43af1e266d640a84baaa6763b009be77d6e111cd
refs/heads/master
2023-04-11T06:38:47.374541
2021-04-28T19:02:46
2021-04-28T19:02:46
301,539,386
0
0
null
null
null
null
UTF-8
C++
false
false
5,381
cpp
PC08.cpp
#include <iostream> #include <string> #include <fstream> #include <iomanip> using namespace std; const string FileName = "stock.txt"; const int MAX = 50; typedef string tProdName[MAX]; typedef double tProdPrice[MAX]; typedef int tProdUnits[MAX]; bool load(tProdName prodName, tProdPrice prodPrice, tProdUnits prodUnits, int& counter); void save(const tProdName prodName, const tProdPrice prodPrice, const tProdUnits prodUnits, int counter); void initCart(tProdUnits cart); void newProd(string& name, double& price, int& units); bool insert(tProdName prodName, tProdPrice prodPrice, tProdUnits prodUnits, string name, double price, int units, int& counter); void print(const tProdName prodName, const tProdPrice prodPrice, const tProdUnits prodUnits, int counter); void dispCart(const tProdUnits cart, int counter, const tProdName prodName, const tProdPrice prodPrice); void sell(tProdUnits prodUnits, tProdUnits cart); int menu(); void addToCart(tProdUnits prodUnits, tProdUnits cart); int main() { tProdName prodName; tProdPrice prodPrice; tProdUnits prodUnits; tProdUnits shoppingCart; int counter = 0, cartCount = 0, option = -1; string name; double price; int units; if (!load(prodName, prodPrice, prodUnits, counter)) cout << "File not found! Exiting..." << endl; else { while (option != 0) { option = menu(); switch (option) { case 1: print(prodName, prodPrice, prodUnits, counter); break; case 2: newProd(name, price, units); if (insert(prodName, prodPrice, prodUnits, name, price, units, counter)) cout << "Product added!" << endl << endl; else cout << "Too many porducts, not possible to add more." << endl; break; case 3: initCart(shoppingCart); break; case 4: print(prodName, prodPrice, prodUnits, counter); addToCart(prodUnits, shoppingCart); break; case 5: dispCart(shoppingCart, counter, prodName, prodPrice); break; case 6: sell(prodUnits, shoppingCart); cout << "Sold!" << endl; break; } cout << endl; } save(prodName, prodPrice, prodUnits, counter); } return 0; } int menu() { int op = -1; while ((op < 0) || (op > 6)) { cout << "1 - Display stock" << endl; cout << "2 - New stock product" << endl; cout << "3 - Create cart" << endl; cout << "4 - Add order to cart" << endl; cout << "5 - Display cart" << endl; cout << "6 - Sell cart" << endl; cout << "0 - Exit" << endl; cout << "Your option: "; cin >> op; if ((op < 0) || (op > 6)) cout << "Invalid option! Try again..." << endl; } cout << endl; return op; } bool load(tProdName prodName, tProdPrice prodPrice, tProdUnits prodUnits, int& counter) { bool ok = false; ifstream file; string name; file.open(FileName); counter = 0; if (file.is_open()) { file >> name; while ((name != "XXX") && (counter < MAX)) { prodName[counter] = name; file >> prodPrice[counter] >> prodUnits[counter]; counter++; file >> name; } file.close(); ok = true; } return ok; } void save(const tProdName prodName, const tProdPrice prodPrice, const tProdUnits prodUnits, int counter) { ofstream outputFile("stock.txt"); if (outputFile.is_open()) { for (int i = 0; i < counter; i++) { outputFile << prodName[i] << " " << prodPrice[i] << " " << prodUnits[i] << endl; } outputFile << "XXX" << endl; //>>>>> CLOSE THE FILE!!!!! (INFO CAN BE LOST) } } void initCart(tProdUnits cart) { // 3 for (int i = 0; i < MAX; i++) cart[i] = 0; } void newProd(string& name, double& price, int& units) { // 2 cout << "Product name: "; cin >> name; cout << "Product price: "; cin >> price; cout << "Product units: "; cin >> units; } bool insert(tProdName prodName, tProdPrice prodPrice, tProdUnits prodUnits, string name, double price, int units, int& counter) { bool ok = false; if (counter < MAX) { prodName[counter] = name; prodPrice[counter] = price; prodUnits[counter] = units; counter++; ok = true; } return ok; } void print(const tProdName prodName, const tProdPrice prodPrice, const tProdUnits prodUnits, int counter) { // 1 cout << "# " << setw(25) << left << "Product" << " Price" << ' ' << "Units" << endl; for (int i = 0; i < counter; i++) { cout << (i + 1) << ' ' << setw(25) << left << prodName[i] << setw(6) << right << prodPrice[i] << setw(6) << right << prodUnits[i] << endl; } } void dispCart(const tProdUnits cart, int counter, const tProdName prodName, const tProdPrice prodPrice) { // 5 double total = 0; for (int i = 0; i < counter; i++) { if (cart[i]) { cout << setw(16) << left << prodName[i] << setw(10) << left << prodPrice[i] << right << "x" << setw(5) << right << cart[i] << " =" << setw(10) << right << fixed << setprecision(2) << (prodPrice[i] * cart[i]) << endl; total += prodPrice[i] * cart[i]; } } cout << "Total" << setw(39) << total << endl; } void sell(tProdUnits prodUnits, tProdUnits cart) { for (int i = 0; i < MAX; i++) { prodUnits[i] -= cart[i]; cart[i] = 0; } } void addToCart(tProdUnits prodUnits, tProdUnits cart) { int num, units; cout << "Product Number: "; cin >> num; num--; cout << "Units to buy: "; cin >> units; while (units > prodUnits[num]) { cout << "Units available: " << prodUnits[num] << " Try again!" << endl; cout << "Units to buy: "; cin >> units; } cart[num] += units; }
9766345a54a444a929ed82a1f65025237b583da5
88bb1c445d0ec6c74473b8ff700808c2be60f6cd
/Source/ASHUMPanelBase.h
eb3291103b2fb04bdc7555552f8d078d5c9b7b3c
[]
no_license
Aleks048/SimpleDistortion
0751f847929bc59de2157a6cf84ca6f707941985
70b9bd7a3fa9dfc22fb76d69ce4ce441566e45d8
refs/heads/master
2023-02-27T15:04:08.576468
2021-02-08T17:20:29
2021-02-08T17:20:29
336,933,882
0
0
null
2021-02-08T17:21:52
2021-02-08T01:57:29
C++
UTF-8
C++
false
false
665
h
ASHUMPanelBase.h
/* ============================================================================== ASHUMPanelBase.h Created: 7 Feb 2021 1:43:49pm Author: ashum048 ashum048: base class. All panels inherit from it ============================================================================== */ #pragma once #include "JuceHeader.h" #include "PluginProcessor.h" class ASHUMPanelBase : public juce::Component { public: ASHUMPanelBase(Dist_Over_BitCrAudioProcessor* inPocessor); ~ASHUMPanelBase(); void paint(juce::Graphics& g) override; protected: juce::String mDistTypeNames[4] { "Clip", "Sin","Tanh","Pow3"}; Dist_Over_BitCrAudioProcessor* mProcessor; };
859a79114384f5b5c9668a59c54c440552cf5967
1ac50a3c9ed746076623c47637def95011aa043a
/Game/project2D/CollisionManager.cpp
c7258cd4a9ec52b304c4a0cc83c7ec2fed1b0004
[ "MIT" ]
permissive
Hypro123/EDMathDemonstration
d9dd27d4829cc0311e283bffbc5cb6323835ffab
77065d6034fd45ea6b0119b6d059c3f76313b316
refs/heads/master
2020-12-30T14:01:16.696983
2017-05-15T22:57:29
2017-05-15T22:57:29
91,280,457
0
0
null
null
null
null
UTF-8
C++
false
false
1,656
cpp
CollisionManager.cpp
#include "collisionManager.h" #include "Collider.h" collisionManager* collisionManager::m_instance = nullptr; collisionManager::collisionManager() { } collisionManager::~collisionManager() { } collisionManager* collisionManager::GetInstance() { return m_instance; } void collisionManager::Create() { if (m_instance == nullptr) m_instance = new collisionManager(); } void collisionManager::Destroy() { delete m_instance; } void collisionManager::CreateObject(Entity* pObject) { m_collisionList.push_back(pObject); } void collisionManager::RemoveObject(Entity* pObject) { auto iter = std::find(m_collisionList.begin(), m_collisionList.end(), pObject); if (iter != m_collisionList.end()) m_collisionList.erase(iter); } Entity* collisionManager::testCollision(Entity* pObject) { for (int i = 0; i < m_collisionList.size(); ++i) { //Dont collide with self if (pObject == m_collisionList[i]) continue; //calc AABB of two objects Collider collider1 = pObject->GetCollider(); collider1.topRight = collider1.topRight + pObject->local_Transform.getPosition(); collider1.botLeft = collider1.botLeft + pObject->local_Transform.getPosition(); Collider collider2 = m_collisionList[i]->GetCollider(); collider2.topRight = collider2.topRight + m_collisionList[i]->local_Transform.getPosition(); collider2.botLeft = collider2.botLeft + m_collisionList[i]->local_Transform.getPosition(); //AABBs overlapping if (collider1.botLeft < collider2.topRight&& collider2.botLeft < collider1.topRight) { return m_collisionList[i]; } } return nullptr; }
fe43abbd909de8d58b2c7bf7183480e298bc734b
67401351095c5ed45460c3e47a80806fcc672c41
/1622-Creating Strings.cpp
967423bcb6134b296df342e9cc347b1331f53041
[]
no_license
cwza/cses
5f3d9feefb04a99a3b68b3da653269ea4fe3f09e
1923cadc355fcdc28a6d542dc53e4b46e75644e9
refs/heads/master
2023-04-03T09:29:23.588680
2021-03-29T01:05:48
2021-03-29T01:05:48
344,027,634
0
0
null
null
null
null
UTF-8
C++
false
false
1,185
cpp
1622-Creating Strings.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<vector<int>> vvi; typedef pair<int, int> pi; void helper(string &path, int counter[26], int n, vector<string> &ans) { if(path.size()==n) { ans.push_back(path); } for(int i = 0; i < 26; ++i) { if(counter[i] > 0) { path.push_back(i+'a'); counter[i]--; helper(path, counter, n, ans); path.pop_back(); counter[i]++; } } } // int main() { // ios::sync_with_stdio(0); // cin.tie(0); // string s; // cin >> s; // int counter[26] = {0}; // for(char ch : s) counter[ch-'a'] += 1; // string path; vector<string> ans; // helper(path, counter, s.size(), ans); // cout << ans.size() << "\n"; // for(string t : ans) cout << t << "\n"; // } int main() { ios::sync_with_stdio(0); cin.tie(0); string s; cin >> s; sort(s.begin(), s.end()); vector<string> ans; do { ans.push_back(s); } while(next_permutation(s.begin(), s.end())); cout << ans.size() << "\n"; for(string t : ans) cout << t << "\n"; }
6e5721af2fccb1f98a524d9269e1be222ac43e38
b0d50570da36190f4402656229bba8304da465d2
/Classes/EventBusinessLayer.h
75dc43f3603e0111676451e4119cde1cd9a977e9
[]
no_license
daxingyou/MyJH2
6e4b78b73d6e1f8eb65ee06794f779253e4343cc
1b7a606adf6ca03bd134b88918c675906ac18e07
refs/heads/master
2022-02-21T04:20:09.943673
2018-12-03T09:03:48
2018-12-03T09:03:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
h
EventBusinessLayer.h
#ifndef _EVENTBUSINESS_LAYER_H_ #define _EVENTBUSINESS_LAYER_H_ #include "cocos2d.h" #include "cocostudio/CocoStudio.h" #include "ui/CocosGUI.h" #include "MapBlock.h" USING_NS_CC; class EventBusinessLayer :public Layer { public: EventBusinessLayer(); ~EventBusinessLayer(); virtual bool init(); static EventBusinessLayer* create(); void buyRes(FOURProperty res); private: void onBtnClick(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type); void onclick(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type); std::vector<cocos2d::ui::ScrollView*> vec_scrollview; void updateScrollviewContent(); void loadScrollviewData(); void loadMyPackageRes(); static bool sortBuyResByType(FOURProperty a, FOURProperty b); void delayShowUI(float dt); void updateRichLabel(); private: cocos2d::ui::Text* carrycountlbl; cocos2d::ui::Text* mycoinlbl; cocos2d::ui::Text* mysilverlbl; std::vector<FOURProperty> vec_buyres; std::vector<FOURProperty> vec_mypackagres; bool clickflag; Vec2 beginTouchPoint; }; #endif
bd2dfa53384b710813047e4735f808a22d14879e
30293a0459635ae5bcc7d97eca7586f0a85ca195
/BoYee/FIRETRUCK.cpp
81113a46df3e600b094ba868d30c35723856d203
[ "MIT" ]
permissive
ClaudeU/Algorithm_Review
e1ab50543d5f84ff8d7a60adb6d26bfd533b4c69
67f2e3e7dca7a39cd9525f62249689d9d1d79994
refs/heads/master
2021-07-03T18:03:55.675704
2017-06-21T18:00:47
2017-06-21T18:00:47
104,836,888
0
0
null
2017-09-26T04:43:55
2017-09-26T04:43:55
null
UTF-8
C++
false
false
2,645
cpp
FIRETRUCK.cpp
#include <iostream> #include <vector> #include <list> #include <limits.h> #include <queue> using namespace std; typedef struct node{ int num; int weight; bool operator>(const node& other) const {return weight> other.weight;} } node; void Print (const vector<int>& v){ //vector<int> v; for (int i=0; i<v.size();i++){ //cout << v[i] << endl; } } void Print_list ( vector<list<node> >& v ) { for (int i=0; i<v.size();i++){ list<node>::iterator iter; for(iter = v[i].begin() ; iter != v[i].end(); iter++) { //cout << (*iter).num << " "<<(*iter).weight << "/ "; } //cout << endl; } } vector<int> extinguishfire(vector<list<node> >& reachable, vector<int>& firestations,vector<int>& accidents,int num_vertex ) { vector<int> result(num_vertex,INT_MAX); priority_queue<node, vector<node>, greater<node> > pq; pq.push({num_vertex,0}); while(!pq.empty()) { node me = pq.top(); pq.pop(); list<node>::iterator iter; for(iter = reachable[me.num].begin(); iter != reachable[me.num].end() ; iter++) { if(me.weight + (*iter).weight < result[(*iter).num]) { result[(*iter).num] = me.weight + (*iter).weight; pq.push({(*iter).num, result[(*iter).num]}); } } Print(result); } return result; } int main(void) { int num_case; cin >> num_case; //cout << "case :" << num_case << endl; while(num_case--) { int num_result; int num_vertex, num_edge, num_firestation, num_accident; cin >> num_vertex >> num_edge >> num_accident >> num_firestation; //cout << "echo " << num_vertex << "/ " <<num_edge<< "/ " <<num_accident<< "/ " <<num_firestation << "/ " << endl ; vector<list<node> > reachable(num_vertex+1); vector<int> firestations; vector<int> accidents; while(num_edge--) { int src, dst, weight; cin >> src >> dst >> weight; //cout << "echo: " << src << "/" << dst << "/" << weight << endl; reachable[src-1].push_back({dst-1, weight}); reachable[dst-1].push_back({src-1, weight}); } //cout << "push edge complete" << endl; int temp = num_accident; while (temp--) { int where; cin >> where; accidents.push_back(where-1); } temp = num_firestation; while (temp--) { int where; cin >> where; firestations.push_back(where-1); } // trick! for(int i =0; i<num_firestation; i++) { reachable[num_vertex].push_back({firestations[i], 0}); } Print_list(reachable); // run dijkstra vector<int> result = extinguishfire(reachable,firestations, accidents, num_vertex ); int sum = 0; // add for(int i =0;i<num_accident;i++) { sum += result[accidents[i]]; } cout << sum << endl; } }
ed2b36a2e5d17880f316ac6580f8c2abb306969a
07c61596c1fba2e2a7034fe5af9707794ea2e2c1
/Kattis/wheresmyinternet.cpp
22b77852f2d07972e6509126fdcc222d412be809
[]
no_license
H-Shen/Collection_of_my_coding_practice
2fcb2f8fef9451ad4a3a9c063bbf6a34ea5966b4
6415552d38a756c9c89de0c774799654c73073a6
refs/heads/master
2023-08-24T21:19:08.886667
2023-08-22T03:47:39
2023-08-22T03:47:39
180,731,825
8
1
null
2021-08-13T18:25:25
2019-04-11T06:48:09
C++
UTF-8
C++
false
false
1,233
cpp
wheresmyinternet.cpp
// https://open.kattis.com/problems/wheresmyinternet // #include <bits/extc++.h> using namespace std; constexpr int maxn = 200005; int father[maxn]; // Father nodes int Rank[maxn]; // Rank int result[maxn]; int result_length = 0; int find(int x) { if (x != father[x]) father[x] = find(father[x]); return father[x]; } void merge(int x, int y) { x = find(x); y = find(y); if (Rank[x] > Rank[y]) { father[y] = x; } else { father[x] = y; if (Rank[x] == Rank[y]) Rank[y] += 1; } } void reset() { for (int i = 1; i < maxn; i++) { father[i] = i; Rank[i] = 0; } } int main() { reset(); int N, M, a, b; scanf("%d %d", &N, &M); for (int i = 0; i < M; ++i) { scanf("%d %d", &a, &b); merge(a, b); } int groupNumber = find(1); for (int i = 2; i <= N; ++i) { if (find(i) != groupNumber) { result[result_length++] = i; } } if (result_length == 0) { printf("Connected\n"); } else { sort(result, result + result_length); for (int i = 0; i < result_length; ++i) { printf("%d\n", result[i]); } } return 0; }
a6ea85279f8e611adfc5d71b2d0254d0a99db058
5538f52b78f533deccdd15e1cc5508082e29b31e
/include/tvr/Common/JSONHelpers.h
c40023350f23a6751e10ad33b3704714e8335c73
[]
no_license
liaoclarke/tvr_runtime
049f800406873c8621f3deda4533e36ec0328109
d406d547922e33b105c60a06ace9b91f656198db
refs/heads/master
2021-01-01T05:43:42.814023
2016-05-29T03:46:23
2016-05-29T03:46:23
58,048,316
0
0
null
null
null
null
UTF-8
C++
false
false
1,154
h
JSONHelpers.h
#ifndef INC_Common_JSONHelpers_h #define INC_Common_JSONHelpers_h // Internal Includes // - none // Library/third-party includes #include <json/value.h> #include <json/reader.h> #include <json/writer.h> // Standard includes #include <string> namespace tvr { namespace common { /// @brief Parses a string as JSON, returning a null value if parsing fails. inline Json::Value jsonParse(std::string const &str) { Json::Reader reader; Json::Value val = Json::nullValue; if (!reader.parse(str, val)) { // in case the failed parse modified the value somehow val = Json::nullValue; } return val; } /// @brief Turns the JSON value into a compact string representation. inline std::string jsonToCompactString(Json::Value const& val) { Json::FastWriter writer; return writer.write(val); } /// @brief Turns the JSON value into a pretty-printed, human-targeted string /// representation. inline std::string jsonToStyledString(Json::Value const& val) { return val.toStyledString(); } } // namespace common } // namespace tvr #endif
e375c49ad07167656beea38feb7ad7b870105f37
87353fd398d01b5eebceaddcb2ef78e39ed4eb6d
/include/ICP.h
8e759c8a822e7148eaba4284ff2f8550ab812f63
[]
no_license
Sadaku1993/graph_slam
a4715a1983d50b2d3743ca4e22c32c110f2b4401
165cae81ff057cc462b2b28c0bdf1dbcdaeabdca
refs/heads/master
2020-04-20T19:57:09.192143
2019-03-15T16:51:32
2019-03-15T16:51:32
169,063,210
5
4
null
null
null
null
UTF-8
C++
false
false
452
h
ICP.h
#ifndef ICP_H #define ICP_H #include <iostream> #include <pcl/point_cloud.h> #include <pcl/registration/icp.h> namespace GRAPH_SLAM { template<typename T_p> class ICP { public: ICP(); void icp(typename pcl::PointCloud<T_p>::Ptr& source_cloud, typename pcl::PointCloud<T_p>::Ptr& target_cloud, Eigen::Matrix4d& transform_matrix); private: }; template class ICP<pcl::PointXYZ>; } #endif
eac18dd4cf8b73e00fbad38902facc7aaab2d47a
3934cdf17301219728a967e8913237284ae57bd3
/test/f32-vsub-relu.cc
cec283c63f52eb56b7dfb06bd0abb9b261cffb96
[ "LicenseRef-scancode-generic-cla", "BSD-3-Clause" ]
permissive
google/XNNPACK
c1a709b570460dd9e352300b18ba75025ace34ac
c758a4a6601513736ae520dd87206c76e8f5f05a
refs/heads/master
2023-08-30T10:43:28.569336
2023-08-30T07:46:17
2023-08-30T07:47:37
208,364,128
1,565
313
NOASSERTION
2023-09-14T19:47:21
2019-09-13T23:48:37
C
UTF-8
C++
false
false
21,792
cc
f32-vsub-relu.cc
// Copyright 2019 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. // // Auto-generated file. Do not edit! // Specification: test/f32-vsub-relu.yaml // Generator: tools/generate-vbinary-test.py #include <gtest/gtest.h> #include <xnnpack/common.h> #include <xnnpack/isa-checks.h> #include <xnnpack/microparams-init.h> #include <xnnpack/vbinary.h> #include "vbinary-microkernel-tester.h" #if XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD TEST(F32_VSUB_RELU__WASMSIMD_U4, batch_eq_4) { VBinaryMicrokernelTester() .batch_size(4) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u4, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__WASMSIMD_U4, batch_div_4) { for (size_t batch_size = 8; batch_size < 40; batch_size += 4) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U4, batch_lt_4) { for (size_t batch_size = 1; batch_size < 4; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U4, batch_gt_4) { for (size_t batch_size = 5; batch_size < 8; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U4, inplace_a) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U4, inplace_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U4, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u4, VBinaryMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD #if XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD TEST(F32_VSUB_RELU__WASMSIMD_U8, batch_eq_8) { VBinaryMicrokernelTester() .batch_size(8) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u8, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__WASMSIMD_U8, batch_div_8) { for (size_t batch_size = 16; batch_size < 80; batch_size += 8) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U8, batch_lt_8) { for (size_t batch_size = 1; batch_size < 8; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U8, batch_gt_8) { for (size_t batch_size = 9; batch_size < 16; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U8, inplace_a) { for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U8, inplace_b) { for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U8, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u8, VBinaryMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD #if XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD TEST(F32_VSUB_RELU__WASMSIMD_U16, batch_eq_16) { VBinaryMicrokernelTester() .batch_size(16) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u16, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__WASMSIMD_U16, batch_div_16) { for (size_t batch_size = 32; batch_size < 160; batch_size += 16) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u16, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U16, batch_lt_16) { for (size_t batch_size = 1; batch_size < 16; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u16, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U16, batch_gt_16) { for (size_t batch_size = 17; batch_size < 32; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u16, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U16, inplace_a) { for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u16, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U16, inplace_b) { for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u16, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASMSIMD_U16, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasmsimd_u16, VBinaryMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD #if XNN_ARCH_WASM || XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD TEST(F32_VSUB_RELU__WASM_U1, batch_eq_1) { VBinaryMicrokernelTester() .batch_size(1) .Test(xnn_f32_vsub_relu_ukernel__wasm_u1, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__WASM_U1, batch_gt_1) { for (size_t batch_size = 2; batch_size < 10; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u1, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U1, inplace_a) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u1, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U1, inplace_b) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u1, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U1, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u1, VBinaryMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_WASM || XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD #if XNN_ARCH_WASM || XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD TEST(F32_VSUB_RELU__WASM_U2, batch_eq_2) { VBinaryMicrokernelTester() .batch_size(2) .Test(xnn_f32_vsub_relu_ukernel__wasm_u2, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__WASM_U2, batch_div_2) { for (size_t batch_size = 4; batch_size < 20; batch_size += 2) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U2, batch_lt_2) { for (size_t batch_size = 1; batch_size < 2; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U2, batch_gt_2) { for (size_t batch_size = 3; batch_size < 4; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U2, inplace_a) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U2, inplace_b) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U2, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u2, VBinaryMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_WASM || XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD #if XNN_ARCH_WASM || XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD TEST(F32_VSUB_RELU__WASM_U4, batch_eq_4) { VBinaryMicrokernelTester() .batch_size(4) .Test(xnn_f32_vsub_relu_ukernel__wasm_u4, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__WASM_U4, batch_div_4) { for (size_t batch_size = 8; batch_size < 40; batch_size += 4) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U4, batch_lt_4) { for (size_t batch_size = 1; batch_size < 4; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U4, batch_gt_4) { for (size_t batch_size = 5; batch_size < 8; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U4, inplace_a) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U4, inplace_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U4, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u4, VBinaryMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_WASM || XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD #if XNN_ARCH_WASM || XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD TEST(F32_VSUB_RELU__WASM_U8, batch_eq_8) { VBinaryMicrokernelTester() .batch_size(8) .Test(xnn_f32_vsub_relu_ukernel__wasm_u8, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__WASM_U8, batch_div_8) { for (size_t batch_size = 16; batch_size < 80; batch_size += 8) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U8, batch_lt_8) { for (size_t batch_size = 1; batch_size < 8; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U8, batch_gt_8) { for (size_t batch_size = 9; batch_size < 16; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__wasm_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U8, inplace_a) { for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U8, inplace_b) { for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__WASM_U8, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__wasm_u8, VBinaryMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_WASM || XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD TEST(F32_VSUB_RELU__SCALAR_U1, batch_eq_1) { VBinaryMicrokernelTester() .batch_size(1) .Test(xnn_f32_vsub_relu_ukernel__scalar_u1, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__SCALAR_U1, batch_gt_1) { for (size_t batch_size = 2; batch_size < 10; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u1, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U1, inplace_a) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u1, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U1, inplace_b) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u1, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U1, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u1, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U2, batch_eq_2) { VBinaryMicrokernelTester() .batch_size(2) .Test(xnn_f32_vsub_relu_ukernel__scalar_u2, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__SCALAR_U2, batch_div_2) { for (size_t batch_size = 4; batch_size < 20; batch_size += 2) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U2, batch_lt_2) { for (size_t batch_size = 1; batch_size < 2; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U2, batch_gt_2) { for (size_t batch_size = 3; batch_size < 4; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U2, inplace_a) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U2, inplace_b) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U2, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u2, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U4, batch_eq_4) { VBinaryMicrokernelTester() .batch_size(4) .Test(xnn_f32_vsub_relu_ukernel__scalar_u4, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__SCALAR_U4, batch_div_4) { for (size_t batch_size = 8; batch_size < 40; batch_size += 4) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U4, batch_lt_4) { for (size_t batch_size = 1; batch_size < 4; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U4, batch_gt_4) { for (size_t batch_size = 5; batch_size < 8; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U4, inplace_a) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U4, inplace_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U4, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u4, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U8, batch_eq_8) { VBinaryMicrokernelTester() .batch_size(8) .Test(xnn_f32_vsub_relu_ukernel__scalar_u8, VBinaryMicrokernelTester::OpType::Sub); } TEST(F32_VSUB_RELU__SCALAR_U8, batch_div_8) { for (size_t batch_size = 16; batch_size < 80; batch_size += 8) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U8, batch_lt_8) { for (size_t batch_size = 1; batch_size < 8; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U8, batch_gt_8) { for (size_t batch_size = 9; batch_size < 16; batch_size++) { VBinaryMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_relu_ukernel__scalar_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U8, inplace_a) { for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U8, inplace_b) { for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u8, VBinaryMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB_RELU__SCALAR_U8, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinaryMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_relu_ukernel__scalar_u8, VBinaryMicrokernelTester::OpType::Sub); } }
f813924f0661728e2e91d1dfbb9f3eb2b837c25f
0bf8cdde9562a400fe1604237a658fae5a170982
/ext/openMVG/dependencies/osi_clp/Clp/src/ClpPrimalColumnPivot.cpp
37e8ae24260601aa719860809cfdbf78a4fdb31f
[ "LicenseRef-scancode-free-unknown", "EPL-1.0", "BSD-3-Clause" ]
permissive
AIBluefisher/EGSfM
64c2108c037a7e730a81690598022586d6ae90aa
e2e505353cdc525b8e814e0019bd0dc67be75fea
refs/heads/master
2021-06-19T02:06:22.904219
2021-02-28T03:11:14
2021-02-28T03:11:14
187,424,684
91
19
BSD-3-Clause
2020-03-03T07:33:47
2019-05-19T02:20:18
C++
UTF-8
C++
false
false
2,340
cpp
ClpPrimalColumnPivot.cpp
/* $Id: ClpPrimalColumnPivot.cpp 1665 2011-01-04 17:55:54Z lou $ */ // Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #include "CoinPragma.hpp" #include "ClpSimplex.hpp" #include "ClpPrimalColumnPivot.hpp" //############################################################################# // Constructors / Destructor / Assignment //############################################################################# //------------------------------------------------------------------- // Default Constructor //------------------------------------------------------------------- ClpPrimalColumnPivot::ClpPrimalColumnPivot () : model_(NULL), type_(-1), looksOptimal_(false) { } //------------------------------------------------------------------- // Copy constructor //------------------------------------------------------------------- ClpPrimalColumnPivot::ClpPrimalColumnPivot (const ClpPrimalColumnPivot & source) : model_(source.model_), type_(source.type_), looksOptimal_(source.looksOptimal_) { } //------------------------------------------------------------------- // Destructor //------------------------------------------------------------------- ClpPrimalColumnPivot::~ClpPrimalColumnPivot () { } //---------------------------------------------------------------- // Assignment operator //------------------------------------------------------------------- ClpPrimalColumnPivot & ClpPrimalColumnPivot::operator=(const ClpPrimalColumnPivot& rhs) { if (this != &rhs) { type_ = rhs.type_; model_ = rhs.model_; looksOptimal_ = rhs.looksOptimal_; } return *this; } void ClpPrimalColumnPivot::saveWeights(ClpSimplex * model, int ) { model_ = model; } // checks accuracy and may re-initialize (may be empty) void ClpPrimalColumnPivot::updateWeights(CoinIndexedVector *) { } // Gets rid of all arrays void ClpPrimalColumnPivot::clearArrays() { } /* Returns number of extra columns for sprint algorithm - 0 means off. Also number of iterations before recompute */ int ClpPrimalColumnPivot::numberSprintColumns(int & ) const { return 0; } // Switch off sprint idea void ClpPrimalColumnPivot::switchOffSprint() { }
357895413cf645c6d0d2af173a5dabf50a0cb457
cfbb3da46c9745b4d30f3aed4765bd6742ae7ce7
/concept1.cpp
3e42f1c6e3620c2c8c27bc8cea83e5b6d28315d4
[]
no_license
emsr/tr2
14b533198c6578c8825bfc422ffa543b8484cfc4
20710638f1c808f26130dc369819bc6cd73b3377
refs/heads/master
2022-05-22T15:15:51.900776
2022-03-07T16:24:02
2022-03-07T16:24:02
7,756,038
5
0
null
null
null
null
UTF-8
C++
false
false
1,349
cpp
concept1.cpp
// $HOME/bin/bin/g++ -std=c++1z -o concept1 concept1.cpp // ./concept1 // Constrained type specifiers. // dcl.spec.auto.constr template<typename T> concept bool C1 = false; template<int N> concept bool C2 = false; template<template<typename> typename X> concept bool C3 = false; template<typename T, int N> class Array {}; template<typename T, template<typename> typename A> class Stack {}; template<typename T> class Alloc {}; void f1(C1); // C1 designates a placeholder type. void f2(Array<auto, C2>); // C2 designates a placeholder for int value. void f3(Stack<auto, C3>); // C3 designates a placeholder for a class template. // #1 template<typename T> concept bool C() { return true; } // #2 template<typename T, typename U> concept bool C() { return true; } // #3 template<typename T> concept bool D = true; // The set of concepts referred to by C includes #1 and #2; // Concept resolution selects #1. void f(C); // The concept-name D refers only to #3. void g(D); // Partial-concept-id. template<typename T, int N = 0> concept bool Seq = true; void f1(Seq<3>); void f2(Seq<>); // Concept specifier. // dcl.spec.concept // Function concept. template<typename T> concept bool F1() { return true; } // Variable concept. template<typename T> concept bool V1{true};
a05b3874a5463b21b4b80fbdec79f58d90b2b414
21308cbccd1aec1139b6e783746caec47e3f1a39
/recursive/unique_binary_search_tree2.cpp
26aee9014a4f46886c01086bf4f8e5d92c116735
[]
no_license
shrimpie/leetcode
1163af5d67878049b9c031389e78a0b820c12bba
08f0a0e58cfc9eb36f98d44090b1de0ca1e6c95e
refs/heads/master
2021-06-15T02:35:13.204173
2016-11-21T00:28:57
2016-11-21T00:28:57
72,703,812
1
0
null
null
null
null
UTF-8
C++
false
false
2,700
cpp
unique_binary_search_tree2.cpp
// Problem description: // Given n, generate all structurally unique BST's (binary search trees) that // store values 1..n? // For example, // Given n = 3, your program should return all 5 unique BST's shown below. // 1 3 3 2 1 // \ / / / \ \ // 3 2 2 1 3 2 // / / \ \ // 2 1 1 3 // Idea: // Define f(n) to be the number of BST's of n. Take n = 3 as an example: // 1. If let 1 be the root, left subtree can have 0 node, right subtree can // have 2 nodes. The combination of left/right subtree is f(0)*f(2) = 2. // 2. If let 2 be the root, left subtree can only be 1, right subtree can only // be 3: f(1)*f(1) = 1. // 3. If let 3 be the root, same as case 1. // In summary: // 1. f(0) = 1 // 2. f(n) = f(0)*f(n-1) + f(1)*f(n-2) + ... + f(n-2)*f(1) + f(n-1)*f(0). #include <iostream> #include <sstream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector<TreeNode*> gen_bst(int min, int max) { vector<TreeNode*> ret; if(min > max) { ret.push_back(NULL); return ret; } for(int i = min; i <= max; ++i) { vector<TreeNode*> left_subtree = gen_bst(min, i - 1); vector<TreeNode*> right_subtree = gen_bst(i + 1, max); for(int j = 0; j < left_subtree.size(); ++j) { for(int k = 0; k < right_subtree.size(); ++k) { TreeNode* root = new TreeNode(i); root->left = left_subtree[j]; root->right = right_subtree[k]; ret.push_back(root); } } } return ret; } vector<TreeNode*> generate_trees(int n) { if(n == 0) return {}; return gen_bst(1, n); } // Here to ease the test case for generated BST, add serialization // of BST, which is also a problem leetcode provides. void serialize(TreeNode* root, ostringstream &out) { if(root) { out << root->val << ' '; serialize(root->left, out); serialize(root->right, out); } else out << "# "; } string serialize(TreeNode* root) { ostringstream out; serialize(root, out); return out.str(); } int main() { int n = 3; auto res = generate_trees(n); vector<string> ans; for(int i = 0; i < res.size(); i++) ans.push_back(serialize(res[i])); vector<string> bsts { "1 # 2 # 3 # # ", "1 # 3 2 # # # ", "2 1 # # 3 # # ", "3 1 # 2 # # # ", "3 2 1 # # # # ", }; cout << "Test case 1 returns " << ((ans.size() == bsts.size() && ans[0] == bsts[0] && ans[1] == bsts[1] && ans[2] == bsts[2] && ans[3] == bsts[3] && ans[4] == bsts[4]) ? "True" : "False") << endl; return 0; }
06f32b59aade80c8a02ce130e78812816f330690
4de4f73edfc6ba804d6490ee1a54b2ea81282121
/10bitsGraph.cpp
66a2298ecb880df1278f5c5759d0a5b07cb7a4b1
[]
no_license
Jolyon0202/10bitsGraph
e8186fc6d4a408eb4614acb74f03ef28e920fbb3
74a8539f6565498e9d5af63a5874f95fd5b1200c
refs/heads/master
2023-08-15T14:21:53.316937
2021-09-22T15:24:38
2021-09-22T15:24:38
408,885,991
0
0
null
null
null
null
UTF-8
C++
false
false
4,119
cpp
10bitsGraph.cpp
#include <GLUT/glut.h> #include <ctime> #include <fstream> #include <iostream> #include <memory> #include <string> #include <time.h> #include <vector> using namespace std; GLdouble width = 512, height = 512; unsigned int userRed = 0; unsigned int userGreen = 0; unsigned int userBlue = 255; // Auxiliary union used to set the values of the 10 bit texture union format2_10_10_10 { struct { unsigned int red : 10; unsigned int green : 10; unsigned int blue : 10; unsigned int alpha : 2; } bits; unsigned int u32All; }; /* Handler for window-repaint event. Call back when the window first appears and whenever the window needs to be re-painted. */ void display() { // Tell OpenGL to use the whole window for drawing glViewport(0, 0, width, height); // DO NOT CHANGE THIS LINE // Do an orthographic parallel projection with the coordinate // system set to first quadrant, limited by screen/window size glMatrixMode(GL_PROJECTION); // DO NOT CHANGE THIS LINE glLoadIdentity(); // DO NOT CHANGE THIS LINE glOrtho(0.0, width, height, 0.0, -1.f, 1.f); // DO NOT CHANGE THIS LINE // Clear the color buffer with current clearing color glClear(GL_COLOR_BUFFER_BIT); // DO NOT CHANGE THIS LINE glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // DO NOT CHANGE THIS LINE // cout << flappyHighScore << endl << spaceRunnerHighScore << endl; glFlush(); // Render now // Map the texture on a screen size quad for display glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex2f(0.0, 0.0); glTexCoord2f(0.0, 1.0); glVertex2f(0.0, height); glTexCoord2f(1.0, 1.0); glVertex2f(width, height); glTexCoord2f(1.0, 0.0); glVertex2f(width, 0.0); glEnd(); glFlush(); glutSwapBuffers(); } /* Main function: GLUT runs as a console application starting at main() */ int main(int argc, char **argv) { glutInit(&argc, argv); // Initialize GLUT glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowSize((int)width, (int)height); glutInitWindowPosition(0, 0); // Position the window's initial top-left corner // request 10 bit colors, a depth buffer, and double buffering glutInitDisplayString("red=10 green=10 blue=10 depth double"); /* create the window and store the handle to it */ int wd = glutCreateWindow("Jolyon Machine" /* title */); // verify that each color channel has 10 bits int red_bits, green_bits, blue_bits; glGetIntegerv(GL_RED_BITS, &red_bits); glGetIntegerv(GL_GREEN_BITS, &green_bits); glGetIntegerv(GL_BLUE_BITS, &blue_bits); printf("red %u bits, green %u bits, blue %u bits\n", red_bits, green_bits, blue_bits); // Allocate a buffer which will be used as the 10 bit texture format2_10_10_10 *drawData = new format2_10_10_10[width * height]; // Fill the buffer with values from the user. userRed, userGreen, // and userBlue are unsigned integers in the range [0,1024). format2_10_10_10 aux; for (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x) { aux.bits.red = userRed; // user input aux.bits.green = userGreen; // user input aux.bits.blue = userBlue; // user input drawData[(int)(x + y * width)].u32All = aux.u32All; } // Create and bind a new texture GLuint texID; glGenTextures(1, &texID); glBindTexture(GL_TEXTURE_2D, texID); // Fill the texture image from the 10 bit buffer data glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, width, height, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, drawData); // Set desired texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); // Register callback handler for window re-paint event glutDisplayFunc(display); // Enter the event-processing loop glutMainLoop(); return 0; }
b1ddf67e1c199f9aff76c797464cc6d05f61e308
cb6e2c3659f84e4b75debe948c1909d3e33f8bc9
/Enums.hpp
e318155c11dfc2dd7e2e023d2f646539cbbb0954
[]
no_license
Pytxhr/taskmgr-hideprocess
d6f2b33bf4704bbb5565614fc90f62ed8ac51455
30b3646042ffa9d2d7e2d66eea9fe83092bd5b0f
refs/heads/main
2023-04-02T00:38:05.800194
2021-03-30T23:41:22
2021-03-30T23:41:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
716
hpp
Enums.hpp
#pragma once #include <Windows.h> typedef struct _SYSTEM_PROCESS_INFORMATION { ULONG NextEntryOffset; ULONG NumberOfThreads; BYTE Reserved1[48]; UNICODE_STRING ImageName; KPRIORITY BasePriority; HANDLE UniqueProcessId; PVOID Reserved2; ULONG HandleCount; ULONG SessionId; PVOID Reserved3; SIZE_T PeakVirtualSize; SIZE_T VirtualSize; ULONG Reserved4; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; PVOID Reserved5; SIZE_T QuotaPagedPoolUsage; PVOID Reserved6; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; SIZE_T PrivatePageCount; LARGE_INTEGER Reserved7[6]; } SYSTEM_PROCESS_INFORMATION;
a9310e79fea79be2b2f4a67a7d58ead27fa97491
7648b587dbd740d545ecb4345517441fb001b569
/src/c/linearModel_detail.h
5d0af7aabd0f77cb7ef318e0906798143cd3edba
[ "BSD-3-Clause" ]
permissive
rupea/LabelFilters
f8c508e244489b5673b3ebe0e51b898c02fa4f9f
a70b1f90427fe44bd43fee842aad34704d51854c
refs/heads/master
2020-03-23T06:57:45.089677
2018-11-13T20:22:38
2018-11-13T20:22:38
141,239,997
6
1
null
null
null
null
UTF-8
C++
false
false
976
h
linearModel_detail.h
/* Copyright (C) 2017 NEC Laboratories America, Inc. ("NECLA"). All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. An additional grant of patent rights * can be found in the PATENTS file in the same directory. */ #ifndef __LINEARMODEL_DETAIL_H #define __LINEARMODEL_DETAIL_H #include "typedefs.h" #include <boost/numeric/conversion/bounds.hpp> //#include <boost/limits.hpp> class PredictionSet; namespace linearmodel_detail { template <typename Eigentype, typename ovaType> std::size_t predict( PredictionSet& predictions, // output Eigentype const& x, ovaType const& w, Eigen::RowVectorXd const& intercept, ActiveSet const* feasible, bool verbose = false, predtype keep_thresh = boost::numeric::bounds<predtype>::lowest(), size_t keep_size = boost::numeric::bounds<size_t>::highest()); } #endif //__LINEARMODEL_DETAIL_H
33903c1a552eb4cc13c2b18978460a92f4d17220
3894c1c0a265dfa91e114ff4df12236454efdb2c
/LeetCode/iter1/c++/IntegerBreak.cpp
592cbb1c0906cda2085d2e5982cec64b245196f1
[]
no_license
jonathenzc/Algorithm
d770802337a8f4f36b94e42722d4d1954b45f408
f6b3d1a3f987dd3f38aa38c6de4b37caef0880bc
refs/heads/master
2020-04-04T00:16:38.780515
2020-03-12T16:10:43
2020-03-12T16:10:43
33,028,640
2
0
null
null
null
null
UTF-8
C++
false
false
686
cpp
IntegerBreak.cpp
#include <iostream> #include <math.h> using namespace std; int integerBreak(int n) { if (n == 1) return 1; else if (n == 2) return 1; else if (n == 3) return 2; int cnt = n/3; int mod = n % 3; int result = 0; if (mod == 1) { cnt--; result = pow(3, cnt) * 4; } else if(mod == 2) { result = pow(3, cnt) * 2; } else result = pow(3,cnt); return result; } int main() { cout << integerBreak(2) << endl << integerBreak(7) << endl << integerBreak(8) << endl << integerBreak(9) << endl << integerBreak(10) << endl << integerBreak(16) << endl << integerBreak(15) << endl << integerBreak(25) << endl << integerBreak(26) << endl; return 0; }
376da33f2a2df9ad89651206bb917c7abdf28218
bebdef83edff1cc8255785369e140ce84d43350a
/Codes/10871_Smaller_than_X.cpp
dfe79f1bb6263bbaa9ae27aff5d06607f1430cd7
[]
no_license
SayYoungMan/BaekJoon_OJ_Solutions
027fe9603c533df74633386dc3f7e15d5b465a00
b764ad1a33dc7c522e044eb0406903937fe8e4cc
refs/heads/master
2023-07-05T13:47:43.260574
2021-08-26T11:42:21
2021-08-26T11:42:21
387,247,523
0
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
10871_Smaller_than_X.cpp
#include <iostream> int main() { int n, x, num; std::cin >> n >> x; for (int i=0; i<n; i++) { std::cin >> num; if (num < x) { std::cout << num << " "; } } return 0; }
4a2ea8df5bebe96b01dd810ff1688b0868f5a9b7
d1542036ca18dbe9cd0dffeb8e4715a14ee9bc76
/include/toyota_localplanner/toyota_localplanner.h
4877ef8a6d1f4cf85c099516737a4285f987bc3d
[]
no_license
Benjaminmar8/toyota_local_planner
0799249ef116e0fee26bfe80af2f8d2999a68d5b
0d9878713e511af435341bf7c9bd2b9b58cf1727
refs/heads/master
2021-01-13T00:57:33.161091
2016-04-26T07:23:02
2016-04-26T07:23:02
57,101,028
4
2
null
null
null
null
UTF-8
C++
false
false
3,225
h
toyota_localplanner.h
#ifndef TOYOTA_LOCALPLANNER_TOYOTA_LOCALPLANNER_H_ #define TOYOTA_LOCALPLANNER_TOYOTA_LOCALPLANNER_H_ #include <ros/ros.h> #include <tf/tf.h> #include <tf/transform_datatypes.h> #include <tf/transform_listener.h> #include <nav_core/base_local_planner.h> #include <costmap_2d/costmap_2d_ros.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/PolygonStamped.h> #include <nav_msgs/Odometry.h> #include <nav_msgs/Path.h> #include <base_local_planner/trajectory_planner_ros.h> #include <base_local_planner/costmap_model.h> #include <toyota_localplanner/vehicle_control.h> #include <visualization_msgs/Marker.h> #include <queue> namespace toyota_localplanner { class ToyotaLocalPlanner : public nav_core::BaseLocalPlanner{ public: ToyotaLocalPlanner(); ~ToyotaLocalPlanner(); void initialize(std::string name, tf::TransformListener* tf, costmap_2d::Costmap2DROS* costmap_ros); bool isGoalReached(); bool setPlan(const std::vector<geometry_msgs::PoseStamped>& global_plan); bool computeVelocityCommands(geometry_msgs::Twist& cmd_vel); std_msgs::Float32 steer, drive; std_msgs::Float32 actual_str, actual_vel; unsigned int id; //std::queue<std_msgs::Float32> steer_queue, drive_queue; private: void odomCallback(const nav_msgs::Odometry::ConstPtr& msg); void pathCallback(const nav_msgs::Path::ConstPtr& msg); void actualvelCallback(const std_msgs::Float32::ConstPtr& msg); void actualstrCallback(const std_msgs::Float32::ConstPtr& msg); double compute_obs_dist_path(int); double compute_obs_time_path(int); double compute_obs_dist_odom(); double compute_obs_time_odom(); ros::Subscriber odom_sub_; ros::Subscriber path_sub_; ros::Subscriber actual_vel_sub_; ros::Subscriber actual_str_sub_; ros::Publisher footprint_projection_path_pub_; ros::Publisher footprint_projection_odom_pub_; ros::Publisher marker_publisher; ros::Publisher steer_publisher; ros::Publisher drive_publisher; tf::TransformListener* tf_; costmap_2d::Costmap2DROS* costmap_ros_; base_local_planner::CostmapModel* costmap_model_; costmap_2d::Costmap2D* costmap_; nav_msgs::Odometry vehicle_odom_; nav_msgs::Path global_path_; geometry_msgs::PolygonStamped footprint_projection_path_; geometry_msgs::PolygonStamped footprint_projection_odom_; visualization_msgs::Marker marker; boost::mutex odom_lock_; //bool newPathFlag; vehicle_control* COMS_; protected: //parameter std::string odom_topic_; std::string path_topic_; std::string steer_topic_; std::string drive_topic_; double inscribed_radius_; double circumscribed_radius_; //double lookahead_step_; //double lookahead_distance_; //double lookahead_time_; double goal_distance_bias_; double goal_heading_bias_; double lethal_cost_threshold_; double planner_patience_; double cost_violation_times_; //double steer_gain_; bool invalid_goal_; //bool use_lookahead_distance_; }; } #endif
f2fcaa55bf45f584aee3556e8ae7f8400f3d7d95
518bf342bc4138982af3e2724e75f1d9ca3ba56c
/solutions/0706. Design HashMap/0706.cpp
501ee55602eaf782badc52e3a47849ac11822343
[ "MIT" ]
permissive
walkccc/LeetCode
dae85af7cc689882a84ee5011f0a13a19ad97f18
a27be41c174565d365cbfe785f0633f634a01b2a
refs/heads/main
2023-08-28T01:32:43.384999
2023-08-20T19:00:45
2023-08-20T19:00:45
172,231,974
692
302
MIT
2023-08-13T14:48:42
2019-02-23T15:46:23
C++
UTF-8
C++
false
false
1,091
cpp
0706.cpp
class MyHashMap { public: /** Initialize your data structure here. */ MyHashMap() : lists(kSize) {} /** value will always be non-negative. */ void put(int key, int value) { auto& pairs = lists[key % kSize]; for (auto& [k, v] : pairs) if (k == key) { v = value; return; } pairs.emplace_back(key, value); } /** Returns the value to which the specified key is mapped, or -1 if this map * contains no mapping for the key */ int get(int key) { const list<pair<int, int>>& pairs = lists[key % kSize]; for (const auto& [k, v] : pairs) if (k == key) return v; return -1; } /** Removes the mapping of the specified value key if this map contains a * mapping for the key */ void remove(int key) { auto& pairs = lists[key % kSize]; for (auto it = pairs.begin(); it != pairs.end(); ++it) if (it->first == key) { pairs.erase(it); return; } } private: static constexpr int kSize = 10000; vector<list<pair<int, int>>> lists; // Each slot store (key, value) list };
79f660a5b5fd62c3dbc5ce358c48c9596673612d
2b9a69bb87049f15460547c9a140d532a00747ad
/user/sniff_thread.cpp
03847ff5b614659239ac7581cdfe2f7f81c97803
[]
no_license
zhang35/VMM-Monitor
ed052c7befe2c9bf734781cbe34a14d3a841df4a
6f6024b8af0394410f170f078566bf37e2a9ad5b
refs/heads/master
2020-04-10T00:04:55.907708
2018-12-06T13:03:11
2018-12-06T13:03:11
160,675,155
5
0
null
null
null
null
UTF-8
C++
false
false
236
cpp
sniff_thread.cpp
#include "sniff_thread.h" sniff_thread::sniff_thread(QObject *parent) : QThread(parent) { stoprun = false; } void sniff_thread::stop() { stoprun=true; } void sniff_thread::run() { getpacket(); }
6c9aba332bb566529b1d1c06120ade27bf8d2752
ddf51c74f4426f38093b3e86861e9a60d907bd85
/contest/codeforces_educational/round_46/e.cpp
1055722b6671ad8fea8a83c8b414c53034419ee9
[]
no_license
TheSkyFucker/acm-icpc
65359e77855459c86f4717cd59b4bbc5b7d40f60
994173541054921e03ff29333242f61f6ac4869d
refs/heads/master
2018-09-26T20:33:54.107075
2018-07-24T17:48:05
2018-07-24T17:48:05
111,862,682
6
2
null
null
null
null
UTF-8
C++
false
false
1,650
cpp
e.cpp
#include<bits/stdc++.h> using namespace std; typedef double db; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; #define fi first #define se second #define mp make_pair #define pb push_back #define pw(x) (1ll << (x)) #define sz(x) ((int)(x).size()) #define all(x) (x).begin(),(x).end() #define rep(i,l,r) for(int i=(l);i<(r);++i) #define per(i,l,r) for(int i=(r)-1;i>=(l);--i) #define dd(x) cout << #x << " = " << x << ", " #define de(x) cout << #x << " = " << x << endl //----- const int N = 3e5 + 7; namespace BCC { const int N = ::N; vi ng[N]; int dfn[N], low[N], id[N], st[N], _st, _; void dfs(int c, int dep, vi g[]) { int cc = 0; st[_st++] = c; dfn[c] = low[c] = dep; for (auto t : g[c]) { if (!dfn[t]) { dfs(t, dep + 1, g); low[c] = min(low[c], low[t]); } else if (dfn[t] != dfn[c] - 1 || cc++) low[c] = min(low[c], dfn[t]); } if (low[c] == dfn[c]) { do { id[st[--_st]] = _; } while (st[_st] != c); _++; } } int dep[N]; int gao(int &rt, int u, int fa, vi g[]) { if (dep[rt] < dep[u]) rt = u; for (auto v : g[u]) { if (v == fa) continue; dep[v] = dep[u] + 1; gao(rt, v, u, g); } } int solve(int n, vi g[]) { rep(i, 0, n) if (!dfn[i]) dfs(i, 1, g); rep(i, 0, n) for (auto j : g[i]) if (id[i] != id[j]) ng[id[i]].pb(id[j]); int rt = 0; gao(rt, 0, -1, ng); fill_n(dep, _, 0); gao(rt, rt, -1, ng); cout << dep[rt]; } }; int n, m; vi g[N]; int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); cin >> n >> m; rep(i, 0, m) { int a, b; cin >> a >> b, a--, b--; g[a].pb(b); g[b].pb(a); } BCC::solve(n, g); return 0; }
88e5caec36f7e4dd74406edc1086cd8fe71223d0
93c2c6bb2962e9a19e38e2c895a246fd58c1400e
/cpp/04_game/bird.cpp
7b28ae2c2cbcfb693e16febd016953817dccf67b
[]
no_license
walterbaidal/Allegro-programs
a931cb66da8ff0850c40ed1b3b022c9c777bea42
fb2e1d442757fbde1540ee045cd95fec264e72dc
refs/heads/master
2021-01-01T18:48:37.590691
2015-05-28T07:49:39
2015-05-28T07:49:39
36,422,969
0
0
null
null
null
null
UTF-8
C++
false
false
4,042
cpp
bird.cpp
#include "mi_allegro.h" #include <stdlib.h> #include <unistd.h> #include <time.h> #include <stdio.h> #define SPRITESHEET "sprites/KTGicPH.png" int main (int argc, char *argv[]) { ALLEGRO_BITMAP *background = NULL; ALLEGRO_BITMAP *title = NULL; ALLEGRO_BITMAP *terrain = NULL; ALLEGRO_BITMAP *play = NULL; ALLEGRO_BITMAP *ranking = NULL; ALLEGRO_BITMAP *footer = NULL; ALLEGRO_BITMAP *playstart = NULL; int pos_x; int pos_y; srand (time (NULL)); iniciar_allegro (); al_install_mouse (); background = al_load_bitmap (SPRITESHEET); title = al_load_bitmap (SPRITESHEET); terrain = al_load_bitmap (SPRITESHEET); play = al_load_bitmap (SPRITESHEET); ranking = al_load_bitmap (SPRITESHEET); footer = al_load_bitmap (SPRITESHEET); playstart = al_load_bitmap (SPRITESHEET); if (!playstart) { al_show_native_message_box (display, "Error", "Error", "No se ha podido crear el bitmap del play start nigga", NULL, ALLEGRO_MESSAGEBOX_ERROR); al_destroy_timer (timer); al_destroy_display (display); exit (EXIT_FAILURE); } if (!background) { al_show_native_message_box (display, "Error", "Error", "No se ha podido crear el bitmap del background", NULL, ALLEGRO_MESSAGEBOX_ERROR); al_destroy_timer (timer); al_destroy_display (display); exit (EXIT_FAILURE); } if (!title) { al_show_native_message_box (display, "Error", "Error", "No se ha podido crear el bitmap del titulo", NULL, ALLEGRO_MESSAGEBOX_ERROR); al_destroy_timer (timer); al_destroy_display (display); exit (EXIT_FAILURE); } if (!terrain) { al_show_native_message_box (display, "Error", "Error", "No se ha podido crear el bitmap del terreno", NULL, ALLEGRO_MESSAGEBOX_ERROR); al_destroy_timer (timer); al_destroy_display (display); exit (EXIT_FAILURE); } if (!play) { al_show_native_message_box (display, "Error", "Error", "No se ha podido crear el bitmap del play", NULL, ALLEGRO_MESSAGEBOX_ERROR); al_destroy_timer (timer); al_destroy_display (display); exit (EXIT_FAILURE); } if (!ranking) { al_show_native_message_box (display, "Error", "Error", "No se ha podido crear el bitmap del ranking", NULL, ALLEGRO_MESSAGEBOX_ERROR); al_destroy_timer (timer); al_destroy_display (display); exit (EXIT_FAILURE); } if (!footer) { al_show_native_message_box (display, "Error", "Error", "No se ha podido crear el bitmap del footer", NULL, ALLEGRO_MESSAGEBOX_ERROR); al_destroy_timer (timer); al_destroy_display (display); exit (EXIT_FAILURE); } while(1){ ALLEGRO_EVENT ev; ALLEGRO_TIMEOUT timeout; al_init_timeout (&timeout, 0.00); bool get_event = al_wait_for_event_until (event_queue, &ev, &timeout); if (get_event){ if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) break; else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES){ pos_x = ev.mouse.x; pos_y = ev.mouse.y; } if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN){ if(ev.mouse.button & 1) break; } } if(redraw && al_is_event_queue_empty (event_queue)) { al_clear_to_color (al_map_rgb (0, 0, 0)); al_draw_bitmap_region(background, 0, 0, 288, 512, 0, 0, 0); al_draw_bitmap_region(title, 702, 182, 178, 48, 50, 110, 0); al_draw_bitmap_region(terrain, 584, 0 , 288, 112 , 0, 400, 0); al_draw_bitmap_region(playstart, 709, 314, 104, 56, 30, 344, 0); al_draw_bitmap_region(play, 708, 235, 104, 56, 30, 344, 0); al_draw_bitmap_region(ranking, 829, 235, 104, 56, 150, 344, 0); al_draw_bitmap_region(footer, 885, 182, 140, 20, 80, 418, 0); al_flip_display(); redraw = false; } } al_destroy_bitmap (background); al_destroy_bitmap (title); al_destroy_bitmap (terrain); al_destroy_bitmap (play); al_destroy_bitmap (playstart); al_destroy_bitmap (ranking); al_destroy_bitmap (footer); destruir_allegro (); return 0; }
67c679d40c0839db316860127c5ffb228580c906
ff7a88ebe49de7c49acf02fac759f2583ddf0e89
/DearGit/git/StatusData.cpp
0c70683d646ac675376a49d214c9a4fe1165686d
[]
no_license
ToasterFuel/DearGit
6770888b74f77a5dad2b88159ffc344f6a56cebe
f0589b70005412ae5b4b6ec70a293f2c07f82cfb
refs/heads/main
2023-02-11T19:19:31.458006
2020-12-29T17:58:09
2020-12-29T17:58:09
322,319,771
1
0
null
null
null
null
UTF-8
C++
false
false
1,922
cpp
StatusData.cpp
#include "StatusData.h" StatusData::StatusData(const git_status_entry* entry) : entry(entry) { } const char* StatusData::Path() { if(IsStaged()) return entry->head_to_index->new_file.path; return entry->index_to_workdir->new_file.path; } GitStatus StatusData::GetStatus() { switch(entry->status) { case GIT_STATUS_CURRENT: return STATUS_UP_TO_DATE; case GIT_STATUS_WT_NEW: return STATUS_NEW; case GIT_STATUS_WT_MODIFIED: return STATUS_MODIFIED; case GIT_STATUS_WT_DELETED: return STATUS_DELETED; case GIT_STATUS_WT_TYPECHANGE: return STATUS_MOVED; case GIT_STATUS_WT_RENAMED: return STATUS_MOVED; case GIT_STATUS_WT_UNREADABLE: return STATUS_MOVED; case GIT_STATUS_IGNORED: return STATUS_FUTURE_WORK_IS_NEEDED; case GIT_STATUS_CONFLICTED: return STATUS_FUTURE_WORK_IS_NEEDED; case GIT_STATUS_INDEX_NEW: return STATUS_NEW; case GIT_STATUS_INDEX_MODIFIED: return STATUS_MODIFIED; case GIT_STATUS_INDEX_DELETED: return STATUS_DELETED; case GIT_STATUS_INDEX_RENAMED: return STATUS_MOVED; case GIT_STATUS_INDEX_TYPECHANGE: return STATUS_MOVED; } return STATUS_UP_TO_DATE; } bool StatusData::IsStaged() { switch(entry->status) { case GIT_STATUS_CURRENT: case GIT_STATUS_WT_NEW: case GIT_STATUS_WT_MODIFIED: case GIT_STATUS_WT_DELETED: case GIT_STATUS_WT_TYPECHANGE: case GIT_STATUS_WT_RENAMED: case GIT_STATUS_WT_UNREADABLE: case GIT_STATUS_IGNORED: case GIT_STATUS_CONFLICTED: return false; case GIT_STATUS_INDEX_NEW: case GIT_STATUS_INDEX_MODIFIED: case GIT_STATUS_INDEX_DELETED: case GIT_STATUS_INDEX_RENAMED: case GIT_STATUS_INDEX_TYPECHANGE: return true; } return false; }
ee718ee20b72934996442d2c584f4c3bfe36ab7d
f39b191acf9bf3d39ffae7bb33af1662c7e8db8d
/HEAP/HEAP/disp.h
526e244fc38b289577cee1d8af1bd0020877271d
[]
no_license
sushmabala/GUI_Traversal_Trees
5fc85e756ea624be2900db25a474bc850e84c988
be67fbc49d4eb75dbc657ed5ad89d3fbe23b1078
refs/heads/master
2022-12-15T09:42:42.688444
2020-09-06T10:55:20
2020-09-06T10:55:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,007
h
disp.h
//#include"ui.h" #pragma once namespace HEAP { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for disp /// </summary> public ref class disp : public System::Windows::Forms::Form { public: disp(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~disp() { if (components) { delete components; } } private: System::Windows::Forms::Button^ a; protected: protected: protected: private: System::Windows::Forms::Label^ label6; private: System::Windows::Forms::Label^ label5; private: System::Windows::Forms::Label^ label4; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::Label^ label1; public: System::Windows::Forms::RichTextBox^ T23; private: public: System::Windows::Forms::RichTextBox^ T25; public: System::Windows::Forms::RichTextBox^ T26; public: System::Windows::Forms::RichTextBox^ T27; public: System::Windows::Forms::RichTextBox^ T28; public: System::Windows::Forms::RichTextBox^ T29; public: System::Windows::Forms::RichTextBox^ T30; public: System::Windows::Forms::RichTextBox^ T31; public: System::Windows::Forms::RichTextBox^ T8; public: System::Windows::Forms::RichTextBox^ T9; public: System::Windows::Forms::RichTextBox^ T10; public: System::Windows::Forms::RichTextBox^ T11; public: System::Windows::Forms::RichTextBox^ T12; public: System::Windows::Forms::RichTextBox^ T13; public: System::Windows::Forms::RichTextBox^ T14; public: System::Windows::Forms::RichTextBox^ T15; public: System::Windows::Forms::RichTextBox^ T16; public: System::Windows::Forms::RichTextBox^ T17; public: System::Windows::Forms::RichTextBox^ T18; public: System::Windows::Forms::RichTextBox^ T19; public: System::Windows::Forms::RichTextBox^ T20; public: System::Windows::Forms::RichTextBox^ T21; public: System::Windows::Forms::RichTextBox^ T22; public: System::Windows::Forms::RichTextBox^ T24; public: System::Windows::Forms::RichTextBox^ T4; public: System::Windows::Forms::RichTextBox^ T5; public: System::Windows::Forms::RichTextBox^ T6; public: System::Windows::Forms::RichTextBox^ T7; public: System::Windows::Forms::RichTextBox^ T2; public: System::Windows::Forms::RichTextBox^ T3; public: System::Windows::Forms::RichTextBox^ T1; private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->a = (gcnew System::Windows::Forms::Button()); this->label6 = (gcnew System::Windows::Forms::Label()); this->label5 = (gcnew System::Windows::Forms::Label()); this->label4 = (gcnew System::Windows::Forms::Label()); this->label3 = (gcnew System::Windows::Forms::Label()); this->label2 = (gcnew System::Windows::Forms::Label()); this->label1 = (gcnew System::Windows::Forms::Label()); this->T23 = (gcnew System::Windows::Forms::RichTextBox()); this->T25 = (gcnew System::Windows::Forms::RichTextBox()); this->T26 = (gcnew System::Windows::Forms::RichTextBox()); this->T27 = (gcnew System::Windows::Forms::RichTextBox()); this->T28 = (gcnew System::Windows::Forms::RichTextBox()); this->T29 = (gcnew System::Windows::Forms::RichTextBox()); this->T30 = (gcnew System::Windows::Forms::RichTextBox()); this->T31 = (gcnew System::Windows::Forms::RichTextBox()); this->T8 = (gcnew System::Windows::Forms::RichTextBox()); this->T9 = (gcnew System::Windows::Forms::RichTextBox()); this->T10 = (gcnew System::Windows::Forms::RichTextBox()); this->T11 = (gcnew System::Windows::Forms::RichTextBox()); this->T12 = (gcnew System::Windows::Forms::RichTextBox()); this->T13 = (gcnew System::Windows::Forms::RichTextBox()); this->T14 = (gcnew System::Windows::Forms::RichTextBox()); this->T15 = (gcnew System::Windows::Forms::RichTextBox()); this->T16 = (gcnew System::Windows::Forms::RichTextBox()); this->T17 = (gcnew System::Windows::Forms::RichTextBox()); this->T18 = (gcnew System::Windows::Forms::RichTextBox()); this->T19 = (gcnew System::Windows::Forms::RichTextBox()); this->T20 = (gcnew System::Windows::Forms::RichTextBox()); this->T21 = (gcnew System::Windows::Forms::RichTextBox()); this->T22 = (gcnew System::Windows::Forms::RichTextBox()); this->T24 = (gcnew System::Windows::Forms::RichTextBox()); this->T4 = (gcnew System::Windows::Forms::RichTextBox()); this->T5 = (gcnew System::Windows::Forms::RichTextBox()); this->T6 = (gcnew System::Windows::Forms::RichTextBox()); this->T7 = (gcnew System::Windows::Forms::RichTextBox()); this->T2 = (gcnew System::Windows::Forms::RichTextBox()); this->T3 = (gcnew System::Windows::Forms::RichTextBox()); this->T1 = (gcnew System::Windows::Forms::RichTextBox()); this->SuspendLayout(); // // a // this->a->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(192)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255))); this->a->Font = (gcnew System::Drawing::Font(L"Engravers MT", 9, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->a->ForeColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(128)), static_cast<System::Int32>(static_cast<System::Byte>(0))); this->a->Location = System::Drawing::Point(488, 413); this->a->Name = L"a"; this->a->Size = System::Drawing::Size(182, 26); this->a->TabIndex = 94; this->a->Text = L"CLOSE"; this->a->UseVisualStyleBackColor = false; this->a->Click += gcnew System::EventHandler(this, &disp::button1_Click); // // label6 // this->label6->AutoSize = true; this->label6->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(224)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->label6->Font = (gcnew System::Drawing::Font(L"Times New Roman", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label6->Location = System::Drawing::Point(-2, 402); this->label6->MinimumSize = System::Drawing::Size(1140, 50); this->label6->Name = L"label6"; this->label6->Size = System::Drawing::Size(1140, 50); this->label6->TabIndex = 93; // // label5 // this->label5->AutoSize = true; this->label5->Font = (gcnew System::Drawing::Font(L"Times New Roman", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label5->ForeColor = System::Drawing::Color::Red; this->label5->Location = System::Drawing::Point(2, 115); this->label5->Name = L"label5"; this->label5->Size = System::Drawing::Size(76, 19); this->label5->TabIndex = 92; this->label5->Text = L"LEVEL 1:"; // // label4 // this->label4->AutoSize = true; this->label4->Font = (gcnew System::Drawing::Font(L"Times New Roman", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label4->ForeColor = System::Drawing::Color::Red; this->label4->Location = System::Drawing::Point(2, 194); this->label4->Name = L"label4"; this->label4->Size = System::Drawing::Size(80, 19); this->label4->TabIndex = 91; this->label4->Text = L"LEVEL 2 :"; // // label3 // this->label3->AutoSize = true; this->label3->Font = (gcnew System::Drawing::Font(L"Times New Roman", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label3->ForeColor = System::Drawing::Color::Red; this->label3->Location = System::Drawing::Point(2, 344); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(80, 19); this->label3->TabIndex = 90; this->label3->Text = L"LEVEL 4:"; // // label2 // this->label2->AutoSize = true; this->label2->Font = (gcnew System::Drawing::Font(L"Times New Roman", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label2->ForeColor = System::Drawing::Color::Red; this->label2->Location = System::Drawing::Point(2, 275); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(80, 19); this->label2->TabIndex = 89; this->label2->Text = L"LEVEL 3 :"; // // label1 // this->label1->AutoSize = true; this->label1->Font = (gcnew System::Drawing::Font(L"Times New Roman", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label1->ForeColor = System::Drawing::Color::Red; this->label1->Location = System::Drawing::Point(2, 52); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(80, 19); this->label1->TabIndex = 88; this->label1->Text = L"LEVEL 0 :"; // // T23 // this->T23->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T23->Location = System::Drawing::Point(587, 323); this->T23->Name = L"T23"; this->T23->Size = System::Drawing::Size(33, 28); this->T23->TabIndex = 87; this->T23->Text = L""; this->T23->Visible = false; // // T25 // this->T25->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T25->Location = System::Drawing::Point(729, 323); this->T25->Name = L"T25"; this->T25->Size = System::Drawing::Size(33, 28); this->T25->TabIndex = 86; this->T25->Text = L""; this->T25->Visible = false; // // T26 // this->T26->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T26->Location = System::Drawing::Point(789, 323); this->T26->Name = L"T26"; this->T26->Size = System::Drawing::Size(33, 28); this->T26->TabIndex = 85; this->T26->Text = L""; this->T26->Visible = false; // // T27 // this->T27->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T27->Location = System::Drawing::Point(859, 323); this->T27->Name = L"T27"; this->T27->Size = System::Drawing::Size(33, 28); this->T27->TabIndex = 84; this->T27->Text = L""; this->T27->Visible = false; // // T28 // this->T28->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T28->Location = System::Drawing::Point(907, 323); this->T28->Name = L"T28"; this->T28->Size = System::Drawing::Size(33, 28); this->T28->TabIndex = 83; this->T28->Text = L""; this->T28->Visible = false; // // T29 // this->T29->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T29->Location = System::Drawing::Point(983, 323); this->T29->Name = L"T29"; this->T29->Size = System::Drawing::Size(33, 28); this->T29->TabIndex = 82; this->T29->Text = L""; this->T29->Visible = false; // // T30 // this->T30->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T30->Location = System::Drawing::Point(1031, 323); this->T30->Name = L"T30"; this->T30->Size = System::Drawing::Size(33, 28); this->T30->TabIndex = 81; this->T30->Text = L""; this->T30->Visible = false; // // T31 // this->T31->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T31->Location = System::Drawing::Point(1096, 323); this->T31->Name = L"T31"; this->T31->Size = System::Drawing::Size(33, 28); this->T31->TabIndex = 80; this->T31->Text = L""; this->T31->Visible = false; // // T8 // this->T8->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T8->Location = System::Drawing::Point(129, 254); this->T8->Name = L"T8"; this->T8->Size = System::Drawing::Size(33, 28); this->T8->TabIndex = 79; this->T8->Text = L""; this->T8->Visible = false; // // T9 // this->T9->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T9->Location = System::Drawing::Point(269, 254); this->T9->Name = L"T9"; this->T9->Size = System::Drawing::Size(33, 28); this->T9->TabIndex = 78; this->T9->Text = L""; this->T9->Visible = false; // // T10 // this->T10->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T10->Location = System::Drawing::Point(417, 254); this->T10->Name = L"T10"; this->T10->Size = System::Drawing::Size(33, 28); this->T10->TabIndex = 77; this->T10->Text = L""; this->T10->Visible = false; // // T11 // this->T11->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T11->Location = System::Drawing::Point(554, 254); this->T11->Name = L"T11"; this->T11->Size = System::Drawing::Size(33, 28); this->T11->TabIndex = 76; this->T11->Text = L""; this->T11->Visible = false; // // T12 // this->T12->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T12->Location = System::Drawing::Point(690, 254); this->T12->Name = L"T12"; this->T12->Size = System::Drawing::Size(33, 28); this->T12->TabIndex = 75; this->T12->Text = L""; this->T12->Visible = false; // // T13 // this->T13->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T13->Location = System::Drawing::Point(827, 254); this->T13->Name = L"T13"; this->T13->Size = System::Drawing::Size(33, 28); this->T13->TabIndex = 74; this->T13->Text = L""; this->T13->Visible = false; // // T14 // this->T14->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T14->Location = System::Drawing::Point(947, 254); this->T14->Name = L"T14"; this->T14->Size = System::Drawing::Size(33, 28); this->T14->TabIndex = 73; this->T14->Text = L""; this->T14->Visible = false; // // T15 // this->T15->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T15->Location = System::Drawing::Point(1070, 254); this->T15->Name = L"T15"; this->T15->Size = System::Drawing::Size(33, 28); this->T15->TabIndex = 72; this->T15->Text = L""; this->T15->Visible = false; // // T16 // this->T16->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T16->Location = System::Drawing::Point(82, 323); this->T16->Name = L"T16"; this->T16->Size = System::Drawing::Size(33, 28); this->T16->TabIndex = 71; this->T16->Text = L""; this->T16->Visible = false; // // T17 // this->T17->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T17->Location = System::Drawing::Point(176, 323); this->T17->Name = L"T17"; this->T17->Size = System::Drawing::Size(33, 28); this->T17->TabIndex = 70; this->T17->Text = L""; this->T17->Visible = false; // // T18 // this->T18->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T18->Location = System::Drawing::Point(224, 323); this->T18->Name = L"T18"; this->T18->Size = System::Drawing::Size(33, 28); this->T18->TabIndex = 69; this->T18->Text = L""; this->T18->Visible = false; // // T19 // this->T19->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T19->Location = System::Drawing::Point(317, 323); this->T19->Name = L"T19"; this->T19->Size = System::Drawing::Size(33, 28); this->T19->TabIndex = 68; this->T19->Text = L""; this->T19->Visible = false; // // T20 // this->T20->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T20->Location = System::Drawing::Point(374, 323); this->T20->Name = L"T20"; this->T20->Size = System::Drawing::Size(33, 28); this->T20->TabIndex = 67; this->T20->Text = L""; this->T20->Visible = false; // // T21 // this->T21->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T21->Location = System::Drawing::Point(458, 323); this->T21->Name = L"T21"; this->T21->Size = System::Drawing::Size(33, 28); this->T21->TabIndex = 66; this->T21->Text = L""; this->T21->Visible = false; // // T22 // this->T22->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T22->Location = System::Drawing::Point(506, 323); this->T22->Name = L"T22"; this->T22->Size = System::Drawing::Size(33, 28); this->T22->TabIndex = 65; this->T22->Text = L""; this->T22->Visible = false; // // T24 // this->T24->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T24->Location = System::Drawing::Point(645, 323); this->T24->Name = L"T24"; this->T24->Size = System::Drawing::Size(33, 28); this->T24->TabIndex = 64; this->T24->Text = L""; this->T24->Visible = false; // // T4 // this->T4->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T4->Location = System::Drawing::Point(203, 173); this->T4->Name = L"T4"; this->T4->Size = System::Drawing::Size(33, 28); this->T4->TabIndex = 63; this->T4->Text = L""; this->T4->Visible = false; // // T5 // this->T5->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T5->Location = System::Drawing::Point(488, 173); this->T5->Name = L"T5"; this->T5->Size = System::Drawing::Size(33, 28); this->T5->TabIndex = 62; this->T5->Text = L""; this->T5->Visible = false; // // T6 // this->T6->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T6->Location = System::Drawing::Point(756, 173); this->T6->Name = L"T6"; this->T6->Size = System::Drawing::Size(33, 28); this->T6->TabIndex = 61; this->T6->Text = L""; this->T6->Visible = false; // // T7 // this->T7->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T7->Location = System::Drawing::Point(1010, 173); this->T7->Name = L"T7"; this->T7->Size = System::Drawing::Size(33, 28); this->T7->TabIndex = 60; this->T7->Text = L""; this->T7->Visible = false; // // T2 // this->T2->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T2->Location = System::Drawing::Point(353, 94); this->T2->Name = L"T2"; this->T2->Size = System::Drawing::Size(33, 28); this->T2->TabIndex = 59; this->T2->Text = L""; this->T2->Visible = false; // // T3 // this->T3->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T3->Location = System::Drawing::Point(894, 94); this->T3->Name = L"T3"; this->T3->Size = System::Drawing::Size(33, 28); this->T3->TabIndex = 58; this->T3->Text = L""; this->T3->Visible = false; // // T1 // this->T1->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192))); this->T1->Location = System::Drawing::Point(555, 31); this->T1->Name = L"T1"; this->T1->Size = System::Drawing::Size(33, 28); this->T1->TabIndex = 57; this->T1->Text = L""; this->T1->Visible = false; // // disp // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(1148, 453); this->Controls->Add(this->a); this->Controls->Add(this->label6); this->Controls->Add(this->label5); this->Controls->Add(this->label4); this->Controls->Add(this->label3); this->Controls->Add(this->label2); this->Controls->Add(this->label1); this->Controls->Add(this->T23); this->Controls->Add(this->T25); this->Controls->Add(this->T26); this->Controls->Add(this->T27); this->Controls->Add(this->T28); this->Controls->Add(this->T29); this->Controls->Add(this->T30); this->Controls->Add(this->T31); this->Controls->Add(this->T8); this->Controls->Add(this->T9); this->Controls->Add(this->T10); this->Controls->Add(this->T11); this->Controls->Add(this->T12); this->Controls->Add(this->T13); this->Controls->Add(this->T14); this->Controls->Add(this->T15); this->Controls->Add(this->T16); this->Controls->Add(this->T17); this->Controls->Add(this->T18); this->Controls->Add(this->T19); this->Controls->Add(this->T20); this->Controls->Add(this->T21); this->Controls->Add(this->T22); this->Controls->Add(this->T24); this->Controls->Add(this->T4); this->Controls->Add(this->T5); this->Controls->Add(this->T6); this->Controls->Add(this->T7); this->Controls->Add(this->T2); this->Controls->Add(this->T3); this->Controls->Add(this->T1); this->Name = L"disp"; this->Text = L"disp"; this->Load += gcnew System::EventHandler(this, &disp::disp_Load); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void disp_Load(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { // this->T1 = System::Convert::ToBase64String( a[0]); //System::Windows::Forms::RichTextBox^ T27 = System::Convert::ToString(a[0]); } }; }
5c91e6caf3a69826b37c7061c2bc1fbca17126b2
37cd8698bb2e7262744a0ad80296474e072aa1e5
/CG/provaPP2/college-Computa-oGr-fica/Trabalhos/Trabalho2/trabalho2.cpp
e5320c434e87f5a85d2f81765ec5cc05378fdbc5
[]
no_license
denihs/college-third-year
b50a47c02827a3e5b16dfe84e64c67a36f49785f
f1ec8b381b9a793fe05f99dd07912fe2c3afbbdf
refs/heads/master
2022-02-26T08:12:23.460205
2019-09-29T21:23:26
2019-09-29T21:23:26
174,235,616
0
0
null
null
null
null
UTF-8
C++
false
false
31,649
cpp
trabalho2.cpp
/* * * Compilador e Biblioteca: gcc, OpenGl/GLUT * Comando para compilação: g++ -o trabalho2 trabalho2.cpp -lglut -lGL -lGLU -lm * * * Tabalho 2 de Computação grafica 3º Ano - Ciência da computação UEMS * Nome: Fernando Lima */ /// Inclusão de libs #include <sstream> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <cstdlib> #include <vector> #include <iostream> #include <cmath> #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif /// Inclusão de defineds #define INACTIVE 0 #define CONCEITO_VECTOR 1 #define ANGULO_VECTOR 2 #define SUM_VECTOR 3 #define SCALAR_PRODUCT 4 #define VECTOR_PRODUCT 5 #define PI 3.14159265358979324 #define NUMBER_PRIMITIVES 5 /// Variaveis globais // Use the STL extension of C++. using namespace std; // Estruturas que contera as informações dos pontos da tela typedef struct { float x; float y; }Pnt; int quadrant = 1, posQuadrant = 0; float wi = 0.0, hei = 0.0; typedef struct { float x1 = 500, x2, y1 = 250, y2; }PntTemp; PntTemp vectorOne, vectorTwo; Pnt currentPoint; // Estrutura que iram conter as coordenadas em tempo real do ponto Pnt center; // Estrutura que ira armazenar as coordenadas do primeiro ponto clicado na tela int drawingSize = 9; // Tamanho original do grid, 9 quadrados espacados igualmente na tela float colorVector[4] = { 0.0 }; // Vetor para quadar a cor atual do desenho, cada posiçao do vetor contem o valor RGB respectivo int nVertices = 100; // Numero de vertices do circulo int isConceitoVector = 1; int Constant = 0; int scalar = 0; static int TYPE = GL_LINE; // Variavel para controle do filled e outline static GLsizei width, height; // OpenGL window size. static float pointSize = 3.0; // Size of point static int primitive = INACTIVE; // Current drawing primitive. static int pointCount = 0; // Number of specified points. static int isGrid = 1; // Is there grid? static int stippleID = 0; /// Definindo as Classes // Line class. class ConceitoVector { public: ConceitoVector(int x1Val, int y1Val, int x2Val, int y2Val) { x1 = x1Val; y1 = y1Val; x2 = x2Val; y2 = y2Val; } void drawConceitoVector(); private: int x1, y1, x2, y2; // x and y co-ordinates of endpoints. }; class Rectangle { public: Rectangle(int x1Val, int y1Val, int x2Val, int y2Val) { x1 = x1Val; y1 = y1Val; x2 = x2Val; y2 = y2Val; } void drawRectangle(); private: int x1, y1, x2, y2; // x and y co-ordinates of diagonally opposite vertices. }; class AnguloVector { public: AnguloVector(int x1Val, int y1Val, int x2Val, int y2Val) { x1 = x1Val; y1 = y1Val; x2 = x2Val; y2 = y2Val; } void drawAnguloVector(); public: int x1, y1, x2, y2; // x and y co-ordinates of endpoints. }; // class polyline. class Circle { public: Circle(int x1Val, int y1Val, int x2Val, int y2Val) { x1 = x1Val; y1= y1Val; x2= x2Val; y2= y2Val; } void drawCircle(); private: int x1, y1, x2, y2; // x and y co-ordinates of endpoints. }; char * itoa (int value, char *result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while (ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } void mousePassiveMotion(int x, int y) { // Essa funçao server para atualizar em tempo // real as coordenadas x e y da estrutura Ptn, // colocando em x e y o valor corrente if (pointCount) { currentPoint.x = x; currentPoint.y = height - y; } glutPostRedisplay(); } /// Funções de classes // Função da classe que Desenha a linha void ConceitoVector:: drawConceitoVector() { glColor3f(colorVector[0], colorVector[1], colorVector[2]); // Aplica as cores RGB, todas contidas nas posições do vetor glBegin(GL_LINES); glVertex3f(x1, y1, 0.0); glVertex3f(x2, y2, 0.0); glEnd(); } // Function to draw a rectangle. void Rectangle::drawRectangle() { glColor3f(colorVector[0], colorVector[1], colorVector[2]); glPolygonMode(GL_FRONT_AND_BACK, TYPE); glRectf(x1, y1, x2, y2); } // Function to draw lines continua. void AnguloVector::drawAnguloVector() { glColor3f(colorVector[0], colorVector[1], colorVector[2]); glBegin(GL_LINES); glVertex3f(x1, y1, 0.0); glVertex3f(x2, y2, 0.0); glEnd(); } // Function to draw circle. void Circle::drawCircle() { glColor3f(0.0, 0.0, 0.0); glBegin(GL_LINES); glVertex3f(x1, y1 , 0.0); glVertex3f(x2 , y2, 0.0); glEnd(); if(x2 > 500 && y2 > 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 - 20 , y2 + 20, 0.0); glVertex3f(x2 + 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 + 15, 0.0); glEnd(); } if(x2 < 500 && y2 > 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 - 20 , y2 + 20, 0.0); glVertex3f(x2 - 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 + 15, 0.0); glEnd(); } if(x2 < 500 && y2 > 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 - 20 , y2 + 20, 0.0); glVertex3f(x2 - 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 + 15, 0.0); glEnd(); } if(x2 < 500 && y2 < 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 - 20, y2 + 20, 0.0); glVertex3f(x2 - 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 - 20, 0.0); glEnd(); } if(x2 > 500 && y2 < 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 + 20, y2 + 20, 0.0); glVertex3f(x2 - 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 - 20, 0.0); glEnd(); } } /// Iterators vector<ConceitoVector>::iterator conceitoVectorIterator; // Iterator to traverse a Line array. vector<Rectangle>::iterator rectanglesIterator; // Iterator to traverse a Rectangle array. vector<AnguloVector>::iterator anguloVectorIterator; // Iterator to traverse a Line array. vector<Circle>::iterator circleIterator; // Iterator to traverse a Line array. /// Vectors vector<ConceitoVector> conceitoVectors; // Vector of lines. vector<Rectangle> rectangles; // Vector of rectangles. vector<AnguloVector> anguloVectors; // Vector of lines. vector<Circle> circles;// Vector of lines. /// Funções para chamada da função da classe, função que intera no vetor void clearAll(void) { conceitoVectors.clear(); rectangles.clear(); anguloVectors.clear(); circles.clear(); primitive = INACTIVE; pointCount = 0; } void drawArrow(float x1, float y1, float x2, float y2) { glColor3f(0.0, 0.0, 0.0); glBegin(GL_LINES); glVertex3f(x1, y1 , 0.0); glVertex3f(x2 , y2, 0.0); glEnd(); if(x2 > 500 && y2 > 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 - 20 , y2 + 20, 0.0); glVertex3f(x2 + 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 + 15, 0.0); glEnd(); } if(x2 >= 500 && y2 == 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2, y2 +20, 0.0); glVertex3f(x2, y2 - 20, 0.0); glVertex3f(x2 + 20, y2 , 0.0); glEnd(); } if(x2 < 500 && y2 == 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 , y2 , 0.0); glVertex3f(x2 + 20, y2 - 20, 0.0); glVertex3f(x2+20, y2 + 20, 0.0); glEnd(); } if(x2 < 500 && y2 > 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 - 20 , y2 + 20, 0.0); glVertex3f(x2 - 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 + 15, 0.0); glEnd(); } if(x2 < 500 && y2 > 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 - 20 , y2 + 20, 0.0); glVertex3f(x2 - 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 + 15, 0.0); glEnd(); } if(x2 < 500 && y2 < 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 - 20, y2 + 20, 0.0); glVertex3f(x2 - 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 - 20, 0.0); glEnd(); } if(x2 > 500 && y2 < 250) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_STRIP); glVertex3f(x2 + 20, y2 + 20, 0.0); glVertex3f(x2 - 20, y2 - 20, 0.0); glVertex3f( x2+15, y2 - 20, 0.0); glEnd(); } } // Function to draw all lines in the lines array. void drawConceitoVectors(void) { // Loop through the lines array drawing each line. conceitoVectorIterator = conceitoVectors.begin(); while(conceitoVectorIterator != conceitoVectors.end()) { conceitoVectorIterator->drawConceitoVector(); conceitoVectorIterator++; } } // Função para desehar todos os retangulos no vetor void drawRectangles(void) { rectanglesIterator = rectangles.begin(); while(rectanglesIterator != rectangles.end()) { rectanglesIterator->drawRectangle(); rectanglesIterator++; } } // Função para desehar todas as poli linhas no vetor void drawAnguloVectors(void) { // Loop through the lines array drawing each line. anguloVectorIterator = anguloVectors.begin(); while(anguloVectorIterator != anguloVectors.end()) { anguloVectorIterator->drawAnguloVector(); anguloVectorIterator++; } } // Função para desehar todos os circulos no vetor void drawCircles(void) { // Loop through the lines array drawing each line. circleIterator = circles.begin(); while(circleIterator != circles.end()) { circleIterator->drawCircle(); circleIterator++; } } void writeBitmapString(void *font, char *string) { char *c; for(c = string; *c != '\0'; c++) glutBitmapCharacter(font, *c); } // Function to draw point selection box in left selection area. void drawConceitoVectorsSelectionBox(void) { glDisable(GL_LINE_STIPPLE); /// Independente se a linha stipple foi ativada, o menu não é para ser ativado também /// Então desativamos /// Se primitiva for igual ponto, a cor do quadrado do ponto é alterada, o Highlight primitive == CONCEITO_VECTOR ? glColor3f(0.8, 0.8, 0.8) : glColor3f(0.08, 0.2, 0.2); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glRectf(0.0, 0.8 * height, 0.25 * width, height); // Draw black boundary. glColor3f(255.0, 255.0, 255.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRectf(0.0, 0.8*height, 0.25 *width, height); // Draw point icon. glPointSize(10); glColor3f(0.0, 0.0, 0.0); /// Desenha o icone (Seta) no box glColor3f(255.0, 255.0, 255.0); glBegin(GL_LINES); /// Desenha a linha do vetor glVertex3f(0.050 * width, 0.860 * height, 0.0); glVertex3f(0.20 * width, 0.930 * height, 0.0); /// Desenha a base da seta glVertex3f(0.21 * width, 0.900 * height, 0.0); glVertex3f(0.19 * width, 0.960 * height, 0.0); /// Desenha o lado superior da seta glVertex3f(0.19 * width, 0.960 * height, 0.0); glVertex3f(0.22 * width, 0.940 * height, 0.0); /// Desenha o lado inferior da seta glVertex3f(0.21 * width, 0.900 * height, 0.0); glVertex3f(0.22 * width, 0.940 * height, 0.0); glEnd(); glColor3f(255.0, 255.0, 255.0); glRasterPos3f(25.00, 410.0, 0.0); writeBitmapString(GLUT_BITMAP_9_BY_15, "Conceito Vetor" ); } // Function to draw line selection box in left selection area. void drawAnguloVectorsSelectionBox(void) { glDisable(GL_LINE_STIPPLE); primitive == ANGULO_VECTOR ? glColor3f(0.8, 0.8, 0.8) : glColor3f(0.08, 0.2, 0.2); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glRectf(0.0, 0.6 * height, 0.25 * width, 0.8 * height); // Draw black boundary. glColor3f(255.0, 255.0, 255.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRectf(0.0, 0.6 * height, 0.25 * width, 0.8 * height); float t = 0.0; /// Desenha o icone (angulo) no box glBegin(GL_LINE_LOOP); for(int i = 0; i < nVertices; ++i) { glColor3ub(255.0, 255.0, 255.0); glVertex3f( (0.115 * width) + 35 * cos(t), (0.680 * height) + 35 * sin(t), 0.0); t += PI / nVertices; } glEnd(); glColor3f(255.0, 255.0, 255.0); glRasterPos3f(25.00, 310.0, 0.0); writeBitmapString(GLUT_BITMAP_9_BY_15, "Angulo de Vetores" ); } // Function to draw rectangle selection box in left selection area. void drawSumVectorsSelectionBox(void) { glDisable(GL_LINE_STIPPLE); primitive == SUM_VECTOR ? glColor3f(0.8, 0.8, 0.8) : glColor3f(0.08, 0.2, 0.2); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glRectf(0.0, 0.4 * height, 0.25 * width, 0.6 * height); // Draw black boundary. glColor3f(255.0, 255.0, 255.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRectf(0.0, 0.4 * height, 0.25 * width, 0.6 * height); glBegin(GL_LINES); /// Desenha a linha do vetor glVertex3f(0.050 * width, 0.550 * height, 0.0); glVertex3f(0.20 * width, 0.550 * height, 0.0); glVertex3f(0.20 * width, 0.500 * height, 0.0); glVertex3f(0.050 * width, 0.500 * height, 0.0); glEnd(); glColor3f(255.0, 255.0, 255.0); glRasterPos3f(25.00, 210.0, 0.0); writeBitmapString(GLUT_BITMAP_9_BY_15, "Produto Escalar" ); } // Function to draw polyLine selection box in left selection area. void drawScalarProductSelectionBox(void) { glDisable(GL_LINE_STIPPLE); primitive == SCALAR_PRODUCT ? glColor3f(0.8, 0.8, 0.8) : glColor3f(0.08, 0.2, 0.2); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glRectf(0.0, 0.2 * height, 0.25 * width, 0.4*height); // Draw black boundary. glColor3f(255.0, 255.0, 255.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRectf(0.0, 0.2 * height, 0.25 * width, 0.4 * height); glBegin(GL_LINES); glVertex3f(0.050 * width, 0.300 * height, 0.0); glVertex3f(0.10 * width, 0.300* height, 0.0); glEnd(); glColor3f(255.0, 255.0, 255.0); glRasterPos3f(0.11 * width, 0.280 * height, 0.0); writeBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, "*"); glColor3f(255.0, 255.0, 255.0); glRasterPos3f(0.14 * width, 0.290 * height, 0.0); writeBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, "C"); glColor3f(255.0, 255.0, 255.0); glRasterPos3f(25.00, 110.0, 0.0); writeBitmapString(GLUT_BITMAP_9_BY_15, "Multip por Escalar"); } // Function to draw circle selection box in left selection area. void drawVectorProductSelectionBox(void) { glDisable(GL_LINE_STIPPLE); float t = 0.0; primitive == VECTOR_PRODUCT ? glColor3f(0.8, 0.8, 0.8) : glColor3f(0.08, 0.2, 0.2); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glRectf(0.0, 0, 0.25 * width, 0.2 * height); // Draw black boundary. glColor3f(255.0, 255.0, 255.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glRectf(0.0, 0, 0.25 * width, 0.2 * height); glBegin(GL_LINES); glVertex3f(0.050 * width, 0.100 * height, 0.0); glVertex3f(0.10 * width, 0.160* height, 0.0); glVertex3f(0.050 * width, 0.100 * height, 0.0); glVertex3f(0.10 * width, 0.100 * height, 0.0); glEnd(); glColor3f(255.0, 255.0, 255.0); glRasterPos3f(25.00, 10.0, 0.0); writeBitmapString(GLUT_BITMAP_9_BY_15, "Soma De Vetores" ); } // Function to draw unused part of left selection area. void drawInactiveArea(void) { } // Function to draw temporary point. void drawTempPoint(void) { glColor3f(1.0, 0.0, 0.0); glPointSize(10); glBegin(GL_POINTS); glVertex3f(center.x, center.y, 0.0); glEnd(); } // Function to draw a grid. void drawGrid(void) { float sum = 200.0; glEnable(GL_LINE_STIPPLE); glLineStipple(1, 0x5555); /// Stipple default do grid glColor3f(0.75, 0.75, 0.75); /// Cor default do grid glBegin(GL_LINES); for (int i = 0; i < 6; ++i) { glVertex3f( sum, 0.0, 0.0); glVertex3f( sum, height, 0.0); sum += 100.0; } sum = 0; for (int i = 0; i < 6; i++) { glVertex3f(0.0, sum, 0.0); glVertex3f(width, sum, 0.0); sum += 83.333333; } glEnd(); glDisable(GL_LINE_STIPPLE); } /// Escreve na tela o texto de qual figura está selecioada, o parametro texto é passado void drawText(char *text) { glColor3f(0.0, 0.0, 15.0); glRasterPos3f(80.0, 55.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, text); } void drawTextScala() { char msg[30]; itoa(abs(scalar),msg, 10); glColor3f(0.0, 0.0, 15.0); glRasterPos3f(210.0, 80.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, "Modulo do produto Escalar: "); glColor3f(0.0, 0.0, 15.0); glRasterPos3f(440.0, 80.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, msg); } /// Função para desenhar plano cartesiano void drawCartesianPlane(void) { glColor3f(0.0,51.0, 0.0); // Aplica as cores RGB, todas contidas nas posições do vetor glBegin(GL_LINES); /// Linha da vertical glVertex3f(500, 0, 0.0); glVertex3f(500, 500, 0.0); /// Linha da horizontal glVertex3f(0.0, 250.0, 0.0); glVertex3f(width, 250.0, 0.0); glEnd(); } void AdrawConceitoVector() { drawArrow(300,83.3333,700,420.6667); glColor3f(0.0, 0.0, 0.0); glRasterPos3f(430.0, 260.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, "V ->"); glColor3f(0.0, 0.0, 0.0); glRasterPos3f(230.0, 60.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, "DIRECAO"); glColor3f(0.0, 0.0, 0.0); glRasterPos3f(580.0, 450.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, "SENTIDO"); glColor3f(0.0, 0.0, 0.0); glRasterPos3f(520.0, 150.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, "| X | -> MODULO DO VETOR"); } void drawArrowQuadrant() { switch(posQuadrant) { case 0: drawArrow(500, 250, 600, 250); break; case 45: drawArrow(500, 250, 600, 333.3333); break; case 90: drawArrow(500, 250, 500, 333.3333); break; case 135: drawArrow(500, 250, 400, 333.3333); break; case 180: drawArrow(500, 250, 400, 250.0); break; case 225: drawArrow(500, 250, 400, 166.6667); break; case 270: drawArrow(500, 250, 500, 166.6667); break; case 315: drawArrow(500, 250, 600, 166.6667); break; case 360: drawArrow(500, 250, 600, 250); break; } } void print(float x1, float y1, float x2, float y2, char *text, float *colors) { glRasterPos3f(30.0, 40.0, 0.0); glDisable(GL_LINE_STIPPLE); glColor3f(colors[0], colors[1], colors[2]); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glRectf(x1, y1, x2, y2); glColor3f(0.0, 0.0, 15.0); glRasterPos3f(x1 + 5, y1 + 10, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_12, text); } void drawOptions(void) { float colors[3]; switch(posQuadrant) { case 0: colors[0] = 244.0, colors[1] = 0.0, colors[2] = 0.24; print(510, 83.3333,540, 120.3333, "0", colors); break; case 45: colors[0] = 12.0, colors[1] = 123.0, colors[2] = 0.24; print(550, 83.3333,580, 120.3333, "45", colors); break; case 90: colors[0] = 1.2, colors[1] = 0.0, colors[2] = 0.0; print(590, 83.3333,620, 120.3333, "90", colors); break; case 135: colors[0] = 12.2, colors[1] = 34.123, colors[2] = 0.01; print(630, 83.3333,660, 120.3333, "135", colors); break; case 180: colors[0] = 0.2, colors[1] = 34.10, colors[2] = 1.20; print(670, 83.3333,700, 120.3333, "180", colors); break; case 225: colors[0] = 0.0, colors[1] = 0.1, colors[2] = 0.24; print(340, 83.3333, 370, 120.3333, "225", colors); break; case 270: colors[0] = 1.1, colors[1] = 0.31, colors[2] = 0.24; print(380, 83.3333, 410, 120.3333, "270", colors); break; case 315: colors[0] = 0.1, colors[1] = 0.0, colors[2] = 0.2; print(420, 83.3333, 450, 120.3333, "315", colors); break; case 360: colors[0] = 1.1, colors[1] = 1.0, colors[2] = 0.2; print(460, 83.3333, 490, 120.3333, "360", colors); break; } } void drawCalc(void) { if(vectorOne.x2 < 500) vectorOne.x2 = -vectorOne.x2; if(vectorOne.y2 < 250) vectorOne.y2 = -vectorOne.y2; if(vectorTwo.x2 < 500) vectorTwo.x2 = -vectorTwo.x2; if(vectorTwo.y2 < 250) vectorTwo.y2 = -vectorTwo.y2; float x1 = (abs(vectorOne.x2) - 500), x2 = (abs(vectorTwo.x2) - 500), y1 = (abs(vectorOne.y2) - 250), y2 = (abs(vectorTwo.y2) - 250); circles.push_back( Circle(500, 250, 500 + (x1 + x2), 250 + (y1 + y2) ) ); } void drawInfoScalar(int pos) { if(pos == 0) { glColor3f(0.0, 0.0, 15.0); glRasterPos3f(220.0, 80.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, "Sentido do vetor -> NUlo" ); } else if(pos < 10) { glColor3f(0.0, 0.0, 15.0); glRasterPos3f(220.0, 80.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, "Sentido do vetor -> NEGATIVO" ); } if(pos >= 10) { glColor3f(0.0, 0.0, 15.0); glRasterPos3f(220.0, 80.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, "Sentido do vetor -> POSITIVO" ); } glColor3f(0.0, 0.0, 15.0); glRasterPos3f(220.0, 30.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, "Modulo do Vetor: " ); char msg[30]; itoa(abs(pos),msg, 10); glColor3f(0.0, 0.0, 15.0); glRasterPos3f(390.0, 30.0, 0.0); writeBitmapString(GLUT_BITMAP_HELVETICA_18, msg); } // Drawing routine. void drawScene(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0, 0.0, 0.0); drawRectangles(); drawAnguloVectors(); drawCircles(); drawConceitoVectors(); if (( (primitive == CONCEITO_VECTOR) || (primitive == SUM_VECTOR) || (primitive == SCALAR_PRODUCT) ) && (pointCount == 1) ) drawTempPoint(); drawCartesianPlane(); if (isGrid) { drawGrid(); } if(primitive == CONCEITO_VECTOR) { AdrawConceitoVector(); } if(primitive == SUM_VECTOR) { drawTextScala(); } if(primitive == ANGULO_VECTOR) { circles.clear(); drawArrowQuadrant(); drawOptions(); } if(primitive == SCALAR_PRODUCT) { circles.clear(); drawArrow(500, 250, 500 + Constant, 250); drawInfoScalar(Constant); } drawSumVectorsSelectionBox(); drawConceitoVectorsSelectionBox(); drawScalarProductSelectionBox(); drawAnguloVectorsSelectionBox(); drawInactiveArea(); drawVectorProductSelectionBox(); glutSwapBuffers(); } // Function to pick primitive if click is in left selection area. void pickPrimitive(int y) { cout << y << endl; if(y > 400 && y < 500) primitive = CONCEITO_VECTOR; else if(y > 300 && y < 400) primitive = ANGULO_VECTOR; else if(y > 200 && y < 400) primitive = SUM_VECTOR; else if(y > 100 && y < 200) primitive = SCALAR_PRODUCT; else if(y > 0 && y < 100) primitive = VECTOR_PRODUCT; cout << primitive << endl; } void resetAndSetCoordinates(float x, float y) { currentPoint.x = x; currentPoint.y = y; center.x = x; center.y = y; pointCount = 1; } void drawPVetorial(void) { if(vectorOne.x2 < 500) vectorOne.x2 = -vectorOne.x2; if(vectorOne.y2 < 250) vectorOne.y2 = -vectorOne.y2; if(vectorTwo.x2 < 500) vectorTwo.x2 = -vectorTwo.x2; if(vectorTwo.y2 < 250) vectorTwo.y2 = -vectorTwo.y2; float x1 = (abs(vectorOne.x2) - 500), x2 = (abs(vectorTwo.x2) - 500), y1 = (abs(vectorOne.y2) - 250), y2 = (abs(vectorTwo.y2) - 250); scalar = (x1 * x2) + (y1 * y2); } void mouseControl(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { y = height - y; // Correct from mouse to OpenGL co-ordinates. // Click outside canvas - do nothing. if (x < 0 || x > width || y < 0 || y > height); // Click in left selection area. else if (x < 0.25 * width) { pickPrimitive(y); pointCount = 0; } if(primitive == SUM_VECTOR) { if(pointCount > 2) { if(pointCount == 3) { drawPVetorial(); pointCount = 0; circles.clear(); } } if(pointCount != 0) { if(pointCount == 1) { vectorOne.x2 = x; vectorOne.y2 = y; } if(pointCount == 2) { vectorTwo.x2 = x; vectorTwo.y2 = y; } drawArrow(500, 250, x, y); circles.push_back( Circle(500, 250, x, y) ); pointCount++; } else pointCount++; } if (primitive == VECTOR_PRODUCT) { if(pointCount > 2) { if(pointCount == 4) { clearAll(); } else { drawCalc(); pointCount = 4; } } else if(pointCount != 0) { if(pointCount == 1) { vectorOne.x2 = x; vectorOne.y2 = y; } if(pointCount == 2) { vectorTwo.x2 = x; vectorTwo.y2 = y; } drawArrow(500, 250, x, y); circles.push_back( Circle(500, 250, x, y) ); pointCount++; } else pointCount++; } } if ((button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN)) pointCount = 0; glutPostRedisplay(); } // Initialization routine. void setup(void) { glClearColor(1.0, 1.0, 1.0, 0.0); } // OpenGL window reshape routine. void resize(int w, int h) { glViewport(0, 0, (GLsizei)w, (GLsizei)h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Set viewing box dimensions equal to window dimensions. glOrtho(0.0, (float)w, 0.0, (float)h, -1.0, 1.0); // Pass the size of the OpenGL window to globals. width = w; height = h; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } // Keyboard input processing routine. void keyInput(unsigned char key, int x, int y) { switch (key) { case 27: exit(0); break; case 49: posQuadrant = 0; break; case 50: posQuadrant = 45; break; case 51: posQuadrant = 90; break; case 52: posQuadrant = 135; break; case 53: posQuadrant = 180; break; case 54: posQuadrant = 225; break; case 55: posQuadrant = 270; break; case 56: posQuadrant = 315; break; case 57: posQuadrant = 360; break; case '-': /// Seta para esquerda Constant -= 10; break; case '+': /// Seta para direita Constant += 10; break; default: break; } } // The right button menu callback function. void rightMenu(int id) { if (id == 1) { clearAll(); glutPostRedisplay(); } if (id==2) exit(0); } // The sub-menu callback function. void grid_menu(int id) { if(id == 3) isGrid = 1; if(id == 4) isGrid = 0; glutPostRedisplay(); } // Controla o line stipple void keyGraus(int key) { switch(key) { case 1: posQuadrant = 0; break; case 2: posQuadrant = 45; break; case 3: posQuadrant = 90; break; case 4: posQuadrant = 135; break; case 5: posQuadrant = 180; break; case 6: posQuadrant = 225; break; case 7: posQuadrant = 270; break; case 8: posQuadrant = 315; break; case 9: posQuadrant = 360; break; default: break; } } void makeMenu(void) { int sub_menu, options_graus; options_graus = glutCreateMenu(keyGraus); glutAddMenuEntry("0 Graus", 1); glutAddMenuEntry("45 Graus", 2); glutAddMenuEntry("90 Graus", 3); glutAddMenuEntry("135 Graus", 4); glutAddMenuEntry("180 Graus", 5); glutAddMenuEntry("225 Graus", 6); glutAddMenuEntry("270 Graus", 7); glutAddMenuEntry("315 Graus", 8); glutAddMenuEntry("360 Graus", 9); sub_menu = glutCreateMenu(grid_menu); glutAddMenuEntry("On", 3); glutAddMenuEntry("Off", 4); glutCreateMenu(rightMenu); glutAddSubMenu("Grid", sub_menu); glutAddSubMenu("Alterar Graus", options_graus); glutAddMenuEntry("Clear", 1); glutAddMenuEntry("Quit", 2); glutAttachMenu(GLUT_RIGHT_BUTTON); } // Routine to output interaction instructions to the C++ window. void printInteraction(void) { cout << "Interaction:" << endl; cout << "Left click on a box on the left to select a primitive." << endl << "Then left click on the drawing area: once for point, twice for line or rectangle." << endl << "Right click for menu options." << endl; } // Main routine. int main(int argc, char **argv) { printInteraction(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize(800, 500); glutInitWindowPosition(100, 100); glutCreateWindow("canvas.cpp"); setup(); glutDisplayFunc(drawScene); glutReshapeFunc(resize); glutKeyboardFunc(keyInput); // Register the mouse callback function. glutMouseFunc(mouseControl); // Register the mouse passive motion callback function. glutPassiveMotionFunc(mousePassiveMotion); makeMenu(); // Create menu. glutMainLoop(); return 0; }
82a495e75df1febd31600b29fc469f8bb8337f30
561ffc56c58f11adf9f2a702a9a0be9ebadffa41
/src/qif.cc
38bac7e99d420c1dc0e79ed5d98dd9c080959ce2
[]
no_license
skanthak/ledger
f9a51149dc8444cf1dedc86ea9af04cb55b200ec
5d41388ff3e971d47f8fb7938be49f3dca85c3d1
refs/heads/master
2021-01-23T08:24:39.629502
2008-10-29T08:00:00
2008-10-29T08:00:00
70,928
1
0
null
null
null
null
UTF-8
C++
false
false
6,856
cc
qif.cc
/* * Copyright (c) 2003-2008, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of New Artisans LLC nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "journal.h" #include "qif.h" #include "utils.h" namespace ledger { #define MAX_LINE 1024 static char line[MAX_LINE + 1]; static path pathname; static unsigned int src_idx; static unsigned int linenum; static inline char * get_line(std::istream& in) { in.getline(line, MAX_LINE); int len = std::strlen(line); if (line[len - 1] == '\r') line[len - 1] = '\0'; linenum++; return line; } bool qif_parser_t::test(std::istream& in) const { char magic[sizeof(unsigned int) + 1]; in.read(magic, sizeof(unsigned int)); magic[sizeof(unsigned int)] = '\0'; in.clear(); in.seekg(0, std::ios::beg); return (std::strcmp(magic, "!Typ") == 0 || std::strcmp(magic, "\n!Ty") == 0 || std::strcmp(magic, "\r\n!T") == 0); } unsigned int qif_parser_t::parse(std::istream& in, session_t& session, journal_t& journal, account_t * master, const path * original_file) { std::auto_ptr<entry_t> entry; std::auto_ptr<amount_t> amount; xact_t * xact; unsigned int count = 0; account_t * misc = NULL; commodity_t * def_commodity = NULL; bool saw_splits = false; bool saw_category = false; xact_t * total = NULL; entry.reset(new entry_t); xact = new xact_t(master); entry->add_xact(xact); pathname = journal.sources.back(); src_idx = journal.sources.size() - 1; linenum = 1; istream_pos_type beg_pos = 0; unsigned long beg_line = 0; #define SET_BEG_POS_AND_LINE() \ if (! beg_line) { \ beg_pos = in.tellg(); \ beg_line = linenum; \ } while (in.good() && ! in.eof()) { char c; in.get(c); switch (c) { case ' ': case '\t': if (peek_next_nonws(in) != '\n') { get_line(in); throw parse_error("Line begins with whitespace"); } // fall through... case '\n': linenum++; case '\r': // skip blank lines break; case '!': get_line(in); if (std::strcmp(line, "Type:Invst") == 0 || std::strcmp(line, "Account") == 0 || std::strcmp(line, "Type:Cat") == 0 || std::strcmp(line, "Type:Class") == 0 || std::strcmp(line, "Type:Memorized") == 0) throw_(parse_error, "QIF files of type " << line << " are not supported."); break; case 'D': SET_BEG_POS_AND_LINE(); get_line(in); // jww (2008-08-01): Is this just a date? entry->_date = parse_date(line); break; case 'T': case '$': { SET_BEG_POS_AND_LINE(); get_line(in); xact->amount.parse(line); unsigned char flags = xact->amount.commodity().flags(); unsigned char prec = xact->amount.commodity().precision(); if (! def_commodity) { def_commodity = amount_t::current_pool->find_or_create("$"); assert(def_commodity); } xact->amount.set_commodity(*def_commodity); def_commodity->add_flags(flags); if (prec > def_commodity->precision()) def_commodity->set_precision(prec); if (c == '$') { saw_splits = true; xact->amount.negate(); } else { total = xact; } break; } case 'C': SET_BEG_POS_AND_LINE(); c = in.peek(); if (c == '*' || c == 'X') { in.get(c); xact->set_state(item_t::CLEARED); } break; case 'N': SET_BEG_POS_AND_LINE(); get_line(in); entry->code = line; break; case 'P': case 'M': case 'L': case 'S': case 'E': { SET_BEG_POS_AND_LINE(); get_line(in); switch (c) { case 'P': entry->payee = line; break; case 'S': xact = new xact_t(NULL); entry->add_xact(xact); // fall through... case 'L': { int len = std::strlen(line); if (line[len - 1] == ']') line[len - 1] = '\0'; xact->account = journal.find_account(line[0] == '[' ? line + 1 : line); if (c == 'L') saw_category = true; break; } case 'M': case 'E': xact->note = line; break; } break; } case 'A': SET_BEG_POS_AND_LINE(); // jww (2004-08-19): these are ignored right now get_line(in); break; case '^': { account_t * other; if (xact->account == master) { if (! misc) misc = journal.find_account("Miscellaneous"); other = misc; } else { other = master; } if (total && saw_category) { if (! saw_splits) total->amount.negate(); // negate, to show correct flow else total->account = other; } if (! saw_splits) { xact_t * nxact = new xact_t(other); // The amount doesn't need to be set because the code below // will balance this xact against the other. entry->add_xact(nxact); } if (journal.add_entry(entry.get())) { entry->src_idx = src_idx; entry->beg_pos = beg_pos; entry->beg_line = beg_line; entry->end_pos = in.tellg(); entry->end_line = linenum; entry.release(); count++; } // reset things for the next entry entry.reset(new entry_t); xact = new xact_t(master); entry->add_xact(xact); saw_splits = false; saw_category = false; total = NULL; beg_line = 0; break; } default: get_line(in); break; } } return count; } } // namespace ledger
a1833d11381f820e4b3920c220dff52470005178
1825283527f5a479204708feeaf55f4ab6d1290b
/leetcode/c++/14/longest-common-prefix.hpp
021cf97ea13983ebd085b0a7197681bcea4f925f
[]
no_license
frankieliu/problems
b82c61d3328ffcc1da2cbc95712563355f5d44b5
911c6622448a4be041834bcab25051dd0f9209b2
refs/heads/master
2023-01-06T14:41:58.044871
2019-11-24T03:47:22
2019-11-24T03:47:22
115,065,956
1
0
null
2023-01-04T07:25:52
2017-12-22T02:06:57
HTML
UTF-8
C++
false
false
613
hpp
longest-common-prefix.hpp
class Solution { public: string longestCommonPrefix(vector<string>& strs) { int l = strs.size(); string s = ""; if (l==0) return s; if (l==1) return strs[0]; int j = 0; bool same = true; while (same) { char c = strs[0][j]; for(int i = 1; i < l; i++) { if ((j == strs[i].size()) || (c != strs[i][j])) { same = false; break; } } if (same) { s+=c; j++; } } return s; } };
6d2dafbe53fcdc4125361ada1348bc12e133d98f
1b90be9561c10508eea59cb36c1f1665d0ef947f
/lib/boost_1.78.0/tools/build/src/engine/filent.cpp
e32879424dc106476021d6c7ec6d98990c0bd379
[ "BSL-1.0", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
stan-dev/math
473e7c1eaf11f84eaf2032c2455e12ba65feef39
bdf281f4e7f8034f47974d14dea7f09e600ac02a
refs/heads/develop
2023-08-31T09:02:59.224115
2023-08-29T15:17:01
2023-08-29T15:17:01
38,388,440
732
240
BSD-3-Clause
2023-09-14T19:44:20
2015-07-01T18:40:54
C++
UTF-8
C++
false
false
15,372
cpp
filent.cpp
/* * Copyright 1993, 1995 Christopher Seiwald. * * This file is part of Jam - see jam.c for Copyright information. */ /* This file is ALSO: * Copyright 2001-2004 David Abrahams. * Copyright 2005 Rene Rivera. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE.txt or copy at * https://www.bfgroup.xyz/b2/LICENSE.txt) */ /* * filent.c - scan directories and archives on NT * * External routines: * file_archscan() - scan an archive for files * file_mkdir() - create a directory * file_supported_fmt_resolution() - file modification timestamp resolution * * External routines called only via routines in filesys.c: * file_collect_dir_content_() - collects directory content information * file_dirscan_() - OS specific file_dirscan() implementation * file_query_() - query information about a path from the OS * file_collect_archive_content_() - collects information about archive members * file_archivescan_() - OS specific file_archivescan() implementation */ #include "jam.h" #ifdef OS_NT #include "filesys.h" #include "object.h" #include "pathsys.h" #include "jam_strings.h" #include "output.h" #ifdef __BORLANDC__ # undef FILENAME /* cpp namespace collision */ #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <assert.h> #include <ctype.h> #include <direct.h> #include <io.h> int file_collect_archive_content_( file_archive_info_t * const archive ); /* * file_collect_dir_content_() - collects directory content information */ int file_collect_dir_content_( file_info_t * const d ) { PATHNAME f; string pathspec[ 1 ]; string pathname[ 1 ]; LIST * files = L0; int32_t d_length; assert( d ); assert( d->is_dir ); assert( list_empty( d->files ) ); d_length = int32_t(strlen( object_str( d->name ) )); memset( (char *)&f, '\0', sizeof( f ) ); f.f_dir.ptr = object_str( d->name ); f.f_dir.len = d_length; /* Prepare file search specification for the FindXXX() Windows API. */ if ( !d_length ) string_copy( pathspec, ".\\*" ); else { /* We can not simply assume the given folder name will never include its * trailing path separator or otherwise we would not support the Windows * root folder specified without its drive letter, i.e. '\'. */ char const trailingChar = object_str( d->name )[ d_length - 1 ] ; string_copy( pathspec, object_str( d->name ) ); if ( ( trailingChar != '\\' ) && ( trailingChar != '/' ) ) string_append( pathspec, "\\" ); string_append( pathspec, "*" ); } /* The following code for collecting information about all files in a folder * needs to be kept synchronized with how the file_query() operation is * implemented (collects information about a single file). */ { /* FIXME: Avoid duplicate FindXXX Windows API calls here and in the code * determining a normalized path. */ WIN32_FIND_DATAA finfo; HANDLE const findHandle = FindFirstFileA( pathspec->value, &finfo ); if ( findHandle == INVALID_HANDLE_VALUE ) { string_free( pathspec ); return -1; } string_new( pathname ); do { OBJECT * pathname_obj; f.f_base.ptr = finfo.cFileName; f.f_base.len = int32_t(strlen( finfo.cFileName )); string_truncate( pathname, 0 ); path_build( &f, pathname ); pathname_obj = object_new( pathname->value ); path_register_key( pathname_obj ); files = list_push_back( files, pathname_obj ); { int found; file_info_t * const ff = file_info( pathname_obj, &found ); ff->is_dir = finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; ff->is_file = !ff->is_dir; ff->exists = 1; timestamp_from_filetime( &ff->time, &finfo.ftLastWriteTime ); // Use the timestamp of the link target, not the link itself // (i.e. stat instead of lstat) if ( finfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT ) { HANDLE hLink = CreateFileA( pathname->value, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL ); BY_HANDLE_FILE_INFORMATION target_finfo[ 1 ]; if ( hLink != INVALID_HANDLE_VALUE && GetFileInformationByHandle( hLink, target_finfo ) ) { ff->is_file = target_finfo->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ? 0 : 1; ff->is_dir = target_finfo->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ? 1 : 0; timestamp_from_filetime( &ff->time, &target_finfo->ftLastWriteTime ); } } } } while ( FindNextFileA( findHandle, &finfo ) ); FindClose( findHandle ); } string_free( pathname ); string_free( pathspec ); d->files = files; return 0; } /* * file_dirscan_() - OS specific file_dirscan() implementation */ void file_dirscan_( file_info_t * const d, scanback func, void * closure ) { assert( d ); assert( d->is_dir ); /* Special case \ or d:\ : enter it */ { char const * const name = object_str( d->name ); if ( name[ 0 ] == '\\' && !name[ 1 ] ) { (*func)( closure, d->name, 1 /* stat()'ed */, &d->time ); } else if ( name[ 0 ] && name[ 1 ] == ':' && name[ 2 ] && !name[ 3 ] ) { /* We have just entered a 3-letter drive name spelling (with a * trailing slash), into the hash table. Now enter its two-letter * variant, without the trailing slash, so that if we try to check * whether "c:" exists, we hit it. * * Jam core has workarounds for that. Given: * x = c:\whatever\foo ; * p = $(x:D) ; * p2 = $(p:D) ; * There will be no trailing slash in $(p), but there will be one in * $(p2). But, that seems rather fragile. */ OBJECT * const dir_no_slash = object_new_range( name, 2 ); (*func)( closure, d->name, 1 /* stat()'ed */, &d->time ); (*func)( closure, dir_no_slash, 1 /* stat()'ed */, &d->time ); object_free( dir_no_slash ); } } } /* * file_mkdir() - create a directory */ int file_mkdir( char const * const path ) { return _mkdir( path ); } /* * file_query_() - query information about a path from the OS * * The following code for collecting information about a single file needs to be * kept synchronized with how the file_collect_dir_content_() operation is * implemented (collects information about all files in a folder). */ int try_file_query_root( file_info_t * const info ) { WIN32_FILE_ATTRIBUTE_DATA fileData; char buf[ 4 ]; char const * const pathstr = object_str( info->name ); if ( !pathstr[ 0 ] ) { buf[ 0 ] = '.'; buf[ 1 ] = 0; } else if ( pathstr[ 0 ] == '\\' && ! pathstr[ 1 ] ) { buf[ 0 ] = '\\'; buf[ 1 ] = '\0'; } else if ( pathstr[ 1 ] == ':' ) { if ( !pathstr[ 2 ] || ( pathstr[ 2 ] == '\\' && !pathstr[ 3 ] ) ) { buf[ 0 ] = pathstr[ 0 ]; buf[ 1 ] = ':'; buf[ 2 ] = '\\'; buf[ 3 ] = '\0'; } else { return 0; } } else { return 0; } /* We have a root path */ if ( !GetFileAttributesExA( buf, GetFileExInfoStandard, &fileData ) ) { info->is_dir = 0; info->is_file = 0; info->exists = 0; timestamp_clear( &info->time ); } else { info->is_dir = fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; info->is_file = !info->is_dir; info->exists = 1; timestamp_from_filetime( &info->time, &fileData.ftLastWriteTime ); } return 1; } void file_query_( file_info_t * const info ) { char const * const pathstr = object_str( info->name ); const char * dir; OBJECT * parent; file_info_t * parent_info; if ( try_file_query_root( info ) ) return; if ( ( dir = strrchr( pathstr, '\\' ) ) ) { parent = object_new_range( pathstr, int32_t(dir - pathstr) ); } else { parent = object_copy( constant_empty ); } parent_info = file_query( parent ); object_free( parent ); if ( !parent_info || !parent_info->is_dir ) { info->is_dir = 0; info->is_file = 0; info->exists = 0; timestamp_clear( &info->time ); } else { info->is_dir = 0; info->is_file = 0; info->exists = 0; timestamp_clear( &info->time ); if ( list_empty( parent_info->files ) ) file_collect_dir_content_( parent_info ); } } /* * file_supported_fmt_resolution() - file modification timestamp resolution * * Returns the minimum file modification timestamp resolution supported by this * Boost Jam implementation. File modification timestamp changes of less than * the returned value might not be recognized. * * Does not take into consideration any OS or file system related restrictions. * * Return value 0 indicates that any value supported by the OS is also supported * here. */ void file_supported_fmt_resolution( timestamp * const t ) { /* On Windows we support nano-second file modification timestamp resolution, * just the same as the Windows OS itself. */ timestamp_init( t, 0, 0 ); } /* * file_archscan() - scan an archive for files */ /* Straight from SunOS */ #define ARMAG "!<arch>\n" #define SARMAG 8 #define ARFMAG "`\n" struct ar_hdr { char ar_name[ 16 ]; char ar_date[ 12 ]; char ar_uid[ 6 ]; char ar_gid[ 6 ]; char ar_mode[ 8 ]; char ar_size[ 10 ]; char ar_fmag[ 2 ]; }; #define SARFMAG 2 #define SARHDR sizeof( struct ar_hdr ) void file_archscan( char const * arch, scanback func, void * closure ) { OBJECT * path = object_new( arch ); file_archive_info_t * archive = file_archive_query( path ); object_free( path ); if ( filelist_empty( archive->members ) ) { if ( file_collect_archive_content_( archive ) < 0 ) return; } /* Report the collected archive content. */ { FILELISTITER iter = filelist_begin( archive->members ); FILELISTITER const end = filelist_end( archive->members ); char buf[ MAXJPATH ]; for ( ; iter != end ; iter = filelist_next( iter ) ) { file_info_t * member_file = filelist_item( iter ); /* Construct member path: 'archive-path(member-name)' */ sprintf( buf, "%s(%s)", object_str( archive->file->name ), object_str( member_file->name ) ); { OBJECT * const member = object_new( buf ); (*func)( closure, member, 1 /* time valid */, &member_file->time ); object_free( member ); } } } } /* * file_archivescan_() - OS specific file_archivescan() implementation */ void file_archivescan_( file_archive_info_t * const archive, archive_scanback func, void * closure ) { } /* * file_collect_archive_content_() - collects information about archive members */ int file_collect_archive_content_( file_archive_info_t * const archive ) { struct ar_hdr ar_hdr; char * string_table = 0; char buf[ MAXJPATH ]; long offset; const char * path = object_str( archive->file->name ); int const fd = open( path , O_RDONLY | O_BINARY, 0 ); if ( ! filelist_empty( archive->members ) ) filelist_free( archive->members ); if ( fd < 0 ) return -1; if ( read( fd, buf, SARMAG ) != SARMAG || strncmp( ARMAG, buf, SARMAG ) ) { close( fd ); return -1; } offset = SARMAG; if ( DEBUG_BINDSCAN ) out_printf( "scan archive %s\n", path ); while ( ( read( fd, &ar_hdr, SARHDR ) == SARHDR ) && !memcmp( ar_hdr.ar_fmag, ARFMAG, SARFMAG ) ) { long lar_date; long lar_size; char * name = 0; char * endname; sscanf( ar_hdr.ar_date, "%ld", &lar_date ); sscanf( ar_hdr.ar_size, "%ld", &lar_size ); lar_size = ( lar_size + 1 ) & ~1; if ( ar_hdr.ar_name[ 0 ] == '/' && ar_hdr.ar_name[ 1 ] == '/' ) { /* This is the "string table" entry of the symbol table, holding * filename strings longer than 15 characters, i.e. those that do * not fit into ar_name. */ string_table = (char*)BJAM_MALLOC_ATOMIC( lar_size + 1 ); if ( read( fd, string_table, lar_size ) != lar_size ) out_printf( "error reading string table\n" ); string_table[ lar_size ] = '\0'; offset += SARHDR + lar_size; continue; } else if ( ar_hdr.ar_name[ 0 ] == '/' && ar_hdr.ar_name[ 1 ] != ' ' ) { /* Long filenames are recognized by "/nnnn" where nnnn is the * string's offset in the string table represented in ASCII * decimals. */ name = string_table + atoi( ar_hdr.ar_name + 1 ); for ( endname = name; *endname && *endname != '\n'; ++endname ); } else { /* normal name */ name = ar_hdr.ar_name; endname = name + sizeof( ar_hdr.ar_name ); } /* strip trailing white-space, slashes, and backslashes */ while ( endname-- > name ) if ( !isspace( *endname ) && ( *endname != '\\' ) && ( *endname != '/' ) ) break; *++endname = 0; /* strip leading directory names, an NT specialty */ { char * c; if ( (c = strrchr( name, '/' )) != nullptr ) name = c + 1; if ( (c = strrchr( name, '\\' )) != nullptr ) name = c + 1; } sprintf( buf, "%.*s", int(endname - name), name ); if ( strcmp( buf, "") != 0 ) { file_info_t * member = 0; /* NT static libraries appear to store the objects in a sequence * reverse to the order in which they were inserted. * Here we reverse the stored sequence by pushing members to front of * member file list to get the intended members order. */ archive->members = filelist_push_front( archive->members, object_new( buf ) ); member = filelist_front( archive->members ); member->is_file = 1; member->is_dir = 0; member->exists = 0; timestamp_init( &member->time, (time_t)lar_date, 0 ); } offset += SARHDR + lar_size; lseek( fd, offset, 0 ); } close( fd ); return 0; } #endif /* OS_NT */
9cc43d1a8b757f18b0567f8b118982b37916926a
067c8359720367352c46db9224ac18893399f131
/The_Time_Of_Ending/TOEEnemyCharacter.cpp
edf90a371673ec6a86b1e5a10f76a6ba469903fc
[]
no_license
acaskanette/TimeOfEndingCodeSamples
68a24b5bd8d98d1d59ad0f99fb89c64059cca6a2
411c4145397cadabbd210a39f3b1acf3c8b5d1e1
refs/heads/master
2021-01-10T14:46:35.128022
2016-04-08T13:20:19
2016-04-08T13:20:19
53,187,219
3
0
null
null
null
null
UTF-8
C++
false
false
1,659
cpp
TOEEnemyCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "The_Time_Of_Ending.h" #include "TOEEnemyCharacter.h" void ATOEEnemyCharacter::BeginPlay() { Super::BeginPlay(); // Set default max walk speed maxWalkSpeed = this->GetCharacterMovement()->MaxWalkSpeed; slowFallOffRate = 10.0f; } void ATOEEnemyCharacter::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); // Check to see if slowed if (SlowStatus()) { SlowFalloff(DeltaSeconds); } } void ATOEEnemyCharacter::BasicAttack() { abilityManager->CastAbility(EAbilityType::MELEE, 0.0, this); } // Slow Amount between 0 and 1, expressed as percentage slow void ATOEEnemyCharacter::OnSlow(float slowAmount_) { this->GetCharacterMovement()->MaxWalkSpeed = slowAmount_ * maxWalkSpeed; } // Slow Amount between 0 and 1, expressed as percentage slow ; newSlowFalloffRate_ determines how fast you recover speed per second void ATOEEnemyCharacter::OnSlowWithFalloff(float slowAmount_, float newSlowFalloffRate_) { this->GetCharacterMovement()->MaxWalkSpeed = slowAmount_ * maxWalkSpeed; slowFallOffRate = newSlowFalloffRate_; } // Returns true if I am slower than my max speed bool ATOEEnemyCharacter::SlowStatus(){ return (this->GetCharacterMovement()->MaxWalkSpeed < maxWalkSpeed); } // Increases speed by the slowFallOffRate each second until you reach max speed void ATOEEnemyCharacter::SlowFalloff(float DeltaSeconds_) { this->GetCharacterMovement()->MaxWalkSpeed += DeltaSeconds_ * slowFallOffRate; if (this->GetCharacterMovement()->MaxWalkSpeed > maxWalkSpeed) { this->GetCharacterMovement()->MaxWalkSpeed = maxWalkSpeed; } }
eb06b4bcb8a889eff656d976531cc0ccbe658e12
9cdab28d2e857f1e1f2fc5bcf768ebe9fbb012d9
/Computos/dlgimportpricelist.h
cb739c1059fb0e2a730e37220e43eca22c09b0db
[]
no_license
diegowald/computos
48534170f649f99d9cda4b806a721476785d6815
5c304838594f8fe34b8ab4ceff1c27154063acf6
refs/heads/master
2021-01-19T09:10:05.216391
2014-11-29T16:17:48
2014-11-29T16:17:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,616
h
dlgimportpricelist.h
#ifndef DLGIMPORTPRICELIST_H #define DLGIMPORTPRICELIST_H #include <QDialog> #include "csvreader.h" #include <QAction> #include <precio.h> namespace Ui { class dlgImportPriceList; } class dlgImportPriceList : public QDialog { Q_OBJECT public: explicit dlgImportPriceList(QWidget *parent = 0); ~dlgImportPriceList(); private slots: void on_cboProviders_currentIndexChanged(const QString &arg1); void on_btnOpenFileDialog_pressed(); void on_chkHeadersOnFirstRow_stateChanged(int arg1); void on_treeCSV_customContextMenuRequested(const QPoint &pos); void mapField(QAction* action); void on_btnImport_pressed(); void on_cboPriceLists_currentIndexChanged(const QString &arg1); private: Ui::dlgImportPriceList *ui; QString newProvider; QString newPriceList; void loadProviders(); void loadPriceLists(); void openFile(); void fillData(); void addToMenu(QMenu * menu, QString text); void actualizarPrecio(QStringList record, listaPrecios::Precio *precio); QString getRecordValue(QStringList record, QString Field); bool editPriceListItem(listaPrecios::Precio *precio); CSVReader *csv; QString SalesName; QString PriceLabel; QString ElementLabel; QString SalesUnitLabel; QString RatioLabel; QString BrandLabel; QString NotesLabel; QString RemoveMappingLabel; QString addToFilterLabel; QString removeFromFilter; int columnSelected; int SalesNameColumn; QMap<int, QString> fieldMapping; boost::shared_ptr<QStringList> filter; }; #endif // DLGIMPORTPRICELIST_H
d9377047b74649ce2fa5dbb7b226db171463b2a3
ba37f5ccb316cbacfe24aa68d3e680947370ffbd
/src/fileInput/gridDynReadDYR.cpp
c3e1e4cbcc4477af7a4b148d3455901858a8917a
[ "BSD-3-Clause" ]
permissive
nightlark/GridDyn
e6fe9ab0251b10d86f269b8951ab1e1dd8b56508
bfcef303c85c5b66bc26e5d16e4df0a07977e594
refs/heads/helics_updates
2021-01-24T06:12:32.115450
2019-07-19T18:12:34
2019-07-19T18:12:34
202,812,824
0
0
NOASSERTION
2019-08-17T00:22:00
2019-08-16T23:43:07
C++
UTF-8
C++
false
false
6,707
cpp
gridDynReadDYR.cpp
/* * LLNS Copyright Start * Copyright (c) 2014-2018, Lawrence Livermore National Security * This work was performed under the auspices of the U.S. Department * of Energy by Lawrence Livermore National Laboratory in part under * Contract W-7405-Eng-48 and in part under Contract DE-AC52-07NA27344. * Produced at the Lawrence Livermore National Laboratory. * All rights reserved. * For details, see the LICENSE file. * LLNS Copyright End */ #include "core/objectFactory.hpp" #include "griddyn/Generator.h" #include "griddyn/gridBus.h" #include "fileInput.h" #include "griddyn/Exciter.h" #include "griddyn/GenModel.h" #include "griddyn/Governor.h" #include "utilities/stringConversion.h" #include <cstdio> #include <fstream> #include <iostream> namespace griddyn { static std::shared_ptr<coreObjectFactory> cof = coreObjectFactory::instance (); void loadGENROU (coreObject *parentObject, stringVec &tokens); void loadESDC1A (coreObject *parentObject, stringVec &tokens); void loadTGOV1 (coreObject *parentObject, stringVec &tokens); void loadEXDC2 (coreObject *parentObject, stringVec &tokens); void loadDYR (coreObject *parentObject, const std::string &fileName, const basicReaderInfo & /*bri*/) { std::ifstream file (fileName.c_str (), std::ios::in); std::string line, line2; // line storage std::string temp1; // temporary storage for substrings if (!(file.is_open ())) { parentObject->log (parentObject, print_level::error, "Unable to open file " + fileName); // return; } while (std::getline (file, line)) { stringOps::trimString (line); if (line.empty ()) { continue; } while (line.back () != '/') { if (std::getline (file, line2)) { stringOps::trimString (line2); line += ' ' + line2; } else { break; } } auto lineTokens = stringOps::splitline (line, " \t\n,", stringOps::delimiter_compression::on); // get rid of the '/' at the end of the last string auto lstr = lineTokens.back (); lineTokens.pop_back (); lstr = lstr.substr (0, lstr.size () - 1); if (!lstr.empty ()) { lineTokens.push_back (lstr); } auto type = lineTokens[1]; stringOps::trimString (type); if (type == "'GENROU'") { loadGENROU (parentObject, lineTokens); } else if (type == "'ESDC1A'") { loadESDC1A (parentObject, lineTokens); } else if (type == "'EXDC2'") { loadESDC1A (parentObject, lineTokens); } else if (type == "'TGOV1'") { loadTGOV1 (parentObject, lineTokens); } else { std::cout << "unknown object type " << type << '\n'; } } } void loadGENROU (coreObject *parentObject, stringVec &tokens) { int id = std::stoi (tokens[0]); gridBus *bus = static_cast<gridBus *> (parentObject->findByUserID ("bus", id)); id = std::stoi (tokens[2]); Generator *gen = bus->getGen (id - 1); auto params = str2vector (tokens, kNullVal); GenModel *sm = static_cast<GenModel *> (cof->createObject ("genmodel", "6")); sm->set ("tdop", params[3]); sm->set ("tdopp", params[4]); sm->set ("tqop", params[5]); sm->set ("tqopp", params[6]); sm->set ("h", params[7]); sm->set ("d", params[8]); sm->set ("xd", params[9]); sm->set ("xq", params[10]); sm->set ("xdp", params[11]); sm->set ("xqp", params[12]); sm->set ("xdpp", params[13]); sm->set ("xqpp", params[13]); sm->set ("xl", params[14]); sm->set ("s1", params[15]); sm->set ("s12", params[16]); gen->add (sm); } void loadESDC1A (coreObject *parentObject, stringVec &tokens) { int id = std::stoi (tokens[0]); gridBus *bus = static_cast<gridBus *> (parentObject->findByUserID ("bus", id)); id = std::stoi (tokens[2]); Generator *gen = bus->getGen (id - 1); auto params = str2vector (tokens, kNullVal); Exciter *sm; if (params[6] > 0.0) // dc1a model must have tb>0 otherwise revert to type1 { sm = static_cast<Exciter *> (cof->createObject ("exciter", "dc1a")); } else { sm = static_cast<Exciter *> (cof->createObject ("exciter", "type1")); } // TODO:: TR not implemented yet, no voltage compensation implemented // sm->set("tr", params[3]); sm->set ("ka", params[4]); sm->set ("ta", params[5]); if (params[6] > 0) { sm->set ("tb", params[6]); sm->set ("tc", params[7]); } sm->set ("vrmax", params[8]); sm->set ("vrmin", params[9]); sm->set ("ke", params[10]); sm->set ("te", params[11]); sm->set ("kf", params[12]); sm->set ("tf", params[13]); // TODO I need to compute the saturation coefficients to translate appropriately gen->add (sm); } void loadEXDC2 (coreObject *parentObject, stringVec &tokens) { int id = std::stoi (tokens[0]); gridBus *bus = static_cast<gridBus *> (parentObject->findByUserID ("bus", id)); id = std::stoi (tokens[2]); Generator *gen = bus->getGen (id - 1); auto params = str2vector (tokens, kNullVal); Exciter *sm = static_cast<Exciter *> (cof->createObject ("exciter", "dc2a")); // TODO:: TR not implemented yet, no voltage compensation implemented // sm->set("tr", params[3]); sm->set ("ka", params[4]); sm->set ("ta", params[5]); sm->set ("tb", params[6]); sm->set ("tc", params[7]); sm->set ("vrmax", params[8]); sm->set ("vrmin", params[9]); sm->set ("ke", params[10]); sm->set ("te", params[11]); sm->set ("kf", params[12]); sm->set ("tf", params[13]); // TODO I need to compute the saturation coefficients to translate appropriately gen->add (sm); } void loadTGOV1 (coreObject *parentObject, stringVec &tokens) { int id = std::stoi (tokens[0]); gridBus *bus = static_cast<gridBus *> (parentObject->findByUserID ("bus", id)); id = std::stoi (tokens[2]); Generator *gen = bus->getGen (id - 1); auto params = str2vector (tokens, kNullVal); Governor *sm = static_cast<Governor *> (cof->createObject ("governor", "tgov1")); // TODO:: TR not implemented yet, no voltage compensation implemented // sm->set("tr", params[3]); sm->set ("r", params[3]); sm->set ("t1", params[4]); sm->set ("pmax", params[5]); sm->set ("pmin", params[6]); sm->set ("t2", params[6]); sm->set ("t3", params[7]); sm->set ("dt", params[8]); gen->add (sm); } }//namespace griddyn