blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
941 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
142 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
121 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
c4cc0b1282c2884f653bdb20750e35d36ac2f20c
c080549fb807238a22d14f2ea0b0e805a0db3b21
/MainMenuState.cpp
050cec4438394ecd432d59c7d400f11a9337d76b
[]
no_license
bodaiboka/sdldemo
d41c17efb63f9efdf98d7fecbb38e8046febf9d2
91a186e0a6f90a6e32cc4974299e1448883a335a
refs/heads/master
2021-01-20T06:47:20.934711
2017-09-08T18:20:04
2017-09-08T18:20:04
101,518,553
0
0
null
null
null
null
UTF-8
C++
false
false
1,929
cpp
#include <iostream> #include "Game.h" #include "MenuButton.h" #include "PlayState.h" #include "HeliState.h" #include "MainMenuState.h" #include "StateParser.h" const std::string MainMenuState::s_menuId = "MENU"; MainMenuState::MainMenuState() { } MainMenuState::~MainMenuState() { } void MainMenuState::update() { // todo for (GameObject* pGameObject : m_gameObjects) { pGameObject->update(); } } void MainMenuState::render() { for (GameObject* pGameObject : m_gameObjects) { pGameObject->draw(); } } bool MainMenuState::onEnter() { StateParser stateParser; stateParser.parseState("assets/data.xml", s_menuId, &m_gameObjects, &m_textureIdList); m_callbacks.push_back(0); m_callbacks.push_back(s_menuToPlay); m_callbacks.push_back(s_menuToHeli); m_callbacks.push_back(s_exitFromMenu); setCallbacks(m_callbacks); std::cout << "entering menuState\n"; return true; } bool MainMenuState::onExit() { for (GameObject* pGameObject : m_gameObjects) { pGameObject->clean(); } m_gameObjects.clear(); for (int i = 0; i < m_textureIdList.size(); i++) { TextureManager::Instance()->clearFromTextureMap(m_textureIdList[i]); } std::cout << "exiting menuState\n"; return true; } void MainMenuState::s_menuToPlay() { std::cout << "play button clicked\n"; Game::Instance()->getStateMachine()->changeState(new PlayState()); } void MainMenuState::s_exitFromMenu() { std::cout << "exit button clicked\n"; Game::Instance()->quit(); } void MainMenuState::s_menuToHeli() { std::cout << "Heli button clicked\n"; Game::Instance()->getStateMachine()->changeState(new HeliState()); } void MainMenuState::setCallbacks(const std::vector<Callback>& callbacks) { for (int i = 0; i < m_gameObjects.size(); i++) { if (dynamic_cast<MenuButton*>(m_gameObjects[i])) { MenuButton* pButton = dynamic_cast<MenuButton*>(m_gameObjects[i]); pButton->setCallback(callbacks[pButton->getCallbackId()]); } } }
daebb8b8cdd6edb2e5f4b892d37ccf35a22c83f0
3b4822ffbda76e8b8f5503746d356da8c3d02ddb
/engine/digest/md5.h
080fafaf1b532c5ba0d32810fc136a40562f666f
[ "MIT" ]
permissive
fcarreiro/genesis
e8982e3c5a9567de3551f83c2e31adbfb7b967a7
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
refs/heads/master
2021-01-10T12:12:09.401644
2016-03-29T17:44:52
2016-03-29T17:44:52
54,992,295
0
0
null
null
null
null
UTF-8
C++
false
false
1,211
h
#ifndef __MD5_H__ #define __MD5_H__ ////////////////////////////////////////////////////////////////////////// // MD5 class ////////////////////////////////////////////////////////////////////////// class CDigestMd5 : public CDigest { public: // default constructor CDigestMd5(); virtual ~CDigestMd5(); public: // initializes the hashing machine virtual bool Initialize(); // appends a string virtual bool Append(const std::string & str); // appends an unknown ptr virtual bool Append(unsigned char *ptr, unsigned long length); // finishes the hash virtual bool Finish(); // get the digest in binary format virtual bool GetDigest(char **ptr); // get the digest in binary format virtual bool GetDigest(std::string & str); // get the digest in hex format virtual bool GetDigestHex(char **ptr); // get the digest in hex format virtual bool GetDigestHex(std::string & str); private: // md5 state md5_state_t m_State; // md5 digest unsigned char m_Digest[16]; }; ////////////////////////////////////////////////////////////////////////// // End ////////////////////////////////////////////////////////////////////////// #endif
8053924328b99e18b05ea488ae7eed67a785bb08
ab0a8234e443a6aa152b9f7b135a1e2560e9db33
/Server/CGSF/CGSFTest/BaseLayerTest/DataStructureTest.cpp
a219e13d3696891b41b832028b448a8a47be3987
[]
no_license
zetarus/Americano
71c358d8d12b144c8858983c23d9236f7d0e941b
b62466329cf6f515661ef9fb9b9d2ae90a032a60
refs/heads/master
2023-04-08T04:26:29.043048
2018-04-19T11:21:14
2018-04-19T11:21:14
104,159,178
9
2
null
2023-03-23T12:10:51
2017-09-20T03:11:44
C++
UHC
C++
false
false
1,333
cpp
////////////////////////////////////////////////////////////////////// //게임 프로그래머를 위한 자료구조와 알고리즘 소스 테스트 ////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "DataStructureTest.h" #include "Array2D.h" #include "Queue.h" #include "Heap.h" using namespace CGBase; int CompareIntDescending( int left, int right ) { if( left < right ) return 1; if( left > right) return -1; return 0; } DataStructureTest::DataStructureTest(void) { } DataStructureTest::~DataStructureTest(void) { } bool DataStructureTest::Run() { ///////////////////////////////// //Array Test ///////////////////////////////// Array2D<int> Array2D_( 5, 4 ); (*Array2D_.Get(4,3)) = 5; int* ArrayValue = Array2D_.Get(4,3); SFASSERT(*ArrayValue == 5); ///////////////////////////////// //Queue Test ///////////////////////////////// LQueue<int> Queue; int Data = 5; Queue.Enqueue(Data); Queue.Enqueue(Data); ///////////////////////////////// //Heap Test ///////////////////////////////// Heap<int> IntHeap( 100, CompareIntDescending ); Data = 7; IntHeap.Enqueue(Data); Data = 10; IntHeap.Enqueue(Data); Data = 8; IntHeap.Enqueue(Data); int HeapTop = IntHeap.Item(); SFASSERT(HeapTop == 7); return true; }
66da49ad572b5fdf8c0b62780cc903c1c96f7831
ce1e8b29ffd9d97ffc5c693fe3bd4ee358b5e1d5
/src/ExtFileHdf5/HDF5/HDF5_Array.cpp
8a9b19e9d01f38757842bf33eddfcc6a871935a8
[ "MIT" ]
permissive
voxie-viewer/voxie
d76fe7d3990b14dea34e654378d82ddeb48f6445
2b4f23116ab1c2fd44b134c4265a59987049dcdb
refs/heads/master
2023-04-14T13:30:18.668070
2023-04-04T10:58:24
2023-04-04T10:58:24
60,341,017
6
1
MIT
2022-11-29T06:52:16
2016-06-03T10:50:54
C++
UTF-8
C++
false
false
1,143
cpp
/* * Copyright (c) 2013 Steffen Kieß * * 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 "Array.hpp"
35d8bf466645d01e2a7ae12971c58d6c31a591a0
2baa02e126332491b6cbfd96f6f68b39dc6dab17
/src/FFRooModelHist.cxx
89379d9bf9323d94ce993207aa60727893ac3229
[]
no_license
werthm/FooFit
c2441027468a6715608c2b3ae395efe839e42268
79ade7da98fc4187941b939f6a5f551c938c8593
refs/heads/master
2021-01-10T01:40:23.687754
2020-04-05T13:38:14
2020-04-05T13:38:14
47,331,402
0
0
null
null
null
null
UTF-8
C++
false
false
13,557
cxx
/************************************************************************* * Author: Dominik Werthmueller, 2015-2019 *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // FFRooModelHist // // // // Class representing a model from a histogram for RooFit. // // // ////////////////////////////////////////////////////////////////////////// #include "TH2.h" #include "TH3.h" #include "TTree.h" #include "RooRealVar.h" #include "RooDataHist.h" #include "RooHistPdf.h" #include "RooGaussModel.h" #include "RooFFTConvPdf.h" #include "FFRooModelHist.h" ClassImp(FFRooModelHist) //______________________________________________________________________________ FFRooModelHist::FFRooModelHist(const Char_t* name, const Char_t* title, TH1* hist, Bool_t gaussConvol, Int_t intOrder) : FFRooModel(name, title, gaussConvol ? hist->GetDimension() * 2 : 0) { // Constructor. // init members fNDim = hist->GetDimension(); fHist = hist; fTree = 0; fWeightVar = ""; fInterpolOrder = intOrder; fDataHist = 0; fIsConvol = gaussConvol; if (fIsConvol) AddGaussConvolPars(); } //______________________________________________________________________________ FFRooModelHist::FFRooModelHist(const Char_t* name, const Char_t* title, Int_t nDim, TTree* tree, const Char_t* weightVar, Bool_t gaussConvol, Int_t intOrder) : FFRooModel(name, title, gaussConvol ? nDim * 2 : 0) { // Constructor. // init members fNDim = nDim; fHist = 0; fTree = tree; fWeightVar = ""; fInterpolOrder = intOrder; if (weightVar) fWeightVar = weightVar; fDataHist = 0; fIsConvol = gaussConvol; if (fIsConvol) AddGaussConvolPars(); } //______________________________________________________________________________ FFRooModelHist::FFRooModelHist(const Char_t* name, const Char_t* title, Int_t nDim, TTree* tree, RooAbsReal** convolPar, const Char_t* weightVar, Int_t intOrder) : FFRooModel(name, title, nDim * 2) { // Constructor. // init members fNDim = nDim; fHist = 0; fTree = tree; fWeightVar = ""; fInterpolOrder = intOrder; if (weightVar) fWeightVar = weightVar; fDataHist = 0; fIsConvol = kTRUE; // set Gaussian convolution parameters for (Int_t i = 0; i < fNPar; i++) fPar[i] = convolPar[i]; } //______________________________________________________________________________ FFRooModelHist::~FFRooModelHist() { // Destructor. if (fHist) delete fHist; if (fTree) delete fTree; if (fDataHist) delete fDataHist; } //______________________________________________________________________________ void FFRooModelHist::DetermineHistoBinning(RooRealVar* var, RooRealVar* par, Int_t* nBin, Double_t* min, Double_t* max) { // Determine the binning of the histogram used to construct the pdf for // the variable 'var' taking into account the parameter 'par'. // Return the number of bins and the lower and upper bounds via 'nBin', // 'min', and 'max', respectively. // calculate the binning RooAbsBinning& binning = var->getBinning(); Double_t binw = binning.averageBinWidth(); // different binning if convolution is used if (fIsConvol) { // extend range due to bias parameter Double_t lmin = TMath::Min(binning.lowBound(), TMath::Min(binning.lowBound() - par->getMin(), binning.lowBound() - par->getMax())); Double_t lmax = TMath::Max(binning.highBound(), TMath::Max(binning.highBound() - par->getMin(), binning.highBound() - par->getMax())); *min = binning.lowBound() - binw; *max = binning.highBound() + binw; // extend range to original binning while (*min > lmin) *min -= binw; while (*max < lmax) *max += binw; *nBin = (*max - *min) / binw; } else { *min = binning.lowBound() - binw; *max = binning.highBound() + binw; *nBin = binning.numBins() + 2; } } //______________________________________________________________________________ void FFRooModelHist::AddGaussConvolPars() { // Init the parameters for the Gaussian convolution. // loop over dimensions for (Int_t i = 0; i < fNDim; i++) { // add convolution parameters TString tmp; tmp = TString::Format("%s_%d_Conv_GMean", GetName(), i); AddParameter(2*i, tmp.Data(), tmp.Data()); tmp = TString::Format("%s_%d_Conv_GSigma", GetName(), i); AddParameter(2*i+1, tmp.Data(), tmp.Data()); } } //______________________________________________________________________________ void FFRooModelHist::BuildModel(RooAbsReal** vars) { // Build the model using the variables 'vars'. // prepare variable set RooArgSet varSet; for (Int_t i = 0; i < fNDim; i++) varSet.add(*vars[i]); // check if variables can be down-casted for (Int_t i = 0; i < fNDim; i++) { if (!vars[i]->InheritsFrom("RooRealVar")) { Error("BuildModel", "Variable '%s' is not of type RooRealVar!", vars[i]->GetName()); return; } } // check if parameters can be down-casted for (Int_t i = 0; i < fNPar; i++) { if (!fPar[i]->InheritsFrom("RooRealVar")) { Error("BuildModel", "Parameter '%s' is not of type RooRealVar!", fPar[i]->GetName()); return; } } // create binned input data if (!fHist && fTree) { // check dimension if (fNDim == 1) { // calculate the binning Int_t nbin_0 = 0; Double_t min_0 = 0, max_0 = 0; if (fIsConvol) DetermineHistoBinning((RooRealVar*)vars[0], (RooRealVar*)fPar[0], &nbin_0, &min_0, &max_0); else DetermineHistoBinning((RooRealVar*)vars[0], 0, &nbin_0, &min_0, &max_0); // create the histogram fHist = new TH1F(TString::Format("hist_%s_%s", vars[0]->GetName(), GetName()).Data(), TString::Format("Histogram variable '%s' of species '%s'", vars[0]->GetTitle(), GetTitle()).Data(), nbin_0, min_0, max_0); // fill the histogram fTree->Draw(TString::Format("%s>>hist_%s_%s", vars[0]->GetName(), vars[0]->GetName(), GetName()).Data(), fWeightVar.Data()); } else if (fNDim == 2) { // calculate the binning Int_t nbin_0 = 0; Int_t nbin_1 = 0; Double_t min_0 = 0, max_0 = 0; Double_t min_1 = 0, max_1 = 0; if (fIsConvol) { DetermineHistoBinning((RooRealVar*)vars[0], (RooRealVar*)fPar[0], &nbin_0, &min_0, &max_0); DetermineHistoBinning((RooRealVar*)vars[1], (RooRealVar*)fPar[2], &nbin_1, &min_1, &max_1); } else { DetermineHistoBinning((RooRealVar*)vars[0], 0, &nbin_0, &min_0, &max_0); DetermineHistoBinning((RooRealVar*)vars[1], 0, &nbin_1, &min_1, &max_1); } // create the histogram fHist = new TH2F(TString::Format("hist_%s_%s_%s", vars[0]->GetName(), vars[1]->GetName(), GetName()).Data(), TString::Format("Histogram variables '%s' and '%s' of species '%s'", vars[0]->GetTitle(), vars[1]->GetTitle(), GetTitle()).Data(), nbin_0, min_0, max_0, nbin_1, min_1, max_1); // fill the histogram fTree->Draw(TString::Format("%s:%s>>hist_%s_%s_%s", vars[1]->GetName(), vars[0]->GetName(), vars[0]->GetName(), vars[1]->GetName(), GetName()).Data(), fWeightVar.Data()); } else if (fNDim == 3) { // calculate the binning Int_t nbin_0 = 0; Int_t nbin_1 = 0; Int_t nbin_2 = 0; Double_t min_0 = 0, max_0 = 0; Double_t min_1 = 0, max_1 = 0; Double_t min_2 = 0, max_2 = 0; if (fIsConvol) { DetermineHistoBinning((RooRealVar*)vars[0], (RooRealVar*)fPar[0], &nbin_0, &min_0, &max_0); DetermineHistoBinning((RooRealVar*)vars[1], (RooRealVar*)fPar[2], &nbin_1, &min_1, &max_1); DetermineHistoBinning((RooRealVar*)vars[2], (RooRealVar*)fPar[4], &nbin_2, &min_2, &max_2); } else { DetermineHistoBinning((RooRealVar*)vars[0], 0, &nbin_0, &min_0, &max_0); DetermineHistoBinning((RooRealVar*)vars[1], 0, &nbin_1, &min_1, &max_1); DetermineHistoBinning((RooRealVar*)vars[2], 0, &nbin_2, &min_2, &max_2); } // create the histogram fHist = new TH3F(TString::Format("hist_%s_%s_%s_%s", vars[0]->GetName(), vars[1]->GetName(), vars[2]->GetName(), GetName()).Data(), TString::Format("Histogram variables '%s', '%s' and '%s' of species '%s'", vars[0]->GetTitle(), vars[1]->GetTitle(), vars[2]->GetTitle(), GetTitle()).Data(), nbin_0, min_0, max_0, nbin_1, min_1, max_1, nbin_2, min_2, max_2); // fill the histogram fTree->Draw(TString::Format("%s:%s:%s>>hist_%s_%s_%s_%s", vars[2]->GetName(), vars[1]->GetName(), vars[0]->GetName(), vars[0]->GetName(), vars[1]->GetName(), vars[2]->GetName(), GetName()).Data(), fWeightVar.Data()); } else { Error("BuildModel", "Cannot convert unbinned input data of dimension %d!", fNDim); return; } } // backup binning of variables Int_t vbins[fNDim]; Double_t vmin[fNDim]; Double_t vmax[fNDim]; for (Int_t i = 0; i < fNDim; i++) { vbins[i] = ((RooRealVar*)vars[i])->getBinning().numBins(); vmin[i] = ((RooRealVar*)vars[i])->getBinning().lowBound(); vmax[i] = ((RooRealVar*)vars[i])->getBinning().highBound(); } // extend variables to range of histogram TAxis* haxes[3] = { fHist->GetXaxis(), fHist->GetYaxis(), fHist->GetZaxis() }; for (Int_t i = 0; i < fNDim; i++) { ((RooRealVar*)vars[i])->setBins(haxes[i]->GetNbins()); ((RooRealVar*)vars[i])->setMin(haxes[i]->GetXmin()); ((RooRealVar*)vars[i])->setMax(haxes[i]->GetXmax()); } // create RooFit histogram if (fDataHist) delete fDataHist; fDataHist = new RooDataHist(TString::Format("%s_RooFit", fHist->GetName()), TString::Format("%s (RooFit)", fHist->GetTitle()), varSet, RooFit::Import(*fHist)); // restore binning of variables for (Int_t i = 0; i < fNDim; i++) { ((RooRealVar*)vars[i])->setBins(vbins[i]); ((RooRealVar*)vars[i])->setMin(vmin[i]); ((RooRealVar*)vars[i])->setMax(vmax[i]); } // create the model pdf if (fPdf) delete fPdf; if (fIsConvol) { // delete old pdfs if (fPdfIntr) delete fPdfIntr; if (fPdfConv) delete fPdfConv; // create pdfs TString tmp; tmp = TString::Format("%s_Conv_Intr", GetName()); fPdfIntr = new RooHistPdf(tmp.Data(), tmp.Data(), varSet, *fDataHist, fInterpolOrder); tmp = TString::Format("%s_Conv_Gauss", GetName()); fPdfConv = new RooGaussModel(tmp.Data(), tmp.Data(), *((RooRealVar*)vars[0]), *fPar[0], *fPar[1]); ((RooRealVar*)vars[0])->setBins(10000, "cache"); fPdf = new RooFFTConvPdf(GetName(), GetTitle(), *((RooRealVar*)vars[0]), *fPdfIntr, *fPdfConv); } else { // create pdf fPdf = new RooHistPdf(GetName(), GetTitle(), varSet, *fDataHist, fInterpolOrder); } }
66536cf940bd5ef3a95d69e3f0ae9420fea01325
64dccd45009486beb7c7f9595bfaa16f9442dc05
/BaseLib/task/sequence_manager/task_queue_selector.cpp
e450659c51504b2c08d9f90034da8a1a8c83fbcc
[]
no_license
xjyu007/BaseLib
cbb2d1baa32012a0bce1a33579336b8f93e722f2
46985fd2551f9e16619f361559c5a8c3a08c6ec5
refs/heads/master
2020-07-16T10:27:18.854060
2019-10-18T08:25:25
2019-10-18T08:25:25
205,770,219
1
1
null
null
null
null
UTF-8
C++
false
false
10,381
cpp
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "task/sequence_manager/task_queue_selector.h" #include <utility> #include "logging.h" #include "task/sequence_manager/associated_thread_id.h" #include "task/sequence_manager/task_queue_impl.h" #include "task/sequence_manager/work_queue.h" #include "threading/thread_checker.h" #include "trace_event/traced_value.h" namespace base::sequence_manager::internal { constexpr const int64_t TaskQueueSelector::per_priority_starvation_tolerance_[]; TaskQueueSelector::TaskQueueSelector( scoped_refptr<AssociatedThreadId> associated_thread, const SequenceManager::Settings& settings) : associated_thread_(std::move(associated_thread)), #if DCHECK_IS_ON() random_task_selection_(settings.random_task_selection_seed != 0), #endif anti_starvation_logic_for_priorities_disabled_( settings.anti_starvation_logic_for_priorities_disabled), delayed_work_queue_sets_("delayed", this, settings), immediate_work_queue_sets_("immediate", this, settings) {} TaskQueueSelector::~TaskQueueSelector() = default; void TaskQueueSelector::AddQueue(TaskQueueImpl* queue) { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); DCHECK(queue->IsQueueEnabled()); AddQueueImpl(queue, TaskQueue::kNormalPriority); } void TaskQueueSelector::RemoveQueue(TaskQueueImpl* queue) { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); if (queue->IsQueueEnabled()) { RemoveQueueImpl(queue); } } void TaskQueueSelector::EnableQueue(TaskQueueImpl* queue) { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); DCHECK(queue->IsQueueEnabled()); AddQueueImpl(queue, queue->GetQueuePriority()); if (task_queue_selector_observer_) task_queue_selector_observer_->OnTaskQueueEnabled(queue); } void TaskQueueSelector::DisableQueue(TaskQueueImpl* queue) { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); DCHECK(!queue->IsQueueEnabled()); RemoveQueueImpl(queue); } void TaskQueueSelector::SetQueuePriority(TaskQueueImpl* queue, TaskQueue::QueuePriority priority) { DCHECK_LT(priority, TaskQueue::kQueuePriorityCount); DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); if (queue->IsQueueEnabled()) { ChangeSetIndex(queue, priority); } else { // Disabled queue is not in any set so we can't use ChangeSetIndex here // and have to assign priority for the queue itself. queue->delayed_work_queue()->AssignSetIndex(priority); queue->immediate_work_queue()->AssignSetIndex(priority); } DCHECK_EQ(priority, queue->GetQueuePriority()); } TaskQueue::QueuePriority TaskQueueSelector::NextPriority( TaskQueue::QueuePriority priority) { DCHECK(priority < TaskQueue::kQueuePriorityCount); return static_cast<TaskQueue::QueuePriority>(static_cast<int>(priority) + 1); } void TaskQueueSelector::AddQueueImpl(TaskQueueImpl* queue, TaskQueue::QueuePriority priority) { #if DCHECK_IS_ON() DCHECK(!CheckContainsQueueForTest(queue)); #endif delayed_work_queue_sets_.AddQueue(queue->delayed_work_queue(), priority); immediate_work_queue_sets_.AddQueue(queue->immediate_work_queue(), priority); #if DCHECK_IS_ON() DCHECK(CheckContainsQueueForTest(queue)); #endif } void TaskQueueSelector::ChangeSetIndex(TaskQueueImpl* queue, TaskQueue::QueuePriority priority) { #if DCHECK_IS_ON() DCHECK(CheckContainsQueueForTest(queue)); #endif delayed_work_queue_sets_.ChangeSetIndex(queue->delayed_work_queue(), priority); immediate_work_queue_sets_.ChangeSetIndex(queue->immediate_work_queue(), priority); #if DCHECK_IS_ON() DCHECK(CheckContainsQueueForTest(queue)); #endif } void TaskQueueSelector::RemoveQueueImpl(TaskQueueImpl* queue) { #if DCHECK_IS_ON() DCHECK(CheckContainsQueueForTest(queue)); #endif delayed_work_queue_sets_.RemoveQueue(queue->delayed_work_queue()); immediate_work_queue_sets_.RemoveQueue(queue->immediate_work_queue()); #if DCHECK_IS_ON() DCHECK(!CheckContainsQueueForTest(queue)); #endif } int64_t TaskQueueSelector::GetSortKeyForPriority( TaskQueue::QueuePriority priority) const { switch (priority) { case TaskQueue::kControlPriority: return std::numeric_limits<int64_t>::min(); case TaskQueue::kBestEffortPriority: return std::numeric_limits<int64_t>::max(); default: if (anti_starvation_logic_for_priorities_disabled_) return per_priority_starvation_tolerance_[priority]; return selection_count_ + per_priority_starvation_tolerance_[priority]; } } void TaskQueueSelector::WorkQueueSetBecameEmpty(size_t set_index) { non_empty_set_counts_[set_index]--; DCHECK_GE(non_empty_set_counts_[set_index], 0); // There are no delayed or immediate tasks for |set_index| so remove from // |active_priorities_|. if (non_empty_set_counts_[set_index] == 0) active_priorities_.erase(static_cast<TaskQueue::QueuePriority>(set_index)); } void TaskQueueSelector::WorkQueueSetBecameNonEmpty(size_t set_index) { non_empty_set_counts_[set_index]++; DCHECK_LE(non_empty_set_counts_[set_index], kMaxNonEmptySetCount); // There is now a delayed or an immediate task for |set_index|, so add to // |active_priorities_|. if (non_empty_set_counts_[set_index] == 1) { const auto priority = static_cast<TaskQueue::QueuePriority>(set_index); active_priorities_.insert(GetSortKeyForPriority(priority), priority); } } void TaskQueueSelector::CollectSkippedOverLowerPriorityTasks( const WorkQueue* selected_work_queue, std::vector<const Task*>* result) const { delayed_work_queue_sets_.CollectSkippedOverLowerPriorityTasks( selected_work_queue, result); immediate_work_queue_sets_.CollectSkippedOverLowerPriorityTasks( selected_work_queue, result); } #if DCHECK_IS_ON() || !defined(NDEBUG) bool TaskQueueSelector::CheckContainsQueueForTest( const TaskQueueImpl * queue) const { bool contains_delayed_work_queue = delayed_work_queue_sets_.ContainsWorkQueueForTest( queue->delayed_work_queue()); bool contains_immediate_work_queue = immediate_work_queue_sets_.ContainsWorkQueueForTest( queue->immediate_work_queue()); DCHECK_EQ(contains_delayed_work_queue, contains_immediate_work_queue); return contains_delayed_work_queue; } #endif WorkQueue* TaskQueueSelector::SelectWorkQueueToService() { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); if (active_priorities_.empty()) return nullptr; // Select the priority from which we will select a task. Usually this is // the highest priority for which we have work, unless we are starving a lower // priority. const auto priority = active_priorities_.min_id(); bool chose_delayed_over_immediate; // Control tasks are allowed to indefinitely stave out other work and any // control tasks we run should not be counted for task starvation purposes. if (priority != TaskQueue::kControlPriority) selection_count_++; WorkQueue* queue = #if DCHECK_IS_ON() random_task_selection_ ? ChooseWithPriority<SetOperationRandom>( priority, &chose_delayed_over_immediate) : #endif ChooseWithPriority<SetOperationOldest>( priority, &chose_delayed_over_immediate); // If we still have any tasks remaining for |set_index| then adjust it's // sort key. if (active_priorities_.IsInQueue(priority)) active_priorities_.ChangeMinKey(GetSortKeyForPriority(priority)); if (chose_delayed_over_immediate) { immediate_starvation_count_++; } else { immediate_starvation_count_ = 0; } return queue; } void TaskQueueSelector::AsValueInto(trace_event::TracedValue* state) const { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); state->SetInteger("immediate_starvation_count", immediate_starvation_count_); } void TaskQueueSelector::SetTaskQueueSelectorObserver(Observer* observer) { task_queue_selector_observer_ = observer; } std::optional<TaskQueue::QueuePriority> TaskQueueSelector::GetHighestPendingPriority() const { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); if (active_priorities_.empty()) return std::nullopt; return active_priorities_.min_id(); } void TaskQueueSelector::SetImmediateStarvationCountForTest( size_t immediate_starvation_count) { immediate_starvation_count_ = immediate_starvation_count; } bool TaskQueueSelector::HasTasksWithPriority( TaskQueue::QueuePriority priority) { return !delayed_work_queue_sets_.IsSetEmpty(priority) || !immediate_work_queue_sets_.IsSetEmpty(priority); } TaskQueueSelector::SmallPriorityQueue::SmallPriorityQueue() { for (size_t i = 0; i < TaskQueue::kQueuePriorityCount; i++) { id_to_index_[i] = kInvalidIndex; } } void TaskQueueSelector::SmallPriorityQueue::insert( int64_t key, TaskQueue::QueuePriority id) { DCHECK_LE(size_, TaskQueue::kQueuePriorityCount); DCHECK_LT(id, TaskQueue::kQueuePriorityCount); DCHECK(!IsInQueue(id)); // Insert while keeping |keys_| sorted. auto i = size_; while (i > 0 && key < keys_[i - 1]) { keys_[i] = keys_[i - 1]; auto moved_id = index_to_id_[i - 1]; index_to_id_[i] = moved_id; id_to_index_[moved_id] = static_cast<uint8_t>(i); i--; } keys_[i] = key; index_to_id_[i] = id; id_to_index_[id] = static_cast<uint8_t>(i); size_++; } void TaskQueueSelector::SmallPriorityQueue::erase(TaskQueue::QueuePriority id) { DCHECK_NE(size_, 0u); DCHECK_LT(id, TaskQueue::kQueuePriorityCount); DCHECK(IsInQueue(id)); // Erase while keeping |keys_| sorted. size_--; for (size_t i = id_to_index_[id]; i < size_; i++) { keys_[i] = keys_[i + 1]; const auto moved_id = index_to_id_[i + 1]; index_to_id_[i] = moved_id; id_to_index_[moved_id] = static_cast<uint8_t>(i); } id_to_index_[id] = kInvalidIndex; } void TaskQueueSelector::SmallPriorityQueue::ChangeMinKey(int64_t new_key) { DCHECK_NE(size_, 0u); const auto id = index_to_id_[0]; size_t i = 0; while ((i + 1) < size_ && keys_[i + 1] < new_key) { keys_[i] = keys_[i + 1]; const auto moved_id = index_to_id_[i + 1]; index_to_id_[i] = moved_id; id_to_index_[moved_id] = static_cast<uint8_t>(i); i++; } keys_[i] = new_key; index_to_id_[i] = id; id_to_index_[id] = static_cast<uint8_t>(i); } } // namespace base
e7c92fe4cb3bd85b39b4193bd66879146016a9c6
b273d8bc40df9e559d637102c4c2c646144c31ff
/src/String.h
966d968e2ce8552cc47c3ba23cbf3a203e576859
[]
no_license
chengfei1995121/ministl
b29f9de01513077718b666442f60dafbdeb17159
05261017d85dcd8897a132b186cb1b4f824fcff5
refs/heads/master
2021-05-12T18:53:25.671942
2018-01-17T09:31:30
2018-01-17T09:31:30
117,078,254
0
0
null
null
null
null
UTF-8
C++
false
false
2,549
h
#ifndef MINISTL_STRING_H #define MINISTL_STRING_H #include<memory> #include<iostream> using namespace std; class String{ public: typedef char value_type; typedef char* iterator; typedef const char* const_iterator; typedef size_t size_type; typedef char* pointer; typedef char& reference; friend ostream &operator<<(ostream &os,const String &s); friend bool operator==(const String &s1,const String &s2); friend bool operator<(const String &s1,const String &s2); friend bool operator<=(const String &s1,const String &s2); friend bool operator>(const String &s1,const String &s2); friend bool operator>=(const String &s1,const String &s2); friend bool operator!=(const String &s1,const String &s2); friend String operator+(const String &s1,const String &s2); friend String operator+(const String &s1,const char *c); friend String operator+(const char *c,const String &s1); String():sstart(nullptr),send(nullptr),scap(nullptr){} String(const String &s1,size_t pos,size_t len=npos); String(const char *c); String(size_t n,char c); String(const String &); String(char *,size_t); String& operator=(const String &); size_t size() const; iterator begin() const; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; iterator end() const; void free(); char &operator[](size_t n); bool empty()const; size_t capacity()const; char at(size_t n); String &operator+=(const String &); String &operator+=(const char *); String &operator+=(const char); void check_size(); void push_back(char c); String &replace(size_t pos,size_t len,const String &); String &insert(size_t pos,const String&); String &insert(size_t pos,const char *); String &insert(size_t pos,size_t n,const char); void clear(); String &erase(size_t pos=0,size_t len=npos); size_t copy(char *,size_t len,size_t pos=0) const; const char *data() const noexcept; size_t find(char c,size_t pos=0) const; size_t find(const String &,size_t pos=0)const; size_t find(const char *,size_t pos=0) const; char &back(); const char &back()const; char &front(); const char &front() const; String substr(size_t pos=0,size_t len=npos) const; void swap(String &); void swap(char *&,char *&); ~String(){ free(); } private: static const size_t npos=-1; static allocator<char> alloc; void reallocate(); char *sstart; char *send; char *scap; }; //allocator<char> String::alloc; #endif
043b80e060c942323a4ea4e27d7fb347e2b485d2
cbb8caed772470637a6a8a576b3062239ce3a35d
/distribution/src/SliderJoint.cpp
131d350d116281439106ef45ca1df714721ec4bc
[]
no_license
Exoamek/GaitSym2019
3c2e4950a572841187638668da4f9ac880b4331d
9dc8c3086ca817f56bab530840c2a762e188261a
refs/heads/master
2023-02-21T16:36:15.852242
2021-01-28T15:23:09
2021-01-28T15:23:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,781
cpp
/* * SliderJoint.cpp * GaitSymODE * * Created by Bill Sellers on 25/05/2012. * Copyright 2012 Bill Sellers. All rights reserved. * */ #include "SliderJoint.h" #include "Simulation.h" #include "Body.h" #include "ode/ode.h" #include <iostream> #include <cmath> #include <sstream> SliderJoint::SliderJoint(dWorldID worldID) : Joint() { setJointID(dJointCreateSlider(worldID, nullptr)); dJointSetData(JointID(), this); dJointSetFeedback(JointID(), JointFeedback()); } SliderJoint::~SliderJoint() { } void SliderJoint::SetSliderAxis(double x, double y, double z) { dVector3 v; v[0] = x; v[1] = y; v[2] = z; dNormalize3(v); dJointSetSliderAxis(JointID(), v[0], v[1], v[2]); } void SliderJoint::GetSliderAxis(dVector3 result) { dJointGetSliderAxis(JointID(), result); } double SliderJoint::GetSliderDistance() { return dJointGetSliderPosition(JointID()) + m_StartDistanceReference; } double SliderJoint::GetSliderDistanceRate() { return dJointGetSliderPositionRate(JointID()); } void SliderJoint::SetStartDistanceReference(double startDistanceReference) { m_StartDistanceReference = startDistanceReference; } void SliderJoint::SetJointStops(double loStop, double hiStop) { if (loStop >= hiStop) throw(__LINE__); // correct for m_StartDistanceReference loStop -= m_StartDistanceReference; hiStop -= m_StartDistanceReference; // note there is safety feature that stops setting incompatible low and high // stops which can cause difficulties. The safe option is to set them twice. dJointSetSliderParam(JointID(), dParamLoStop, loStop); dJointSetSliderParam(JointID(), dParamHiStop, hiStop); dJointSetSliderParam(JointID(), dParamLoStop, loStop); dJointSetSliderParam(JointID(), dParamHiStop, hiStop); // we don't want bouncy stops dJointSetSliderParam(JointID(), dParamBounce, 0); } void SliderJoint::SetStopCFM(double cfm) { dJointSetSliderParam (JointID(), dParamStopCFM, cfm); } void SliderJoint::SetStopERP(double erp) { dJointSetSliderParam (JointID(), dParamStopERP, erp); } void SliderJoint::SetStopSpringDamp(double springConstant, double dampingConstant, double integrationStep) { double ERP = integrationStep * springConstant/(integrationStep * springConstant + dampingConstant); double CFM = 1/(integrationStep * springConstant + dampingConstant); SetStopERP(ERP); SetStopCFM(CFM); } void SliderJoint::SetStopSpringERP(double springConstant, double ERP, double integrationStep) { double CFM = ERP / (integrationStep * springConstant); SetStopERP(ERP); SetStopCFM(CFM); } void SliderJoint::SetStopBounce(double bounce) { dJointSetSliderParam (JointID(), dParamBounce, bounce); } void SliderJoint::Update() { } std::string SliderJoint::dumpToString() { std::stringstream ss; ss.precision(17); ss.setf(std::ios::scientific); if (firstDump()) { setFirstDump(false); ss << "Time\tXA\tYA\tZA\tDistance\tDistanceRate\tFX1\tFY1\tFZ1\tTX1\tTY1\tTZ1\tFX2\tFY2\tFZ2\tTX2\tTY2\tTZ2\n"; } dVector3 a; GetSliderAxis(a); ss << simulation()->GetTime() << "\t" << a[0] << "\t" << a[1] << "\t" << a[2] << "\t" << GetSliderDistance() << "\t" << GetSliderDistanceRate() << "\t" << JointFeedback()->f1[0] << "\t" << JointFeedback()->f1[1] << "\t" << JointFeedback()->f1[2] << "\t" << JointFeedback()->t1[0] << "\t" << JointFeedback()->t1[1] << "\t" << JointFeedback()->t1[2] << "\t" << JointFeedback()->f2[0] << "\t" << JointFeedback()->f2[1] << "\t" << JointFeedback()->f2[2] << "\t" << JointFeedback()->t2[0] << "\t" << JointFeedback()->t2[1] << "\t" << JointFeedback()->t2[2] << "\t" << "\n"; return ss.str(); }
aa8dcb37ff5cfb58d8fc5582bff8ed3dcffa10fe
43959ff8574c78b042d92081f9dec8e8c26d761f
/algo/상수.cpp
1453072a4ebaf6875664cddc0331f56ba651e5d0
[]
no_license
yunsangq/algo
00579f827f724e9f9a267f3071f1762d32934116
01fecca52cc528c15dfaebe5fc4ba3d944b6333c
refs/heads/master
2021-04-18T22:47:39.591786
2018-03-30T22:54:50
2018-03-30T22:54:50
126,771,580
0
0
null
null
null
null
UTF-8
C++
false
false
436
cpp
#include <stdio.h> int main() { char s[10] = { 0 }, a[4] = { 0 }, b[4] = { 0 }; int _a = 0, _b = 0; fgets(s, 10, stdin); for (int i = 6; i >= 0; i--) { if (i < 3) { a[2 - i] = s[i]; } else if (i > 3) { b[6 - i] = s[i]; } } int mul = 100; for (int i = 0; i < 3; i++) { _a += (a[i]-'0') * mul; _b += (b[i]-'0') * mul; mul /= 10; } if (_a >= _b) printf("%d\n", _a); else printf("%d\n", _b); return 0; }
3af6453b01ad0855ef36be6cc2ee90ee2869e573
23c1284c85ee214ef18b81588a49d225f0e543f7
/L4/matrix.cpp
ac581c928c600fcc3b69f8482575643e3763b3a6
[]
no_license
mbolinas/220L4
1209a3e9abd7fe1c12703f46472890ef10f230a9
18d70d9c2df4d2121ac5d31770e6f2f76272b6eb
refs/heads/master
2021-07-11T04:36:16.029672
2017-10-12T22:59:19
2017-10-12T22:59:19
106,753,704
0
0
null
null
null
null
UTF-8
C++
false
false
1,002
cpp
/* * matrix.cpp * * Created on: Oct 11, 2017 * Author: Marc */ #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; #include "matrix.hpp" matrix::matrix(){ x = 0; y = 0; make(); } matrix::matrix(int w, int l){ x = w; y = l; make(); } void matrix::make(){ mat = new string*[x]; for(int c = 0; c < x; c++){ mat[c] = new string[y]; } for(int i = 0; i < x; i++){ for(int j = 0; j < y; j++){ mat[i][j] = "0"; } } } void matrix::print(){ for(int i = 0; i < x; i++){ for(int j = 0; j < y; j++){ cout << mat[i][j] << " "; } cout << endl; } cout << endl; } void matrix::add_x(){ int how_many_x_to_give_to_ya = 5; while(how_many_x_to_give_to_ya > 0){ int i = rand() % x; int j = rand() % y; if(mat[i][j] != "x"){ mat[i][j] = "x"; how_many_x_to_give_to_ya--; } } } matrix::~matrix(){ for(int i = 0; i < x; i++){ delete mat[i]; } delete mat; }
c31c089c4eb1d1f09853fd781063a391de8c9f1f
ad006f5c883debb2687436be23e3c096be5bec35
/LeetCode/pass/add_two_numbers.cpp
a397f418bc82480795c9bbd98aa2fd46f4d56748
[]
no_license
Haoson/leetcode
540021a6ac01886f2887b1399eae9d79b081b9ee
d0bf550a360f9b13112cd27029b4ca758d1045ad
refs/heads/master
2021-01-25T03:49:17.411295
2015-03-12T18:22:43
2015-03-12T18:22:43
31,490,075
0
0
null
null
null
null
UTF-8
C++
false
false
1,445
cpp
/************************************************************************* > File Name: add_two_numbers.cpp > Author:Haoson > Created Time: Mon 09 Mar 2015 09:13:11 AM PDT > Description: ************************************************************************/ #include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode dummy(-1);//辅助dummy节点 ListNode *res = &dummy; ListNode* ptr1 = l1,*ptr2 = l2; int carry = 0; while(ptr1||ptr2){ int num = carry+(ptr1?ptr1->val:0)+(ptr2?ptr2->val:0); carry = num/10; num = num%10; res->next = new ListNode(num); res = res->next; if(ptr1)ptr1 = ptr1->next; if(ptr2)ptr2 = ptr2->next; } if(carry>0)res->next = new ListNode(carry);//进位导致位数增多情况 return dummy.next; } }; int main(int argc,char* argv[]){ Solution s; ListNode a(2);ListNode a1(4);ListNode a2(3); a.next = &a1; a1.next = &a2; ListNode b(5);ListNode b1(6);ListNode b2(4); b.next = &b1; b1.next = &b2; ListNode * res = s.addTwoNumbers(&a,&b); while(res){ cout<<res->val<<" "; res = res->next; } cout<<endl; return 0; }
d72ee8c88a960c8c66e0d5edd680740dcb1651a8
2444e0dab75bedfb04fe630eb144e25350726d2a
/examples/SendMeasurement/SendMeasurement.ino
a1861f8b552cae1225d40516c91b046dfb37fd1c
[]
no_license
elpinjo/CumulocityClient
5ccd3d50168d8e1f4a05124f0e148e24cf525972
ae91ac49df1bb0def2042d60087e50f3d63eb57f
refs/heads/master
2021-05-21T14:45:03.773960
2020-12-10T08:12:00
2020-12-10T08:12:00
252,685,057
4
4
null
2020-12-10T08:12:01
2020-04-03T09:15:24
C++
UTF-8
C++
false
false
1,253
ino
#include <CumulocityClient.h> #ifdef ESP8266 #include <ESP8266WiFi.h> #else //ESP32 #include <WiFi.h> #endif const char* ssid = "........"; const char* wifiPassword = "........"; char* host = "xxx.cumulocity.com"; char* username = "........"; // fixed credentials can be registered in the Administration section char* c8yPassword = "........"; // create a user in usermanagement with the "device"role and fill the credentials here char* tenant = "........"; //tenant ID can be found by clicking on your name in the top right corner of Cumulocity char* clientId = "........."; //Should be a unique identifier for this device, e.g. IMEI, MAC address or SerialNumber //uint64_t chipid = ESP.getEfuseMac(); WiFiClient wifiClient; CumulocityClient c8yClient(wifiClient, clientId); void setup() { Serial.begin(115200); WiFi.begin(ssid, wifiPassword); Serial.print("Connecting to WiFi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("connected to wifi"); c8yClient.connect(host, tenant, username, c8yPassword); c8yClient.registerDevice(clientId, "c8y_esp32"); } void loop() { delay(1000); c8yClient.loop(); c8yClient.createMeasurement("Temperature", "T", "20.5", "*C"); }
d4deaf33912f2aa2f9a98a90b79be0ccd51c24fa
2b4ce6a8d61cce6b2c063f6d5c2f6f8a6cbe23f9
/include/Hawk/Math/Detail/Vector.hpp
0c297ab9dd3bc9008dec6952302f7a7ba9896843
[ "MIT" ]
permissive
MikhailGorobets/VolumeRender
ee82f70c2cb499638fefa50ef70c144d28dcbb40
c85f23fe225d1e56e54910752be845b9d1e32860
refs/heads/master
2023-06-25T01:44:15.340185
2023-06-17T09:59:03
2023-06-17T10:49:12
189,657,415
48
17
MIT
2023-06-17T10:49:13
2019-05-31T20:55:59
C++
UTF-8
C++
false
false
11,617
hpp
/* * MIT License * * Copyright(c) 2021 Mikhail Gorobets * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this softwareand 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 noticeand 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. */ #pragma once #include <Hawk/Common/INumberArray.hpp> namespace Hawk::Math::Detail { template<typename T, U32 N> class Vector final: public INumberArray<T, N> { static_assert(std::is_same<T, F32>() || std::is_same<T, F64>() || std::is_same<T, I32>() || std::is_same<T, U32>(), "Invalid scalar type for Vector"); public: constexpr Vector() noexcept = default; constexpr Vector(T v) noexcept; template <typename... Args> constexpr Vector(typename std::enable_if<sizeof...(Args) + 1 == N, T>::type const& head, Args... tail) noexcept; private: T m_Data[N]; }; template<typename T> class Vector<T, 2> final: public INumberArray<T, 2> { static_assert(std::is_same<T, F32>() || std::is_same<T, F64>() || std::is_same<T, I32>() || std::is_same<T, U32>(), "Invalid scalar type for Vector"); public: union { struct { T x, y; }; struct { T r, g; }; struct { T v[2]; }; }; public: constexpr Vector() noexcept = default; constexpr Vector(T v) noexcept; template <typename... Args> constexpr Vector(typename std::enable_if<sizeof...(Args) + 1 == 2, T>::type const& head, Args... tail) noexcept; }; template<typename T> class Vector<T, 3> final: public INumberArray<T, 3> { static_assert(std::is_same<T, F32>() || std::is_same<T, F64>() || std::is_same<T, I32>() || std::is_same<T, U32>(), "Invalid scalar type for Vector"); public: union { struct { T x, y, z; }; struct { T r, g, b; }; struct { T v[3]; }; }; public: constexpr Vector() noexcept = default; constexpr Vector(T v) noexcept; constexpr Vector(Vector<T, 2> const& x, T y) noexcept; template <typename... Args> constexpr Vector(typename std::enable_if<sizeof...(Args) + 1 == 3, T>::type const& head, Args... tail) noexcept; }; template<typename T> class Vector<T, 4> final: public INumberArray<T, 4> { static_assert(std::is_same<T, F32>() || std::is_same<T, F64>() || std::is_same<T, I32>() || std::is_same<T, U32>() || std::is_same<T, I16>() || std::is_same<T, U16>() || std::is_same<T, U8>(), "Invalid scalar type for Vector"); public: union { struct { T x, y, z, w; }; struct { T r, g, b, a; }; struct { T v[4]; }; }; public: constexpr Vector() noexcept = default; constexpr Vector(T v) noexcept; constexpr Vector(Vector<T, 3> const& x, T y) noexcept; constexpr Vector(Vector<T, 2> const& x, T y, T z) noexcept; template <typename... Args> constexpr Vector(typename std::enable_if<sizeof...(Args) + 1 == 4, T>::type const& head, Args... tail) noexcept; }; template<typename T, U32 N> constexpr auto operator==(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->bool; template<typename T, U32 N> constexpr auto operator!=(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->bool; template<typename T, U32 N> constexpr auto operator+(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>; template<typename T, U32 N> constexpr auto operator-(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>; template<typename T, U32 N> constexpr auto operator*(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>; template<typename T, U32 N> constexpr auto operator/(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>; template<typename T, U32 N> constexpr auto operator-(Vector<T, N> const& rhs) noexcept->Vector<T, N>; template<typename T, U32 N> constexpr auto operator*(Vector<T, N> const& lhs, T rhs) noexcept->Vector<T, N>; template<typename T, U32 N> constexpr auto operator*(T lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>; template<typename T, U32 N> constexpr auto operator/(Vector<T, N> const& lhs, T rhs) noexcept->Vector<T, N>; template<typename T, U32 N> constexpr auto operator+=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>&; template<typename T, U32 N> constexpr auto operator-=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>&; template<typename T, U32 N> constexpr auto operator*=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>&; template<typename T, U32 N> constexpr auto operator/=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>&; template<typename T, U32 N> constexpr auto operator*=(Vector<T, N>& lhs, T rhs) noexcept->Vector<T, N>&; template<typename T, U32 N> constexpr auto operator/=(Vector<T, N>& lhs, T rhs) noexcept->Vector<T, N>&; } namespace Hawk::Math::Detail { template<typename T, U32 N> template<typename ...Args> ILINE constexpr Vector<T, N>::Vector(typename std::enable_if<sizeof...(Args) + 1 == N, T>::type const& head, Args ...tail) noexcept : m_Data{head, T{ tail }...} {} template<typename T, U32 N> ILINE constexpr Vector<T, N>::Vector(T v) noexcept { for (auto& e : *this) e = v; } template<typename T> ILINE constexpr Vector<T, 2>::Vector(T v) noexcept : x{v}, y{v} {} template<typename T> ILINE constexpr Vector<T, 3>::Vector(T v) noexcept : x{v}, y{v}, z{v} {} template<typename T> ILINE constexpr Vector<T, 3>::Vector(Vector<T, 2> const& x, T y) noexcept : x{x.x}, y{x.y}, z{y} {} template<typename T> ILINE constexpr Vector<T, 4>::Vector(Vector<T, 3> const& x, T y) noexcept : x{x.x}, y{x.y}, z{x.z}, w{y} {} template<typename T> ILINE constexpr Vector<T, 4>::Vector(Vector<T, 2> const& x, T y, T z) noexcept : x{x.x}, y{x.y}, z{y}, w{z} {} template<typename T> ILINE constexpr Vector<T, 4>::Vector(T v) noexcept : x{v}, y{v}, z{v}, w{v} {} template<typename T> template<typename ...Args> ILINE constexpr Vector<T, 2>::Vector(typename std::enable_if<sizeof...(Args) + 1 == 2, T>::type const& head, Args ...tail) noexcept : v{head, T{ tail }...} {} template<typename T> template<typename ...Args> ILINE constexpr Vector<T, 3>::Vector(typename std::enable_if<sizeof...(Args) + 1 == 3, T>::type const& head, Args ...tail) noexcept : v{head, T{ tail }...} {} template<typename T> template<typename ...Args> ILINE constexpr Vector<T, 4>::Vector(typename std::enable_if<sizeof...(Args) + 1 == 4, T>::type const& head, Args ...tail) noexcept : v{head, T{ tail }...} {} template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator==(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept -> bool { for (auto index = 0u; index < N; index++) if (!(std::abs(lhs[index] - rhs[index]) <= std::numeric_limits<T>::epsilon())) return false; return true; } template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator!=(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept -> bool { return !(lhs == rhs); } template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator+(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept-> Vector<T, N> { auto result = Vector<T, N>{}; for (auto index = 0u; index < N; index++) result[index] = lhs[index] + rhs[index]; return result; } template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator*(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N> { auto result = Vector<T, N>{}; for (auto index = 0; index < N; index++) result[index] = lhs[index] * rhs[index]; return result; } template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator/(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N> { auto result = Vector<T, N>{}; for (auto index = 0; index < N; index++) result[index] = lhs[index] / rhs[index]; return result; } template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator-(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept-> Vector<T, N> { auto result = Vector<T, N>{}; for (auto index = 0u; index < N; index++) result[index] = lhs[index] - rhs[index]; return result; } template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator-(Vector<T, N> const& rhs) noexcept -> Vector<T, N> { auto result = Vector<T, N>{}; for (auto index = 0u; index < N; index++) result[index] = -rhs[index]; return result; } template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator*(T lhs, Vector<T, N> const& rhs) noexcept-> Vector<T, N> { auto result = Vector<T, N>{}; for (auto index = 0; index < N; index++) result[index] = lhs * rhs[index]; return result; } template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator*(Vector<T, N> const& lhs, T rhs) noexcept-> Vector<T, N> { return rhs * lhs; } template<typename T, U32 N> [[nodiscard]] ILINE constexpr auto operator/(Vector<T, N> const& lhs, T rhs) noexcept -> Vector<T, N> { return (T{1} / rhs) * lhs; } template<typename T, U32 N> ILINE constexpr auto operator+=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N>& { lhs = lhs + rhs; return lhs; } template<typename T, U32 N> ILINE constexpr auto operator-=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N>& { lhs = lhs - rhs; return lhs; } template<typename T, U32 N> ILINE constexpr auto operator*=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N>& { lhs = lhs * rhs; return lhs; } template<typename T, U32 N> ILINE constexpr auto operator/=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N>& { lhs = lhs / rhs; return lhs; } template<typename T, U32 N> ILINE constexpr auto operator*=(Vector<T, N>& lhs, T rhs) noexcept -> Vector<T, N>& { lhs = lhs * rhs; return lhs; } template<typename T, U32 N> ILINE constexpr auto operator/=(Vector<T, N>& lhs, T rhs) noexcept -> Vector<T, N>& { lhs = lhs / rhs; return lhs; } }
823e04b79fdae967ccd89d475aa8181988c2710f
1354c730933ce135496f3e6bd50a30983dc81e39
/Ch_8/Ch8_Rev9and10.cpp
033d7450c9133f81b3ce9f51a964c3543b78bf40
[]
no_license
slorello89/PracticeProblems
0ce0dc350ae3417448a53d436ad6bb33fcd946c4
f70e47bee63f8c8488baf8fcd8066d729fc43a7d
refs/heads/master
2022-08-24T07:29:21.575171
2020-05-21T18:19:34
2020-05-21T18:19:34
265,920,529
0
0
null
2020-05-21T18:16:46
2020-05-21T18:16:45
null
UTF-8
C++
false
false
1,150
cpp
//chapter 8 review 9 and 10 works and works :) (work on uppercase sensititvity) #include <iostream> #include <string> #include <vector> using namespace std; string Reverse (string phrase) //reverses a string using arrays { string word; for(int Letter = phrase.length()-1; Letter>=0; Letter --){ word+=phrase[Letter]; } return(word); } string Uppercase(string S) //determines if strings are the same regaurdless of case { for(int Letter=0; Letter<S.length(); Letter++){ if ((S[Letter]>='a')&&(S[Letter]<='z')){ S[Letter] = S[Letter] - 'a' + 'A'; } } return(S); } bool isPalendrom(string word) //determines if something is a palidrome { string reversed = Reverse(word); if(Uppercase(word)==word){ word = Uppercase(word); } return word == reversed; } int main() //calls function { string phrase; cout << "Enter a word to be reversed: "; cin >> phrase; // cout << Reverse(phrase); if(isPalendrom(phrase)){ cout << phrase << " is a palendrome"; } else{ cout << phrase << " is not a palendrome"; } return(0); }
c7914b7b26041b88df4a6ae27df10a64ecb777fc
3a0da4368b6874c297328025b381cb7c7e5233ee
/source/game/field.cpp
9cb440b17a1cfbdd0b22ae7448aa179401b02566
[]
no_license
Unlogicaly/MIPT_task2_memo
7bc173a544c13ead8d4d36af82874251194b944f
330f15ccff5e2dea8a547f49ff8fa801cf204e9a
refs/heads/master
2020-09-08T16:46:14.004445
2019-12-09T17:20:49
2019-12-09T17:20:49
221,187,355
0
0
null
2019-11-23T09:01:46
2019-11-12T10:09:23
null
UTF-8
C++
false
false
3,612
cpp
#include "field.h" #include <algorithm> #include <chrono> #include <random> // Generate shuffled range from 0 to max std::vector<int> rand_range(int max, long long seed = 0) { if (seed == 0) seed = std::chrono::system_clock::now().time_since_epoch().count(); std::vector<int> res(max); for (decltype(res.size()) i = 0; i < res.size(); ++i) { res[i] = static_cast<int>(i); } std::shuffle(res.begin(), res.end(), std::default_random_engine{seed}); return res; } Card *Field::get_card(int x, int y) { return cards[(x - get_side_gap()) / (get_size() + get_shift())][(y - get_up_gap()) / (get_size() + get_shift())]; } Field::Field(bool &_end, int x_resol, int y_resol) : myWin(_end, x_resol, y_resol), opened{nullptr, nullptr} { long long seed = std::chrono::system_clock::now().time_since_epoch().count(); myWin::color(Graph_lib::Color::white); std::vector<std::string> pictures; get_names(pictures); std::shuffle(pictures.begin(), pictures.end(), std::default_random_engine{seed}); std::vector<int> pairs = rand_range(get_height() * get_width(), seed); for (auto i = 0; i < get_width(); ++i) { cards.emplace_back(); for (auto j = 0; j < get_height(); ++j) cards[i].push_back(nullptr); } for (auto i = 0; i < get_height() * get_width(); i += 2) { int i1 = pairs[i] / get_width(), j1 = pairs[i] % get_width(); cards[j1][i1] = new Card(get_point(j1, i1), get_size(), get_pic(pictures[i / 2], get_size(), get_size()), cb_show); attach(*cards[j1][i1]); attach(*cards[j1][i1]->show); int i2 = pairs[i + 1] / get_width(), j2 = pairs[i + 1] % get_width(); cards[j2][i2] = new Card(get_point(j2, i2), get_size(), get_pic(pictures[i / 2], get_size(), get_size()), cb_show); attach(*cards[j2][i2]); attach(*cards[j2][i2]->show); } } void Field::treat_last(Card *last) { for (auto &lines : cards) { for (auto *card : lines) { if (!card->is_found and card != last) { card->is_found = true; last->is_found = true; card->show->hide(); last->show->hide(); card->click(); started = false; return; } } } } void Field::flip(Graph_lib::Address pwin) { Fl_Widget &w = Graph_lib::reference_to<Fl_Widget>(pwin); auto c = get_card(w.x(), w.y()); if (!opened.first) opened.first = c; else if (!opened.second) { if (opened.first == c) return; opened.second = c; } else { if (opened.first->get_name() == opened.second->get_name()) { opened.first->show->hide(); opened.second->show->hide(); opened.first->is_found = true; opened.second->is_found = true; ready++; if (c == opened.first or c == opened.second) { opened.first = nullptr; opened.second = nullptr; return; } } else { opened.first->click(); opened.second->click(); } opened.first = c; opened.second = nullptr; } c->click(); if (ready == get_height() * get_width() / 2 - 1) { treat_last(c); asc(); } Fl::redraw(); } Field::~Field() { for (auto &line : cards) for (auto *card : line) delete card; }
a64ca0915344d733241503014b6e420aa4c49653
e99b3e5153bc6865be1d9a1f592f15599901ae54
/catkin_ws/src/motor_communication/include/motor_communication/motor_communication.h
bcca1143bfd4e806cd3c8518d93ed4f2b9dfcfb7
[]
no_license
AutoModelCar/model_car
dfdc6ac48ade56ee6ca0ac7b477ef85edcb3f091
fed4cef394e412ec1f3aaa51586a6eb7689b4cc7
refs/heads/version-1
2021-01-20T18:19:36.983343
2018-03-29T12:08:02
2018-03-29T12:08:02
62,126,597
8
27
null
2017-09-11T16:04:30
2016-06-28T09:07:07
Makefile
UTF-8
C++
false
false
1,066
h
#include <ros/ros.h> #include <ros/message_operations.h> #include <std_msgs/String.h> #include <std_msgs/Int16.h> #include <std_msgs/Bool.h> #include <string> #include <iostream> #include <cstdio> #include <unistd.h> #include "serial/serial.h" #include <sstream> #include <ros/console.h> #include <sstream> using std::string; using std::exception; using std::cout; using std::cerr; using std::endl; using std::vector; typedef int16_t speed_MMpS_t; class motor_communication { private: //! Node handle in the private namespace ros::NodeHandle priv_nh_; std::string serial_port_;//="/dev/ttySAC2"; int baud_rate_;//=115200; std::string result; size_t bytes_wrote; serial::Serial my_serial; //serial::Serial my_serial; //my_serial(serial_port_, 115200, serial::Timeout::simpleTimeout(1000)); public: motor_communication(); ~motor_communication(); void init(); void run(int speed); void my_sleep(unsigned long milliseconds); void stop(); void start(); double getSpeed(); };
7e3106183688079988a4c8206679ffed0aad98ae
9b7964822100a804450fadfe3cd7ea72180eadcb
/src/qt/askpassphrasedialog.cpp
06d3efa953d4d636477843be05b9c1d7eba55980
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thnass/adeptio
7415d6300e0aec964e2223c4c7b19ea51b173816
65aad9209588e62a3e58d6187a88253d3d5f04b1
refs/heads/master
2020-08-04T03:40:56.444722
2019-10-01T01:28:09
2019-10-01T01:28:09
211,990,234
0
0
MIT
2019-10-01T01:25:17
2019-10-01T01:25:16
null
UTF-8
C++
false
false
11,460
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2019 The Adeptio developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "guiutil.h" #include "walletmodel.h" #include "allocators.h" #include <QKeyEvent> #include <QMessageBox> #include <QPushButton> #include <QWidget> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::AskPassphraseDialog), mode(mode), model(model), context(context), fCapsLock(false) { ui->setupUi(this); this->setStyleSheet(GUIUtil::loadStyleSheet()); ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint()); ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint()); ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint()); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); this->model = model; switch (mode) { case Mode::Encrypt: // Ask passphrase x2 ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.")); ui->passLabel1->hide(); ui->passEdit1->hide(); setWindowTitle(tr("Encrypt wallet")); break; case Mode::UnlockAnonymize: ui->anonymizationCheckBox->show(); case Mode::Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Mode::Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case Mode::ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } // Set checkbox "For anonymization, automint, and staking only" depending on from where we were called if (context == Context::Unlock_Menu || context == Context::Mint_zADE || context == Context::BIP_38) { ui->anonymizationCheckBox->setChecked(true); } else { ui->anonymizationCheckBox->setChecked(false); } // It doesn't make sense to show the checkbox for sending ADE because you wouldn't check it anyway. if (context == Context::Send_ADE || context == Context::Send_zADE) { ui->anonymizationCheckBox->hide(); } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if (!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch (mode) { case Mode::Encrypt: { if (newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR ADE</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval == QMessageBox::Yes) { if (newpass1 == newpass2) { if (model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("ADE will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your ADEs from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Mode::UnlockAnonymize: case Mode::Unlock: if (!model->setWalletLocked(false, oldpass, ui->anonymizationCheckBox->isChecked())) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Mode::Decrypt: if (!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Mode::ChangePass: if (newpass1 == newpass2) { if (model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch (mode) { case Mode::Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Mode::UnlockAnonymize: // Old passphrase x1 case Mode::Unlock: // Old passphrase x1 case Mode::Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case Mode::ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent* event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent* ke = static_cast<QKeyEvent*>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject* object, QEvent* event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent* ke = static_cast<QKeyEvent*>(event); QString str = ke->text(); if (str.length() != 0) { const QChar* psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); }
4e819acf146f27409a91823959b917c370f3fac9
65588b3f0d822485522c820b25e8d2583061027e
/ModularTwoChoice/ModularTwoChoice.ino
762f61c806d27883e6f49be3ba82e5c6e61250b6
[]
no_license
cxrodgers/ArduFSM
7847af6f5b28f9aaf26fa069180474344b6a8bb2
7c582867f5229a1b6f1abd4d58a82cbc360fdcad
refs/heads/master
2022-01-17T13:03:48.802929
2020-04-03T16:05:04
2020-04-03T16:05:04
17,423,002
3
6
null
2016-12-14T20:59:05
2014-03-05T00:52:21
Python
UTF-8
C++
false
false
11,376
ino
/* A two-alternative choice behavior with left and right lick ports. TODO ---- * Move the required states, like TRIAL_START and WAIT_FOR_NEXT_TRIAL, as well as all required variables like flag_start_trial, into TrialSpeak.cpp. * move definitions of trial_params to header file, so can be auto-generated * diagnostics: which state it is in on each call (or subset of calls) Here are the things that the user should have to change for each protocol: * Enum of states * User-defined states in switch statement * param_abbrevs, param_values, tpidx_*, N_TRIAL_PARAMS */ #include "chat.h" #include "hwconstants.h" #include <Servo.h> #ifndef __HWCONSTANTS_H_USE_STEPPER_DRIVER #include <Stepper.h> #endif #include "TimedState.h" #include "States.h" #ifndef __HWCONSTANTS_H_USE_IR_DETECTOR #include "mpr121.h" #include <Wire.h> // also for mpr121 #endif #ifdef __HWCONSTANTS_H_USE_IR_DETECTOR #include "ir_detector.h" #endif // Make this true to generate random responses for debugging #define FAKE_RESPONDER 0 extern char* param_abbrevs[N_TRIAL_PARAMS]; extern long param_values[N_TRIAL_PARAMS]; extern bool param_report_ET[N_TRIAL_PARAMS]; extern char* results_abbrevs[N_TRIAL_RESULTS]; extern long results_values[N_TRIAL_RESULTS]; extern long default_results_values[N_TRIAL_RESULTS]; //// Miscellaneous globals // flag to remember whether we've received the start next trial signal // currently being used in both setup() and loop() so it can't be staticked bool flag_start_trial = 0; //// Declarations int take_action(char *protocol_cmd, char *argument1, char *argument2); //// User-defined variables, etc, go here /// these should all be staticked into loop() STATE_TYPE next_state; // touched monitor uint16_t sticky_touched = 0; // initial position of stim arm .. user must ensure this is correct extern long sticky_stepper_position; /// not sure how to static these since they are needed by both loop and setup // Servo Servo linServo; // Stepper // We won't assign till we know if it's 2pin or 4pin #ifndef __HWCONSTANTS_H_USE_STEPPER_DRIVER Stepper *stimStepper = 0; #endif //// Setup function void setup() { unsigned long time = millis(); int status = 1; Serial.begin(115200); Serial.print(time); Serial.println(" DBG begin setup"); //// Begin user protocol code //// Put this in a user_setup1() function? // MPR121 touch sensor setup #ifndef __HWCONSTANTS_H_USE_IR_DETECTOR pinMode(TOUCH_IRQ, INPUT); digitalWrite(TOUCH_IRQ, HIGH); //enable pullup resistor Wire.begin(); #endif // output pins pinMode(L_REWARD_VALVE, OUTPUT); pinMode(R_REWARD_VALVE, OUTPUT); pinMode(__HWCONSTANTS_H_HOUSE_LIGHT, OUTPUT); pinMode(__HWCONSTANTS_H_BACK_LIGHT, OUTPUT); // initialize the house light to ON digitalWrite(__HWCONSTANTS_H_HOUSE_LIGHT, HIGH); digitalWrite(__HWCONSTANTS_H_BACK_LIGHT, HIGH); // random number seed randomSeed(analogRead(3)); // attach servo linServo.attach(LINEAR_SERVO); //linServo.write(1850); // move close for measuring //// Run communications until we've received all setup info // Later make this a new flag. For now wait for first trial release. while (!flag_start_trial) { status = communications(time); if (status != 0) { Serial.println("comm error in setup"); delay(1000); } } //// Now finalize the setup using the received initial parameters // user_setup2() function? #ifdef __HWCONSTANTS_H_USE_STEPPER_DRIVER pinMode(__HWCONSTANTS_H_STEP_ENABLE, OUTPUT); pinMode(__HWCONSTANTS_H_STEP_PIN, OUTPUT); pinMode(__HWCONSTANTS_H_STEP_DIR, OUTPUT); // Make sure it's off digitalWrite(__HWCONSTANTS_H_STEP_ENABLE, LOW); digitalWrite(__HWCONSTANTS_H_STEP_PIN, LOW); digitalWrite(__HWCONSTANTS_H_STEP_DIR, LOW); #endif #ifndef __HWCONSTANTS_H_USE_STEPPER_DRIVER pinMode(TWOPIN_ENABLE_STEPPER, OUTPUT); pinMode(TWOPIN_STEPPER_1, OUTPUT); pinMode(TWOPIN_STEPPER_2, OUTPUT); // Make sure it's off digitalWrite(TWOPIN_ENABLE_STEPPER, LOW); // Initialize stimStepper = new Stepper(__HWCONSTANTS_H_NUMSTEPS, TWOPIN_STEPPER_1, TWOPIN_STEPPER_2); #endif // Opto (collides with one of the 4-pin setups) pinMode(__HWCONSTANTS_H_OPTO, OUTPUT); digitalWrite(__HWCONSTANTS_H_OPTO, HIGH); // thresholds for MPR121 #ifndef __HWCONSTANTS_H_USE_IR_DETECTOR mpr121_setup(TOUCH_IRQ, param_values[tpidx_TOU_THRESH], param_values[tpidx_REL_THRESH]); #endif #ifndef __HWCONSTANTS_H_USE_STEPPER_DRIVER // Set the speed of the stepper stimStepper->setSpeed(param_values[tpidx_STEP_SPEED]); #endif // initial position of the stepper sticky_stepper_position = param_values[tpidx_STEP_INITIAL_POS]; // linear servo setup linServo.write(param_values[tpidx_SRV_FAR]); delay(param_values[tpidx_SERVO_SETUP_T]); } //// Loop function void loop() { /* Called over and over again. On each call, the behavior is determined by the current state. */ //// Variable declarations // get the current time as early as possible in this function unsigned long time = millis(); static STATE_TYPE current_state = WAIT_TO_START_TRIAL; // The next state, by default the same as the current state next_state = current_state; // misc int status = 1; //// User protocol variables uint16_t touched = 0; //// Run communications status = communications(time); //// User protocol code // could put other user-specified every_loop() stuff here // Poll touch inputs #ifndef __HWCONSTANTS_H_USE_IR_DETECTOR touched = pollTouchInputs(); #endif #ifdef __HWCONSTANTS_H_USE_IR_DETECTOR if (time % 500 == 0) { touched = pollTouchInputs(time, 1); } else { touched = pollTouchInputs(time, 0); } #endif // announce sticky if (touched != sticky_touched) { Serial.print(time); Serial.print(" TCH "); Serial.println(touched); sticky_touched = touched; } //// Begin state-dependent operations // Try to replace every case with a single function or object call // Ultimately this could be a dispatch table. // Also, eventually we'll probably want them to return next_state, // but currently it's generally passed by reference. stateDependentOperations(current_state, time); //// Update the state variable if (next_state != current_state) { Serial.print(time); Serial.print(" ST_CHG "); Serial.print(current_state); Serial.print(" "); Serial.println(next_state); Serial.print(millis()); Serial.print(" ST_CHG2 "); Serial.print(current_state); Serial.print(" "); Serial.println(next_state); } current_state = next_state; return; } //// Take protocol action based on user command (ie, setting variable) int take_action(char *protocol_cmd, char *argument1, char *argument2) { /* Protocol action. Currently two possible actions: if protocol_cmd == 'SET': argument1 is the variable name. argument2 is the data. if protocol_cmd == 'ACT': argument1 is converted into a function based on a dispatch table. REWARD_L : reward the left valve REWARD_R : reward the right valve REWARD : reward the current valve This logic could be incorporated in TrialSpeak, but we would need to provide the abbreviation, full name, datatype, and optional handling logic for each possible variable. So it seems to make more sense here. Return values: 0 - command parsed successfully 2 - unimplemented protocol_cmd 4 - unknown variable on SET command 5 - data conversion error 6 - unknown asynchronous action */ int status; //~ Serial.print("DBG take_action "); //~ Serial.print(protocol_cmd); //~ Serial.print("-"); //~ Serial.print(argument1); //~ Serial.print("-"); //~ Serial.println(argument2); if (strncmp(protocol_cmd, "SET\0", 4) == 0) { // Find index into param_abbrevs int idx = -1; for (int i=0; i < N_TRIAL_PARAMS; i++) { if (strcmp(param_abbrevs[i], argument1) == 0) { idx = i; break; } } // Error if not found, otherwise set if (idx == -1) { Serial.print("ERR param not found "); Serial.println(argument1); return 4; } else { // Convert to int status = safe_int_convert(argument2, param_values[idx]); // Debug //~ Serial.print("DBG setting var "); //~ Serial.print(idx); //~ Serial.print(" to "); //~ Serial.println(argument2); // Error report if (status != 0) { Serial.println("ERR can't set var"); return 5; } } } else if (strncmp(protocol_cmd, "ACT\0", 4) == 0) { // Dispatch if (strncmp(argument1, "REWARD_L\0", 9) == 0) { asynch_action_reward_l(); } else if (strncmp(argument1, "REWARD_R\0", 9) == 0) { asynch_action_reward_r(); } else if (strncmp(argument1, "REWARD\0", 7) == 0) { asynch_action_reward(); } else if (strncmp(argument1, "THRESH\0", 7) == 0) { asynch_action_set_thresh(); } else if (strncmp(argument1, "HLON\0", 5) == 0) { asynch_action_light_on(); } else return 6; } else { // unknown command return 2; } return 0; } int safe_int_convert(char *string_data, long &variable) { /* Check that string_data can be converted to long before setting variable. Returns 1 if string data could not be converted to %d. */ long conversion_var = 0; int status; // Parse into %d // Returns number of arguments successfully parsed status = sscanf(string_data, "%ld", &conversion_var); //~ Serial.print("DBG SIC "); //~ Serial.print(string_data); //~ Serial.print("-"); //~ Serial.print(conversion_var); //~ Serial.print("-"); //~ Serial.print(status); //~ Serial.println("."); if (status == 1) { // Good, we converted one variable variable = conversion_var; return 0; } else { // Something went wrong, probably no variables converted Serial.print("ERR SIC cannot parse -"); Serial.print(string_data); Serial.println("-"); return 1; } } void asynch_action_reward_l() { unsigned long time = millis(); Serial.print(time); Serial.println(" EV AAR_L"); digitalWrite(L_REWARD_VALVE, HIGH); delay(param_values[tpidx_REWARD_DUR_L]); digitalWrite(L_REWARD_VALVE, LOW); } void asynch_action_reward_r() { unsigned long time = millis(); Serial.print(time); Serial.println(" EV AAR_R"); digitalWrite(R_REWARD_VALVE, HIGH); delay(param_values[tpidx_REWARD_DUR_R]); digitalWrite(R_REWARD_VALVE, LOW); } void asynch_action_reward() { if (param_values[tpidx_REWSIDE] == LEFT) asynch_action_reward_l(); else if (param_values[tpidx_REWSIDE] == RIGHT) asynch_action_reward_r(); else Serial.println("ERR unknown rewside"); } void asynch_action_set_thresh() { unsigned long time = millis(); Serial.print(time); Serial.println(" EV AAST"); #ifndef __HWCONSTANTS_H_USE_IR_DETECTOR mpr121_setup(TOUCH_IRQ, param_values[tpidx_TOU_THRESH], param_values[tpidx_REL_THRESH]); #endif } void asynch_action_light_on() { unsigned long time = millis(); Serial.print(time); Serial.println(" EV HLON"); digitalWrite(__HWCONSTANTS_H_HOUSE_LIGHT, HIGH); }
e51a9273650d20294496d17c8147533b97d84669
c9d6cb1013c82eade42d7cdee1db78afec957c20
/Sources/N-body/NBodyComputePrefs.h
9094cf9488e3dadd0ca0a27aab498031b29d77ec
[]
no_license
ooper-shlab/MetalNBody-Swift
0422add7d94b5f3cf2d1bc9abc57c5f5525ec886
621436876e1cffe675bfe0950ecb381408cb75bd
refs/heads/master
2021-01-10T05:57:56.526638
2019-04-20T07:41:05
2019-04-20T07:41:05
48,329,901
2
1
null
null
null
null
UTF-8
C++
false
false
618
h
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: N-Body compute preferences common structure for the kernel and the utility class. */ #ifndef _NBODY_COMPUTE_PREFS_H_ #define _NBODY_COMPUTE_PREFS_H_ #ifdef __cplusplus namespace NBody { namespace Compute { struct Prefs { float timestep; float damping; float softeningSqr; unsigned int particles; }; // Prefs typedef Prefs Prefs; } // Compute } // NBody #endif #endif
bfe0083495af299a41cad0f48a1d23d0cc04d21e
2a02d8873c8825eb3fef2b352fcda238961831c9
/more/codeforces/1662H.cpp
6cf00eba608e60208a56f739ea47b768d577edab
[]
no_license
Stypox/olympiad-exercises
eb42b93a10ae566318317dfa3daaa65b7939621b
70c6e83a6774918ade532855e818b4822d5b367b
refs/heads/master
2023-04-13T22:30:55.122026
2023-04-10T15:09:17
2023-04-10T15:09:17
168,403,900
4
0
null
null
null
null
UTF-8
C++
false
false
587
cpp
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } void tryAll(int g, set<int>& res) { for(int i=1;i<=sqrt(g)+5;++i){ if (g%i==0) { res.insert(i); res.insert(g/i); } } } int main() { int T; cin>>T; while(T--){ int W,L; cin>>W>>L; set<int> res; tryAll(gcd(W-1, L-1), res); tryAll(gcd(W-2, L), res); tryAll(gcd(W, L-2), res); tryAll(gcd(W, 2), res); tryAll(gcd(2, L), res); cout<<res.size(); for(auto i=res.begin();i!=res.end();++i){ cout<<" "<<*i; } cout<<"\n"; } }
ab645fd0267761ac318a9360b7c0d3793d29bb97
43452fbcbe43bda467cd24e5f161c93535bc2bd5
/src/geomega/src/MDGeometry.cxx
4cd0c789ea1065005e4657dee8d22336cebff63e
[]
no_license
xtsinghua/megalib
cae2e256ad5ddf9d7b6cdb9d2b680a76dd902e4f
0bd5c161c606c32a642efb34a963b6e2c07b81a0
refs/heads/master
2021-01-11T05:46:51.442857
2015-04-15T17:56:22
2015-04-15T17:56:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
218,124
cxx
/* * MDGeometry.cxx * * * Copyright (C) by Andreas Zoglauer. * All rights reserved. * * * This code implementation is the intellectual property of * Andreas Zoglauer. * * By copying, distributing or modifying the Program (or any work * based on the Program) you indicate your acceptance of this statement, * and all its terms. * */ //////////////////////////////////////////////////////////////////////////////// // // MDGeometry // //////////////////////////////////////////////////////////////////////////////// // Include the header: #include "MDGeometry.h" // Standard libs: #include <iostream> #include <fstream> #include <limits> #include <sstream> #include <iomanip> #include <cctype> #include <cmath> using namespace std; // ROOT libs: #include <TNode.h> #include <TGeometry.h> #include <TCanvas.h> #include <TView.h> #include <TROOT.h> #include <TSystem.h> #include <TObjString.h> #include <TMath.h> #include <TGeoOverlap.h> #include <TObjArray.h> // MEGAlib libs: #include "MGlobal.h" #include "MAssert.h" #include "MStreams.h" #include "MFile.h" #include "MTokenizer.h" #include "MDShape.h" #include "MDShapeBRIK.h" #include "MDShapeTRD1.h" #include "MDShapeTRD2.h" #include "MDShapeSPHE.h" #include "MDShapeTUBS.h" #include "MDShapeCONE.h" #include "MDShapeCONS.h" #include "MDShapeTRAP.h" #include "MDShapeGTRA.h" #include "MDShapePCON.h" #include "MDShapePGON.h" #include "MDShapeSubtraction.h" #include "MDShapeUnion.h" #include "MDShapeIntersection.h" #include "MDCalorimeter.h" #include "MDStrip2D.h" #include "MDStrip3D.h" #include "MDStrip3DDirectional.h" #include "MDACS.h" #include "MDDriftChamber.h" #include "MDAngerCamera.h" #include "MDVoxel3D.h" #include "MDSystem.h" #include "MTimer.h" #include "MString.h" //////////////////////////////////////////////////////////////////////////////// #ifdef ___CINT___ ClassImp(MDGeometry) #endif //////////////////////////////////////////////////////////////////////////////// MDGeometry::MDGeometry() { // default constructor m_GeometryScanned = false; m_WorldVolume = 0; m_StartVolume = ""; m_ShowVolumes = true; m_DefaultColor = -1; m_IgnoreShortNames = false; m_DoSanityChecks = true; m_ComplexER = true; m_NodeList = new TObjArray(); m_IncludeList = new TObjArray(); m_Name = "\"Geometry, which was not worth a name...\"" ; m_Version = "0.0.0.0"; m_SphereRadius = DBL_MAX; m_SpherePosition = MVector(DBL_MAX, DBL_MAX, DBL_MAX); m_DistanceToSphereCenter = DBL_MAX; m_GeoView = 0; m_Geometry = 0; m_LastVolumes.clear(); m_LastVolumePosition = 0; m_TriggerUnit = new MDTriggerUnit(this); m_System = new MDSystem("NoName"); // Make sure we ignore the default ROOT geometry... // BUG: In case we are multi-threaded and some one interact with the geometry // before the gGeoManager is reset during new, we will get a seg-fault! gGeoManager = 0; // ... before m_Geometry = new TGeoManager("Geomega geometry", "Geomega"); } //////////////////////////////////////////////////////////////////////////////// MDGeometry::~MDGeometry() { // default destructor Reset(); delete m_TriggerUnit; delete m_System; } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::Reset() { // Reset this class to default values for (unsigned int i = 0; i < m_VolumeList.size(); ++i) { delete m_VolumeList[i]; } m_VolumeList.clear(); for (unsigned int i = 0; i < m_MaterialList.size(); ++i) { delete m_MaterialList[i]; } m_MaterialList.clear(); for (unsigned int i = 0; i < m_DetectorList.size(); ++i) { delete m_DetectorList[i]; } m_DetectorList.clear(); m_NDetectorTypes.clear(); m_NDetectorTypes.resize(MDDetector::c_MaxDetector+1); for (unsigned int i = 0; i < m_TriggerList.size(); ++i) { delete m_TriggerList[i]; } m_TriggerList.clear(); for (unsigned int i = 0; i < m_ShapeList.size(); ++i) { delete m_ShapeList[i]; } m_ShapeList.clear(); for (unsigned int i = 0; i < m_OrientationList.size(); ++i) { delete m_OrientationList[i]; } m_OrientationList.clear(); for (unsigned int i = 0; i < m_VectorList.size(); ++i) { delete m_VectorList[i]; } m_VectorList.clear(); m_ConstantList.clear(); m_ConstantMap.clear(); m_WorldVolume = 0; // m_StartVolume = ""; // This is a start option of geomega, so do not reset! m_IncludeList->Delete(); m_NodeList->Delete(); if (m_GeoView != 0) { if (gROOT->FindObject("MainCanvasGeomega") != 0) { delete m_GeoView; } m_GeoView = 0; } // Create a new geometry // BUG: In case we are multi-threaded and some one interact with the geometry // before the gGeoManager is reset during new, we will get a seg-fault! gGeoManager = 0; delete m_Geometry; m_Geometry = new TGeoManager("Give it a good name", "MissingName"); delete m_System; m_System = new MDSystem("NoName"); m_IgnoreShortNames = false; m_DoSanityChecks = true; m_ComplexER = true; m_VirtualizeNonDetectorVolumes = false; m_LastVolumes.clear(); m_LastVolumePosition = 0; m_DetectorSearchTolerance = 0.000001; m_CrossSectionFileDirectory = g_MEGAlibPath + "/resource/geometries/materials"; MDVolume::ResetIDs(); MDDetector::ResetIDs(); MDMaterial::ResetIDs(); m_GeometryScanned = false; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::IsScanned() { // Return true if the geometry setup-file has been scanned/read successfully return m_GeometryScanned; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::ScanSetupFile(MString FileName, bool CreateNodes, bool VirtualizeNonDetectorVolumes, bool AllowCrossSectionCreation) { // Scan the setup-file and create the geometry //if (IsScanned() == false) { // mout<<"Loading geometry file: "<<FileName<<endl; //} int Stage = 1; MTimer Timer; double TimeLimit = 10; bool FoundDepreciated = false; // First clean the geometry ... Reset(); // Save if we want to virtualize non detector volumes for speed increase: // If the file contains such a statement, this one is overwritten m_VirtualizeNonDetectorVolumes = VirtualizeNonDetectorVolumes; // If the is set the visibility of everything but the sensitive volume to zero bool ShowOnlySensitiveVolumes = false; m_FileName = FileName; if (m_FileName == "") { mout<<" *** Error: No geometry file name given"<<endl; return false; } MFile::ExpandFileName(m_FileName); if (gSystem->IsAbsoluteFileName(m_FileName) == false) { m_FileName = gSystem->WorkingDirectory() + MString("/") + m_FileName; } if (gSystem->AccessPathName(m_FileName) == 1) { mgui<<"Geometry file \""<<m_FileName<<"\" does not exist. Aborting."<<error; return false; } m_CrossSectionFileDirectory = MFile::GetDirectoryName(m_FileName); m_CrossSectionFileDirectory += "/auxiliary"; mdebug<<"Started scanning of geometry... This may take a while..."<<endl; MDMaterial* M = 0; MDMaterial* MCopy = 0; MDVolume* V = 0; MDVolume* VCopy = 0; MDDetector* D = 0; MDTrigger* T = 0; MDSystem* S = 0; MDVector* Vector = 0; MDShape* Shape = 0; MDOrientation* Orientation = 0; // For scaling some volumes: map<MDVolume*, double> ScaledVolumes; // Since the geometry-file can include other geometry files, // we have to store the whole file in memory vector<MDDebugInfo> FileContent; if (AddFile(m_FileName, FileContent) == false) { mout<<" *** Error reading included files. Aborting!"<<endl; return false; } // Now scan the data and search for "Include" files and add them // to the original stored file content MTokenizer Tokenizer; for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) continue; if (Tokenizer.IsTokenAt(0, "Include") == true) { // Test for old material path if (Tokenizer.GetTokenAt(1).EndsWith("resource/geometries/materials/Materials.geo") == true) { mout<<" *** Deprectiated *** "<<endl; mout<<"You are using the old MEGAlib material path:"<<endl; mout<<m_DebugInfo.GetText()<<endl; mout<<"Please update to the new path now!"<<endl; mout<<"Change: resource/geometries To: resource/examples/geomega "<<endl; mout<<endl; FoundDepreciated = true; } MString FileName = Tokenizer.GetTokenAt(1); MFile::ExpandFileName(FileName, m_FileName); if (MFile::Exists(FileName) == false) { mout<<" *** Error finding file "<<FileName<<endl; Typo("File IO error"); return false; } vector<MDDebugInfo> AddFileContent; if (AddFile(FileName, AddFileContent) == false) { mout<<" *** Error reading file "<<FileName<<endl; Typo("File IO error"); return false; } for (unsigned int j = 0; j < AddFileContent.size(); ++j) { //FileContent.push_back(AddFileContent[j]); FileContent.insert(FileContent.begin() + (i+1) + j, AddFileContent[j]); } } } if (FileContent.size() == 0) { mgui<<"File is \""<<m_FileName<<"\" empty or binary!"<<error; return false; } ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (reading of file(s)) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } // Find lines which are continued in a second line by the "\\" keyword for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) continue; // Of course the real token is "\\" if (Tokenizer.IsTokenAt(Tokenizer.GetNTokens()-1, "\\\\") == true) { //cout<<"Found \\\\: "<<Tokenizer.ToString()<<endl; // Prepend this text to the next line if (FileContent.size() > i+1) { //cout<<"Next: "<<FileContent[i+1].GetText()<<endl; MString Prepend = ""; for (unsigned int t = 0; t < Tokenizer.GetNTokens()-1; ++t) { Prepend += Tokenizer.GetTokenAt(t); Prepend += " "; } FileContent[i+1].Prepend(Prepend); FileContent[i].SetText(""); //cout<<"Prepended: "<< FileContent[i+1].GetText()<<endl; } } } // Find constants // for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) continue; // Constants if (Tokenizer.IsTokenAt(0, "Constant") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain three entries, e.g. \"Constant Distance 10.5\""); return false; } map<MString, MString>::iterator Iter = m_ConstantMap.find(Tokenizer.GetTokenAt(1)); if (Iter != m_ConstantMap.end()) { if (m_ConstantMap[Tokenizer.GetTokenAt(1)] != Tokenizer.GetTokenAt(2)) { Typo("Constant has already been defined and both are not identical!"); return false; } } m_ConstantMap[Tokenizer.GetTokenAt(1)] = Tokenizer.GetTokenAt(2); m_ConstantList.push_back(Tokenizer.GetTokenAt(1)); } } // Take care of maths and constants containing constants, containing constants... bool ConstantChanged = true; while (ConstantChanged == true) { // Step 1: Solve maths: for (map<MString, MString>::iterator Iter1 = m_ConstantMap.begin(); Iter1 != m_ConstantMap.end(); ++Iter1) { if (MTokenizer::IsMaths((*Iter1).second) == true) { bool ContainsConstant = false; for (map<MString, MString>::iterator Iter2 = m_ConstantMap.begin(); Iter2 != m_ConstantMap.end(); ++Iter2) { if (ContainsReplacableConstant((*Iter1).second, (*Iter2).first) == true) { ContainsConstant = true; //cout<<"Replaceable constant: "<<(*Iter1).second<<" (namely:"<<(*Iter2).first<<")"<<endl; break; } else { //cout<<"No replaceable constant: "<<(*Iter1).second<<" (test:"<<(*Iter2).first<<")"<<endl; } } if (ContainsConstant == false) { MString Constant = (*Iter1).second; MTokenizer::EvaluateMaths(Constant); (*Iter1).second = Constant; } } } // Step 2: Replace constants in constants bool ConstantChangableWithMath = false; ConstantChanged = false; for (map<MString, MString>::iterator Iter1 = m_ConstantMap.begin(); Iter1 != m_ConstantMap.end(); ++Iter1) { //cout<<(*Iter1).first<<" - "<<(*Iter1).second<<" Pos: "<<i++<<" of "<<m_ConstantMap.size()<<endl; for (map<MString, MString>::iterator Iter2 = m_ConstantMap.begin(); Iter2 != m_ConstantMap.end(); ++Iter2) { //cout<<"Map size: "<<m_ConstantMap.size()<<endl; if (ContainsReplacableConstant((*Iter1).second, (*Iter2).first) == true) { //cout<<" ---> "<<(*Iter2).first<<" - "<<(*Iter2).second<<endl; //cout<<(*Iter1).second<<" contains "<<(*Iter2).first<<endl; if (MTokenizer::IsMaths((*Iter2).second) == false) { MString Constant = (*Iter1).second; ReplaceWholeWords(Constant, (*Iter2).first, (*Iter2).second); (*Iter1).second = Constant; ConstantChanged = true; } else { ConstantChangableWithMath = true; } } } } if (ConstantChanged == false && ConstantChangableWithMath == true) { mout<<" *** Error ***"<<endl; mout<<"Recursively defined constant found!"<<endl; return false; } } // Do the final replace: for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { // No maths since we are not yet ready for it... Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) continue; MString Init = Tokenizer.GetTokenAt(0); if (Init == "Volume" || Init == "Material" || Init == "Trigger" || Init == "System" || Init == "Strip2D" || Init == "MDStrip2D" || Init == "Strip3D" || Init == "MDStrip3D" || Init == "Strip3DDirectional" || Init == "MDStrip3DDirectional" || Init == "DriftChamber" || Init == "MDDriftChamber" || Init == "AngerCamera" || Init == "MDAngerCamera" || Init == "Simple" || Init == "Scintillator" || Init == "ACS" || Init == "MDACS" || Init == "Calorimeter" || Init == "MDCalorimeter" || Init == "Voxel3D" || Init == "MDVoxel3D") { continue; } for (map<MString, MString>::iterator Iter = m_ConstantMap.begin(); Iter != m_ConstantMap.end(); ++Iter) { FileContent[i].Replace((*Iter).first, (*Iter).second, true); } } ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (analyzing constant) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } // Check for Vectors FIRST since those are used in ForVector loops... for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { // No maths since we are not yet ready for it... Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) continue; if (Tokenizer.IsTokenAt(0, "Vector") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Vector MyMatrix\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddVector(new MDVector(Tokenizer.GetTokenAt(1))); continue; } } for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { // No maths since we are not yet ready for it... Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) continue; if ((Vector = GetVector(Tokenizer.GetTokenAt(0))) != 0) { Tokenizer.Analyse(m_DebugInfo.GetText()); // let's do some maths... if (Tokenizer.IsTokenAt(1, "Matrix") == true) { // We need at least 9 keywords: if (Tokenizer.GetNTokens() < 9) { Typo("Vector.Matrix must contain at least nine keywords," " e.g. \"MaskMatrix.Matrix 3 1.0 3 1.0 1 0.0 1 0 1 0 1 0 1 0 1\""); return false; } unsigned int x_max = Tokenizer.GetTokenAtAsUnsignedInt(2); unsigned int y_max = Tokenizer.GetTokenAtAsUnsignedInt(4); unsigned int z_max = Tokenizer.GetTokenAtAsUnsignedInt(6); double dx = Tokenizer.GetTokenAtAsDouble(3); double dy = Tokenizer.GetTokenAtAsDouble(5); double dz = Tokenizer.GetTokenAtAsDouble(7); // Now we know the real number of keywords: if (Tokenizer.GetNTokens() != 8+x_max*y_max*z_max) { Typo("This version of Vector.Matrix does not contain the right amount of numbers\""); return false; } for (unsigned int z = 0; z < z_max; ++z) { for (unsigned int y = 0; y < y_max; ++y) { for (unsigned int x = 0; x < x_max; ++x) { Vector->Add(MVector(x*dx, y*dy, z*dz), Tokenizer.GetTokenAtAsDouble(8 + x + y*x_max + z*x_max*y_max)); } } } } else { Typo("Unrecognized vector option"); return false; } } } ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (evaluating vectors) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } // Check for "For"-loops as well as the special "ForVector"-loop int ForDepth = 0; int CurrentDepth = 0; vector<MDDebugInfo>::iterator Iter; for (Iter = FileContent.begin(); Iter != FileContent.end(); /* ++Iter erase */) { m_DebugInfo = (*Iter); if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) { ++Iter; continue; } if (Tokenizer.IsTokenAt(0, "For") == true) { Tokenizer.Analyse(m_DebugInfo.GetText(), true); // redo for math's evaluation just here CurrentDepth = ForDepth; ForDepth++; if (Tokenizer.GetNTokens() != 5) { Typo("Line must contain five entries, e.g. \"For I 3 -11.0 11.0\""); return false; } MString Index = Tokenizer.GetTokenAt(1); if (Tokenizer.GetTokenAtAsDouble(2) <= 0 || std::isnan(Tokenizer.GetTokenAtAsDouble(2))) { // std:: is required mout<<"Loop number: "<<Tokenizer.GetTokenAtAsDouble(2)<<endl; Typo("Loop number in for loop must be a positive integer"); return false; } unsigned int Loops = Tokenizer.GetTokenAtAsUnsignedInt(2); double Start = Tokenizer.GetTokenAtAsDouble(3); double Step = Tokenizer.GetTokenAtAsDouble(4); // Remove for line Iter = FileContent.erase(Iter++); // Store content of for loop: vector<MDDebugInfo> ForLoopContent; for (; Iter != FileContent.end(); /* ++Iter erase */) { m_DebugInfo = (*Iter); if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) { Iter++; continue; } if (Tokenizer.IsTokenAt(0, "For") == true) { ForDepth++; } if (Tokenizer.IsTokenAt(0, "Done") == true) { ForDepth--; if (ForDepth == CurrentDepth) { Iter = FileContent.erase(Iter++); break; } } ForLoopContent.push_back(m_DebugInfo); Iter = FileContent.erase(Iter++); } // Add new content at the same place: vector<MDDebugInfo>::iterator LastIter = Iter; int Position = 0; for (unsigned int l = 1; l <= Loops; ++l) { MString LoopString; LoopString += l; MString ValueString; ValueString += (Start + (l-1)*Step); vector<MDDebugInfo>::iterator ForIter; for (ForIter = ForLoopContent.begin(); ForIter != ForLoopContent.end(); ++ForIter) { m_DebugInfo = (*ForIter); m_DebugInfo.Replace(MString("%") + Index, LoopString); m_DebugInfo.Replace(MString("$") + Index, ValueString); LastIter = FileContent.insert(LastIter, m_DebugInfo); LastIter++; Position++; } } Iter = LastIter - Position; continue; } if (Tokenizer.IsTokenAt(0, "ForVector") == true) { // Take care of nesting CurrentDepth = ForDepth; ForDepth++; if (Tokenizer.GetNTokens() != 6) { Typo("The ForVector-line must contain six entries, e.g. \"ForVector MyVector X Y Z V\""); return false; } // Retrieve data: Vector = GetVector(Tokenizer.GetTokenAt(1)); if (Vector == 0) { Typo("ForVector-line: cannot find vector\""); return false; } MString XIndex = Tokenizer.GetTokenAt(2); MString YIndex = Tokenizer.GetTokenAt(3); MString ZIndex = Tokenizer.GetTokenAt(4); MString VIndex = Tokenizer.GetTokenAt(5); // Remove for line Iter = FileContent.erase(Iter++); // Store content of ForVector loop: vector<MDDebugInfo> ForLoopContent; for (; Iter != FileContent.end(); /* ++Iter erase */) { m_DebugInfo = (*Iter); if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) { Iter++; continue; } if (Tokenizer.IsTokenAt(0, "ForVector") == true) { ForDepth++; } if (Tokenizer.IsTokenAt(0, "DoneVector") == true) { ForDepth--; if (ForDepth == CurrentDepth) { Iter = FileContent.erase(Iter++); break; } } ForLoopContent.push_back(m_DebugInfo); Iter = FileContent.erase(Iter++); } // Add new content at the same place: vector<MDDebugInfo>::iterator LastIter = Iter; int Position = 0; for (unsigned int l = 1; l <= Vector->GetSize(); ++l) { MString LoopString; LoopString += l; MString XValueString; XValueString += Vector->GetPosition(l-1).X(); MString YValueString; YValueString += Vector->GetPosition(l-1).Y(); MString ZValueString; ZValueString += Vector->GetPosition(l-1).Z(); MString ValueString; ValueString += Vector->GetValue(l-1); vector<MDDebugInfo>::iterator ForIter; for (ForIter = ForLoopContent.begin(); ForIter != ForLoopContent.end(); ++ForIter) { m_DebugInfo = (*ForIter); m_DebugInfo.Replace(MString("%") + XIndex, LoopString); m_DebugInfo.Replace(MString("$") + XIndex, XValueString); m_DebugInfo.Replace(MString("%") + YIndex, LoopString); m_DebugInfo.Replace(MString("$") + YIndex, YValueString); m_DebugInfo.Replace(MString("%") + ZIndex, LoopString); m_DebugInfo.Replace(MString("$") + ZIndex, ZValueString); m_DebugInfo.Replace(MString("%") + VIndex, LoopString); m_DebugInfo.Replace(MString("$") + VIndex, ValueString); LastIter = FileContent.insert(LastIter, m_DebugInfo); LastIter++; Position++; } } Iter = LastIter - Position; continue; } ++Iter; } ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (evaluating for loops) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } // Find random numbers TRandom3 R; R.SetSeed(11031879); // Do never modify!!!! for (unsigned int i = 0; i < FileContent.size(); i++) { while (FileContent[i].Contains("RandomDouble") == true) { //cout<<"Before: "<<FileContent[i].GetText()<<endl; FileContent[i].ReplaceFirst("RandomDouble", R.Rndm()); //cout<<"after: "<<FileContent[i].GetText()<<endl; } } // // All constants and for loops are expanded, let's print some text ;-) // for (unsigned int i = 0; i < FileContent.size(); i++) { // cout<<FileContent[i].GetText()<<endl; // } ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (evaluating random numbers) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } // Check for "If"-clauses int IfDepth = 0; int CurrentIfDepth = 0; for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(FileContent[i].GetText()) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) { continue; } if (Tokenizer.IsTokenAt(0, "If") == true) { // Take care of nesting CurrentIfDepth = IfDepth; IfDepth++; if (Tokenizer.GetNTokens() != 2) { Typo("The If-line must contain two entries, the last one must be math, e.g. \"If { 1 == 2 } or If { $Value > 0 } \""); return false; } // Retrieve data: bool Bool = Tokenizer.GetTokenAtAsBoolean(1); // Clear the if line FileContent[i].SetText(""); // Forward its endif: for (unsigned int j = i+1; j < FileContent.size(); ++j) { if (Tokenizer.Analyse(FileContent[j].GetText(), false) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) { continue; } if (Tokenizer.IsTokenAt(0, "If") == true) { IfDepth++; } if (Tokenizer.IsTokenAt(0, "EndIf") == true) { IfDepth--; if (IfDepth == CurrentIfDepth) { FileContent[j].SetText(""); break; } } if (Bool == false) { FileContent[j].SetText(""); } } } // Is if } // global loop ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (evaluating if clauses) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } // All constants and for loops are expanded, let's print some text ;-) for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText(), true) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) continue; if (Tokenizer.IsTokenAt(0, "Print") == true || Tokenizer.IsTokenAt(0, "Echo") == true) { if (Tokenizer.GetNTokens() < 2) { Typo("Line must contain at least two entries, e.g. \"Print Me!\""); return false; } //mout<<" *** User Info start ***"<<endl; mout<<" *** User Info: "; for (unsigned int t = 1; t < Tokenizer.GetNTokens(); ++t) { mout<<Tokenizer.GetTokenAt(t)<<" "; } mout<<endl; //mout<<" *** User Info end ***"<<endl; } } // First loop: // Find the master keyword, volumes, material, detectors // for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() == 0) continue; // Let's scan for first order keywords: // Here we have: // - Name // - Version // - Material // - Volume // - Detector // - Trigger // - System // - Vector // - Shape // - Orientation // Volume (Most frequent, so start with this one) if (Tokenizer.IsTokenAt(0, "Volume") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Volume D1Main\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddVolume(new MDVolume(Tokenizer.GetTokenAt(1), CreateShortName(Tokenizer.GetTokenAt(1)))); continue; } // Name else if (Tokenizer.IsTokenAt(0, "Name") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Name MEGA\""); return false; } m_Name = Tokenizer.GetTokenAt(1); m_Geometry->SetNameTitle(m_Name, "A Geomega geometry"); continue; } // Version else if (Tokenizer.IsTokenAt(0, "Version") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Version 1.1.123\""); return false; } m_Version = Tokenizer.GetTokenAt(1); continue; } // Surrounding sphere else if (Tokenizer.IsTokenAt(0, "SurroundingSphere") == true) { if (Tokenizer.GetNTokens() != 6) { Typo("Line must contain five values: Radius, xPos, yPos, zPos of sphere center, Distance to sphere center"); return false; } m_SphereRadius = Tokenizer.GetTokenAtAsDouble(1); m_SpherePosition = MVector(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4)); m_DistanceToSphereCenter = Tokenizer.GetTokenAtAsDouble(5); if (m_SphereRadius != m_DistanceToSphereCenter) { Typo("Limitation: Concerning your surrounding sphere: The sphere radius must equal the distance to the sphere for the time being. Sorry."); return false; } continue; } // Show volumes else if (Tokenizer.IsTokenAt(0, "ShowVolumes") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two values: ShowVolumes false"); return false; } m_ShowVolumes = Tokenizer.GetTokenAtAsBoolean(1); continue; } // Show volumes else if (Tokenizer.IsTokenAt(0, "ShowOnlySensitiveVolumes") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two values: ShowVolumes false"); return false; } ShowOnlySensitiveVolumes = Tokenizer.GetTokenAtAsBoolean(1); continue; } // Do Sanity checks else if (Tokenizer.IsTokenAt(0, "DoSanityChecks") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two values: DoSanityChecks false"); return false; } m_DoSanityChecks = Tokenizer.GetTokenAtAsBoolean(1); continue; } // Virtualize all non detector volumes else if (Tokenizer.IsTokenAt(0, "VirtualizeNonDetectorVolumes") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two values: VirtualizeNonDetectorVolumes false"); return false; } m_VirtualizeNonDetectorVolumes = Tokenizer.GetTokenAtAsBoolean(1); continue; } // Complex event reconstruction else if (Tokenizer.IsTokenAt(0, "ComplexER") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two values: ComplexER false"); return false; } m_ComplexER = Tokenizer.GetTokenAtAsBoolean(1); continue; } // Ignore short names else if (Tokenizer.IsTokenAt(0, "IgnoreShortNames") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two values: IgnoreShortNames true"); return false; } m_IgnoreShortNames = Tokenizer.GetTokenAtAsBoolean(1); continue; } // Default color else if (Tokenizer.IsTokenAt(0, "DefaultColor") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two values: DefaultColor 3"); return false; } m_DefaultColor = Tokenizer.GetTokenAtAsInt(1); continue; } // Detector search tolerance else if (Tokenizer.IsTokenAt(0, "DetectorSearchTolerance") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two values: DetectorSearchTolerance 0.000001"); return false; } m_DetectorSearchTolerance = Tokenizer.GetTokenAtAsDouble(1); continue; } // General absorption file directory else if (Tokenizer.IsTokenAt(0, "AbsorptionFileDirectory") == true || Tokenizer.IsTokenAt(0, "CrossSectionFilesDirectory") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two values: CrossSectionFilesDirectory auxiliary"); return false; } m_CrossSectionFileDirectory = Tokenizer.GetTokenAtAsString(1); MFile::ExpandFileName(m_CrossSectionFileDirectory); if (gSystem->IsAbsoluteFileName(m_CrossSectionFileDirectory) == false) { m_CrossSectionFileDirectory = MString(MFile::GetDirectoryName(m_FileName)) + "/" + m_CrossSectionFileDirectory; } continue; } // Material else if (Tokenizer.IsTokenAt(0, "Material") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Material Aluminimum\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddMaterial(new MDMaterial(Tokenizer.GetTokenAt(1), CreateShortName(Tokenizer.GetTokenAt(1)), CreateShortName(Tokenizer.GetTokenAt(1), 19, false, true))); continue; } // Shape else if (Tokenizer.IsTokenAt(0, "Shape") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain three strings, e.g. \"Shape BOX RedBox\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(2)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(2)) == true) { return false; } } AddShape(Tokenizer.GetTokenAt(1), Tokenizer.GetTokenAt(2)); continue; } // Orientation else if (Tokenizer.IsTokenAt(0, "Orientation") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Orientation RedBoxOrientation\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddOrientation(new MDOrientation(Tokenizer.GetTokenAt(1))); continue; } // Trigger else if (Tokenizer.IsTokenAt(0, "Trigger") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Trigger D1D2\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddTrigger(new MDTrigger(Tokenizer.GetTokenAt(1))); continue; } // System else if (Tokenizer.IsTokenAt(0, "System") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"System D1D2\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } m_System = new MDSystem(Tokenizer.GetTokenAt(1)); continue; } // Detectors: Strip2D else if (Tokenizer.IsTokenAt(0, "Strip2D") == true || Tokenizer.IsTokenAt(0, "MDStrip2D") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Strip2D Tracker\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddDetector(new MDStrip2D(Tokenizer.GetTokenAt(1))); continue; } // Detectors: Strip3D else if (Tokenizer.IsTokenAt(0, "Strip3D") == true || Tokenizer.IsTokenAt(0, "MDStrip3D") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Strip3D Germanium\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddDetector(new MDStrip3D(Tokenizer.GetTokenAt(1))); continue; } // Detectors: Strip3DDirectional else if (Tokenizer.IsTokenAt(0, "Strip3DDirectional") == true || Tokenizer.IsTokenAt(0, "MDStrip3DDirectional") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Strip3DDirectional ThickSiliconWafer\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddDetector(new MDStrip3DDirectional(Tokenizer.GetTokenAt(1))); continue; } // Detectors: DriftChamber else if (Tokenizer.IsTokenAt(0, "DriftChamber") == true || Tokenizer.IsTokenAt(0, "MDDriftChamber") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"DriftChamber Xenon\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddDetector(new MDDriftChamber(Tokenizer.GetTokenAt(1))); continue; } // Detectors: AngerCamera else if (Tokenizer.IsTokenAt(0, "AngerCamera") == true || Tokenizer.IsTokenAt(0, "MDAngerCamera") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"AngerCamera Angers\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddDetector(new MDAngerCamera(Tokenizer.GetTokenAt(1))); continue; } // Detectors: ACS else if (Tokenizer.IsTokenAt(0, "Scintillator") == true || Tokenizer.IsTokenAt(0, "Simple") == true || Tokenizer.IsTokenAt(0, "ACS") == true || Tokenizer.IsTokenAt(0, "MDACS") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Scintillator ACS1\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddDetector(new MDACS(Tokenizer.GetTokenAt(1))); continue; } // Detectors: Calorimeter else if (Tokenizer.IsTokenAt(0, "Calorimeter") == true || Tokenizer.IsTokenAt(0, "MDCalorimeter") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Calorimeter athena\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddDetector(new MDCalorimeter(Tokenizer.GetTokenAt(1))); continue; } // Detectors: Voxel3D else if (Tokenizer.IsTokenAt(0, "Voxel3D") == true || Tokenizer.IsTokenAt(0, "MDVoxel3D") == true) { if (Tokenizer.GetNTokens() != 2) { Typo("Line must contain two strings, e.g. \"Voxel3D MyVoxler\""); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(1)) == false) { return false; } if (NameExists(Tokenizer.GetTokenAt(1)) == true) { return false; } } AddDetector(new MDVoxel3D(Tokenizer.GetTokenAt(1))); continue; } } // Now we can do some basic evaluation of the input: if (m_SphereRadius == DBL_MAX) { Typo("You have to define a surrounding sphere!"); return false; } ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (analyzing primary keywords) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } // // Second loop: // Search for copies/clones of different volumes and named detectors // // for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() < 3) continue; // Check for volumes with copies if (Tokenizer.IsTokenAt(1, "Copy") == true) { if ((V = GetVolume(Tokenizer.GetTokenAt(0))) != 0) { if (GetVolume(Tokenizer.GetTokenAt(2)) != 0) { Typo("A volume of this name already exists!"); return false; } VCopy = new MDVolume(Tokenizer.GetTokenAt(2)); AddVolume(VCopy); V->AddClone(VCopy); } else if ((M = GetMaterial(Tokenizer.GetTokenAt(0))) != 0) { if (GetMaterial(Tokenizer.GetTokenAt(2)) != 0) { Typo("A material of this name already exists!"); return false; } MCopy = new MDMaterial(Tokenizer.GetTokenAt(2), CreateShortName(Tokenizer.GetTokenAt(2)), CreateShortName(Tokenizer.GetTokenAt(2), 19)); AddMaterial(MCopy); M->AddClone(MCopy); } } else if (Tokenizer.IsTokenAt(1, "NamedDetector") == true || Tokenizer.IsTokenAt(1, "Named") == true) { if ((D = GetDetector(Tokenizer.GetTokenAt(0))) != 0) { if (D->IsNamedDetector() == true) { Typo("You cannot add a named detector to a named detector!"); return false; } if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain three strings, e.g. MyStripDetector.Named Strip1. Are you using the old NamedDetector format?"); return false; } if (m_DoSanityChecks == true) { if (ValidName(Tokenizer.GetTokenAt(2)) == false) { Typo("You don't have a valid detector name!"); return false; } if (NameExists(Tokenizer.GetTokenAt(2)) == true) { Typo("The name alreday exists!"); return false; } } MDDetector* Clone = D->Clone(); Clone->SetName(Tokenizer.GetTokenAt(2)); if (D->AddNamedDetector(Clone) == false) { Typo("Unable to add a named detector!"); return false; } AddDetector(Clone); } } // Umdrehen: Copy gefunden, dann Volumen/ Detector zuordnen // --> Fehler falls kein Volumen vorhanden } ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (analyzing \"Copies\") finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } //////////////////////////////////////////////////////////////////////////////////////////// // Third loop: // Fill the volumes, materials with life... for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() < 2) continue; // Now the first token is some kind of name, so we have to find the // according object and fill it // Check for Materials: if ((M = GetMaterial(Tokenizer.GetTokenAt(0))) != 0) { if (Tokenizer.IsTokenAt(1, "Density") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and 3 doubles," " e.g. \"Alu.Density 2.77\""); return false; } M->SetDensity(Tokenizer.GetTokenAtAsDouble(2)); } else if (Tokenizer.IsTokenAt(1, "RadiationLength") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and 3 doubles," " e.g. \"Alu.RadiationLength 8.9\""); return false; } M->SetRadiationLength(Tokenizer.GetTokenAtAsDouble(2)); } else if (Tokenizer.IsTokenAt(1, "Component") == true || Tokenizer.IsTokenAt(1, "ComponentByAtoms") == true) { if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) { Typo("Line must contain two strings and 3 doubles," " e.g. \"Alu.ComponentByAtoms 27.0 13.0 1.0\"" " or three string and one double\"" " e.g. \"Alu.ComponentByAtoms Al 1.0\""); return false; } if (Tokenizer.GetNTokens() == 4) { if (M->SetComponent(Tokenizer.GetTokenAtAsString(2), Tokenizer.GetTokenAtAsDouble(3), MDMaterialComponent::c_ByAtoms) == false) { Typo("Element not found!"); return false; } } else { M->SetComponent(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), MDMaterialComponent::c_ByAtoms); } } else if (Tokenizer.IsTokenAt(1, "ComponentByMass") == true) { if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) { Typo("Line must contain two strings and 3 doubles," " e.g. \"Alu.ComponentByMass 27.0 13.0 1.0\"" " or three string and one double\"" " e.g. \"Alu.ComponentByMass Al 1.0\""); return false; } if (Tokenizer.GetNTokens() == 4) { if (M->SetComponent(Tokenizer.GetTokenAtAsString(2), Tokenizer.GetTokenAtAsDouble(3), MDMaterialComponent::c_ByMass) == false) { Typo("Element not found!"); return false; } } else { M->SetComponent(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), MDMaterialComponent::c_ByMass); } } else if (Tokenizer.IsTokenAt(1, "Sensitivity") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one int," " e.g. \"Alu.Sensitivity 1\""); return false; } M->SetSensitivity(Tokenizer.GetTokenAtAsInt(2)); // } // // Check for total absorption coefficients: // else if (Tokenizer.IsTokenAt(1, "TotalAbsorptionFile") == true) { // if (Tokenizer.GetNTokens() < 3) { // Typo("Line must contain three strings" // " e.g. \"Wafer.TotalAbsorptionFile MyFile.abs"); // return false; // } // M->SetAbsorptionFileName(Tokenizer.GetTokenAfterAsString(2)); } else if (Tokenizer.IsTokenAt(1, "Copy") == true) { // No warning... } else { Typo("Unrecognized material option"); return false; } } // end materials // Check for orientations: else if ((Orientation = GetOrientation(Tokenizer.GetTokenAt(0))) != 0) { if (Orientation->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } } // end orientations // Check for shapes: else if ((Shape = GetShape(Tokenizer.GetTokenAt(0))) != 0) { if (Shape->GetType() == "Subtraction") { if (Tokenizer.IsTokenAt(1, "Parameters") == true) { if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) { Typo("The shape subtraction needs 4-5 parameters"); return false; } MDShape* Minuend = GetShape(Tokenizer.GetTokenAt(2)); MDShape* Subtrahend = GetShape(Tokenizer.GetTokenAt(3)); MDOrientation* Orientation = 0; if (Tokenizer.GetNTokens() == 5) { Orientation = GetOrientation(Tokenizer.GetTokenAt(4)); if (Orientation == 0) { Typo("The orientation was not found!"); return false; } } else { Orientation = new MDOrientation(Shape->GetName() + "_Orientation"); AddOrientation(Orientation); } if (Minuend == 0) { Typo("The minuend shape was not found!"); return false; } if (Subtrahend == 0) { Typo("The subtrahend shape was not found!"); return false; } if (dynamic_cast<MDShapeSubtraction*>(Shape)->Set(Minuend, Subtrahend, Orientation) == false) { Typo("Unable to parse the shape correctly"); return false; } } } else if (Shape->GetType() == "Union") { if (Tokenizer.IsTokenAt(1, "Parameters") == true) { if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) { Typo("The shape Union needs 4-5 parameters"); return false; } MDShape* Augend = GetShape(Tokenizer.GetTokenAt(2)); MDShape* Addend = GetShape(Tokenizer.GetTokenAt(3)); MDOrientation* Orientation = 0; if (Tokenizer.GetNTokens() == 5) { Orientation = GetOrientation(Tokenizer.GetTokenAt(4)); if (Orientation == 0) { Typo("The orientation was not found!"); return false; } } else { Orientation = new MDOrientation(Shape->GetName() + "_Orientation"); AddOrientation(Orientation); } if (Augend == 0) { Typo("The augend shape was not found!"); return false; } if (Addend == 0) { Typo("The addend shape was not found!"); return false; } if (dynamic_cast<MDShapeUnion*>(Shape)->Set(Augend, Addend, Orientation) == false) { Typo("Unable to parse the shape Union correctly"); return false; } } } else if (Shape->GetType() == "Intersection") { if (Tokenizer.IsTokenAt(1, "Parameters") == true) { if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) { Typo("The shape Intersection needs 4-5 parameters"); return false; } MDShape* Left = GetShape(Tokenizer.GetTokenAt(2)); MDShape* Right = GetShape(Tokenizer.GetTokenAt(3)); MDOrientation* Orientation = 0; if (Tokenizer.GetNTokens() == 5) { Orientation = GetOrientation(Tokenizer.GetTokenAt(4)); if (Orientation == 0) { Typo("The orientation was not found!"); return false; } } else { Orientation = new MDOrientation(Shape->GetName() + "_Orientation"); AddOrientation(Orientation); } if (Left == 0) { Typo("The left shape was not found!"); return false; } if (Right == 0) { Typo("The right shape was not found!"); return false; } if (dynamic_cast<MDShapeIntersection*>(Shape)->Set(Left, Right, Orientation) == false) { Typo("Unable to parse the shape Intersection correctly"); return false; } } } else { if (Shape->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } } } // end shapes // Check for triggers: else if ((T = GetTrigger(Tokenizer.GetTokenAt(0))) != 0) { if (Tokenizer.IsTokenAt(1, "PositiveDetectorType") == true) { mout<<" *** Deprectiated *** "<<endl; mout<<"The \"PositiveDetectorType\" keyword is no longer supported!"<<endl; mout<<"Replace it with:"<<endl; mout<<T->GetName()<<".Veto false"<<endl; mout<<T->GetName()<<".TriggerByChannel true"<<endl; mout<<T->GetName()<<".DetectorType " <<MDDetector::GetDetectorTypeName(Tokenizer.GetTokenAtAsInt(2)) <<" "<<Tokenizer.GetTokenAtAsInt(3)<<endl; mout<<"Using the above..."<<endl; mout<<endl; FoundDepreciated = true; if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain two strings and 2 integer," " e.g. \"D1D2Trigger.DetectorType 1 2\""); return false; } // Check if such a detector type exists: bool Found = false; for (unsigned int d = 0; d < GetNDetectors(); ++d) { if (GetDetectorAt(d)->GetType() == Tokenizer.GetTokenAtAsInt(2)) { Found = true; break; } } if (Found == false) { Typo("Line contains a not defined detector type!"); return false; } T->SetVeto(false); T->SetTriggerByChannel(true); T->SetDetectorType(Tokenizer.GetTokenAtAsInt(2), Tokenizer.GetTokenAtAsInt(3)); } else if (Tokenizer.IsTokenAt(1, "TriggerByChannel") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one boolean," " e.g. \"D1D2Trigger.TriggerByChannel true\""); return false; } T->SetTriggerByChannel(Tokenizer.GetTokenAtAsBoolean(2)); } else if (Tokenizer.IsTokenAt(1, "TriggerByDetector") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one boolean," " e.g. \"D1D2Trigger.TriggerByDetector true\""); return false; } T->SetTriggerByDetector(Tokenizer.GetTokenAtAsBoolean(2)); } else if (Tokenizer.IsTokenAt(1, "Veto") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one boolean," " e.g. \"D1D2Trigger.Veto true\""); return false; } T->SetVeto(Tokenizer.GetTokenAtAsBoolean(2)); } else if (Tokenizer.IsTokenAt(1, "DetectorType") == true) { if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain three strings and one int," " e.g. \"D1D2Trigger.DetectorType Strip3D 1\""); return false; } if (MDDetector::IsValidDetectorType(Tokenizer.GetTokenAtAsString(2)) == false) { Typo("Line must contain a valid detector type, e.g. Strip2D, DriftChamber, etc."); return false; } // Check if such a detector type exists: bool Found = false; for (unsigned int d = 0; d < GetNDetectors(); ++d) { if (GetDetectorAt(d)->GetTypeName() == Tokenizer.GetTokenAtAsString(2)) { Found = true; break; } } if (Found == false) { Typo("Line contains a not defined detector type!"); return false; } T->SetDetectorType(MDDetector::GetDetectorType(Tokenizer.GetTokenAtAsString(2)), Tokenizer.GetTokenAtAsInt(3)); } else if (Tokenizer.IsTokenAt(1, "Detector") == true) { if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain three strings and one int," " e.g. \"D1D2Trigger.Detector MyStrip2D 1\""); return false; } MDDetector* TriggerDetector; if ((TriggerDetector = GetDetector(Tokenizer.GetTokenAt(2))) == 0) { Typo("A detector of this name does not exist!"); return false; } T->SetDetector(TriggerDetector, Tokenizer.GetTokenAtAsInt(3)); } else if (Tokenizer.IsTokenAt(1, "GuardringDetectorType") == true) { if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain three strings and one int," " e.g. \"D1D2Trigger.GuardringDetectorType Strip3D 1\""); return false; } if (MDDetector::IsValidDetectorType(Tokenizer.GetTokenAtAsString(2)) == false) { Typo("Line must contain a valid detector type, e.g. Strip2D, DriftChamber, etc."); return false; } T->SetGuardringDetectorType(MDDetector::GetDetectorType(Tokenizer.GetTokenAtAsString(2)), Tokenizer.GetTokenAtAsInt(3)); } else if (Tokenizer.IsTokenAt(1, "GuardringDetector") == true) { if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain three strings and one int," " e.g. \"D1D2Trigger.GuardringDetector MyStrip2D 1\""); return false; } MDDetector* TriggerDetector; if ((TriggerDetector = GetDetector(Tokenizer.GetTokenAt(2))) == 0) { Typo("A detector of this name does not exist!"); return false; } T->SetGuardringDetector(TriggerDetector, Tokenizer.GetTokenAtAsInt(3)); } else if (Tokenizer.IsTokenAt(1, "NegativeDetectorType") == true) { mout<<" *** Outdated *** "<<endl; mout<<"The \"NegativeDetectorType\" keyword is no longer supported!"<<endl; return false; } else { Typo("Unrecognized trigger option"); return false; } } // Check for volumes else if ((S = GetSystem(Tokenizer.GetTokenAt(0))) != 0) { if (Tokenizer.IsTokenAt(1, "TimeResolution") == true) { if (Tokenizer.GetNTokens() >= 3) { MString Type = Tokenizer.GetTokenAt(2); Type.ToLower(); if (Type == "ideal" || Type == "none" || Type == "no" || Type == "nix" || Type == "perfect") { m_System->SetTimeResolutionType(MDSystem::c_TimeResolutionTypeIdeal); } else if (Type == "gauss" || Type == "gaus") { if (Tokenizer.GetNTokens() == 4) { m_System->SetTimeResolutionType(MDSystem::c_TimeResolutionTypeGauss); m_System->SetTimeResolutionGaussSigma(Tokenizer.GetTokenAtAsDouble(3)); } else { Typo("Line must contain three strings and one double," " e.g. \"MEGA.TimeResolution Gauss 2.0E-6\""); return false; } } else { Typo("Unrecognized time resolution type."); return false; } } else { Typo("Not enough tokens."); return false; } } else { Typo("Unrecognized system option"); return false; } } // Check for volumes else if ((V = GetVolume(Tokenizer.GetTokenAt(0))) != 0) { if (Tokenizer.IsTokenAt(1, "Material") == true) { if ((M = GetMaterial(Tokenizer.GetTokenAt(2))) == 0) { Typo("Unknown material found!"); return false; } V->SetMaterial(M); } else if (Tokenizer.IsTokenAt(1, "Shape") == true) { if (Tokenizer.GetNTokens() < 3) { Typo("Not enough input parameters for this shape!"); return false; } MString ShapeID = Tokenizer.GetTokenAtAsString(2); ShapeID.ToLowerInPlace(); if (ShapeID.AreIdentical("brik") == true || ShapeID.AreIdentical("box") == true) { MDShapeBRIK* BRIK = new MDShapeBRIK(V->GetName() + "_Shape"); if (BRIK->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(BRIK); AddShape(BRIK); } else if (ShapeID.AreIdentical("pcon") == true) { MDShapePCON* PCON = new MDShapePCON(V->GetName() + "_Shape"); if (PCON->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(PCON); AddShape(PCON); } else if (ShapeID.AreIdentical("pgon") == true) { MDShapePGON* PGON = new MDShapePGON(V->GetName() + "_Shape"); if (PGON->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(PGON); AddShape(PGON); } // Sphere: else if (ShapeID.AreIdentical("sphe") == true || ShapeID.AreIdentical("sphere") == true) { MDShapeSPHE* SPHE = new MDShapeSPHE(V->GetName() + "_Shape"); if (SPHE->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(SPHE); AddShape(SPHE); } // Cylinder: else if (ShapeID.AreIdentical("tubs") == true || ShapeID.AreIdentical("tube") == true) { MDShapeTUBS* TUBS = new MDShapeTUBS(V->GetName() + "_Shape"); if (TUBS->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(TUBS); AddShape(TUBS); } // Cone: else if (ShapeID.AreIdentical("cone") == true) { MDShapeCONE* CONE = new MDShapeCONE(V->GetName() + "_Shape"); if (CONE->Parse(Tokenizer, m_DebugInfo) == false) { Typo("Shape of CONE not ok"); return false; } V->SetShape(CONE); AddShape(CONE); } // CONS: else if (ShapeID.AreIdentical("cons") == true) { MDShapeCONS* CONS = new MDShapeCONS(V->GetName() + "_Shape"); if (CONS->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(CONS); AddShape(CONS); } // General trapezoid: else if (ShapeID.AreIdentical("trap") == true) { MDShapeTRAP* TRAP = new MDShapeTRAP(V->GetName() + "_Shape"); if (TRAP->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(TRAP); AddShape(TRAP); } // General twisted trapezoid: else if (ShapeID.AreIdentical("gtra") == true) { MDShapeGTRA* GTRA = new MDShapeGTRA(V->GetName() + "_Shape"); if (GTRA->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(GTRA); AddShape(GTRA); } // Simple trapezoid else if (ShapeID.AreIdentical("trd1") == true) { MDShapeTRD1* TRD1 = new MDShapeTRD1(V->GetName() + "_Shape"); if (TRD1->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(TRD1); AddShape(TRD1); } // Simple trapezoid else if (ShapeID.AreIdentical("trd2") == true) { MDShapeTRD2* TRD2 = new MDShapeTRD2(V->GetName() + "_Shape"); if (TRD2->Parse(Tokenizer, m_DebugInfo) == false) { Reset(); return false; } V->SetShape(TRD2); AddShape(TRD2); } // Simple union of two shapes else if (ShapeID.AreIdentical("union") == true) { MDShapeUnion* Union = new MDShapeUnion(V->GetName() + "_Shape"); if (Tokenizer.GetNTokens() != 6) { Typo("The shape Union needs 6 parameters"); return false; } MDShape* Augend = GetShape(Tokenizer.GetTokenAt(3)); MDShape* Addend = GetShape(Tokenizer.GetTokenAt(4)); MDOrientation* Orientation = GetOrientation(Tokenizer.GetTokenAt(5)); if (Augend == 0) { Typo("The augend shape was not found!"); return false; } if (Addend == 0) { Typo("The addend shape was not found!"); return false; } if (Orientation == 0) { Typo("The orientation was not found!"); return false; } if (Union->Set(Augend, Addend, Orientation) == false) { Typo("Unable to parse the shape Union correctly"); return false; } V->SetShape(Union); AddShape(Union); } // Subtraction else if (ShapeID.AreIdentical("subtraction") == true) { MDShapeSubtraction* Subtraction = new MDShapeSubtraction(V->GetName() + "_Shape"); if (Tokenizer.GetNTokens() != 6) { Typo("The shape subtraction needs 6 parameters"); return false; } MDShape* Minuend = GetShape(Tokenizer.GetTokenAt(3)); MDShape* Subtrahend = GetShape(Tokenizer.GetTokenAt(4)); MDOrientation* Orientation = GetOrientation(Tokenizer.GetTokenAt(5)); if (Minuend == 0) { Typo("The minuend shape was not found!"); return false; } if (Subtrahend == 0) { Typo("The subtrahend shape was not found!"); return false; } if (Orientation == 0) { Typo("The orientation was not found!"); return false; } if (Subtraction->Set(Minuend, Subtrahend, Orientation) == false) { Typo("Unable to parse the shape correctly"); return false; } V->SetShape(Subtraction); AddShape(Subtraction); } // Intersection else if (ShapeID.AreIdentical("intersection") == true) { MDShapeIntersection* Intersection = new MDShapeIntersection(V->GetName() + "_Shape"); if (Tokenizer.GetNTokens() != 6) { Typo("The shape Intersection needs 6 parameters"); return false; } MDShape* Left = GetShape(Tokenizer.GetTokenAt(3)); MDShape* Right = GetShape(Tokenizer.GetTokenAt(4)); MDOrientation* Orientation = GetOrientation(Tokenizer.GetTokenAt(5)); if (Left == 0) { Typo("The left shape was not found!"); return false; } if (Right == 0) { Typo("The right shape was not found!"); return false; } if (Orientation == 0) { Typo("The orientation was not found!"); return false; } if (Intersection->Set(Left, Right, Orientation) == false) { Typo("Unable to parse the shape Intersection correctly"); return false; } V->SetShape(Intersection); AddShape(Intersection); } // Now check if it is in the list else { MDShape* Shape = GetShape(Tokenizer.GetTokenAt(2)); if (Shape != 0) { V->SetShape(Shape); } else { Typo("Unknown shape found!"); return false; } } } else if (Tokenizer.IsTokenAt(1, "Mother") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain three strings" " e.g. \"Triangle.Mother WorldVolume\""); return false; } if (Tokenizer.IsTokenAt(2, "0")) { V->SetWorldVolume(); if (m_WorldVolume != 0) { Typo("You are only allowed to have one world volume!"); return false; } m_WorldVolume = V; } else { if (GetVolume(Tokenizer.GetTokenAt(2)) == 0) { Typo("A volume of this name does not exist!"); return false; } if (GetVolume(Tokenizer.GetTokenAt(2)) == V) { Typo("A volume can't be its own mother!"); return false; } if (GetVolume(Tokenizer.GetTokenAt(2))->IsClone() == true) { Typo("You are not allowed to set a volume as mother which is created via \"Copy\". Use the original volume!"); return false; } if (V->SetMother(GetVolume(Tokenizer.GetTokenAt(2))) == false) { Typo("Mother could not be set (Do you have some cyclic mother-relations defined?)"); return false; } } } else if (Tokenizer.IsTokenAt(1, "Color") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one integer" " e.g. \"Triangle.Color 2\""); return false; } if (Tokenizer.GetTokenAtAsInt(2) < 0) { Typo("The color value needs to be positive"); return false; } V->SetColor(Tokenizer.GetTokenAtAsInt(2)); } else if (Tokenizer.IsTokenAt(1, "LineStyle") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one integer" " e.g. \"Triangle.LineStyle 1\""); return false; } if (Tokenizer.GetTokenAtAsInt(2) < 0) { Typo("The line style value needs to be positive"); return false; } V->SetLineStyle(Tokenizer.GetTokenAtAsInt(2)); } else if (Tokenizer.IsTokenAt(1, "LineWidth") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one integer" " e.g. \"Triangle.LineWidth 1\""); return false; } if (Tokenizer.GetTokenAtAsInt(2) < 0) { Typo("The line width value needs to be positive"); return false; } V->SetLineWidth(Tokenizer.GetTokenAtAsInt(2)); } else if (Tokenizer.IsTokenAt(1, "Scale") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one integer" " e.g. \"Triangle.Scale 2.0\""); return false; } if (Tokenizer.GetTokenAtAsDouble(2) <= 0) { Typo("The color value needs to be positive"); return false; } ScaledVolumes[V] = Tokenizer.GetTokenAtAsDouble(2); } else if (Tokenizer.IsTokenAt(1, "Virtual") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one boolean" " e.g. \"Triangle.Virtual true\""); return false; } V->SetVirtual(Tokenizer.GetTokenAtAsBoolean(2)); } else if (Tokenizer.IsTokenAt(1, "Many") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one boolean" " e.g. \"Triangle.Many true\""); return false; } V->SetMany(Tokenizer.GetTokenAtAsBoolean(2)); } else if (Tokenizer.IsTokenAt(1, "Visibility") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and one integer" " e.g. \"Triangle.Visibility 1\""); return false; } if (Tokenizer.GetTokenAtAsInt(2) < -1 || Tokenizer.GetTokenAtAsInt(2) > 3) { Typo("The visibility needs to be -1, 0, 1, 2, or 3"); return false; } V->SetVisibility(Tokenizer.GetTokenAtAsInt(2)); } else if (Tokenizer.IsTokenAt(1, "Absorptions") == true) { mout<<" *** Deprectiated *** "<<endl; mout<<"The \"Absorptions\" keyword is no longer supported"<<endl; mout<<"All cross section files have fixed file names, and can be found in the directory given by"<<endl; mout<<"the keyword CrossSectionFilesDirectory or in \"auxiliary\" as default"<<endl; mout<<endl; FoundDepreciated = true; } else if (Tokenizer.IsTokenAt(1, "Orientation") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain three strings," " e.g. \"Wafer.Orientation WaferOrientation\""); return false; } Orientation = GetOrientation(Tokenizer.GetTokenAtAsString(2)); if (Orientation == 0) { Typo("Cannot find the requested orientation. Did you define it?"); return false; } V->SetPosition(Orientation->GetPosition()); V->SetRotation(Orientation->GetRotationMatrix()); } else if (Tokenizer.IsTokenAt(1, "Position") == true) { if (Tokenizer.GetNTokens() != 5) { Typo("Line must contain two strings and 3 doubles," " e.g. \"Wafer.Position 3.5 1.0 0.0\""); return false; } V->SetPosition(MVector(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4))); } else if (Tokenizer.IsTokenAt(1, "Rotation") == true || Tokenizer.IsTokenAt(1, "Rotate") == true) { if (Tokenizer.GetNTokens() != 5 && Tokenizer.GetNTokens() != 8) { Typo("Line must contain two strings and 3 doubles," " e.g. \"Wafer.Rotation 60.0 0.0 0.0\""); return false; } if (Tokenizer.GetNTokens() == 5) { V->SetRotation(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4)); } else { double theta1 = Tokenizer.GetTokenAtAsDouble(2); double theta2 = Tokenizer.GetTokenAtAsDouble(4); double theta3 = Tokenizer.GetTokenAtAsDouble(6); if (theta1 < 0 || theta1 > 180) { Typo("Theta1 of Rotation needs per definition to be within [0;180]"); return false; } if (theta2 < 0 || theta2 > 180) { Typo("Theta2 of Rotation needs per definition to be within [0;180]"); return false; } if (theta3 < 0 || theta3 > 180) { Typo("Theta3 of Rotation needs per definition to be within [0;180]"); return false; } V->SetRotation(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), Tokenizer.GetTokenAtAsDouble(5), Tokenizer.GetTokenAtAsDouble(6), Tokenizer.GetTokenAtAsDouble(7)); } } else if (Tokenizer.IsTokenAt(1, "Copy") == true) { // No warning... } else { Typo("Unrecognized volume option!"); return false; } } // end Volume } // end third loop... ///////////////////////////////////////////////////////////////////////////////////// // Fourth loop: // Fill the detector not before everything else is done! for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() < 2) continue; // Check for detectors: if ((D = GetDetector(Tokenizer.GetTokenAt(0))) != 0) { // Check for global tokens // Check for simulation in voxels instead of a junk volume if (Tokenizer.IsTokenAt(1, "VoxelSimulation") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and 1 boolean," " e.g. \"Wafer.VoxelSimulation true\""); return false; } if (Tokenizer.GetTokenAtAsBoolean(2) == true) { D->UseDivisions(CreateShortName(MString("X" + D->GetName())), CreateShortName(MString("Y" + D->GetName())), CreateShortName(MString("Z" + D->GetName()))); } } // Check for sensitive volume else if (Tokenizer.IsTokenAt(1, "SensitiveVolume") == true) { // Check and reject named detector if (D->IsNamedDetector() == true) { Typo("SensitiveVolume cannot be used with a named detector! It's inherited from its template detector."); return false; } // Test if volume exists: if ((V = GetVolume(Tokenizer.GetTokenAt(2))) == 0) { Typo("A volume of this name does not exist!"); return false; } D->AddSensitiveVolume(V); } // Check for detector volume else if (Tokenizer.IsTokenAt(1, "DetectorVolume") == true) { // Check and reject named detector if (D->IsNamedDetector() == true) { Typo("DetectorVolume cannot be used with a named detector! It's inherited from its template detector."); return false; } // Test if volume exists: if ((V = GetVolume(Tokenizer.GetTokenAt(2))) == 0) { Typo("A volume of this name does not exist!"); return false; } D->SetDetectorVolume(V); } // Check for NoiseThresholdEqualsTriggerThreshold else if (Tokenizer.IsTokenAt(1, "NoiseThresholdEqualsTriggerThreshold") == true || Tokenizer.IsTokenAt(1, "NoiseThresholdEqualTriggerThreshold") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain one string and one bool," " e.g. \"Wafer.NoiseThresholdEqualsTriggerThreshold true\""); return false; } D->SetNoiseThresholdEqualsTriggerThreshold(Tokenizer.GetTokenAtAsBoolean(2)); } // Check for noise threshold else if (Tokenizer.IsTokenAt(1, "NoiseThreshold") == true) { if (Tokenizer.GetNTokens() < 3 || Tokenizer.GetNTokens() > 4) { Typo("Line must contain one string and 2 doubles," " e.g. \"Wafer.NoiseThreshold 30 10\""); return false; } D->SetNoiseThreshold(Tokenizer.GetTokenAtAsDouble(2)); if (Tokenizer.GetNTokens() == 4) { D->SetNoiseThresholdSigma(Tokenizer.GetTokenAtAsDouble(3)); } } // Check for trigger threshold else if (Tokenizer.IsTokenAt(1, "TriggerThreshold") == true) { if (Tokenizer.GetNTokens() < 3 || Tokenizer.GetNTokens() > 4) { Typo("Line must contain one string and 2 double," " e.g. \"Wafer.TriggerThreshold 30 10\""); return false; } D->SetTriggerThreshold(Tokenizer.GetTokenAtAsDouble(2)); if (Tokenizer.GetNTokens() == 4) { D->SetTriggerThresholdSigma(Tokenizer.GetTokenAtAsDouble(3)); } } // Check for failure rate else if (Tokenizer.IsTokenAt(1, "FailureRate") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain one string and 1 double," " e.g. \"Wafer.FailureRate 0.01\""); return false; } D->SetFailureRate(Tokenizer.GetTokenAtAsDouble(2)); } // Check for minimum and maximum overflow else if (Tokenizer.IsTokenAt(1, "Overflow") == true) { if (Tokenizer.GetNTokens() < 3 || Tokenizer.GetNTokens() > 4) { Typo("Line must contain one string and 2 doubles," " e.g. \"Wafer.Overflow 350 100\""); return false; } D->SetOverflow(Tokenizer.GetTokenAtAsDouble(2)); if (Tokenizer.GetNTokens() == 4) { D->SetOverflowSigma(Tokenizer.GetTokenAtAsDouble(3)); } else { D->SetOverflowSigma(0.0); } } // Check for energy loss maps else if (Tokenizer.IsTokenAt(1, "EnergyLossMap") == true) { // Check and reject named detector if (D->IsNamedDetector() == true) { Typo("EnergyLossMap cannot be used with a named detector! It's inherited from its template detector."); return false; } if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings," " e.g. \"Wafer.EnergyLossMap MyEnergyLoss\""); return false; } MString FileName = Tokenizer.GetTokenAt(2); MFile::ExpandFileName(FileName, m_FileName); if (MFile::Exists(FileName) == false) { Typo("File does not exist."); return false; } D->SetEnergyLossMap(FileName); } // Check for energy resolution else if (Tokenizer.IsTokenAt(1, "EnergyResolutionAt") == true || Tokenizer.IsTokenAt(1, "EnergyResolution") == true) { if (Tokenizer.GetNTokens() < 3) { Typo("EnergyResolution keyword not correct."); return false; } MString Type = Tokenizer.GetTokenAt(2); char* Tester; double d = strtod(Type.Data(), &Tester); if (d != 0) d = 0; // Just to prevent the compiler from complaining if (Tester != Type.Data()) { // We have a number - do it the old way if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 6) { Typo("Line must contain one string and 2-4 doubles," " e.g. \"Wafer.EnergyResolutionAt 662 39 (20 -2)\""); return false; } mout<<" *** Deprectiated *** "<<endl; mout<<"The \"EnergyResolution\" keyword format has changed. Please see the geomega manual."<<endl; mout<<"Using a Gaussian resolution in compatibility mode."<<endl; mout<<endl; //FoundDepreciated = true; D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGauss); if (Tokenizer.GetNTokens() == 4) { D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)); } else if (Tokenizer.GetNTokens() == 5) { D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)); } else if (Tokenizer.GetNTokens() == 6) { D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(2) + Tokenizer.GetTokenAtAsDouble(5), Tokenizer.GetTokenAtAsDouble(3)); } } else { // New way: Type.ToLower(); if (Type == "ideal" || Type == "perfect") { D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeIdeal); } else if (Type == "none" || Type == "no") { D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeNone); } else if (Type == "gauss" || Type == "gaus") { if (Tokenizer.GetNTokens() != 6 ) { Typo("EnergyResolution keyword not correct. Example:" "\"Wafer.EnergyResolution Gauss 122 122 2.0\""); return false; } if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeGauss && D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) { Typo("The energy resolution type cannot change!"); return false; } D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGauss); D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), Tokenizer.GetTokenAtAsDouble(5)); } else if (Type == "lorentz" || Type == "lorenz") { if (Tokenizer.GetNTokens() != 6 ) { Typo("EnergyResolution keyword not correct. Example:" "\"Wafer.EnergyResolution Lorentz 122 122 2.0\""); return false; } if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeLorentz && D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) { Typo("The energy resolution type cannot change!"); return false; } D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeLorentz); D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), Tokenizer.GetTokenAtAsDouble(5)); } else if (Type == "gauslandau" || Type == "gausslandau" || Type == "gauss-landau") { if (Tokenizer.GetNTokens() != 9 ) { Typo("EnergyResolution keyword not correct. Example:" "\"Wafer.EnergyResolution GaussLandau 122 122 2.0 122 3.0 0.2\""); return false; } if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeGaussLandau && D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) { Typo("The energy resolution type cannot change!"); return false; } D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGaussLandau); D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), Tokenizer.GetTokenAtAsDouble(5), Tokenizer.GetTokenAtAsDouble(6), Tokenizer.GetTokenAtAsDouble(7), Tokenizer.GetTokenAtAsDouble(8)); } else { Typo("Unknown EnergyResolution parameters."); return false; } } } // Check for energy resolution type else if (Tokenizer.IsTokenAt(1, "EnergyResolutionType") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings," " e.g. \"Wafer.EnergyResolutionType Gauss\""); return false; } if (Tokenizer.GetTokenAtAsString(2) == "Gauss" || Tokenizer.GetTokenAtAsString(2) == "Gaus") { D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGauss); } else if (Tokenizer.GetTokenAtAsString(2) == "Lorentz") { D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeLorentz); } else { Typo("Unkown energy resolution type!"); return false; } } // Check for energy resolution type else if (Tokenizer.IsTokenAt(1, "EnergyCalibration") == true) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings," " e.g. \"Wafer.EnergyCalibration File.dat\""); return false; } MString FileName = Tokenizer.GetTokenAtAsString(2); MFile::ExpandFileName(FileName, m_FileName); MFunction Calibration; if (Calibration.Set(FileName, "DP") == false) { Typo("Unable to read file"); return false; } D->SetEnergyCalibration(Calibration); } // Check for time resolution else if (Tokenizer.IsTokenAt(1, "TimeResolution") == true || Tokenizer.IsTokenAt(1, "TimeResolutionAt") == true) { if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain one string and 2 doubles," " e.g. \"Wafer.TimeResolutionAt 662 0.0000001\""); return false; } D->SetTimeResolution(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)); } // Check for pulse-form: else if (Tokenizer.IsTokenAt(1, "PulseShape") == true) { if (Tokenizer.GetNTokens() != 14) { Typo("Line must contain one string and 12 doubles," " e.g. \"Wafer.PulseShape <10xFitParameter> FitStart FitStop\""); return false; } D->SetPulseShape(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), Tokenizer.GetTokenAtAsDouble(5), Tokenizer.GetTokenAtAsDouble(6), Tokenizer.GetTokenAtAsDouble(7), Tokenizer.GetTokenAtAsDouble(8), Tokenizer.GetTokenAtAsDouble(9), Tokenizer.GetTokenAtAsDouble(10), Tokenizer.GetTokenAtAsDouble(11), Tokenizer.GetTokenAtAsDouble(12), Tokenizer.GetTokenAtAsDouble(13)); } // Check for structural size else if (Tokenizer.IsTokenAt(1, "StructuralSize") == true) { mout<<" *** Deprectiated *** "<<endl; mout<<"The \"StructuralSize\" keyword is no longer supported, since it contained redundant information"<<endl; mout<<endl; FoundDepreciated = true; // if (Tokenizer.GetNTokens() != 5) { // Typo("Line must contain one string and 3 doubles," // " e.g. \"Wafer.StructuralSize 0.0235, 3.008, 0.5\""); // return false; // } // D->SetStructuralSize(MVector(Tokenizer.GetTokenAtAsDouble(2), // Tokenizer.GetTokenAtAsDouble(3), // Tokenizer.GetTokenAtAsDouble(4))); } // Check for structural offset else if (Tokenizer.IsTokenAt(1, "StructuralOffset") == true) { // Check and reject named detector if (D->IsNamedDetector() == true) { Typo("StructuralOffset cannot be used with a named detector! It's inherited from its template detector."); return false; } if (Tokenizer.GetNTokens() != 5) { Typo("Line must contain one string and 3 doubles," " e.g. \"Wafer.StructuralOffset 0.142, 0.142, 0.0\""); return false; } D->SetStructuralOffset(MVector(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4))); } // Check for structural pitch else if (Tokenizer.IsTokenAt(1, "StructuralPitch") == true) { // Check and reject named detector if (D->IsNamedDetector() == true) { Typo("StructuralPitch cannot be used with a named detector! It's inherited from its template detector."); return false; } if (Tokenizer.GetNTokens() != 5) { Typo("Line must contain one string and 3 doubles," " e.g. \"Wafer.StructuralPitch 0.0, 0.0, 0.0\""); return false; } D->SetStructuralPitch(MVector(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4))); } // Check for SiStrip specific tokens: else if (Tokenizer.IsTokenAt(1, "Width") == true) { mout<<" *** Deprectiated *** "<<endl; mout<<"The \"Width\" keyword is no longer supported, since it contained redundant information"<<endl; mout<<endl; FoundDepreciated = true; // if (D->GetDetectorType() != MDDetector::c_Strip2D && // D->GetDetectorType() != MDDetector::c_DriftChamber && // D->GetDetectorType() != MDDetector::c_Strip3D) { // Typo("Option Width only supported for StripxD & DriftChamber"); // return false; // } // if (Tokenizer.GetNTokens() != 4) { // Typo("Line must contain one string and 2 doubles," // " e.g. \"Wafer.Width 6.3, 6.3\""); // return false; // } // dynamic_cast<MDStrip2D*>(D)->SetWidth(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)); } else if (Tokenizer.IsTokenAt(1, "Pitch") == true) { mout<<" *** Deprectiated *** "<<endl; mout<<"The \"Pitch\" keyword is no longer supported, since it contained redundant information"<<endl; mout<<endl; FoundDepreciated = true; // if (D->GetDetectorType() != MDDetector::c_Strip2D && // D->GetDetectorType() != MDDetector::c_Strip3D && // D->GetDetectorType() != MDDetector::c_DriftChamber) { // Typo("Option Pitch only supported for StripxD & DriftChamber"); // return false; // } // if (Tokenizer.GetNTokens() != 4) { // Typo("Line must contain one string and 2 doubles," // " e.g. \"Wafer.Pitch 0.047 0.047\""); // return false; // } // dynamic_cast<MDStrip2D*>(D)->SetPitch(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)); } else if (Tokenizer.IsTokenAt(1, "Offset") == true) { // Check and reject named detector if (D->IsNamedDetector() == true) { Typo("Offset cannot be used with a named detector! It's inherited from its template detector."); return false; } if (D->GetDetectorType() != MDDetector::c_Strip2D && D->GetDetectorType() != MDDetector::c_Strip3D && D->GetDetectorType() != MDDetector::c_Strip3DDirectional && D->GetDetectorType() != MDDetector::c_Voxel3D && D->GetDetectorType() != MDDetector::c_DriftChamber) { Typo("Option Offset only supported for StripxD & DriftChamber"); return false; } if (D->GetDetectorType() == MDDetector::c_Voxel3D) { if (Tokenizer.GetNTokens() != 5) { Typo("Line must contain one string and 3 doubles," " e.g. \"Voxler.Offset 0.2 0.2 0.2\""); return false; } dynamic_cast<MDVoxel3D*>(D)->SetOffset(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4)); } else { if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain one string and 2 doubles," " e.g. \"Wafer.Offset 0.2 0.2\""); return false; } dynamic_cast<MDStrip2D*>(D)->SetOffset(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)); } } else if (Tokenizer.IsTokenAt(1, "StripNumber") == true || Tokenizer.IsTokenAt(1, "Strip") == true || Tokenizer.IsTokenAt(1, "Strips") == true) { // Check and reject named detector if (D->IsNamedDetector() == true) { Typo("StripNumber cannot be used with a named detector! It's inherited from its template detector."); return false; } if (D->GetDetectorType() != MDDetector::c_Strip2D && D->GetDetectorType() != MDDetector::c_Strip3D && D->GetDetectorType() != MDDetector::c_Strip3DDirectional && D->GetDetectorType() != MDDetector::c_DriftChamber) { Typo("Option StripNumber only supported for StripxD & DriftChamber"); return false; } if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain one string and 2 doubles," " e.g. \"Wafer.StripNumber 128 128\""); return false; } dynamic_cast<MDStrip2D*>(D)->SetNStrips(Tokenizer.GetTokenAtAsInt(2), Tokenizer.GetTokenAtAsInt(3)); } else if (Tokenizer.IsTokenAt(1, "PixelNumber") == true || Tokenizer.IsTokenAt(1, "Pixels") == true || Tokenizer.IsTokenAt(1, "Pixel") == true || Tokenizer.IsTokenAt(1, "VoxelNumber") == true || Tokenizer.IsTokenAt(1, "Voxels") == true || Tokenizer.IsTokenAt(1, "Voxel") == true) { if (D->GetDetectorType() != MDDetector::c_Voxel3D) { Typo("Option Strip/Voxel number only supported for Voxel3D"); return false; } // Check and reject named detector if (D->IsNamedDetector() == true) { Typo("Pixels/voxels cannot be used with a named detector! It's inherited from its template detector."); return false; } if (Tokenizer.GetNTokens() != 5) { Typo("Line must contain one string and 3 doubles," " e.g. \"Voxler.StripNumber 128 128 128\""); return false; } dynamic_cast<MDVoxel3D*>(D)->SetNVoxels(Tokenizer.GetTokenAtAsInt(2), Tokenizer.GetTokenAtAsInt(3), Tokenizer.GetTokenAtAsInt(4)); } else if (Tokenizer.IsTokenAt(1, "StripLength") == true) { mout<<" *** Deprectiated *** "<<endl; mout<<"The \"StripLength\" keyword is no longer supported, since it contained redundant information"<<endl; mout<<endl; FoundDepreciated = true; // if (D->GetDetectorType() != MDDetector::c_Strip2D && // D->GetDetectorType() != MDDetector::c_Strip3D && // D->GetDetectorType() != MDDetector::c_DriftChamber) { // Typo("Option StripLength only supported for StripxD & DriftChamber"); // return false; // } // if (Tokenizer.GetNTokens() != 4) { // Typo("Line must contain one string and 2 doubles," // " e.g. \"Wafer.StripLength 6.016 6.016\""); // return false; // } // dynamic_cast<MDStrip2D*>(D)->SetStripLength(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)); } else if (Tokenizer.IsTokenAt(1, "Orientation") == true) { mout<<" *** Deprectiated *** "<<endl; mout<<"The \"Orientation\" keyword is no longer supported, since it contained redundant information"<<endl; mout<<endl; FoundDepreciated = true; // if (D->GetDetectorType() != MDDetector::c_Strip2D && // D->GetDetectorType() != MDDetector::c_Strip3D && // D->GetDetectorType() != MDDetector::c_DriftChamber) { // Typo("Option StripLength only supported for StripxD & DriftChamber"); // return false; // } // if (Tokenizer.GetNTokens() != 3) { // Typo("Line must contain one string and one integer," // " e.g. \"Wafer.Orientation 2\""); // return false; // } // dynamic_cast<MDStrip2D*>(D)->SetOrientation(Tokenizer.GetTokenAtAsInt(2)); } // Check for guard ring threshold else if (Tokenizer.IsTokenAt(1, "GuardringTriggerThreshold") == true) { if (D->GetDetectorType() != MDDetector::c_Strip2D && D->GetDetectorType() != MDDetector::c_Strip3D && D->GetDetectorType() != MDDetector::c_Voxel3D && D->GetDetectorType() != MDDetector::c_Strip3DDirectional && D->GetDetectorType() != MDDetector::c_DriftChamber) { Typo("Option GuardRingTriggerThreshold only supported for StripxD & DriftChamber"); return false; } if (Tokenizer.GetNTokens() < 3 || Tokenizer.GetNTokens() > 4) { Typo("Line must contain two strings and 2 double," " e.g. \"Wafer.GuardringTriggerThreshold 30 10\""); return false; } if (D->GetDetectorType() == MDDetector::c_Voxel3D) { dynamic_cast<MDVoxel3D*>(D)->SetGuardringTriggerThreshold(Tokenizer.GetTokenAtAsDouble(2)); if (Tokenizer.GetNTokens() == 4) { dynamic_cast<MDVoxel3D*>(D)->SetGuardringTriggerThresholdSigma(Tokenizer.GetTokenAtAsDouble(3)); } } else { dynamic_cast<MDStrip2D*>(D)->SetGuardringTriggerThreshold(Tokenizer.GetTokenAtAsDouble(2)); if (Tokenizer.GetNTokens() == 4) { dynamic_cast<MDStrip2D*>(D)->SetGuardringTriggerThresholdSigma(Tokenizer.GetTokenAtAsDouble(3)); } } } // Check for guard ring energy resolution else if (Tokenizer.IsTokenAt(1, "GuardringEnergyResolution") == true || Tokenizer.IsTokenAt(1, "GuardringEnergyResolutionAt") == true) { if (D->GetDetectorType() != MDDetector::c_Strip2D && D->GetDetectorType() != MDDetector::c_Strip3D && D->GetDetectorType() != MDDetector::c_Voxel3D && D->GetDetectorType() != MDDetector::c_Strip3DDirectional && D->GetDetectorType() != MDDetector::c_DriftChamber) { Typo("Option GuardringEnergyResolutionAt only supported for StripxD & DriftChamber"); return false; } if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain two strings and 2 doubles," " e.g. \"Wafer.GuardringEnergyResolutionAt 30 10\""); return false; } if (D->GetDetectorType() == MDDetector::c_Voxel3D) { if (dynamic_cast<MDVoxel3D*>(D)->SetGuardringEnergyResolution(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)) == false) { Typo("Incorrect input"); return false; } } else { if (dynamic_cast<MDStrip2D*>(D)->SetGuardringEnergyResolution(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)) == false) { Typo("Incorrect input"); return false; } } } // Check for Calorimeter specific tokens: else if (Tokenizer.IsTokenAt(1, "NoiseAxis") == true) { mout<<" *** Unsupported *** "<<endl; mout<<"The \"NoiseAxis\" keyword is no longer supported!"<<endl; mout<<"For all detectors, the z-axis is by default the depth-noised axis"<<endl; mout<<"For the depth resolution, use the \"DepthResolution\" keyword"<<endl; mout<<endl; FoundDepreciated = true; } else if (Tokenizer.IsTokenAt(1, "DepthResolution") == true || Tokenizer.IsTokenAt(1, "DepthResolutionAt") == true) { bool Return = true; if (D->GetDetectorType() == MDDetector::c_Calorimeter) { if (Tokenizer.GetNTokens() == 4) { Return = dynamic_cast<MDCalorimeter*>(D)->SetDepthResolutionAt(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), 0); } else if (Tokenizer.GetNTokens() == 5) { Return = dynamic_cast<MDCalorimeter*>(D)->SetDepthResolutionAt(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4)); } } else if (D->GetDetectorType() == MDDetector::c_Strip3D || D->GetDetectorType() == MDDetector::c_Strip3DDirectional || D->GetDetectorType() == MDDetector::c_DriftChamber) { if (Tokenizer.GetNTokens() == 4) { Return = dynamic_cast<MDStrip3D*>(D)->SetDepthResolutionAt(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), 0); } else if (Tokenizer.GetNTokens() == 5) { Return = dynamic_cast<MDStrip3D*>(D)->SetDepthResolutionAt(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4)); } } else { Typo("Option DepthResolution only supported for Calorimeter, Strip3D, Strip3DDirectional, DriftChamber"); return false; } if (Return == false) { Typo("Incorrect input"); return false; } } else if (Tokenizer.IsTokenAt(1, "DepthResolutionThreshold") == true) { if (D->GetDetectorType() == MDDetector::c_Strip3D || D->GetDetectorType() == MDDetector::c_Strip3DDirectional || D->GetDetectorType() == MDDetector::c_DriftChamber) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and 1 doubles," " e.g. \"Wafer.DepthResolutionThreshold 25.0\""); return false; } dynamic_cast<MDStrip3D*>(D)->SetDepthResolutionThreshold(Tokenizer.GetTokenAtAsDouble(2)); } else { Typo("Option DepthResolutionThreshold only supported for Strip3D, Strip3DDirectional, DriftChamber"); return false; } } // Check for Scintillator specific tokens: else if (Tokenizer.IsTokenAt(1, "HitPosition") == true) { mout<<" *** Obsolete *** "<<endl; mout<<"The \"HitPosition\" keyword is no longer necessary in the current version and thus not used - please delete it!"<<endl; } // Check for Strip3D and higher specific tokens: else if (Tokenizer.IsTokenAt(1, "EnergyResolutionDepthCorrection") == true || Tokenizer.IsTokenAt(1, "EnergyResolutionDepthCorrectionAt") == true) { if (D->GetDetectorType() != MDDetector::c_Strip3D && D->GetDetectorType() != MDDetector::c_Strip3DDirectional && D->GetDetectorType() != MDDetector::c_DriftChamber) { Typo("Option EnergyResolutionDepthCorrectionAt only supported for StripxD & DriftChamber"); return false; } if (Tokenizer.GetNTokens() < 3) { Typo("EnergyResolution keyword not correct."); return false; } MString Type = Tokenizer.GetTokenAt(2); char* Tester; double d = strtod(Type.Data(), &Tester); if (d != 0) d = 0; // Just to prevent the compiler from complaining if (Tester != Type.Data()) { // We have a number - do it the old way if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain one string and 2," " e.g. \"Wafer.EnergyResolutionDeothCorrection 0.0 1.0\""); return false; } if (dynamic_cast<MDStrip3D*>(D)->SetEnergyResolutionDepthCorrection(Tokenizer.GetTokenAtAsDouble(2), 1.0, Tokenizer.GetTokenAtAsDouble(3)) == false) { Typo("Incorrect input"); return false; } } else { // New way: Type.ToLower(); if (Type == "gauss" || Type == "gaus") { if (Tokenizer.GetNTokens() != 6 ) { Typo("EnergyResolution keyword not correct. Example:" "\"Wafer.EnergyResolutionDepthCorrection Gauss 1.0 122 2.0\""); return false; } if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeGauss && D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) { Typo("The energy resolution type cannot change!"); return false; } D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGauss); dynamic_cast<MDStrip3D*>(D)->SetEnergyResolutionDepthCorrection(Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), Tokenizer.GetTokenAtAsDouble(5)); } else if (Type == "lorentz" || Type == "lorenz") { if (Tokenizer.GetNTokens() != 6 ) { Typo("EnergyResolution keyword not correct. Example:" "\"Wafer.EnergyResolution Lorentz 122 122 2.0\""); return false; } if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeLorentz && D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) { Typo("The energy resolution type cannot change!"); return false; } D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeLorentz); dynamic_cast<MDStrip3D*>(D)->SetEnergyResolutionDepthCorrection(Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), Tokenizer.GetTokenAtAsDouble(5)); } else if (Type == "gauslandau" || Type == "gausslandau" || Type == "gauss-landau") { if (Tokenizer.GetNTokens() != 9 ) { Typo("EnergyResolution keyword not correct. Example:" "\"Wafer.EnergyResolution GaussLandau 122 122 2.0 122 3.0 0.2\""); return false; } if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeGaussLandau && D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) { Typo("The energy resolution type cannot change!"); return false; } D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGaussLandau); dynamic_cast<MDStrip3D*>(D)->SetEnergyResolutionDepthCorrection(Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4), Tokenizer.GetTokenAtAsDouble(5), Tokenizer.GetTokenAtAsDouble(6), Tokenizer.GetTokenAtAsDouble(7), Tokenizer.GetTokenAtAsDouble(8)); } else { Typo("Unknown EnergyResolutionDepthCorrection parameters."); return false; } } } else if (Tokenizer.IsTokenAt(1, "TriggerThresholdDepthCorrection") == true || Tokenizer.IsTokenAt(1, "TriggerThresholdDepthCorrectionAt") == true) { if (D->GetDetectorType() != MDDetector::c_Strip3D && D->GetDetectorType() != MDDetector::c_Strip3DDirectional && D->GetDetectorType() != MDDetector::c_DriftChamber) { Typo("Option TriggerThresholdDepthCorrectionAt only supported for StripxD & DriftChamber"); return false; } if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain two strings and 2 doubles," " e.g. \"Wafer.TriggerThresholdDepthCorrectionGuardringTriggerThresholdAt 30 10\""); return false; } if (dynamic_cast<MDStrip3D*>(D)->SetTriggerThresholdDepthCorrection(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)) == false) { Typo("Incorrect input"); return false; } } else if (Tokenizer.IsTokenAt(1, "NoiseThresholdDepthCorrection") == true || Tokenizer.IsTokenAt(1, "NoiseThresholdDepthCorrectionAt") == true) { if (D->GetDetectorType() != MDDetector::c_Strip3D && D->GetDetectorType() != MDDetector::c_Strip3DDirectional && D->GetDetectorType() != MDDetector::c_DriftChamber) { Typo("Option NoiseThresholdDepthCorrectionAt only supported for StripxD & DriftChamber"); return false; } if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain two strings and 2 doubles," " e.g. \"Wafer.NoiseThresholdDepthCorrectionGuardringNoiseThresholdAt 30 10\""); return false; } if (dynamic_cast<MDStrip3D*>(D)->SetNoiseThresholdDepthCorrection(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)) == false) { Typo("Incorrect input"); return false; } } // Check for Strip3DDirectional specific tokens: else if (Tokenizer.IsTokenAt(1, "DirectionalResolution") == true || Tokenizer.IsTokenAt(1, "DirectionalResolutionAt") == true) { if (D->GetDetectorType() == MDDetector::c_Strip3DDirectional) { if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) { Typo("Line must contain two strings and 2 doubles," " e.g. \"Wafer.DirectionResolutionAt 662 39\""); return false; } if (Tokenizer.GetNTokens() == 4) { dynamic_cast<MDStrip3DDirectional*>(D) ->SetDirectionalResolutionAt(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)*c_Rad, 1E-6); } else if (Tokenizer.GetNTokens() == 5) { dynamic_cast<MDStrip3DDirectional*>(D) ->SetDirectionalResolutionAt(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)*c_Rad, Tokenizer.GetTokenAtAsDouble(4)); } } else { Typo("Option DirectionResolution only supported for Strip3DDirectional"); return false; } } // Check for Anger camera specific tokens else if (Tokenizer.IsTokenAt(1, "PositionResolution") == true || Tokenizer.IsTokenAt(1, "PositionResolutionAt") == true) { if (D->GetDetectorType() != MDDetector::c_AngerCamera) { Typo("Option PositionResolution only supported for AngerCamera"); return false; } if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain two strings and 2 doubles," " e.g. \"Wafer.PositionResolutionAt 30 10\""); return false; } dynamic_cast<MDAngerCamera*>(D)->SetPositionResolution(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)); } else if (Tokenizer.IsTokenAt(1, "Positioning") == true) { if (D->GetDetectorType() == MDDetector::c_AngerCamera) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and 1 double:" " e.g. \"Anger.Postioning XYZ\""); return false; } if (Tokenizer.GetTokenAtAsString(2) == "XYZ") { dynamic_cast<MDAngerCamera*>(D)->SetPositioning(MDGridPoint::c_XYZAnger); } else if (Tokenizer.GetTokenAtAsString(2) == "XY") { dynamic_cast<MDAngerCamera*>(D)->SetPositioning(MDGridPoint::c_XYAnger); } else { Typo("Unknown positioning type"); return false; } } else { Typo("Option Positioning only supported for AngerCamera"); return false; } // Check for DriftChamber specific tokens: } else if (Tokenizer.IsTokenAt(1, "LightSpeed") == true) { if (D->GetDetectorType() == MDDetector::c_DriftChamber) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two string and 3 doubles:," " e.g. \"Chamber.LightSpeed 18E+9\""); return false; } dynamic_cast<MDDriftChamber*>(D)->SetLightSpeed(Tokenizer.GetTokenAtAsDouble(2)); } else { Typo("Option LightSpeed only supported for DriftChamber"); return false; } } else if (Tokenizer.IsTokenAt(1, "LightDetectorPosition") == true) { if (D->GetDetectorType() == MDDetector::c_DriftChamber) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and 1 double:" " e.g. \"Chamber.LightDetectorPosition 3\""); return false; } dynamic_cast<MDDriftChamber*>(D)->SetLightDetectorPosition(Tokenizer.GetTokenAtAsInt(2)); } else { Typo("Option LightDetectorPosition only supported for DriftChamber"); return false; } } else if (Tokenizer.IsTokenAt(1, "DriftConstant") == true) { if (D->GetDetectorType() == MDDetector::c_DriftChamber) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two string and 1 double:" " e.g. \"Chamber.DriftConstant 3\""); return false; } dynamic_cast<MDDriftChamber*>(D)->SetDriftConstant(Tokenizer.GetTokenAtAsDouble(2)); } else { Typo("Option DriftConstant only supported for DriftChamber"); return false; } } else if (Tokenizer.IsTokenAt(1, "EnergyPerElectron") == true) { if (D->GetDetectorType() == MDDetector::c_DriftChamber) { if (Tokenizer.GetNTokens() != 3) { Typo("Line must contain two strings and 1 double:" " e.g. \"Chamber.EnergyPerElectron 3\""); return false; } dynamic_cast<MDDriftChamber*>(D)->SetEnergyPerElectron(Tokenizer.GetTokenAtAsDouble(2)); } else { Typo("Option EnergyPerElectron only supported for DriftChamber"); return false; } } else if (Tokenizer.IsTokenAt(1, "LightEnergyResolution") == true || Tokenizer.IsTokenAt(1, "LightEnergyResolutionAt") == true) { if (D->GetDetectorType() == MDDetector::c_DriftChamber) { if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain two strings and 2 doubles," " e.g. \"Wafer.LightEnergyResolutionAt 662 39\""); return false; } dynamic_cast<MDDriftChamber*>(D) ->SetLightEnergyResolution(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3)); } else { Typo("Option LightEnergyResolution only supported for DriftChamber"); return false; } } else if (Tokenizer.IsTokenAt(1, "Assign") == true) { // Handle this one after the volume tree is completed } else if (Tokenizer.IsTokenAt(1, "BlockTrigger") == true) { // Handle this one after validation of the detector } else if (Tokenizer.IsTokenAt(1, "NamedDetector") == true || Tokenizer.IsTokenAt(1, "Named")) { // Already handled } else { Typo("Unrecognized detector option"); return false; } } // end detector // Now we have some unassigned token ... else{ //Typo("Unrecognized option..."); //return false; } } // end fourth loop ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (analyzing all properties) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } if (m_WorldVolume == 0) { mout<<" *** Error *** No world volume"<<endl; mout<<"One volume needs to be the world volume!"<<endl; mout<<"It is charcterized by e.g. \"WorldVolume.Mother 0\" (0 = nil)"<<endl; mout<<"Stopping to scan geometry file!"<<endl; Reset(); return false; } // The world volume is not allowed to have copies/clones if (m_WorldVolume->GetNClones() > 0) { mout<<" *** Error *** World volume"<<endl; mout<<"World volume is not allowed to have copies/clones!"<<endl; mout<<"Stopping to scan geometry file!"<<endl; Reset(); return false; } if (m_WorldVolume->GetCloneTemplate() != 0) { mout<<" *** Error *** World volume"<<endl; mout<<"World volume is not allowed to be cloned/copied!"<<endl; mout<<"Stopping to scan geometry file!"<<endl; Reset(); return false; } // if (ShowOnlySensitiveVolumes == true) { for (unsigned int i = 0; i < GetNVolumes(); i++) { if (GetVolumeAt(i)->IsSensitive() == true) { GetVolumeAt(i)->SetVisibility(1); } else { GetVolumeAt(i)->SetVisibility(0); } } } // Validate the orientations for (unsigned int s = 0; s < GetNOrientations(); ++s) { if (m_OrientationList[s]->Validate() == false) { Reset(); return false; } } // Validate the shapes (attention: some shapes are valuated multiple times internally)... for (unsigned int s = 0; s < GetNShapes(); ++s) { if (m_ShapeList[s]->Validate() == false) { Reset(); return false; } } // Set a possible default color for all volumes: if (m_DefaultColor >= 0) { for (unsigned int i = 0; i < GetNVolumes(); i++) { m_VolumeList[i]->SetColor(m_DefaultColor); } } // Fill the clones with life: for (unsigned int i = 0; i < GetNVolumes(); i++) { if (m_VolumeList[i]->CopyDataToClones() == false) { return false; } } for (unsigned int i = 0; i < GetNMaterials(); i++) { if (m_MaterialList[i]->CopyDataToClones() == false) { return false; } } for (unsigned int i = 0; i < GetNDetectors(); i++) { if (m_DetectorList[i]->CopyDataToNamedDetectors() == false) { return false; } } if (m_ShowVolumes == false) { for (unsigned int i = 0; i < GetNVolumes(); i++) { if (m_VolumeList[i]->GetVisibility() <= 1) { m_VolumeList[i]->SetVisibility(0); } } } // Scale some volumes: map<MDVolume*, double>::iterator ScaleIter; for (ScaleIter = ScaledVolumes.begin(); ScaleIter != ScaledVolumes.end(); ++ScaleIter) { if ((*ScaleIter).first->IsClone() == false) { (*ScaleIter).first->Scale((*ScaleIter).second); } else { mout<<" *** Error *** Scaling is not applicable to clones/copies"<<endl; Reset(); return false; } } m_WorldVolume->ResetCloneTemplateFlags(); ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (generating clones) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } for (unsigned int i = 0; i < GetNVolumes(); i++) { if (m_VolumeList[i] != 0) { //cout<<(int) m_VolumeList[i]<<"!"<<m_VolumeList[i]->GetName()<<endl; //cout<<m_VolumeList[i]->ToString()<<endl; } } if (m_WorldVolume->Validate() == false) { return false; } // Virtualize non-detector volumes if (m_VirtualizeNonDetectorVolumes == true) { mout<<" *** Info *** "<<endl; mout<<"Non-detector volumes are virtualized --- you cannot calculate absorptions!"<<endl; m_WorldVolume->VirtualizeNonDetectorVolumes(); } m_WorldVolume->RemoveVirtualVolumes(); // mimp<<"Error if there are not positioned volumes --> otherwise GetRandomPosition() fails"<<endl; if (m_WorldVolume->Validate() == false) { return false; } if (VirtualizeNonDetectorVolumes == false) { if (m_WorldVolume->ValidateClonesHaveSameMotherVolume() == false) { return false; } } // A final loop over the data checks for the detector keyword "Assign" // We need a final volume tree, thus this is really the final loop for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() < 2) continue; // Check for detectors: if ((D = GetDetector(Tokenizer.GetTokenAt(0))) != 0) { // Check for global tokens // Check for simulation in voxels instead of a junk volume if (Tokenizer.IsTokenAt(1, "Assign") == true) { if (D->IsNamedDetector() == false) { Typo("The Assign keyword can only be used with named detectors"); return false; } MVector Pos; if (Tokenizer.GetNTokens() == 3) { vector<MString> VolumeNames = Tokenizer.GetTokenAtAsString(2).Tokenize("."); if (VolumeNames.size() == 0) { Typo("The volume sequence is empty!"); return false; } if (m_WorldVolume->GetName() != VolumeNames[0]) { Typo("The volume sequence must start with the world volume!"); return false; } MDVolumeSequence Seq; MDVolume* Start = m_WorldVolume; Seq.AddVolume(Start); for (unsigned int i = 1; i < VolumeNames.size(); ++i) { bool Found = false; for (unsigned int v = 0; v < Start->GetNDaughters(); ++v) { //cout<<"Looking for "<<VolumeNames[i]<<" in "<<Start->GetDaughterAt(v)->GetName()<<endl; if (Start->GetDaughterAt(v)->GetName() == VolumeNames[i]) { Found = true; Start = Start->GetDaughterAt(v); Seq.AddVolume(Start); //cout<<"Found: "<<VolumeNames[i]<<endl; break; } } if (Found == false) { Typo("Cannot find all volumes in the volume sequence! Make sure you placed the right volumes!"); return false; } } if (Start->GetDetector() == 0) { Typo("The volume sequence does not point to a detector!"); return false; } if (Start->GetDetector() != D->GetNamedAfterDetector()) { Typo("The volume sequence does not point to the right detector!"); return false; } if (Start->IsSensitive() == 0) { Typo("The volume sequence does not point to a sensitive volume!"); return false; } Pos = Start->GetShape()->GetRandomPositionInside(); Pos = Seq.GetPositionInFirstVolume(Pos, Start); } else if (Tokenizer.GetNTokens() == 5) { Pos[0] = Tokenizer.GetTokenAtAsDouble(2); Pos[1] = Tokenizer.GetTokenAtAsDouble(3); Pos[2] = Tokenizer.GetTokenAtAsDouble(4); } else { Typo("Line must contain two strings and one volume sequence (\"NamedWafer.Assign WorldVolume.Tracker.Wafer1\")" " or two strings and three numbers as absolute position (\"NamedWafer.Assign 12.0 0.0 0.0\")"); return false; } MDVolumeSequence* VS = new MDVolumeSequence(); m_WorldVolume->GetVolumeSequence(Pos, VS); D->SetVolumeSequence(*VS); delete VS; } } } // Take care of the start volume: if (m_StartVolume != "") { MDVolume* SV = 0; mout<<"Trying to set start volume as world volume ... "; if ((SV = GetVolume(m_StartVolume)) != 0) { if (SV->IsVirtual() == true) { mout<<"impossible, it's a virtual volume..."<<endl; mgui<<"Start volume cannot be shown, because it's a virtual volume. Showing whole geometry."<<error; } else if (SV->GetMother() == 0 && SV != m_WorldVolume) { mout<<"impossible, it's not a regular positioned volume, but a clone template..."<<endl; mgui<<"Start volume cannot be shown, because it's not a regular positioned volume, but a clone template. Showing whole geometry."<<error; } else { // Determine the correct rotation and position of this volume, to keep all positions correct: MVector Position(0, 0, 0); TMatrixD Rotation; Rotation.ResizeTo(3,3); Rotation(0,0) = 1; Rotation(1,1) = 1; Rotation(2,2) = 1; MDVolume* Volume = SV; while (Volume->GetMother() != 0) { Position = Volume->GetInvRotationMatrix()*Position; Position += Volume->GetPosition(); Rotation *= Volume->GetInvRotationMatrix(); Volume = Volume->GetMother(); } if (Volume != m_WorldVolume) { mout<<"impossible, it doesn't have a regular volume tree..."<<endl; mgui<<"Start volume cannot be shown, because it doesn't have a regular volume tree. Showing whole geometry."<<error; } else { m_WorldVolume->RemoveAllDaughters(); SV->SetMother(m_WorldVolume); SV->SetPosition(Position); SV->SetRotation(Rotation); mout<<"done"<<endl; } } } else { mout<<"failed!"<<endl; mgui<<"Start volume not found in volume tree."<<error; } } // Take care of preferred visible volumes if (m_PreferredVisibleVolumeNames.size() > 0) { // Take care of preferred visible volumes - make everything not visible if (m_PreferredVisibleVolumeNames.size() > 0) { for (unsigned int i = 0; i < GetNVolumes(); i++) { m_VolumeList[i]->SetVisibility(0); for (unsigned int c = 0; c < GetVolumeAt(i)->GetNClones(); ++c) { GetVolumeAt(i)->GetCloneAt(c)->SetVisibility(0); } } } bool FoundOne = false; for (auto N: m_PreferredVisibleVolumeNames) { for (unsigned int i = 0; i < GetNVolumes(); i++) { if (GetVolumeAt(i)->GetName() == N) { GetVolumeAt(i)->SetVisibility(1); FoundOne = true; } for (unsigned int c = 0; c < GetVolumeAt(i)->GetNClones(); ++c) { if (GetVolumeAt(i)->GetCloneAt(c)->GetName() == N) { GetVolumeAt(i)->GetCloneAt(c)->SetVisibility(1); FoundOne = true; } } } } if (FoundOne == false) { mout<<"ERROR: None of your preferred visible volumes has been found!"<<endl; } } // // Validation routines for the detectors: // // Determine the common volume for all sensitive volumes of all detectors for (unsigned int i = 0; i < GetNDetectors(); i++) { if (m_DetectorList[i]->GetNSensitiveVolumes() > 1) { // Check that the sensitive volumes are no copies for (unsigned int l = 0; l < m_DetectorList[i]->GetNSensitiveVolumes(); ++l) { //cout<<"clone test for "<<m_DetectorList[i]->GetSensitiveVolume(l)->GetName()<<endl; if (m_DetectorList[i]->GetSensitiveVolume(l)->IsClone() == true || m_DetectorList[i]->GetSensitiveVolume(l)->IsCloneTemplate() == true ) { Typo("If your detector has multiple sensitive volumes, then those cannot by copies or a template for copies."); return false; } } vector<vector<MDVolume*> > Volumes; for (unsigned int l = 0; l < m_DetectorList[i]->GetNSensitiveVolumes(); ++l) { vector<MDVolume*> MotherVolumes; MotherVolumes.push_back(m_DetectorList[i]->GetSensitiveVolume(l)); //cout<<"Tree "<<l<<": "<<MotherVolumes.back()->GetName()<<endl; while (MotherVolumes.back() != 0 && MotherVolumes.back()->GetMother()) { MotherVolumes.push_back(MotherVolumes.back()->GetMother()); //cout<<"Tree "<<l<<": "<<MotherVolumes.back()->GetName()<<endl; } Volumes.push_back(MotherVolumes); } // Replace volumes by mother volumes until we have a common mother, or reached the end of the volume tree // Loop of all mothers of the first volume --- those are the test volumes for (unsigned int m = 0; m < Volumes[0].size(); ++m) { MDVolume* Test = Volumes[0][m]; if (Test == 0) break; //cout<<"Testing: "<<Test->GetName()<<endl; bool FoundTest = true; for (unsigned int l = 1; l < Volumes.size(); ++l) { bool Found = false; for (unsigned int m = 0; m < Volumes[l].size(); ++m) { //cout<<"Comparing to: "<<Volumes[l][m]->GetName()<<" of tree "<<Volumes[l][0]->GetName()<<endl; if (Test == Volumes[l][m]) { //cout<<"Found sub"<<endl; Found = true; break; } } if (Found == false) { FoundTest = false; break; } } if (FoundTest == true) { m_DetectorList[i]->SetCommonVolume(Test); mout<<"Common mother volume for sensitive detectors of "<<m_DetectorList[i]->GetName()<<": "<<Test->GetName()<<endl; break; } } if (m_DetectorList[i]->GetCommonVolume() == 0) { mout<<" *** Error *** Multiple sensitive volumes per detector restriction"<<endl; mout<<"If your detector has multiple sensitive volumes, those must have a common volume and there are no copies allowed starting with the sensitive volume up to the common volume."<<endl; mout<<"Stopping to scan geometry file!"<<endl; Reset(); return false; } } // The common volume is automatically set to the detector volume in MDetector::Validate(), if there is only one sensitive volume // Make sure there is always only one sensitive volume of a certain type in the common volume // Due to the above checks it is enough to simply check the number of sensitive volumes in the common volume if (m_DetectorList[i]->GetNSensitiveVolumes() > 1 && m_DetectorList[i]->GetNSensitiveVolumes() != m_DetectorList[i]->GetCommonVolume()->GetNSensitiveVolumes()) { mout<<" *** Error *** Multiple sensitive volumes per detector restriction"<<endl; mout<<"If your detector has multiple sensitive volumes, those must have a common volume, in which exactly one of those volumes is positioned, and in addition no other sensitive volume. The latter is not the case."<<endl; mout<<"Stopping to scan geometry file!"<<endl; Reset(); return false; } } bool IsValid = true; for (unsigned int i = 0; i < GetNDetectors(); i++) { if (m_DetectorList[i]->Validate() == false) { IsValid = false; } m_NDetectorTypes[m_DetectorList[i]->GetDetectorType()]++; } // Special detector loop for blocked channels: for (unsigned int i = 0; i < FileContent.size(); i++) { m_DebugInfo = FileContent[i]; if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) { Typo("Tokenizer error"); return false; } if (Tokenizer.GetNTokens() < 2) continue; // Check for detectors: if ((D = GetDetector(Tokenizer.GetTokenAt(0))) != 0) { // Check for simulation in voxels instead of a junk volume if (Tokenizer.IsTokenAt(1, "BlockTrigger") == true) { if (Tokenizer.GetNTokens() != 4) { Typo("Line must contain two strings and 2 integerd," " e.g. \"Wafer.BlockTrigger 0 0 \""); return false; } D->BlockTriggerChannel(Tokenizer.GetTokenAtAsInt(2), Tokenizer.GetTokenAtAsInt(3)); } } } // Trigger sanity checks: for (unsigned int i = 0; i < GetNTriggers(); i++) { if (m_TriggerList[i]->Validate() == false) { IsValid = false; } } // Make sure that all detectors which have only veto triggers have NoiseThresholdEqualsTriggerThreshold setf for (unsigned int d = 0; d < GetNDetectors(); ++d) { int NVetoes = 0; int NTriggers = 0; for (unsigned int t = 0; t < GetNTriggers(); ++t) { if (GetTriggerAt(t)->Applies(GetDetectorAt(d)) == true) { if (GetTriggerAt(t)->IsVeto() == true) { NVetoes++; } else { NTriggers++; } } } if (NVetoes > 0 && NTriggers == 0 && GetDetectorAt(d)->GetNoiseThresholdEqualsTriggerThreshold() == false) { mout<<" *** Error *** Triggers with vetoes"<<endl; mout<<"A detector (here: "<<GetDetectorAt(d)->GetName()<<"), which only has veto triggers, must have the flag \"NoiseThresholdEqualsTriggerThreshold true\"!"<<endl; Reset(); return false; } } // Material sanity checks for (unsigned int i = 0; i < GetNMaterials(); i++) { m_MaterialList[i]->SetCrossSectionFileDirectory(m_CrossSectionFileDirectory); if (m_MaterialList[i]->Validate() == false) { IsValid = false; } } // Check if all cross sections are present if not try to create them bool CrossSectionsPresent = true; for (unsigned int i = 0; i < GetNMaterials(); i++) { if (m_MaterialList[i]->AreCrossSectionsPresent() == false) { CrossSectionsPresent = false; break; } } if (CrossSectionsPresent == false && AllowCrossSectionCreation == true) { if (CreateCrossSectionFiles() == false) { mout<<" *** Warning *** "<<endl; mout<<"Not all cross section files are present!"<<endl; } } // Check if we can apply the keyword komplex ER // Does not cover all possibilities (e.g. rotated detector etc.) if (m_ComplexER == false) { int NTrackers = 0; for (unsigned int i = 0; i < GetNDetectors(); i++) { if (m_DetectorList[i]->GetDetectorType() == MDDetector::c_Strip2D) { if (dynamic_cast<MDStrip2D*>(m_DetectorList[i])->GetOrientation() != 2) { mout<<" *** Error *** ComplexER"<<endl; mout<<"This keyword can only be applied for tracker which are oriented in z-axis!"<<endl; Reset(); return false; } else { NTrackers++; } } } if (NTrackers > 1) { mout<<" *** Error *** ComplexER"<<endl; mout<<"This keyword can only be applied if only one or none tracker is available!"<<endl; Reset(); return false; } } // We need a trigger criteria if (GetNTriggers() == 0) { mout<<" *** Warning *** "<<endl; mout<<"You have not defined any trigger criteria!!"<<endl; } else { // Check if each detector has a trigger criterion: vector<MDDetector*> Detectors; for (unsigned int i = 0; i < GetNDetectors(); ++i) Detectors.push_back(m_DetectorList[i]); for (unsigned int t = 0; t < GetNTriggers(); ++t) { vector<MDDetector*> TriggerDetectors = m_TriggerList[t]->GetDetectors(); for (unsigned int d1 = 0; d1 < Detectors.size(); ++d1) { for (unsigned int d2 = 0; d2 < TriggerDetectors.size(); ++d2) { if (Detectors[d1] == 0) continue; if (Detectors[d1] == TriggerDetectors[d2]) { Detectors[d1] = 0; break; } // If we have a named detectors, in case the "named after detector" has a trigger criteria, we are fine if (Detectors[d1]->IsNamedDetector() == true) { if (Detectors[d1]->GetNamedAfterDetector() == TriggerDetectors[d2]) { Detectors[d1] = 0; break; } } } } vector<int> TriggerDetectorTypes = m_TriggerList[t]->GetDetectorTypes(); for (unsigned int d1 = 0; d1 < Detectors.size(); ++d1) { if (Detectors[d1] == 0) continue; for (unsigned int d2 = 0; d2 < TriggerDetectorTypes.size(); ++d2) { if (Detectors[d1]->GetDetectorType() == TriggerDetectorTypes[d2]) { Detectors[d1] = 0; break; } } } } for (unsigned int i = 0; i < Detectors.size(); ++i) { if (Detectors[i] != 0) { mout<<" *** Warning *** "<<endl; mout<<"You have not defined any trigger criterion for detector: "<<Detectors[i]->GetName()<<endl; } } } if (IsValid == false) { mout<<" *** Error *** "<<endl; mout<<"There were errors while scanning this file. Correct them first!!"<<endl; Reset(); return false; } ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (validation & post-processing) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } // Geant4 requires that the world volume is the first volume in the list // Thus resort the list m_VolumeList.erase(find(m_VolumeList.begin(), m_VolumeList.end(), m_WorldVolume)); m_VolumeList.insert(m_VolumeList.begin(), m_WorldVolume); // The last stage is to optimize the geometry for hit searches: m_WorldVolume->OptimizeVolumeTree(); m_GeometryScanned = true; ++Stage; if (Timer.ElapsedTime() > TimeLimit) { mout<<"Stage "<<Stage<<" (volume tree optimization) finished after "<<Timer.ElapsedTime()<<" sec"<<endl; } mdebug<<"Geometry "<<m_FileName<<" successfully scanned within "<<Timer.ElapsedTime()<<"s"<<endl; mdebug<<"It contains "<<GetNVolumes()<<" volumes"<<endl; if (FoundDepreciated == true) { mgui<<"Your geometry contains depreciated information (see console output for details)."<<endl; mgui<<"Please update it now to the latest conventions!"<<show; } return true; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::AddFile(MString FileName, vector<MDDebugInfo>& FileContent) { FileContent.clear(); MFile::ExpandFileName(FileName); // First edit the file name: if (gSystem->IsAbsoluteFileName(FileName) == false) { FileName = MFile::GetDirectoryName(m_FileName) + MString("/") + FileName; } if (gSystem->AccessPathName(FileName) == 1) { mout<<" *** Error *** "<<endl; mout<<"Included file \""<<FileName<<"\" does not exist."<<endl; return false; } if (IsIncluded(FileName) == true) { //mout<<" *** Warning *** "<<endl; //mout<<"The file has been included multiple times: "<<FileName<<endl; return true; } int LineCounter = 0; int LineLength = 10000; char* LineBuffer = new char[LineLength]; ifstream FileStream; FileStream.open(FileName); if (FileStream.is_open() == 0) { mout<<" *** Error *** "<<endl; mout<<"Can't open file "<<FileName<<endl; delete [] LineBuffer; return false; } int Comment = 0; MTokenizer Tokenizer; MDDebugInfo Info; while (FileStream.getline(LineBuffer, LineLength, '\n')) { Info = MDDebugInfo(LineBuffer, FileName, LineCounter++); Tokenizer.Analyse(Info.GetText(), false); if (Tokenizer.GetNTokens() >=1 && Tokenizer.GetTokenAt(0) == "Exit") { mout<<"Found \"Exit\" in file "<<FileName<<endl; break; } if (Tokenizer.GetNTokens() >= 1 && Tokenizer.GetTokenAt(0) == "EndComment") { //mout<<"Found \"EndComment\" in file "<<FileName<<endl; Comment--; if (Comment < 0) { mout<<" *** Error *** "<<endl; mout<<"Found \"EndComment\" without \"BeginComment\" in file "<<FileName<<endl; FileContent.clear(); delete [] LineBuffer; return false; } continue; } if (Tokenizer.GetNTokens() >= 1 && Tokenizer.GetTokenAt(0) == "BeginComment") { //mout<<"Found \"BeginComment\" in file "<<FileName<<endl; Comment++; continue; } if (Comment == 0) { FileContent.push_back(Info); } } // Add an empty line, just in case the file didn't end with a new line FileContent.push_back(MDDebugInfo(" ", FileName, LineCounter++)); AddInclude(FileName); delete [] LineBuffer; FileStream.close(); return true; } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::Typo(MString Typo) { // Print an error message mout<<" *** Error *** in setup file "<<m_DebugInfo.GetFileName()<<" at line "<<m_DebugInfo.GetLine()<<":"<<endl; mout<<"\""<<m_DebugInfo.GetText()<<"\""<<endl; mout<<Typo<<endl; mout<<"Stopping to scan geometry file!"<<endl; Reset(); } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::NameExists(MString Name) { // Return true if the name Name already exists // Since all new names pass through this function (because we have to check // if it already exists), we can make sure that we are case insensitive! for (unsigned int i = 0; i < GetNVolumes(); i++) { if (Name.AreIdentical(m_VolumeList[i]->GetName(), true)) { Typo("A volume of this name (case insensitive) already exists!"); return true; } } for (unsigned int i = 0; i < GetNMaterials(); i++) { if (Name.AreIdentical(m_MaterialList[i]->GetName(), true)) { Typo("A material of this name (case insensitive) already exists!"); return true; } } for (unsigned int i = 0; i < GetNDetectors(); i++) { if (Name.AreIdentical(m_DetectorList[i]->GetName(), true)) { Typo("A detector of this name (case insensitive) already exists!"); return true; } } for (unsigned int i = 0; i < GetNTriggers(); i++) { if (Name.AreIdentical(m_TriggerList[i]->GetName(), true)) { Typo("A trigger of this name (case insensitive) already exists!"); return true; } } for (unsigned int i = 0; i < GetNVectors(); i++) { if (Name.AreIdentical(m_VectorList[i]->GetName(), true)) { Typo("A vector of this name (case insensitive) already exists!"); return true; } } for (unsigned int i = 0; i < m_ConstantList.size(); i++) { if (Name.AreIdentical(m_ConstantList[i], true)) { Typo("A constant of this name (case insensitive) already exists!"); return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::DrawGeometry(TCanvas* Canvas) { // The geometry must have been loaded previously // You cannot display 2 geometries at once! if (m_GeometryScanned == false) { mgui<<"Geometry has to be scanned before it can be drawn!"<<endl; return false; } // Start by deleting the old windows: if (m_GeoView != 0) { if (gROOT->FindObject("MainCanvasGeomega") != 0) { delete m_GeoView; } m_GeoView = 0; } mdebug<<"NVolumes: "<<m_WorldVolume->GetNVisibleVolumes()<<endl; // Only draw the new windows if there are volumes to be drawn: if (m_WorldVolume->GetNVisibleVolumes() == 0) { mgui<<"There are no visible volumes in your geometry!"<<warn; return false; } MTimer Timer; double TimerLimit = 5; if (Canvas == 0) { m_GeoView = new TCanvas("MainCanvasGeomega","MainCanvasGeomega",800,800); } else { Canvas->cd(); } m_WorldVolume->CreateRootGeometry(m_Geometry, 0); // m_Geometry->CloseGeometry(); // we do not close the geometry, m_Geometry->SetMultiThread(true); m_Geometry->SetVisLevel(1000); m_Geometry->SetNsegments(2*m_Geometry->GetNsegments()); m_Geometry->SetVisDensity(-1.0); //m_Geometry->Voxelize("ALL"); // Make sure we use the correct geometry for interactions gGeoManager = m_Geometry; if (m_Geometry->GetTopVolume() != 0) m_Geometry->GetTopVolume()->Draw("ogle"); if (m_Geometry->GetListOfNavigators() == nullptr) { m_Geometry->AddNavigator(); } m_Geometry->SetCurrentNavigator(0); if (Timer.ElapsedTime() > TimerLimit) { mout<<"Geometry drawn within "<<Timer.ElapsedTime()<<"s"<<endl; } return true; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::AreCrossSectionsPresent() { // Check if all absorption files are present: for (unsigned int i = 0; i < m_MaterialList.size(); ++i) { if (m_MaterialList[i]->AreCrossSectionsPresent() == false) { return false; } } return true; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::TestIntersections() { // Test for intersections // Attention: Not all can be found! cout<<"Testing intersections!"<<endl; if (IsScanned() == false) { Error("bool MDGeometry::TestIntersections()", "You have to scan the geometry file first!"); return false; } if (m_WorldVolume->ValidateIntersections() == false) { return false; } cout<<"Testing intersections finished!"<<endl; return true; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::CheckOverlaps() { // Check for overlaps using the ROOT overlap checker if (IsScanned() == false) { Error("bool MDGeometry::TestIntersections()", "You have to scan the geometry file first!"); return false; } m_WorldVolume->CreateRootGeometry(m_Geometry, 0); m_Geometry->CloseGeometry(); m_Geometry->CheckOverlaps(0.000001); TObjArray* Overlaps = m_Geometry->GetListOfOverlaps(); if (Overlaps->GetEntries() > 0) { mout<<"List of extrusions and overlaps: "<<endl; for (int i = 0; i < Overlaps->GetEntries(); ++i) { TGeoOverlap* O = (TGeoOverlap*) (Overlaps->At(i)); if (O->IsOverlap() == true) { mout<<"Overlap: "<<O->GetFirstVolume()->GetName()<<" with "<<O->GetSecondVolume()->GetName()<<" by "<<O->GetOverlap()<<" cm"<<endl; } if (O->IsExtrusion() == true) { mout<<"Extrusion: "<<O->GetSecondVolume()->GetName()<<" extrudes "<<O->GetFirstVolume()->GetName()<<" by "<<O->GetOverlap()<<" cm"<<endl; } } } else { mout<<endl; mout<<"No extrusions and overlaps detected with ROOT (ROOT claims to be able to detect 95% of them)"<<endl; } return Overlaps->GetEntries() > 0 ? false : true; } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::DumpInformation() { // Dump the geometry information: if (IsScanned() == false) { Error("bool MDGeometry::DumpInformation()", "You have to scan the geometry file first!"); return; } cout<<ToString()<<endl; } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::CalculateMasses() { // Calculate the masses of the geometry if (IsScanned() == false) { Error("bool MDGeometry::DumpInformation()", "You have to scan the geometry file first!"); return; } double Total = 0; map<MDMaterial*, double> Masses; map<MDMaterial*, double>::iterator MassesIter; m_WorldVolume->GetMasses(Masses); size_t NameWidth = 0; for (MassesIter = (Masses.begin()); MassesIter != Masses.end(); MassesIter++) { if ((*MassesIter).first->GetName().Length() > NameWidth) { NameWidth = (*MassesIter).first->GetName().Length(); } } ostringstream out; out.setf(ios_base::fixed, ios_base::floatfield); out.precision(3); out<<endl; out<<"Mass summary by material: "<<endl; out<<endl; for (MassesIter = (Masses.begin()); MassesIter != Masses.end(); MassesIter++) { out<<setw(NameWidth+2)<<(*MassesIter).first->GetName()<<" : "<<setw(12)<<(*MassesIter).second<<" g"<<endl; Total += (*MassesIter).second; } out<<endl; out<<setw(NameWidth+2)<<"Total"<<" : "<<setw(12)<<Total<<" g"<<endl; out<<endl; out<<"No warranty for this information!"<<endl; out<<"This information is only valid, if "<<endl; out<<"(a) No volume intersects any volume which is not either its mother or daughter."<<endl; out<<"(b) All daughters lie completely inside their mothers"<<endl; out<<"(c) The material information is correct"<<endl; out<<"(d) tbd."<<endl; mout<<out.str()<<endl; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::WriteGeant3Files() { // Create GEANT3 files if (m_GeometryScanned == false) { Error("bool MDGeometry::WriteGeant3Files()", "Geometry has to be scanned first"); return false; } // Some sanity checks: if (GetNMaterials() > 200) { mout<<"Error: GMega only supports 200 materials at the moment!"<<endl; return false; } // open the geometry-file: fstream FileStream; // = new fstream(); // gcc 2.95.3: FileStream.open("ugeom.f", ios::out, 0664); FileStream.open("ugeom.f", ios_base::out); // Write header: ostringstream Text; Text<< "************************************************************************\n" "*\n" "* Copyright (C) by the MEGA-team.\n" "* All rights reserved.\n" "*\n" "*\n" "* This code implementation is the intellectual property of the \n" "* MEGA-team at MPE.\n" "*\n" "* By copying, distributing or modifying the Program (or any work\n" "* based on the Program) you indicate your acceptance of this \n" "* statement, and all its terms.\n" "*\n" "************************************************************************\n" "\n" "\n" " SUBROUTINE UGEOM\n" "\n" "************************************************************************\n" "*\n" "* Initializes the geometry\n" "*\n" "* Author: This file has been automatically generated by the \n" "* geometry-program GeoMega "<<g_VersionString<<"\n" "*\n" "************************************************************************\n" "\n" " IMPLICIT NONE\n" "\n" "\n" " INCLUDE 'common.f'\n" "\n" "\n" "\n" " INTEGER IVOL\n" " DIMENSION IVOL("<<MDVolume::m_IDCounter<<")\n" " REAL UBUF\n" " DIMENSION UBUF(2)\n\n"<<endl; FileStream<<WFS(Text.str().c_str()); Text.str(""); for (unsigned int i = 0; i < GetNMaterials(); i++) { FileStream<<WFS(m_MaterialList[i]->GetGeant3DIM()); } for (unsigned int i = 0; i < GetNVolumes(); i++) { FileStream<<WFS(m_VolumeList[i]->GetGeant3DIM()); } for (unsigned int i = 0; i < GetNMaterials(); i++) { FileStream<<WFS(m_MaterialList[i]->GetGeant3DATA()); } for (unsigned int i = 0; i < GetNVolumes(); i++) { FileStream<<WFS(m_VolumeList[i]->GetGeant3DATA()); } Text<<endl<< " ZNMAT = "<<GetNMaterials()<<endl; FileStream<<WFS(Text.str().c_str()); Text.str(""); for (unsigned int i = 0; i < GetNMaterials(); i++) { FileStream<<WFS(m_MaterialList[i]->GetGeant3()); } Text<<endl<< " CALL GPART"<<endl<< " CALL GPHYSI"<<endl<<endl; FileStream<<WFS(Text.str().c_str()); Text.str(""); FileStream<<WFS(m_WorldVolume->GetGeant3())<<endl; //FileStream.setf(ios_base::fixed, ios_base::floatfield); FileStream.setf(ios::fixed, ios::floatfield); //FileStream.precision(3); // Finally position the volumes MString Name, MotherName, CopyName; // Scan through the tree... int IDCounter = 1; FileStream<<WFS(m_WorldVolume->GetGeant3Position(IDCounter))<<endl; Text<<endl; Text<<" CALL GGCLOS"<<endl; Text<<" GEONAM = \""<<m_FileName<<"\""<<endl; double MinDist; MVector RSize = m_WorldVolume->GetSize(); MinDist = RSize.X(); if (RSize.Y() < MinDist) MinDist = RSize.Y(); if (RSize.Z() < MinDist) MinDist = RSize.Z(); Text<<" MDIST = "<<MinDist<<endl; Text<<endl; Text<<" SPHR = "<<m_SphereRadius<<endl; Text<<" SPHX = "<<m_SpherePosition.X()<<endl; Text<<" SPHY = "<<m_SpherePosition.Y()<<endl; Text<<" SPHZ = "<<m_SpherePosition.Z()<<endl; Text<<" SPHD = "<<m_DistanceToSphereCenter<<endl; Text<<endl; Text<<" RETURN"<<endl; Text<<" END"<<endl;; FileStream<<WFS(Text.str().c_str()); Text.str(""); FileStream.close(); // open the geometry-file: // gcc 2.95.3: FileStream.open("detinit.f", ios::out, 0664); FileStream.open("detinit.f", ios_base::out); Text<< "************************************************************************\n" "*\n" "* Copyright (C) by the MEGA-team.\n" "* All rights reserved.\n" "*\n" "*\n" "* This code implementation is the intellectual property of the \n" "* MEGA-team at MPE.\n" "*\n" "* By copying, distributing or modifying the Program (or any work\n" "* based on the Program) you indicate your acceptance of this \n" "* statement, and all its terms.\n" "*\n" "************************************************************************\n" "\n" "\n" " SUBROUTINE DETINIT\n" "\n" "************************************************************************\n" "*\n" "* Initializes the detectors\n" "*\n" "* Author: This file has been automatically generated by the \n" "* geometry-program GeoMega "<<g_VersionString<<"\n" "*\n" "************************************************************************\n" "\n" " IMPLICIT NONE\n" "\n" " INCLUDE 'common.f'\n" "\n"<<endl; Text<<" NDET = "<<GetNDetectors()<<endl<<endl; if (GetNDetectors() > 0) { Text<<" NSENS = "<<GetDetectorAt(0)->GetGlobalNSensitiveVolumes()<<endl<<endl; } // Write detectors for(unsigned int i = 0; i < GetNDetectors(); i++) { Text<<m_DetectorList[i]->GetGeant3(); } // Write trigger conditions Text<<" TNTRIG = "<<GetNTriggers()<<endl<<endl; for(unsigned int i = 0; i < GetNTriggers(); i++) { Text<<m_TriggerList[i]->GetGeant3(i+1); } Text<<endl; Text<<" EVINFO = 1"<<endl; Text<<" SNAM = '"<<m_Name<<"_"<<m_Version<<"'"<<endl<<endl; Text<<" RETURN"<<endl; Text<<" END"<<endl; FileStream<<WFS(Text.str().c_str()); Text.str(""); FileStream.close(); // Clean up... m_WorldVolume->ResetCloneTemplateFlags(); return true; } //////////////////////////////////////////////////////////////////////////////// MString MDGeometry::WFS(MString Text) { // Real name: WrapFortranStrings // A line in a FORTRAN77 file is not allowed to be larger than 72 characters // This functions cuts the lines appropriately: size_t CutLength = 72; if (Text.Length() <= CutLength) return Text; MString Cut; MString PreCut; MString Beyond; MString Formated; while (Text.Length() > 0) { int NextRet = Text.First('\n'); if (NextRet == -1) { NextRet = Text.Length(); } else { NextRet += 1; } Cut = Text.GetSubString(0, NextRet); Text.Remove(0, NextRet); if (Cut.Length() <= CutLength || Cut.BeginsWith("*") == true) { Formated += Cut; } else { Beyond = Cut.GetSubString(CutLength+1 , Cut.Length()); bool BeyondHasText = false; for (size_t c = 0; c < Beyond.Length(); ++c) { char t = Beyond[c]; if (t != ' ' || t != '\n') { BeyondHasText = true; break; } } if (BeyondHasText == true) { // Check if we can wrap the line at a comma... PreCut = Cut.GetSubString(0, CutLength-1); size_t NiceLength = PreCut.Last(',')+1; if (NiceLength < CutLength/2) NiceLength = CutLength; Formated += Cut.GetSubString(0, NiceLength) + "\n"; Cut.Remove(0, NiceLength); while (Cut.Length() > 0) { // Check if we can wrap the line at a comma... PreCut = Cut.GetSubString(0, CutLength-7); size_t NiceLength2 = PreCut.Last(',')+1; if (NiceLength2 < CutLength/2) NiceLength2 = CutLength-6; Formated += " &" + Cut.GetSubString(0, NiceLength2); Cut.Remove(0, NiceLength2); if (Cut.Length() > 0) Formated += MString("\n"); } } else { Formated += Cut; } } } return Formated + Text; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::WriteMGeantFiles(MString FilePrefix, bool StoreIAs, bool StoreVetoes) { // This routine generates an intermediate geometry-file, which can be decoded // by MGEANT or MGGPOD // // Guest author: RMK MString FileName; fstream FileStream; if (m_GeometryScanned == false) { Error("bool MDGeometry::WriteMGeantFiles()", "Geometry has to be scanned first"); return false; } // Extract file part of pathname MString theFile = m_FileName; if (theFile.Contains("/")) { theFile.Remove(0,theFile.Last('/')+1); } // --------------------------------------------------------------------------- // Create the materials file: MEGA_materials.mat // --------------------------------------------------------------------------- // if (FilePrefix == "") { FileName = "materials.mat"; } else { FileName = FilePrefix + ".mat"; } // gcc 2.95.3: FileStream.open("MEGA_materials.mat", ios::out, 0664); FileStream.open(FileName, ios_base::out); FileStream<< "! +============================================================================+"<<endl<< "! MEGA_materials.mat MGEANT/MGGPOD materials list file "<<endl<< "! "<<endl<< "! Based on setup file: "<< theFile << endl << "! "<<endl<< "! Copyright (C) by the MEGA-team. "<<endl<< "! All rights reserved. "<<endl<< "! "<<endl<< "! Author: This file has been automatically generated by the "<<endl<< "! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<< "! +============================================================================+"<<endl<< "! Built-in Materials (numbers 1-16) --> "<<endl<< "! hydrogen, deuterium, helium, lithium, beryllium, carbon, nitrogen, "<<endl<< "! neon, aluminum, iron, copper, tungsten, lead, uranium, air, vacuum "<<endl<< "! "<<endl<< "! Format for User Materials --> "<<endl<< "! mate imate chmat A Z dens radl absl(=1.0) nwbuf <CR> "<<endl<< "! [ubuf] "<<endl<< "! mixt imate chmat nlmat dens <CR> "<<endl<< "! A(1) Z(1) wmat(1) "<<endl<< "! ... "<<endl<< "! A(N) Z(N) wmat(N) "<<endl<< "! (wmat = prop by number(nlmat<0) or weight(nlmat>0); N = abs(nlmat)) "<<endl<< "! "<<endl<< "! umix imate chmat nlmat dens <CR> "<<endl<< "! A(1) elenam(1) wmat(1) "<<endl<< "! ... "<<endl<< "! A(N) elenam(N) wmat(N) "<<endl<< "! (wmat = prop by number(nlmat<0) or weight(nlmat>0); N = abs(nlmat), "<<endl<< "! use A(i) == 0.0 to select natural isotopic abundance mixture) "<<endl<< "! "<<endl<< "! +============================================================================+"<<endl; FileStream<<endl<<endl; for (unsigned int i = 0; i < GetNMaterials(); i++) { FileStream << m_MaterialList[i]->GetMGeant(); } FileStream << endl << "end" << endl; FileStream.close(); // --------------------------------------------------------------------------- // Create the tracking media file: MEGA_media.med // --------------------------------------------------------------------------- if (FilePrefix == "") { FileName = "media.med"; } else { FileName = FilePrefix + ".med"; } // gcc 2.95.3: FileStream.open("MEGA_media.med", ios::out, 0664); FileStream.open(FileName, ios_base::out); FileStream<< "! +============================================================================+"<<endl<< "! MEGA_media.med MGEANT/MGGPOD tracking media list file "<<endl<< "! "<<endl<< "! Based on setup file: " << theFile << endl << "! "<<endl<< "! Copyright (C) by the MEGA-team. "<<endl<< "! All rights reserved. "<<endl<< "! "<<endl<< "! Author: This file has been automatically generated by the "<<endl<< "! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<< "! +============================================================================+"<<endl<< "! Format for User Media --> "<<endl<< "! tmed itmed chmed chmat pass/dete/shld/mask -> "<<endl<< "! ->ifield fieldm *tmaxfd *stemax *deemax epsil *stmin nwbuf <CR> "<<endl<< "! [ubuf] "<<endl<< "! (* set negative for automatic calculation of tracking parameter) "<<endl<< "! tpar chmed chpar parval "<<endl<< "! +============================================================================+"<<endl; FileStream<<endl<<endl; FileStream<<"! Some additional comments:"<<endl; FileStream<<"! Adjust material sorting by hand to dete, pass, shld, or mask"<<endl; FileStream<<"! as required - see MGEANT manual!"<<endl; FileStream<<endl<<endl; for (unsigned int i = 0; i < GetNMaterials(); i++) { // Check if a detector consists of this material: int Sensitivity = 0; for (unsigned int d = 0; d < GetNDetectors(); ++d) { for (unsigned int v = 0; v < GetDetectorAt(d)->GetNSensitiveVolumes(); ++v) { if (GetDetectorAt(d)->GetSensitiveVolume(v)->GetMaterial()->GetName() == GetMaterialAt(i)->GetName()) { if (GetDetectorAt(d)->GetDetectorType() == MDDetector::c_ACS) { Sensitivity = 2; } else { Sensitivity = 1; } } } } FileStream << m_MaterialList[i]->GetMGeantTmed(Sensitivity); } FileStream << endl << "end" << endl; FileStream.close(); // --------------------------------------------------------------------------- // Create the geometry file: MEGA_setup.geo // --------------------------------------------------------------------------- if (FilePrefix == "") { FileName = "setup.geo"; } else { FileName = FilePrefix + ".geo"; } // gcc 2.95.3: FileStream.open("MEGA_setup.geo", ios::out, 0664); FileStream.open(FileName, ios_base::out); FileStream<< "! +============================================================================+"<<endl<< "! MEGA_setup.geo MGEANT/MGGPOD geometry list file "<<endl<< "! "<<endl<< "! Based on setup file: " << theFile << endl << "! "<<endl<< "! Copyright (C) by the MEGA-team. "<<endl<< "! All rights reserved. "<<endl<< "! "<<endl<< "! Author: This file has been automatically generated by the "<<endl<< "! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<< "! +============================================================================+"<<endl<< "! Format for Shape and Position Parameters Input --> "<<endl<< "! rotm irot theta1 phi1 theta2 phi2 theta3 phi3 "<<endl<< "! volu chname chshap chmed npar <CR> "<<endl<< "! [parms] "<<endl<< "! posi chname copy chmoth x y z irot chonly "<<endl<< "! posp chname copy chmoth x y z irot chonly npar <CR> "<<endl<< "! parms "<<endl<< "! divn chname chmoth ndiv iaxis "<<endl<< "! dvn2 chname chmoth ndiv iaxis co chmed "<<endl<< "! divt chname chmoth step iaxis chmed ndvmx "<<endl<< "! dvt2 chname chmoth step iaxis co chmed ndvmx "<<endl<< "! divx chname chmoth ndiv iaxis step co chmed ndvmx "<<endl<< "! satt chname chiatt ival "<<endl<< "! tree ndets firstdetnum detlvl shldlvl masklvl "<<endl<< "! Euclid support => "<<endl<< "! eucl filename "<<endl<< "! ROTM irot theta1 phi1 theta2 phi2 theta3 phi3 "<<endl<< "! VOLU 'chname' 'chshap' numed npar <CR> "<<endl<< "! [parms] "<<endl<< "! POSI 'chname' copy 'chmoth' x y z irot 'chonly' "<<endl<< "! POSP 'chname' copy 'chmoth' x y z irot 'chonly' npar <CR> "<<endl<< "! parms "<<endl<< "! DIVN 'chname' 'chmoth' ndiv iaxis "<<endl<< "! DVN2 'chname' 'chmoth' ndiv iaxis co numed "<<endl<< "! DIVT 'chname' 'chmoth' step iaxis numed ndvmx "<<endl<< "! DVT2 'chname' 'chmoth' step iaxis co numed ndvmx "<<endl<< "! +============================================================================+"<<endl; FileStream<<endl<<endl; // Tree command - not needed for ACT / INIT - but do not delete // FileStream << "! Tree Structure (must be modified manually!)" << endl; // FileStream << "tree 1 1 1 1 1" << endl << endl; // Volume tree data FileStream << m_WorldVolume->GetMGeant() << endl; // Volume position data int IDCounter = 1; FileStream << m_WorldVolume->GetMGeantPosition(IDCounter) << endl; FileStream << endl << "end" << endl; FileStream.close(); // --------------------------------------------------------------------------- // Create the detector initialization file: detector.det // --------------------------------------------------------------------------- if (FilePrefix == "") { FileName = "detector.det"; } else { FileName = FilePrefix + "_detector.det"; } // open the geometry-file: FileStream.open(FileName, ios_base::out); FileStream<< "! +============================================================================+"<<endl<< "! detector.det MGGPOD-MEGALIB-extension detector & trigger description "<<endl<< "! "<<endl<< "! Based on setup file: " << theFile << endl << "! "<<endl<< "! Copyright (C) by the MEGA-team. "<<endl<< "! All rights reserved. "<<endl<< "! "<<endl<< "! Author: This file has been automatically generated by the "<<endl<< "! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<< "! +============================================================================+"<<endl<< "\n"<<endl; FileStream<<"NDET "<<GetNDetectors()<<endl<<endl; if (GetNDetectors() > 0) { FileStream<<"NSEN "<<GetDetectorAt(0)->GetGlobalNSensitiveVolumes()<<endl<<endl; } // Write detectors for(unsigned int i = 0; i < GetNDetectors(); i++) { FileStream<<m_DetectorList[i]->GetMGeant(); } // Write trigger conditions FileStream<<"NTRG "<<GetNTriggers()<<endl<<endl; for(unsigned int i = 0; i < GetNTriggers(); i++) { FileStream<<m_TriggerList[i]->GetMGeant(i+1); } FileStream<<endl; FileStream<<"END"<<endl; FileStream.close(); if (FilePrefix == "") { FileName = "megalib.ini"; } else { FileName = FilePrefix + "_megalib.ini"; } // open the geometry-file: FileStream.open(FileName, ios_base::out); FileStream<< "! +============================================================================+"<<endl<< "! megalib.ini MGGPOD-MEGALIB-extension setup input file "<<endl<< "! "<<endl<< "! Based on setup file: " << theFile << endl << "! "<<endl<< "! Copyright (C) by the MEGA-team. "<<endl<< "! All rights reserved. "<<endl<< "! "<<endl<< "! Author: This file has been automatically generated by the "<<endl<< "! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<< "! +============================================================================+"<<endl<< "\n"<<endl; FileStream<<endl; FileStream<<"GNAM "<<theFile<<endl; FileStream<<endl; FileStream<<"VERS 24"<<endl; FileStream<<endl; if (StoreIAs == true) { FileStream<<"EIFO 1"<<endl; } else { FileStream<<"EIFO 0"<<endl; } if (StoreVetoes == true) { FileStream<<"VIFO 1"<<endl; } else { FileStream<<"VIFO 0"<<endl; } FileStream<<endl; FileStream<<"END"<<endl; FileStream.close(); // Clean up... m_WorldVolume->ResetCloneTemplateFlags(); return true; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::ValidName(MString Name) { // Return true if name is a valid name, i.e. only contains alphanumeric // characters as well as "_" for (size_t i = 0; i < Name.Length(); ++i) { if (isalnum(Name[i]) == 0 && Name[i] != '_') { mout<<" *** Error *** in Name \""<<Name<<"\""<<endl; mout<<"Names are only allowed to contain alphanumeric characters as well as \"_\""<<endl; return false; } } return true; } //////////////////////////////////////////////////////////////////////////////// MString MDGeometry::MakeValidName(MString Name) { // Makes a valid name out of "Name" // If the returned string is empty this task was impossible MString ValidName; for (size_t i = 0; i < Name.Length(); ++i) { if (isalnum(Name[i]) != 0 || Name[i] == '_' || Name[i] == '-') { ValidName += Name[i]; } } return ValidName; } //////////////////////////////////////////////////////////////////////////////// MString MDGeometry::CreateShortName(MString Name, unsigned int Length, bool Fill, bool KeepKeywords) { // Create a Length character short name out of name, which is not in one of // the lists (detectors, materials, volumes) // e.g. if there exist two volumes, TrackerBox and TrackerStalk, // the first one is called TRAC, the second TRA0 if (m_IgnoreShortNames == true) { return "IGNO"; } MString SN; Name.ToLower(); bool FoundMicsetKeyword = false; MString MicsetKeyword = "_micset"; if (KeepKeywords == true && Name.Contains(MicsetKeyword) == true) { //mout<<" *** Info ***"<<endl; //mout<<"Special MGGPOD material keyword "<<MicsetKeyword<<" found!"<<endl; FoundMicsetKeyword = true; Name.ReplaceAll(MicsetKeyword, ""); Length -= MicsetKeyword.Length(); } bool FoundGeRecoilKeyword = false; MString GeRecoilKeyword = "_ge_recoil"; if (KeepKeywords == true && Name.Contains(GeRecoilKeyword) == true) { //mout<<" *** Info ***"<<endl; //mout<<"Special MGGPOD material keyword "<<GeRecoilKeyword<<" found!"<<endl; FoundGeRecoilKeyword = true; Name.ReplaceAll(GeRecoilKeyword, ""); Length -= GeRecoilKeyword.Length(); } bool FoundSiRecoilKeyword = false; MString SiRecoilKeyword = "_si_recoil"; if (KeepKeywords == true && Name.Contains(SiRecoilKeyword) == true) { //mout<<" *** Info ***"<<endl; //mout<<"Special MGGPOD material keyword "<<SiRecoilKeyword<<" found!"<<endl; FoundSiRecoilKeyword = true; Name.ReplaceAll(SiRecoilKeyword, ""); Length -= SiRecoilKeyword.Length(); } bool FoundCZTRecoilKeyword = false; MString CZTRecoilKeyword = "_czt_recoil"; if (KeepKeywords == true && Name.Contains(CZTRecoilKeyword) == true) { //mout<<" *** Info ***"<<endl; //mout<<"Special MGGPOD material keyword "<<CZTRecoilKeyword<<" found!"<<endl; FoundCZTRecoilKeyword = true; Name.ReplaceAll(CZTRecoilKeyword, ""); Length -= CZTRecoilKeyword.Length(); } bool FoundAddRecoilKeyword = false; MString AddRecoilKeyword = "_addrec"; if (KeepKeywords == true && Name.Contains(AddRecoilKeyword) == true) { mout<<" *** Info ***"<<endl; mout<<"Special MGGPOD material keyword "<<AddRecoilKeyword<<" found!"<<endl; FoundAddRecoilKeyword = true; Name.ReplaceAll(AddRecoilKeyword, ""); Length -= AddRecoilKeyword.Length(); } // Remove everything which is not alphanumerical from the name: for (size_t i = 0; i < Name.Length(); ++i) { if (isalnum(Name[i]) == false && Name[i] != '_' && Name[i] != '-') { Name.Remove(i, 1); } } // Keep only first "Length" charcters:callgrind.out.16396 Name = Name.GetSubString(0, Length); if (Length < 4) Length = 4; // if we are smaller, we can try to expand the name: if (Name.Length() < Length) { if (ShortNameExists(Name) == true) { unsigned int MaxExpand = 0; if (pow(10.0, (int) (Length-Name.Length())) - 1 > numeric_limits<unsigned int>::max()) { MaxExpand = numeric_limits<unsigned int>::max(); } else { MaxExpand = (unsigned int) (pow(10.0, (int) (Length-Name.Length())) - 1.0); } for (unsigned int i = 1; i < MaxExpand; ++i) { SN = Name; SN += i; if (ShortNameExists(SN) == false) { Name = SN; break; } } } } // If we still haven't found a suited short name: if (ShortNameExists(Name) == true) { // Step one: test the first "Length" letters SN = Name.Replace(Length, Name.Length() - Length, ""); if (ShortNameExists(SN) == true) { // Step three: Replace the last character by a number ... for (int j = (int) '0'; j < (int) '9'; j++) { SN[Length-1] = (char) j; if (ShortNameExists(SN) == false) { break; } } } if (ShortNameExists(SN) == true) { // Step four: Replace the last two characters by a numbers ... for (int i = (int) '0'; i < (int) '9'; i++) { for (int j = (int) '0'; j < (int) '9'; j++) { SN[Length-2] = (char) i; SN[Length-1] = (char) j; if (ShortNameExists(SN) == false) { break; } } if (ShortNameExists(SN) == false) { break; } } } if (ShortNameExists(SN) == true) { // Step five: Replace the last three characters by a numbers ... for (int k = (int) '0'; k < (int) '9'; k++) { for (int i = (int) '0'; i < (int) '9'; i++) { for (int j = (int) '0'; j < (int) '9'; j++) { SN[Length-3] = (char) k; SN[Length-2] = (char) i; SN[Length-1] = (char) j; if (ShortNameExists(SN) == false) { break; } } if (ShortNameExists(SN) == false) { break; } } if (ShortNameExists(SN) == false) { break; } } } if (ShortNameExists(SN) == true) { // That's too much: merr<<"You have too many volumes starting with "<<Name<<endl; merr<<"Please add \"IgnoreShortNames true\" into your geometry file!"<<endl; merr<<"As a result you are not able to do Geant3/MGEANT/MGGPOS simulations"<<endl; m_IgnoreShortNames = true; return "IGNO"; } Name = SN; } if (KeepKeywords == true && FoundMicsetKeyword == true) { Name += MicsetKeyword; Length += MicsetKeyword.Length(); } if (KeepKeywords == true && FoundGeRecoilKeyword == true) { Name += GeRecoilKeyword; Length += GeRecoilKeyword.Length(); } if (KeepKeywords == true && FoundSiRecoilKeyword == true) { Name += SiRecoilKeyword; Length += SiRecoilKeyword.Length(); } if (KeepKeywords == true && FoundCZTRecoilKeyword == true) { Name += CZTRecoilKeyword; Length += CZTRecoilKeyword.Length(); } if (KeepKeywords == true && FoundAddRecoilKeyword == true) { Name += AddRecoilKeyword; Length += AddRecoilKeyword.Length(); } // We always need a name which has exactly Length characters while (Name.Length() < Length) { if (Fill == true) { Name += '_'; } else { Name += ' '; } } return Name; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::ShortNameExists(MString Name) { // Check all lists if "Name" is already listed MString ObjectName; MString ShortName; MString OriginalMGeantShortName; MString ShortNameDivisionX; MString ShortNameDivisionY; MString ShortNameDivisionZ; Name.ToLower(); // Test volumes for (unsigned int i = 0; i < GetNVolumes(); i++) { ObjectName = m_VolumeList[i]->GetName(); ObjectName.ToLower(); ShortName = m_VolumeList[i]->GetShortName(); ShortName.ToLower(); if (Name == ObjectName || Name == ShortName) { return true; } } // Test materials for (unsigned int i = 0; i < GetNMaterials(); i++) { ObjectName = m_MaterialList[i]->GetName(); ObjectName.ToLower(); ShortName = m_MaterialList[i]->GetShortName(); ShortName.ToLower(); OriginalMGeantShortName = m_MaterialList[i]->GetOriginalMGeantShortName(); OriginalMGeantShortName.ToLower(); if (Name == ObjectName || Name == ShortName || Name == OriginalMGeantShortName) { return true; } } // Test detectors for (unsigned int i = 0; i < GetNDetectors(); i++) { ObjectName = m_DetectorList[i]->GetName(); ObjectName.ToLower(); ShortNameDivisionX = m_DetectorList[i]->GetShortNameDivisionX(); ShortNameDivisionX.ToLower(); ShortNameDivisionY = m_DetectorList[i]->GetShortNameDivisionY(); ShortNameDivisionY.ToLower(); ShortNameDivisionZ = m_DetectorList[i]->GetShortNameDivisionZ(); ShortNameDivisionZ.ToLower(); if (Name == ObjectName || Name == ShortNameDivisionX || Name == ShortNameDivisionY || Name == ShortNameDivisionZ) { return true; } } // Test triggers for (unsigned int i = 0; i < GetNTriggers(); i++) { ObjectName = m_TriggerList[i]->GetName(); ObjectName.ToLower(); if (Name == ObjectName) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::AddVolume(MDVolume* Volume) { // Add a volume to the list m_VolumeList.push_back(Volume); } //////////////////////////////////////////////////////////////////////////////// MDVolume* MDGeometry::GetWorldVolume() { // return the world volume return m_WorldVolume; } //////////////////////////////////////////////////////////////////////////////// MDVolume* MDGeometry::GetVolumeAt(const unsigned int i) const { // return the volume at position i in the list. Counting starts with zero! if (i < m_VolumeList.size()) { return m_VolumeList[i]; } else { merr<<"Index ("<<i<<") out of bounds (0, "<<GetNVolumes()-1<<")"<<endl; return 0; } } //////////////////////////////////////////////////////////////////////////////// MDVolume* MDGeometry::GetVolume(const MString& Name) { // Return the volume with name Name or 0 if it does not exist // This function is not reentrant!!!! // ---> begin extremely time critical const unsigned int Size = 20; list<MDVolume*>::iterator I; for (I = m_LastVolumes.begin(); I != m_LastVolumes.end(); ++I) { if ((*I)->GetName().AreIdentical(Name)) { return (*I); } } unsigned int i, i_max = m_VolumeList.size(); for (i = m_LastVolumePosition; i < i_max; ++i) { if (m_VolumeList[i]->GetName().AreIdentical(Name)) { m_LastVolumes.push_front(m_VolumeList[i]); if (m_LastVolumes.size() > Size) m_LastVolumes.pop_back(); m_LastVolumePosition = i; return m_VolumeList[i]; } } for (i = 0; i < m_LastVolumePosition; ++i) { if (m_VolumeList[i]->GetName().AreIdentical(Name)) { m_LastVolumes.push_front(m_VolumeList[i]); if (m_LastVolumes.size() > Size) m_LastVolumes.pop_back(); m_LastVolumePosition = i; return m_VolumeList[i]; } } // Not optimized: //unsigned int i, i_max = m_VolumeList.size(); //for (i = 0; i < i_max; ++i) { // if (Name == m_VolumeList[i]->GetName()) { // return m_VolumeList[i]; // } //} // Infos: CompareTo is faster than == // <--- end extremely time critical return 0; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetVolumeIndex(const MString& Name) { // Return the index of volume with name Name or g_UnsignedIntNotDefined if it does not exist unsigned int i, i_max = m_VolumeList.size(); for (i = 0; i < i_max; ++i) { if (Name == m_VolumeList[i]->GetName()) { return i; } } return g_UnsignedIntNotDefined; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetNVolumes() const { // Return the number of volumes in the list return m_VolumeList.size(); } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::AddDetector(MDDetector* Detector) { // Add a volume to the list m_DetectorList.push_back(Detector); } //////////////////////////////////////////////////////////////////////////////// MDDetector* MDGeometry::GetDetectorAt(unsigned int i) { // return the volume at position i in the list. Counting starts with zero! if (i < GetNDetectors()) { return m_DetectorList[i]; } else { merr<<"Index ("<<i<<") out of bounds (0, "<<GetNDetectors()-1<<")"<<endl; return 0; } } //////////////////////////////////////////////////////////////////////////////// MDDetector* MDGeometry::GetDetector(const MString& Name) { // Return the detector with name Name or 0 if it does not exist for (unsigned int i = 0; i < GetNDetectors(); i++) { if (Name == m_DetectorList[i]->GetName()) { return m_DetectorList[i]; } } return 0; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetDetectorIndex(const MString& Name) { // Return the index of material with name Name or g_UnsignedIntNotDefined if it does not exist unsigned int i, i_max = GetNDetectors(); for (i = 0; i < i_max; i++) { if (Name == m_DetectorList[i]->GetName()) { return i; } } return g_UnsignedIntNotDefined; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetNDetectors() { // Return the number of volumes in the list return m_DetectorList.size(); } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::AddShape(const MString& Type, const MString& Name) { // Add a shape to the list MString S = Type; S.ToLowerInPlace(); if (S == "box" || S == "brik") { AddShape(new MDShapeBRIK(Name)); } else if (S == "sphe" || S == "sphere") { AddShape(new MDShapeSPHE(Name)); } else if (S == "cone") { AddShape(new MDShapeCONE(Name)); } else if (S == "cons") { AddShape(new MDShapeCONS(Name)); } else if (S == "pcon") { AddShape(new MDShapePCON(Name)); } else if (S == "pgon") { AddShape(new MDShapePGON(Name)); } else if (S == "tubs" || S == "tube") { AddShape(new MDShapeTUBS(Name)); } else if (S == "trap") { AddShape(new MDShapeTRAP(Name)); } else if (S == "trd1") { AddShape(new MDShapeTRD1(Name)); } else if (S == "trd2") { AddShape(new MDShapeTRD2(Name)); } else if (S == "gtra") { AddShape(new MDShapeGTRA(Name)); } else if (S == "subtraction") { AddShape(new MDShapeSubtraction(Name)); } else if (S == "union") { AddShape(new MDShapeUnion(Name)); } else if (S == "intersection") { AddShape(new MDShapeIntersection(Name)); } else { Typo("Line does not contain a known shape type!"); return false; } return true; } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::AddShape(MDShape* Shape) { // Add a shape to the list m_ShapeList.push_back(Shape); } //////////////////////////////////////////////////////////////////////////////// MDShape* MDGeometry::GetShapeAt(unsigned int i) { // return the shape at position i in the list. Counting starts with zero! if (i < GetNShapes()) { return m_ShapeList[i]; } else { merr<<"Index ("<<i<<") out of bounds (0, "<<GetNShapes()-1<<")"<<endl; return 0; } } //////////////////////////////////////////////////////////////////////////////// MDShape* MDGeometry::GetShape(const MString& Name) { // Return the shape with name Name or 0 if it does not exist for (unsigned int i = 0; i < GetNShapes(); i++) { if (Name == m_ShapeList[i]->GetName()) { return m_ShapeList[i]; } } return 0; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetShapeIndex(const MString& Name) { // Return the index of the shape with name Name or g_UnsignedIntNotDefined if it does not exist unsigned int i, i_max = GetNShapes(); for (i = 0; i < i_max; i++) { if (Name == m_ShapeList[i]->GetName()) { return i; } } return g_UnsignedIntNotDefined; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetNShapes() { // Return the number of shapes in the list return m_ShapeList.size(); } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::AddOrientation(MDOrientation* Orientation) { // Add an orientation to the list m_OrientationList.push_back(Orientation); } //////////////////////////////////////////////////////////////////////////////// MDOrientation* MDGeometry::GetOrientationAt(unsigned int i) { // return the orientation at position i in the list. Counting starts with zero! if (i < GetNOrientations()) { return m_OrientationList[i]; } else { merr<<"Index ("<<i<<") out of bounds (0, "<<GetNOrientations()-1<<")"<<endl; return 0; } } //////////////////////////////////////////////////////////////////////////////// MDOrientation* MDGeometry::GetOrientation(const MString& Name) { // Return the orientation with name Name or 0 if it does not exist for (unsigned int i = 0; i < GetNOrientations(); i++) { if (Name == m_OrientationList[i]->GetName()) { return m_OrientationList[i]; } } return 0; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetOrientationIndex(const MString& Name) { // Return the index of the orientation with name Name or g_UnsignedIntNotDefined if it does not exist unsigned int i, i_max = GetNOrientations(); for (i = 0; i < i_max; i++) { if (Name == m_OrientationList[i]->GetName()) { return i; } } return g_UnsignedIntNotDefined; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetNOrientations() { // Return the number of orientations in the list return m_OrientationList.size(); } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::AddMaterial(MDMaterial* Material) { // Add a material to the list m_MaterialList.push_back(Material); } //////////////////////////////////////////////////////////////////////////////// MDMaterial* MDGeometry::GetMaterialAt(unsigned int i) { // return the material at position i in the list. Counting starts with zero! if (i < GetNMaterials()) { return m_MaterialList[i]; } else { merr<<"Index ("<<i<<") out of bounds (0, "<<GetNMaterials()-1<<")"<<endl; return 0; } } //////////////////////////////////////////////////////////////////////////////// MDMaterial* MDGeometry::GetMaterial(const MString& Name) { // Return the material with name Name or 0 if it does not exist for (unsigned int i = 0; i < GetNMaterials(); i++) { if (Name == m_MaterialList[i]->GetName()) { return m_MaterialList[i]; } } return 0; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetMaterialIndex(const MString& Name) { // Return the material with name Name or 0 if it does not exist unsigned int i, i_max = GetNMaterials(); for (i = 0; i < i_max; i++) { if (Name == m_MaterialList[i]->GetName()) { return i; } } return g_UnsignedIntNotDefined; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetNMaterials() { // Return the number of materials in the list return m_MaterialList.size(); } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::AddTrigger(MDTrigger* Trigger) { // Add a material to the list m_TriggerList.push_back(Trigger); } //////////////////////////////////////////////////////////////////////////////// MDTrigger* MDGeometry::GetTriggerAt(unsigned int i) { // return the material at position i in the list. Counting starts with zero! if (i < GetNTriggers()) { return m_TriggerList[i]; } else { merr<<"Index ("<<i<<") out of bounds (0, "<<GetNTriggers()-1<<")"<<endl; return 0; } } //////////////////////////////////////////////////////////////////////////////// MDTrigger* MDGeometry::GetTrigger(const MString& Name) { // Return the material with name Name or 0 if it does not exist unsigned int i; for (i = 0; i < GetNTriggers(); i++) { if (Name == m_TriggerList[i]->GetName()) { return m_TriggerList[i]; } } return 0; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetTriggerIndex(const MString& Name) { // Return the material with name Name or 0 if it does not exist unsigned int i, i_max = GetNTriggers(); for (i = 0; i < i_max; i++) { if (Name == m_TriggerList[i]->GetName()) { return i; } } return g_UnsignedIntNotDefined; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetNTriggers() { // Return the number of materials in the list return m_TriggerList.size(); } //////////////////////////////////////////////////////////////////////////////// MDSystem* MDGeometry::GetSystem(const MString& Name) { // Return the system with name Name or 0 if it does not exist if (m_System->GetName() == Name) { return m_System; } return 0; } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::AddVector(MDVector* Vector) { // Add a vector to the list m_VectorList.push_back(Vector); } //////////////////////////////////////////////////////////////////////////////// MDVector* MDGeometry::GetVectorAt(unsigned int i) { // return the vector at position i in the list. Counting starts with zero! if (i < GetNVectors()) { return m_VectorList[i]; } else { merr<<"Index ("<<i<<") out of bounds (0, "<<GetNVectors()-1<<")"<<endl; return 0; } } //////////////////////////////////////////////////////////////////////////////// MDVector* MDGeometry::GetVector(const MString& Name) { // Return the vector with name Name or 0 if it does not exist unsigned int i; for (i = 0; i < GetNVectors(); i++) { if (Name == m_VectorList[i]->GetName()) { return m_VectorList[i]; } } return 0; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetVectorIndex(const MString& Name) { // Return the vector with name Name or 0 if it does not exist unsigned int i, i_max = GetNVectors(); for (i = 0; i < i_max; i++) { if (Name == m_VectorList[i]->GetName()) { return i; } } return g_UnsignedIntNotDefined; } //////////////////////////////////////////////////////////////////////////////// unsigned int MDGeometry::GetNVectors() { // Return the number of vectors in the list return m_VectorList.size(); } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::AddInclude(MString FileName) { // Add the name of an included file if (IsIncluded(FileName) == false) { m_IncludeList->AddLast(new TObjString(FileName)); } } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::IsIncluded(MString FileName) { // Check if the file has already been included for (int i = 0; i < GetNIncludes(); i++) { if (dynamic_cast<TObjString*>(m_IncludeList->At(i))->GetString().CompareTo(FileName) == 0) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// int MDGeometry::GetNIncludes() { // Get the number of included files: return m_IncludeList->GetLast()+1; } //////////////////////////////////////////////////////////////////////////////// MString MDGeometry::ToString() { // unsigned int i; ostringstream out; out<<endl<<"Description of geometry: "<<m_Name<<", version: "<<m_Version<<endl; out<<endl<<endl<<"Description of volumes:"<<endl; for (i = 0; i < m_VolumeList.size(); ++i) { out<<m_VolumeList[i]->GetName()<<endl;; out<<m_VolumeList[i]->ToString()<<endl;; } out<<endl<<endl<<"Description of volume-tree:"<<endl; if (m_WorldVolume != 0) { out<<m_WorldVolume->ToStringVolumeTree(0)<<endl; } out<<endl<<endl<<"Description of materials:"<<endl<<endl; for (i = 0; i < m_MaterialList.size(); ++i) { out<<m_MaterialList[i]->ToString(); } out<<endl<<endl<<"Description of detectors:"<<endl<<endl; for (i = 0; i < m_DetectorList.size(); ++i) { out<<m_DetectorList[i]->ToString()<<endl; } out<<endl<<endl<<"Description of triggers:"<<endl<<endl; for (i = 0; i < m_TriggerList.size(); ++i) { out<<m_TriggerList[i]->ToString()<<endl; } return out.str().c_str(); } //////////////////////////////////////////////////////////////////////////////// MString MDGeometry::GetName() { // return m_Name; } //////////////////////////////////////////////////////////////////////////////// MString MDGeometry::GetFileName() { // return m_FileName; } //////////////////////////////////////////////////////////////////////////////// double MDGeometry::GetStartSphereRadius() const { return m_SphereRadius; } //////////////////////////////////////////////////////////////////////////////// double MDGeometry::GetStartSphereDistance() const { return m_DistanceToSphereCenter; } //////////////////////////////////////////////////////////////////////////////// MVector MDGeometry::GetStartSpherePosition() const { return m_SpherePosition; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::HasComplexER() { // Return true if the co0mplex geometry is used for event reconstrcution, // i.e. if volume sequences are necessary return m_ComplexER; } //////////////////////////////////////////////////////////////////////////////// vector<MDMaterial*> MDGeometry::GetListOfUnusedMaterials() { // Return a list of unused materials // First create a list of used materials: vector<MDMaterial*> Used; for (unsigned int v = 0; v < m_VolumeList.size(); ++v) { MDMaterial* M = m_VolumeList[v]->GetMaterial(); if (find(Used.begin(), Used.end(), M) == Used.end()) { Used.push_back(M); } } // Now create a list of not used materials: vector<MDMaterial*> Unused; for (unsigned int m = 0; m < m_MaterialList.size(); ++m) { if (find(Used.begin(), Used.end(), m_MaterialList[m]) == Used.end()) { Unused.push_back(m_MaterialList[m]); } } return Unused; } //////////////////////////////////////////////////////////////////////////////// MDVolumeSequence MDGeometry::GetVolumeSequence(MVector Pos, bool ForceDetector, bool ForceSensitiveVolume) { // Return the volume sequence for this position... MDVolumeSequence* VSpointer = GetVolumeSequencePointer(Pos, ForceDetector, ForceSensitiveVolume); MDVolumeSequence VS = *VSpointer; delete VSpointer; return VS; } //////////////////////////////////////////////////////////////////////////////// MDVolumeSequence* MDGeometry::GetVolumeSequencePointer(MVector Pos, bool ForceDetector, bool ForceSensitiveVolume) { // Return the volume sequence for this position... MDVolumeSequence* VS = new MDVolumeSequence(); m_WorldVolume->GetVolumeSequence(Pos, VS); if ((ForceDetector == true && VS->GetDetector() == 0) || (ForceSensitiveVolume == true && VS->GetSensitiveVolume() == 0)) { MVector OrigPos = Pos; double Tolerance = m_DetectorSearchTolerance; ostringstream out; out<<endl; out<<" Warning:"<<endl; if (VS->GetDetector() == 0) { out<<" No detector volume could be found for the hit at position "; } else { out<<" No sensitive volume could be found for the hit at position "; } out<<setprecision(20)<<OrigPos[0]<<", "<<OrigPos[1]<<", "<<OrigPos[2]<<setprecision(6)<<endl; if (VS->GetDeepestVolume() != 0) { out<<" The deepest volume is: "<<VS->GetDeepestVolume()->GetName()<<endl; } out<<" Possible reasons are: "<<endl; out<<" * The hit is just (+-"<<Tolerance<<" cm) outside the border of the volume:" <<endl; out<<" -> Make sure you have stored your simulation file with enough digits"<<endl; out<<" (cosima keyword \"StoreScientific\") so that the volume borders can be separated"<<endl; out<<" -> Make sure your search tolerance given in the geometry file (geomega keyword"<<endl; out<<" \"DetectorSearchTolerance\") is not too small"<<endl; out<<" * The current and the simulation geometry are not identical"<<endl; out<<" * There are overlaps in your geometry:"<<endl; // Check for overlaps: vector<MDVolume*> OverlappingVolumes; m_WorldVolume->FindOverlaps(Pos, OverlappingVolumes); if (OverlappingVolumes.size() > 1) { out<<" The following volumes overlap:"<<endl; for (unsigned int i = 0; i < OverlappingVolumes.size(); ++i) { out<<" "<<OverlappingVolumes[i]->GetName()<<endl; } } else { out<<" -> No simple overlaps found, but you might do a full overlap check anyway..."<<endl; } // Start the search within a tolerance limit if (VS->GetDetector() == 0) { out<<" Searching for a detector within "<<Tolerance<<" cm around the given position..."<<endl; } else { out<<" Searching for a sensitive volume within "<<Tolerance<<" cm around the given position..."<<endl; } Pos = OrigPos; Pos[0] += Tolerance; VS->Reset(); m_WorldVolume->GetVolumeSequence(Pos, VS); if (VS->GetDeepestVolume() != 0) { if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } } Pos = OrigPos; Pos[0] -= Tolerance; VS->Reset(); m_WorldVolume->GetVolumeSequence(Pos, VS); if (VS->GetDeepestVolume() != 0) { if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } } Pos = OrigPos; Pos[1] += Tolerance; VS->Reset(); m_WorldVolume->GetVolumeSequence(Pos, VS); if (VS->GetDeepestVolume() != 0) { if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } } Pos = OrigPos; Pos[1] -= Tolerance; VS->Reset(); m_WorldVolume->GetVolumeSequence(Pos, VS); if (VS->GetDeepestVolume() != 0) { if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } } Pos = OrigPos; Pos[2] += Tolerance; VS->Reset(); m_WorldVolume->GetVolumeSequence(Pos, VS); if (VS->GetDeepestVolume() != 0) { if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } } Pos = OrigPos; Pos[2] -= Tolerance; VS->Reset(); m_WorldVolume->GetVolumeSequence(Pos, VS); if (VS->GetDeepestVolume() != 0) { if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) { out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl; return VS; } } out<<" --> No suitable volume found!"<<endl; // Only print the warning if we did not find anything mout<<out.str()<<endl; } return VS; } //////////////////////////////////////////////////////////////////////////////// MVector MDGeometry::GetGlobalPosition(const MVector& PositionInDetector, const MString& NamedDetector) { //! Use this function to convert a position within a NAMED detector //! (i.e. uniquely identifyable) into a position in the global coordinate system MVector Position = g_VectorNotDefined; // Find the detector (class) which contains the given named detector bool Found = false; for (unsigned d = 0; d < m_DetectorList.size(); ++d) { if (m_DetectorList[d]->HasNamedDetector(NamedDetector) == true) { Position = m_DetectorList[d]->GetGlobalPosition(PositionInDetector, NamedDetector); Found = true; break; } } if (Found == false) { mout<<" *** Error *** Named detector not found: "<<NamedDetector<<endl; } return Position; } //////////////////////////////////////////////////////////////////////////////// MVector MDGeometry::GetRandomPositionInVolume(const MString& Name) { //! Return a random position in the given volume --- excluding daughter volumes! //! Any of the clone templates!!! (needed by Cosima) if (m_GeometryScanned == false) { merr<<"Geometry has to be scanned first!"<<endl; return g_VectorNotDefined; } MDVolume* Volume = GetVolume(Name); if (Volume == 0) { merr<<"No volume of this name exists: "<<Name<<endl; return g_VectorNotDefined; } if (Volume->IsClone()) { Volume = Volume->GetCloneTemplate(); } //cout<<"Volume: "<<Name<<endl; // First find out how many placements we have: vector<int> Placements; int TreeDepth = -1; m_WorldVolume->GetNPlacements(Volume, Placements, TreeDepth); int Total = 1; //cout<<"Placements"<<endl; for (unsigned int i = 0; i < Placements.size(); ++i) { //cout<<Placements[i]<<endl; if (Placements[i] != 0) { Total *= Placements[i]; } } //cout<<"Total: "<<Total<<endl; int Random = gRandom->Integer(Total); //cout<<"Random: "<<Random<<endl; // Update the placements to reflect the ID of the random volume vector<int> NewPlacements; for (unsigned int i = 0; i < Placements.size(); ++i) { if (Placements[i] != 0) { Total = Total/Placements[i]; NewPlacements.push_back(Random / Total); Random = Random % Total; } else { //NewPlacements[i] = 0; } } //cout<<"New placements"<<endl; //for (unsigned int i = 0; i < NewPlacements.size(); ++i) { // cout<<NewPlacements[i]<<endl; //} TreeDepth = -1; MVector Pos = m_WorldVolume->GetRandomPositionInVolume(Volume, NewPlacements, TreeDepth); //cout<<Pos<<endl; return Pos; } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::CreateCrossSectionFiles() { // Create the x-section files if cosima is present mout<<endl; mout<<"Cross sections have changed or are missing. Starting calculation using cosima (Geant4)!"<<endl; mout<<endl; if (MFile::Exists(g_MEGAlibPath + "/bin/cosima") == false) { mout<<" *** Warning ***"<<endl; mout<<"Cannot create cross section files since cosima is not present."<<endl; return false; } // (1) Create a mimium cosima file: MString FileName = gSystem->TempDirectory(); FileName += "/DelMe.source"; ofstream out; out.open(FileName); if (out.is_open() == false) { mout<<" *** Error ***"<<endl; mout<<"Unable to create cosima source file for cross section creation"<<endl; return false; } out<<"Version 1"<<endl; out<<"Geometry "<<m_FileName<<endl; out<<"PhysicsListEM Standard"<<endl; out<<"CreateCrossSectionFiles "<<m_CrossSectionFileDirectory<<endl; out.close(); // (2) Run cosima mout<<"-------- Cosima output start --------"<<endl; MString WorkingDirectory = gSystem->WorkingDirectory(); gSystem->ChangeDirectory(gSystem->TempDirectory()); gSystem->Exec(MString("cosima ") + FileName); gSystem->Exec(MString("rm -f DelMe.*.sim ") + FileName); gSystem->ChangeDirectory(WorkingDirectory); mout<<"-------- Cosima output stop ---------"<<endl; // (3) Check if cross sections are loaded could be created bool Success = true; for (unsigned int i = 0; i < GetNMaterials(); i++) { if (m_MaterialList[i]->LoadCrossSections(true) == false) { Success = false; } } if (Success == false) { mout<<" *** Warning ***"<<endl; mout<<"Cannot load create cross section files correctly."<<endl; mout<<"Please read the above error output for a possible fix..."<<endl; return false; } return true; } //////////////////////////////////////////////////////////////////////////////// void MDGeometry::ReplaceWholeWords(MString& Text, const MString& OldWord, const MString& NewWord) { // In "Text" replace all occurances of OldWord with NewWord if the character // after "OldWord is not alphanumerical or "_" // This algorithm also appears MDDebugInfo::Replace if (Text.Length() > 0) { size_t Pos = 0; while ((Pos = Text.Index(OldWord, Pos)) != MString::npos) { //cout<<Text<<":"<<Pos<<endl; if (Text.Length() > Pos + OldWord.Length()) { //cout<<"i: "<<Text[Pos + OldWord.Length()]<<endl; if (isalnum(Text[Pos + OldWord.Length()]) != 0 || Text[Pos + OldWord.Length()] == '_') { //cout<<"cont."<<endl; Pos += OldWord.Length(); continue; } } if (Pos > 0) { if (isalnum(Text[Pos - 1]) != 0 || Text[Pos - 1] == '_') { //cout<<"cont."<<endl; Pos += OldWord.Length(); continue; } } Text.Replace(Pos, OldWord.Length(), NewWord); Pos += NewWord.Length(); } } } //////////////////////////////////////////////////////////////////////////////// bool MDGeometry::ContainsReplacableConstant(const MString& Text, const MString& Constant) { // Check if "Text" contains Constant as a real keyword if (Text.Contains(Constant) == false) return false; if (Text.Length() > 0) { size_t Pos = 0; while ((Pos = Text.Index(Constant, Pos)) != MString::npos) { // Found it! // The characters immediately before and after are not allowed to be alphanumerical or "_" if (Text.Length() > Pos + Constant.Length()) { //cout<<"i: "<<Text[Pos + OldWord.Length()]<<endl; if (isalnum(Text[Pos + Constant.Length()]) || Text[Pos + Constant.Length()] == '_') { return false; } } if (Pos > 0) { if (isalnum(Text[Pos - 1]) || Text[Pos - 1] == '_') { return false; } } Pos += Constant.Length(); } } return true; } // MDGeometry.cxx: the end... ////////////////////////////////////////////////////////////////////////////////
233edd190ed154c2aa075ddba767fafdcecee3d3
d0ff2c67da042ebfe6b0cd3f7fbbfdd24999e0c4
/specFW2/cmdmd.cpp
97b9ab6fd27c1eb4e90f2345df2bfaa662e334ff
[]
no_license
Pkijoe/specFW2
ed8e0b9a595faf57dfc345c4647196494fffd257
053a8c32ea481fc23a523e1249c55a574f808e2f
refs/heads/master
2020-04-07T00:03:15.362800
2018-11-15T18:45:17
2018-11-15T18:45:17
157,889,646
0
0
null
null
null
null
UTF-8
C++
false
false
4,968
cpp
//=========================================================================== // // Module Name: cmdMD.cpp // // Function: This routine selects the mode of operation: // SETUP-0,NOT_ON-1,COLD-2,HOT-A,READY-R,DIAG-X,AUTO-Z // // Original Author: T Frazzini // // Copyright (c) 2005, PerkinElmer, LAS. All rights reserved. // //=========================================================================== #include "StdAfx.h" #include "SpecFW2.h" #include "ParserThread.h" unsigned int CParserThread::cmdMD() { WORD status(NO_ERRORS); char cMode; theApp.EnterCriticalSection1(&m_CriticalSection); // Protect critical parameters strcpy(m_nDataOutBuf, "MD00"); cMode = *m_pCmdPtr++; m_nBytesRead++; if (m_cStartupMode > NOT_ON && m_cStartupMode < READY) { status = ERR_CMD; memcpy(&m_nDataOutBuf[2], "01", 2); } else { switch (cMode) { // case SETUP: // case AUTO: case DIAG: m_cOperationMode = cMode; m_cStartupMode = cMode; break; case MFG: //........................................................... // Mfg mode entry placed into the Spectrometer log. { char* szStr = new char[40]; GetDateTimeStamp(szStr); sprintf(&szStr[19], " Mode: Mfg (DCM)\0"); AddToSpecLog(szStr); } //........................................................... m_cOperationMode = cMode; m_cStartupMode = cMode; break; case READY: //........................................................... // Ready mode entry placed into the Spectrometer log. { char* szStr = new char[40]; GetDateTimeStamp(szStr); sprintf(&szStr[19], " Mode: Ready (DCM)\0"); AddToSpecLog(szStr); } //........................................................... m_cOperationMode = cMode; m_cStartupMode = cMode; break; case COLD: //........................................................... // Cold mode entry placed into the Spectrometer log. { char* szStr = new char[40]; GetDateTimeStamp(szStr); sprintf(&szStr[19], " Mode: Cold (DCM)\0"); AddToSpecLog(szStr); } //........................................................... m_cInitFlag = YES; /* Intialization to start */ if ( m_bCCDPower ) /* DETECTOR POWER OFF IF ON */ { m_bCCDPower = false; } m_cOperationMode = READY; m_cStartupMode = cMode; break; case HOT: //........................................................... // Hot mode entry placed into the Spectrometer log. { char* szStr = new char[40]; GetDateTimeStamp(szStr); sprintf(&szStr[19], " Mode: Hot (DCM)\0"); AddToSpecLog(szStr); } //........................................................... m_cInitFlag = YES; /* Intialization to start */ if ( m_bCCDPower ) /* DETECTOR POWER OFF IF ON */ { m_bCCDPower = false; } m_cOperationMode = READY; m_cStartupMode = cMode; break; default: status = ERR_PARA; memcpy(&m_nDataOutBuf[2], "07", 2); break; } } if (status == NO_ERRORS) { // Just in case system is in Sleep mode - disable checking m_bSleepFlag = false; m_nWarning = 0; // Clear ALL Warnings m_nFatal = 0; // Clear ALL Fatal messages if (m_cOperationMode == AUTO) { m_nOPmode = TEST; // TEST MODE m_nTestMode = NORMAL; // TEST MODE, NORMAL m_bTestMode = false; m_bOverscanMode = false; } else { m_nOPmode = NORMAL; // NORMAL MODE, NOT TESTING m_nTestMode = NORMAL; // NORMAL m_bTestMode = false; m_bOverscanMode = false; } } theApp.LeaveCriticalSection1(&m_CriticalSection); // Remove protection return status; } //=========================================================================== /*** Revision History *** 01/28/17 KR CBF-143 - Remove unwanted thermal commands $Log: /IcarusBased/SpecFW/cmdmd.cpp $ * * 8 4/07/08 5:09p Nashth * Added Mfg mode to History log. * * 7 4/07/08 10:41a Nashth * Second attempt at Spectrometer history log. * * 6 3/31/08 5:31p Nashth * Implementation of spectrometer history log... First pass. * * 5 11/29/05 11:30a Nashth * Trace printfs added to Main critical section for Enter/Leave for * debugging. * * 4 9/30/05 9:23a Frazzitl * Changed variable names to make more readable * * 3 8/18/05 13:49 Frazzitl * Implemented Sleep mode. Time is checked in CommandServer if enabled. * At correct time, the system must be restarted - not yet implemented. * Disabled if any legal Mode Command is accepted. * * 2 8/01/05 3:11p Nashth * Protected critical parameters via critical section to allow the HW Init * thread to run. Also, started the HW Init thread. However the system * continues to come up READY. * * 1 3/17/05 11:17 Frazzitl * Initial version of Optima Spectrometer firmware using the Icarus board, * TcpIp, and the new Sarnoff detector. $NoKeywords: $ ** End of Rev History **/
4eb5c32754ef2223d725d5d175d5e2fa735db957
5e3854a39930f676bedc35bd01a0aebf3fb431c6
/algorithm/leetcode10_regular-expression-matching.cpp
ffbba9ae6a89f91d211897b89ca352147ea4309e
[]
no_license
kobe24o/LeetCode
a6f17f71f456055b0f740e9f5a91626c5885212f
519145d4c27e60ff001154df8d0e258508a2039f
refs/heads/master
2022-08-04T12:44:33.841722
2022-07-30T06:55:47
2022-07-30T06:55:47
198,562,034
36
17
null
null
null
null
UTF-8
C++
false
false
1,441
cpp
class Solution { public: bool isMatch(string s, string p) { int m = s.size(), n = p.size(), i, j; vector<vector<int>> dp(m+1, vector<int>(n+1, false)); dp[0][0] = true; for(i = 0; i <= m; ++i) { for(j = 1; j <= n; ++j) { if(p[j-1] == '*')//p第j个字符为* { dp[i][j] |= dp[i][j-2];//*匹配0次前面的字符 if(match(s,p,i,j-1)) //s第i个和p的第j-1个可以匹配, *匹配再多匹配一次i-1 dp[i][j] |= dp[i-1][j]; } else//p第j个字符不为* { if(match(s,p,i,j))//必须是i、j能够匹配 dp[i][j] |= dp[i-1][j-1]; } } } return dp[m][n]; } bool match(string &s, string &p, int i, int j) { //第i,j个字符能匹配 return i>0 && (p[j-1]=='.' || p[j-1]==s[i-1]); } }; class Solution { public: bool isMatch(string s, string p) { if(p.empty()) return s.empty(); if(p[1]=='*') { return isMatch(s, p.substr(2)) || ((!s.empty() && (s[0]==p[0] || p[0]=='.')) && isMatch(s.substr(1),p)); } else return (!s.empty() && (s[0]==p[0]||p[0]=='.')) && isMatch(s.substr(1),p.substr(1)); } };
31b1eaf261f7244551a344a64dd046bd47567283
f0f0cdbc587382a25941bfbed229f0057492696d
/olivia/bytearray.h
63c6026decef16efec41e6382947eddcd69d6edc
[]
no_license
YuyiLin-Oliva/tinyServer
428b796a9c8d4ce738cea34ec4b4658f3c850413
9e632dda6954c97fba3d8e4a73a1f2042edf1685
refs/heads/master
2021-03-17T21:03:16.953237
2020-03-13T10:33:54
2020-03-13T10:33:54
247,017,865
3
0
null
null
null
null
UTF-8
C++
false
false
11,330
h
//二进制数组(序列化/反序列化) #ifndef __BYTEARRAY_H__ #define __BYTEARRAY_H__ #include <memory> #include <string> #include <stdint.h> #include <sys/types.h> #include <sys/socket.h> #include <vector> namespace olivia { /** * @brief 二进制数组,提供基础类型的序列化,反序列化功能 */ class ByteArray { public: typedef std::shared_ptr<ByteArray> ptr; //ByteArray的存储节点 struct Node { /** * @brief 构造指定大小的内存块 * @param[in] s 内存块字节数 */ Node(size_t s); Node(); //析构函数,释放内存 ~Node(); //内存块地址指针 char* ptr; //下一个内存块地址 Node* next; /// 内存块大小 size_t size; }; /** * @brief 使用指定长度的内存块构造ByteArray * @param[in] base_size 内存块大小 */ ByteArray(size_t base_size = 4096); ~ByteArray(); /** * @brief 写入固定长度int8_t类型的数据 * @post m_position += sizeof(value) * 如果m_position > m_size 则 m_size = m_position */ void writeFint8 (int8_t value); void writeFuint8 (uint8_t value); //写入固定长度int16_t类型的数据(大端/小端) void writeFint16 (int16_t value); void writeFuint16(uint16_t value); /** * @brief 写入固定长度int32_t类型的数据(大端/小端) * @post m_position += sizeof(value) * 如果m_position > m_size 则 m_size = m_position */ void writeFint32 (int32_t value); void writeFuint32(uint32_t value); void writeFint64 (int64_t value); void writeFuint64(uint64_t value); // /** // * @brief 写入有符号Varint32类型的数据 // * @post m_position += 实际占用内存(1 ~ 5) // * 如果m_position > m_size 则 m_size = m_position // */ // void writeInt32 (int32_t value); // void writeUint32 (uint32_t value); /** // * @brief 写入有符号Varint64类型的数据 // * @post m_position += 实际占用内存(1 ~ 10) // * 如果m_position > m_size 则 m_size = m_position // */ // void writeInt64 (int64_t value); // void writeUint64 (uint64_t value); /** * @brief 写入float类型的数据 * @post m_position += sizeof(value) * 如果m_position > m_size 则 m_size = m_position */ void writeFloat (float value); void writeDouble (double value); /** * @brief 写入std::string类型的数据,用uint16_t作为长度类型 * @post m_position += 2 + value.size() * 如果m_position > m_size 则 m_size = m_position */ void writeStringF16(const std::string& value); /** * @brief 写入std::string类型的数据,用uint32_t作为长度类型 * @post m_position += 4 + value.size() * 如果m_position > m_size 则 m_size = m_position */ void writeStringF32(const std::string& value); /** * @brief 写入std::string类型的数据,用uint64_t作为长度类型 * @post m_position += 8 + value.size() * 如果m_position > m_size 则 m_size = m_position */ void writeStringF64(const std::string& value); // /** // * @brief 写入std::string类型的数据,用无符号Varint64作为长度类型 // * @post m_position += Varint64长度 + value.size() // * 如果m_position > m_size 则 m_size = m_position // */ // void writeStringVint(const std::string& value); /** * @brief 写入std::string类型的数据,无长度 * @post m_position += value.size() * 如果m_position > m_size 则 m_size = m_position */ void writeStringWithoutLength(const std::string& value); /** * @brief 读取int8_t类型的数据 * @pre getReadSize() >= sizeof(int8_t) * @post m_position += sizeof(int8_t); * @exception 如果getReadSize() < sizeof(int8_t) 抛出 std::out_of_range */ int8_t readFint8(); uint8_t readFuint8(); /** * @brief 读取int16_t类型的数据 * @pre getReadSize() >= sizeof(int16_t) * @post m_position += sizeof(int16_t); * @exception 如果getReadSize() < sizeof(int16_t) 抛出 std::out_of_range */ int16_t readFint16(); uint16_t readFuint16(); /** * @brief 读取int32_t类型的数据 * @pre getReadSize() >= sizeof(int32_t) * @post m_position += sizeof(int32_t); * @exception 如果getReadSize() < sizeof(int32_t) 抛出 std::out_of_range */ int32_t readFint32(); uint32_t readFuint32(); /** * @brief 读取int64_t类型的数据 * @pre getReadSize() >= sizeof(int64_t) * @post m_position += sizeof(int64_t); * @exception 如果getReadSize() < sizeof(int64_t) 抛出 std::out_of_range */ int64_t readFint64(); uint64_t readFuint64(); // /** // * @brief 读取有符号Varint32类型的数据 // * @pre getReadSize() >= 有符号Varint32实际占用内存 // * @post m_position += 有符号Varint32实际占用内存 // * @exception 如果getReadSize() < 有符号Varint32实际占用内存 抛出 std::out_of_range // */ // int32_t readInt32(); // uint32_t readUint32(); // /** // * @brief 读取有符号Varint64类型的数据 // * @pre getReadSize() >= 有符号Varint64实际占用内存 // * @post m_position += 有符号Varint64实际占用内存 // * @exception 如果getReadSize() < 有符号Varint64实际占用内存 抛出 std::out_of_range // */ // int64_t readInt64(); // uint64_t readUint64(); /** * @brief 读取float类型的数据 * @pre getReadSize() >= sizeof(float) * @post m_position += sizeof(float); * @exception 如果getReadSize() < sizeof(float) 抛出 std::out_of_range */ float readFloat(); /** * @brief 读取double类型的数据 * @pre getReadSize() >= sizeof(double) * @post m_position += sizeof(double); * @exception 如果getReadSize() < sizeof(double) 抛出 std::out_of_range */ double readDouble(); /** * @brief 读取std::string类型的数据,用uint16_t作为长度 * @pre getReadSize() >= sizeof(uint16_t) + size * @post m_position += sizeof(uint16_t) + size; * @exception 如果getReadSize() < sizeof(uint16_t) + size 抛出 std::out_of_range */ std::string readStringF16(); /** * @brief 读取std::string类型的数据,用uint32_t作为长度 * @pre getReadSize() >= sizeof(uint32_t) + size * @post m_position += sizeof(uint32_t) + size; * @exception 如果getReadSize() < sizeof(uint32_t) + size 抛出 std::out_of_range */ std::string readStringF32(); /** * @brief 读取std::string类型的数据,用uint64_t作为长度 * @pre getReadSize() >= sizeof(uint64_t) + size * @post m_position += sizeof(uint64_t) + size; * @exception 如果getReadSize() < sizeof(uint64_t) + size 抛出 std::out_of_range */ std::string readStringF64(); // /** // * @brief 读取std::string类型的数据,用无符号Varint64作为长度 // * @pre getReadSize() >= 无符号Varint64实际大小 + size // * @post m_position += 无符号Varint64实际大小 + size; // * @exception 如果getReadSize() < 无符号Varint64实际大小 + size 抛出 std::out_of_range // */ // std::string readStringVint(); /** * @brief 清空ByteArray * @post m_position = 0, m_size = 0 */ void clear(); /** * @brief 写入size长度的数据 * @param[in] buf 内存缓存指针 * @param[in] size 数据大小 * @post m_position += size, 如果m_position > m_size 则 m_size = m_position */ void write(const void* buf, size_t size); /** * @brief 读取size长度的数据 * @param[out] buf 内存缓存指针 * @param[in] size 数据大小 * @post m_position += size, 如果m_position > m_size 则 m_size = m_position * @exception 如果getReadSize() < size 则抛出 std::out_of_range */ void read(void* buf, size_t size); /** * @brief 读取size长度的数据 * @param[out] buf 内存缓存指针 * @param[in] size 数据大小 * @param[in] position 读取开始位置 * @exception 如果 (m_size - position) < size 则抛出 std::out_of_range */ void read(void* buf, size_t size, size_t position) const; //返回ByteArray当前位置 size_t getPosition() const { return m_position;} /** * @brief 设置ByteArray当前位置 * @post 如果m_position > m_size 则 m_size = m_position * @exception 如果m_position > m_capacity 则抛出 std::out_of_range */ void setPosition(size_t v); /** * @brief 把ByteArray的数据写入到文件中 * @param[in] name 文件名 */ bool writeToFile(const std::string& name) const; /** * @brief 从文件中读取数据 * @param[in] name 文件名 */ bool readFromFile(const std::string& name); //返回内存块的大小 size_t getBaseSize() const { return m_baseSize;} //返回可读取数据大小 size_t getReadSize() const { return m_size - m_position;} //是否是小端 bool isLittleEndian() const; //设置是否为小端 void setIsLittleEndian(bool val); //将ByteArray里面的数据[m_position, m_size)转成std::string std::string toString() const; //将ByteArray里面的数据[m_position, m_size)转成16进制的std::string(格式:FF FF FF) std::string toHexString() const; /** * @brief 获取可读取的缓存,保存成iovec数组 * @param[out] buffers 保存可读取数据的iovec数组 * @param[in] len 读取数据的长度,如果len > getReadSize() 则 len = getReadSize() * @return 返回实际数据的长度 */ uint64_t getReadBuffers(std::vector<iovec>& buffers, uint64_t len = ~0ull) const; //获取可读取的缓存,保存成iovec数组,从position位置开始 uint64_t getReadBuffers(std::vector<iovec>& buffers, uint64_t len, uint64_t position) const; /** * @brief 获取可写入的缓存,保存成iovec数组 * @param[out] buffers 保存可写入的内存的iovec数组 * @param[in] len 写入的长度 * @return 返回实际的长度 * @post 如果(m_position + len) > m_capacity 则 m_capacity扩容N个节点以容纳len长度 */ uint64_t getWriteBuffers(std::vector<iovec>& buffers, uint64_t len); //返回数据的长度 size_t getSize() const { return m_size;} private: //扩容ByteArray,使其可以容纳size个数据(如果原本可以可以容纳,则不扩容) void addCapacity(size_t size); //获取当前的可写入容量 size_t getCapacity() const { return m_capacity - m_position;} private: // 内存块的大小 size_t m_baseSize; // 当前操作位置 size_t m_position; // 当前的总容量 size_t m_capacity; // 当前数据的大小 size_t m_size; // 字节序,默认大端 int8_t m_endian; /// 第一个内存块指针 Node* m_root; // 当前操作的内存块指针 Node* m_cur; }; } #endif
c940a681d180a60eb17cfc861ba1f29f3b711180
ac7707d2c5e1c286593305cd5a9b63f66cacaf20
/CS 142/Chapter Quizzes/Chapter Quizzes/Chapter Quizzes.cpp
b400a40ecb44f868d6991625f42220ba222844c1
[]
no_license
jacobparry/CS142_IntroToProgramming
73e715e88376a58ca451d4264366b02019f9da52
488da02361b73429b36c98088527b1a599fcefe9
refs/heads/master
2020-03-10T03:17:30.238152
2018-04-11T22:23:54
2018-04-11T22:23:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
841
cpp
#include <iostream> #include <iomanip> #include <string> #include <vector> #include <cstdlib> #include <ctime> using namespace std; const int NOT_FOUND = -1; const int times_to_shuffle = 100; const int EVEN = 0; const int POW_OF_2 = 2; const int TRUE_POW = 1; int main() { bool power = false; vector<string> restaurants(8); int number_of_restaurants = 0; for (int i = 0; i < restaurants.size(); i++) { number_of_restaurants++; } double true_power = number_of_restaurants; int number_of_rounds = 0; if ((number_of_restaurants % 2) == EVEN) { bool trial = true; while (trial) { true_power = true_power / POW_OF_2; number_of_rounds++; if (true_power == TRUE_POW) { trial = false; } else if (true_power < TRUE_POW) { trial = false; } } } else { } system("pause"); return 0; }
1bac8385ea203fe822b832a79335a9dddd6c7b47
944acde16ef16cb39caa55b8f93decd290407e7e
/main.cpp
18acb18b2d2ef87fdb50de3a8ab36ca00ea5e7d9
[]
no_license
mfg637/extended_numbers_x128
8c55832316faf15a99f6707ad8eb49b4a356fd0f
b562587d2493920ecdca3d12baed4ef845c2265f
refs/heads/master
2020-07-26T19:49:42.665923
2019-12-22T21:01:13
2019-12-22T21:01:13
208,749,731
0
0
null
null
null
null
UTF-8
C++
false
false
3,643
cpp
#include <iostream> #include <fstream> #include <random> #include "src/deserialisation.h" #include "src/int/UInt128.h" #include "src/int/Int128.h" int main(int argc, char **argv) { std::ifstream test("test.bin"); if (test.is_open()){ ExtNumsArray a = deserialize(test); std::cout << a.array_size << ' '; //IExtNums& sum = *(new Int128(0, 0)); Int128 sum(0, 0); Int128 incr(0, 1); for (unsigned i = 0; i<a.array_size; i++){ IExtNums* current_elem = a.array[i]; IExtNums* prev_value = current_elem; current_elem = &((*prev_value) + incr); delete prev_value; current_elem->text_out(std::cout); sum = (Int128&)((IExtNums&)(sum) + *current_elem); std::cout << ' '; } std::cout << std::endl << "sum of array elems: "; sum.text_out(std::cout); std::cout << std::endl; test.close(); delete [] a.array; } std::cout << "Hello world!" << std::endl; //overflow test UInt128 a(0, 0xffffffffffffffff); std::cout << "a = " << a << std::endl; UInt128 b(0, 2); std::cout << "b = " << b << std::endl; UInt128 print_test(0xffffffffffffffff, 0xffffffffffffffff); std::cout << "print_test = " << print_test << std::endl; UInt128 result1 = a+b; std::cout << "result1 = " << result1 << std::endl; UInt128 result2 = result1 - b; std::cout << "result2 = " << result2 << std::endl; UInt128 result3 = a * b; std::cout << "result3 = " << result3 << std::endl; UInt128 c(0, 10); std::cout << "c = " << c << std::endl; UInt128 result4 = a * c; std::cout << "result4 = " << result4 << std::endl; UInt128 result5 = result4 / c; std::cout << "result5 = " << result5 << std::endl; Int128 d(0xffffffffffffffff, 0xffffffffffffffff); std::cout << "d = " << d << std::endl; Int128 e(0, 2); std::cout << "e = " << e << std::endl; Int128 result6 = d + e; std::cout<< "result6 = " << result6 <<std::endl; Int128 result7 = d - e; std::cout << "result7 = " << result7 << std::endl; Int128 result8 = d * e; std::cout << "result8 = " << result8 << std::endl; Int128 result9 = result8 / e; std::cout << "result9 = " << result9 << std::endl; Int128 result10 = d * e - e; std::cout << "result10 = "<< result10 << std::endl; UInt128 f(0, 0); std::cout << "f = "; std::cin >> f; if (!std::cin.bad()){ std::cout << "f = " << f << std::endl; }else{ std::cout << "incorrent 128bit unsigned number"; return 1; } Int128 g(0, 0); std::cout << "g = "; std::cin >> g; if (!std::cin.bad()){ std::cout << "g = " << g << std::endl; }else{ std::cout << "incorrent 128bit signed integer number"; return 1; } UInt128 h("150"); std::cout << "h = " << h << std::endl; Int128 m("-150"); std::cout << "m = " << m << std::endl; std::ofstream test_file("test.bin"); IExtNums** array = new IExtNums*[6]; std::default_random_engine generator; std::uniform_int_distribution<long long int> signed_distribution(std::numeric_limits<long long int>::min(), std::numeric_limits<long long int>::max()); std::uniform_int_distribution<long long unsigned> unsigned_distribution; std::uniform_int_distribution<char> bool_distribution(0, 1); for (int i=0; i<6; i++){ bool isSigned = (bool)((bool_distribution(generator))>0); long long int b = 0; long long unsigned l = unsigned_distribution(generator); if (isSigned){ bool isNegate = bool_distribution(generator); if (isNegate){ b = -1; l = (~l)+1; } array[i] = new Int128(b, l); }else{ array[i] = new UInt128(0, l); } } serialize(array, 6, test_file); test_file.close(); delete[] array; return 0; }
da99729ecea2e077622c5363bf8ed655e6ed6dbf
1d8d4257b1af9217c5bf36367c38f04fcf475698
/RayTracingDemo/GeometricObjects/Triangles/SmoothUVMeshTriangle.h
ed4ea4bf226d854919b5a6a7fb1fb988339beae9
[]
no_license
kagtag/RayTracingDemo
ed53780fdc91163cbe45d277efa01f14f21b4944
9e0660e31859afd0126e93761331a05b3d8fa831
refs/heads/master
2020-04-13T01:09:52.738823
2019-02-05T14:31:10
2019-02-05T14:31:10
162,866,164
0
0
null
null
null
null
UTF-8
C++
false
false
271
h
#pragma once #include "SmoothMeshTriangle.h" class SmoothUVMeshTriangle : public SmoothMeshTriangle { public: SmoothUVMeshTriangle(); SmoothUVMeshTriangle(Mesh* mesh, int v0, int v1, int v2); virtual bool hit(const Ray& ray, double& tmin, ShadeRec& sr) const; };
1b3b335960fc82212b9b3f811794363057c1e2d9
753a70bc416e8dced2853f278b08ef60cdb3c768
/include/tensorflow/lite/micro/kernels/mul.cc
2e6464208bdbfe56bf2e6b1314b19ed9f513fb60
[ "MIT" ]
permissive
finnickniu/tensorflow_object_detection_tflite
ef94158e5350613590641880cb3c1062f7dd0efb
a115d918f6894a69586174653172be0b5d1de952
refs/heads/master
2023-04-06T04:59:24.985923
2022-09-20T16:29:08
2022-09-20T16:29:08
230,891,552
60
19
MIT
2023-03-25T00:31:18
2019-12-30T09:58:41
C++
UTF-8
C++
false
false
6,675
cc
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/kernels/internal/reference/mul.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/mul.h" #include "tensorflow/lite/kernels/internal/reference/process_broadcast_shapes.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace micro { namespace mul { constexpr int kInput1Tensor = 0; constexpr int kInput2Tensor = 1; constexpr int kOutputTensor = 0; struct OpData { int32_t output_activation_min; int32_t output_activation_max; int32_t output_multiplier; int output_shift; }; TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node, TfLiteMulParams* params, OpData* data) { const TfLiteTensor* input1 = GetInput(context, node, kInput1Tensor); const TfLiteTensor* input2 = GetInput(context, node, kInput2Tensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TF_LITE_ENSURE_EQ(context, input1->type, input2->type); if (output->type == kTfLiteUInt8) { CalculateActivationRangeUint8(params->activation, output, &data->output_activation_min, &data->output_activation_max); } else if (output->type == kTfLiteInt8) { CalculateActivationRangeInt8(params->activation, output, &data->output_activation_min, &data->output_activation_max); } if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) { double real_multiplier = input1->params.scale * input2->params.scale / output->params.scale; QuantizeMultiplier(real_multiplier, &data->output_multiplier, &data->output_shift); } return kTfLiteOk; } TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { return kTfLiteOk; } void EvalQuantized(TfLiteContext* context, TfLiteNode* node, TfLiteMulParams* params, OpData* data, const TfLiteTensor* input1, const TfLiteTensor* input2, TfLiteTensor* output) { if (output->type == kTfLiteInt8 || output->type == kTfLiteUInt8) { tflite::ArithmeticParams op_params; SetActivationParams(data->output_activation_min, data->output_activation_max, &op_params); op_params.input1_offset = -input1->params.zero_point; op_params.input2_offset = -input2->params.zero_point; op_params.output_offset = output->params.zero_point; op_params.output_multiplier = data->output_multiplier; op_params.output_shift = data->output_shift; bool need_broadcast = reference_ops::ProcessBroadcastShapes( GetTensorShape(input1), GetTensorShape(input2), &op_params); #define TF_LITE_MUL(type, opname, dtype) \ type::opname(op_params, GetTensorShape(input1), \ GetTensorData<dtype>(input1), GetTensorShape(input2), \ GetTensorData<dtype>(input2), GetTensorShape(output), \ GetTensorData<dtype>(output)); if (output->type == kTfLiteInt8) { if (need_broadcast) { TF_LITE_MUL(reference_integer_ops, BroadcastMul4DSlow, int8_t); } else { TF_LITE_MUL(reference_integer_ops, Mul, int8_t); } } else if (output->type == kTfLiteUInt8) { if (need_broadcast) { TF_LITE_MUL(reference_ops, BroadcastMul4DSlow, uint8_t); } else { TF_LITE_MUL(reference_ops, Mul, uint8_t); } } #undef TF_LITE_MUL } } void EvalFloat(TfLiteContext* context, TfLiteNode* node, TfLiteMulParams* params, OpData* data, const TfLiteTensor* input1, const TfLiteTensor* input2, TfLiteTensor* output) { float output_activation_min, output_activation_max; CalculateActivationRange(params->activation, &output_activation_min, &output_activation_max); tflite::ArithmeticParams op_params; SetActivationParams(output_activation_min, output_activation_max, &op_params); bool need_broadcast = reference_ops::ProcessBroadcastShapes( GetTensorShape(input1), GetTensorShape(input2), &op_params); #define TF_LITE_MUL(opname) \ reference_ops::opname(op_params, GetTensorShape(input1), \ GetTensorData<float>(input1), GetTensorShape(input2), \ GetTensorData<float>(input2), GetTensorShape(output), \ GetTensorData<float>(output)); if (need_broadcast) { TF_LITE_MUL(BroadcastMul4DSlow); } else { TF_LITE_MUL(Mul); } #undef TF_LITE_MUL } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteMulParams*>(node->builtin_data); OpData data; const TfLiteTensor* input1 = GetInput(context, node, kInput1Tensor); const TfLiteTensor* input2 = GetInput(context, node, kInput2Tensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); CalculateOpData(context, node, params, &data); switch (input1->type) { case kTfLiteUInt8: case kTfLiteInt8: EvalQuantized(context, node, params, &data, input1, input2, output); break; case kTfLiteFloat32: EvalFloat(context, node, params, &data, input1, input2, output); break; default: context->ReportError(context, "Type %d not currently supported.", input1->type); return kTfLiteError; } return kTfLiteOk; } } // namespace mul TfLiteRegistration* Register_MUL() { static TfLiteRegistration r = {nullptr, nullptr, mul::Prepare, mul::Eval}; return &r; } } // namespace micro } // namespace ops } // namespace tflite
a6e33853276bc2ae67f69b6915f7180c0f752eed
da0d71b758d95e532056bc705b186666837709b7
/src/libfauxdcore/tuple-compiler.cc
58202b7ed49edf1bc075a54703e9978abe12b6d0
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
ZachBacon/fauxdacious
fc3f3aa5bf6cbf0f88b7e33a0e3fd4c8971a124a
a2bbdaed2fee91d8f5d84fd2c21b41cf9452620a
refs/heads/master
2021-05-19T23:46:26.626551
2020-03-04T16:45:28
2020-03-04T16:45:28
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
12,833
cc
/* * tuple_compiler.c * Copyright (c) 2007 Matti 'ccr' Hämäläinen * Copyright (c) 2011-2014 John Lindgren * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions, and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions, and the following disclaimer in the documentation * provided with the distribution. * * This software is provided "as is" and without any warranty, express or * implied. In no event shall the authors be liable for any damages arising from * the use of this software. */ #include <stdlib.h> #include <string.h> #include <new> #include <glib.h> #include "audstrings.h" #include "runtime.h" #include "tuple-compiler.h" struct Variable { enum { Invalid = 0, Text, Integer, Field } type; String text; int integer; Tuple::Field field; bool set (const char * name, bool literal); bool exists (const Tuple & tuple) const; Tuple::ValueType get (const Tuple & tuple, String & tmps, int & tmpi) const; }; enum class Op { Invalid = 0, Var, Exists, Equal, Unequal, Greater, GreaterEqual, Less, LessEqual, Empty }; struct TupleCompiler::Node { Op op; Variable var1, var2; Index<Node> children; }; typedef TupleCompiler::Node Node; bool Variable::set (const char * name, bool literal) { if (g_ascii_isdigit (name[0])) { type = Integer; integer = atoi (name); } else if (literal) { type = Text; text = String (name); } else { type = Field; field = Tuple::field_by_name (name); if (field < 0) { AUDWARN ("Invalid variable '%s'.\n", name); return false; } } return true; } bool Variable::exists (const Tuple & tuple) const { g_return_val_if_fail (type == Field, false); return tuple.get_value_type (field) != Tuple::Empty; } Tuple::ValueType Variable::get (const Tuple & tuple, String & tmps, int & tmpi) const { switch (type) { case Text: tmps = text; return Tuple::String; case Integer: tmpi = integer; return Tuple::Int; case Field: switch (tuple.get_value_type (field)) { case Tuple::String: tmps = tuple.get_str (field); return Tuple::String; case Tuple::Int: tmpi = tuple.get_int (field); return Tuple::Int; default: return Tuple::Empty; } default: g_return_val_if_reached (Tuple::Empty); } } TupleCompiler::TupleCompiler () {} TupleCompiler::~TupleCompiler () {} static StringBuf get_item (const char * & str, char endch, bool & literal) { const char * s = str; StringBuf buf (-1); char * set = buf; char * stop = buf + buf.len (); if (* s == '"') { if (! literal) { buf = StringBuf (); // release space before AUDWARN AUDWARN ("Unexpected string literal at '%s'.\n", s); return StringBuf (); } s ++; } else literal = false; if (literal) { while (* s != '"') { if (* s == '\\') s ++; if (! * s) { buf = StringBuf (); // release space before AUDWARN AUDWARN ("Unterminated string literal.\n"); return StringBuf (); } if (set == stop) throw std::bad_alloc (); * set ++ = * s ++; } s ++; } else { while (g_ascii_isalnum (* s) || * s == '-') { if (set == stop) throw std::bad_alloc (); * set ++ = * s ++; } } if (* s != endch) { buf = StringBuf (); // release space before AUDWARN AUDWARN ("Expected '%c' at '%s'.\n", endch, s); return StringBuf (); } str = s + 1; buf.resize (set - buf); return buf; } static bool compile_expression (Index<Node> & nodes, const char * & expression); static bool parse_construct (Node & node, const char * & c) { bool literal1 = true, literal2 = true; StringBuf tmps1 = get_item (c, ',', literal1); if (! tmps1) return false; StringBuf tmps2 = get_item (c, ':', literal2); if (! tmps2) return false; if (! node.var1.set (tmps1, literal1)) return false; if (! node.var2.set (tmps2, literal2)) return false; return compile_expression (node.children, c); } /* Compile format expression into Node tree. */ static bool compile_expression (Index<Node> & nodes, const char * & expression) { const char * c = expression; while (* c && * c != '}') { Node & node = nodes.append (); if (* c == '$') { /* Expression? */ if (c[1] != '{') { AUDWARN ("Expected '${' at '%s'.\n", c); return false; } c += 2; switch (* c) { case '?': case '(': { if (* c == '?') { node.op = Op::Exists; c ++; } else { if (strncmp (c, "(empty)?", 8)) { AUDWARN ("Expected '(empty)?' at '%s'.\n", c); return false; } node.op = Op::Empty; c += 8; } bool literal = false; StringBuf tmps = get_item (c, ':', literal); if (! tmps) return false; if (! node.var1.set (tmps, false)) return false; if (! compile_expression (node.children, c)) return false; break; } case '=': case '!': node.op = (* c == '=') ? Op::Equal : Op::Unequal; if (c[1] != '=') { AUDWARN ("Expected '%c=' at '%s'.\n", c[0], c); return false; } c += 2; if (! parse_construct (node, c)) return false; break; case '<': case '>': if (c[1] == '=') { node.op = (* c == '<') ? Op::LessEqual : Op::GreaterEqual; c += 2; } else { node.op = (* c == '<') ? Op::Less : Op::Greater; c ++; } if (! parse_construct (node, c)) return false; break; default: { bool literal = false; StringBuf tmps = get_item (c, '}', literal); if (! tmps) return false; c --; node.op = Op::Var; if (! node.var1.set (tmps, false)) return false; } } if (* c != '}') { AUDWARN ("Expected '}' at '%s'.\n", c); return false; } c ++; } else if (* c == '{') { AUDWARN ("Unexpected '%c' at '%s'.\n", * c, c); return false; } else { /* Parse raw/literal text */ StringBuf buf (-1); char * set = buf; char * stop = buf + buf.len (); while (* c && * c != '$' && * c != '{' && * c != '}') { if (* c == '\\') { c ++; if (! * c) { buf = StringBuf (); // release space before AUDWARN AUDWARN ("Incomplete escaped character.\n"); return false; } } if (set == stop) throw std::bad_alloc (); * set ++ = * c ++; } buf.resize (set - buf); node.op = Op::Var; node.var1.type = Variable::Text; node.var1.text = String (buf); } } expression = c; return true; } bool TupleCompiler::compile (const char * expr) { const char * c = expr; Index<Node> nodes; if (! compile_expression (nodes, c)) return false; if (* c) { AUDWARN ("Unexpected '%c' at '%s'.\n", * c, c); return false; } root_nodes = std::move (nodes); return true; } void TupleCompiler::reset () { root_nodes.clear (); } /* Evaluate tuple in given TupleEval expression in given * context and return resulting string. */ static void eval_expression (const Index<Node> & nodes, const Tuple & tuple, StringBuf & out) { for (const Node & node : nodes) { switch (node.op) { case Op::Var: { String tmps; int tmpi; switch (node.var1.get (tuple, tmps, tmpi)) { case Tuple::String: out.insert (-1, tmps); break; case Tuple::Int: str_insert_int (out, -1, tmpi); break; default: break; } break; } case Op::Equal: case Op::Unequal: case Op::Less: case Op::LessEqual: case Op::Greater: case Op::GreaterEqual: { bool result = false; String tmps1, tmps2; int tmpi1 = 0, tmpi2 = 0; Tuple::ValueType type1 = node.var1.get (tuple, tmps1, tmpi1); Tuple::ValueType type2 = node.var2.get (tuple, tmps2, tmpi2); if (type1 != Tuple::Empty && type2 != Tuple::Empty) { int resulti; if (type1 == type2) { if (type1 == Tuple::String) resulti = strcmp (tmps1, tmps2); else resulti = tmpi1 - tmpi2; } else { if (type1 == Tuple::Int) resulti = tmpi1 - atoi (tmps2); else resulti = atoi (tmps1) - tmpi2; } switch (node.op) { case Op::Equal: result = (resulti == 0); break; case Op::Unequal: result = (resulti != 0); break; case Op::Less: result = (resulti < 0); break; case Op::LessEqual: result = (resulti <= 0); break; case Op::Greater: result = (resulti > 0); break; case Op::GreaterEqual: result = (resulti >= 0); break; default: g_warn_if_reached (); } } if (result) eval_expression (node.children, tuple, out); break; } case Op::Exists: if (node.var1.exists (tuple)) eval_expression (node.children, tuple, out); break; case Op::Empty: if (! node.var1.exists (tuple)) eval_expression (node.children, tuple, out); break; default: g_warn_if_reached (); } } } void TupleCompiler::format (Tuple & tuple) const { tuple.unset (Tuple::FormattedTitle); // prevent recursion StringBuf buf (0); eval_expression (root_nodes, tuple, buf); if (buf[0]) { tuple.set_str (Tuple::FormattedTitle, buf); return; } /* formatting failed, try fallbacks */ for (Tuple::Field fallback : {Tuple::Title, Tuple::Basename}) { String title = tuple.get_str (fallback); if (title) { tuple.set_str (Tuple::FormattedTitle, title); return; } } tuple.set_str (Tuple::FormattedTitle, ""); }
6216176ab7a139296c7d6a179f86c421abe5b309
575c265b54bbb7f20b74701753174678b1d5ce2c
/lottery/Classes/lottery/dzpk/utils/RoomOtherPlayer.cpp
8731d364b511cbc223a64d29afb1eccb8f5202aa
[]
no_license
larryzen/Project3.x
c8c8a0be1874647909fcb1a0eb453c46d6d674f1
cdc2bf42ea737c317fe747255d2ff955f80dbdae
refs/heads/master
2020-12-04T21:27:46.777239
2019-03-02T06:30:26
2019-03-02T06:30:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,155
cpp
#include "RoomOtherPlayer.h" #include "RoomPlayer.h" #include "Sound.h" #include "PlayerModel.h" #include "Venue.h" #include "StringFormat.h" #include "Players.h" //#include "RoomCardAction.h" //#include "RoomScene.h" //#include "RoomInfo.h" //#include "RoomPopFrame.h" //#include "RoomOtherInfo.h" //#include "GlobalHttpReq.h" RoomOtherPlayer::RoomOtherPlayer(): click_index(0), my_sound_id(-1), seatAction(false) { } RoomOtherPlayer::~RoomOtherPlayer() { do{ CC_BREAK_IF(my_sound_id==-1); Sound::getInstance()->stopEffect(my_sound_id); }while(0); } bool RoomOtherPlayer::init() { if (!Layer::init()) { return false; } return true; } CCPoint RoomOtherPlayer::getPostBySeatID(int id , bool bvar) { int x,y; CCSize WinSize = CCDirector::sharedDirector()->getVisibleSize(); int X[9] = { WinSize.width/2+0, WinSize.width/2-173, WinSize.width/2-340, WinSize.width/2-340, WinSize.width/2-173, WinSize.width/2+173, WinSize.width/2+340, WinSize.width/2+340, WinSize.width/2+173, }; int Y[9] = { WinSize.height/2-110, WinSize.height/2-110, WinSize.height/2-33, WinSize.height/2+107, WinSize.height/2+165, WinSize.height/2+165, WinSize.height/2+107, WinSize.height/2-33, WinSize.height/2-110, }; int mySeatID =0;//RoomScene::getMySeatID(); if (bvar) mySeatID = -1; if (mySeatID!=-1) { if (mySeatID==id) { x=X[0]; y=Y[0]; }else if ( mySeatID<id ) { x=X[id-mySeatID]; y=Y[id-mySeatID]; }else { x=X[9-mySeatID+id]; y=Y[9-mySeatID+id]; } } else { x=X[id]; y=Y[id]; } return ccp(x,y); } CCSprite *RoomOtherPlayer::getPlayerAvatar(int seatid) { ////玩家头像 //const char* genderPicName = RoomScene::getRff()[seatid].sex==1 ? "rooms/photo/room_photo_1.png" : "rooms/photo/room_photo_2.png"; //std::string headerFile = "no_custom_head"; //CCHttpAgent::getInstance()->getImagePath(RoomScene::getRff()[seatid].user_id,headerFile); //CCSprite* photo = CCSprite::create(genderPicName); // //CCLog("座位id:%d , uid: %d , headerFile = %s " , seatid , RoomScene::getRff()[seatid].user_id , headerFile.c_str()); //if (headerFile.compare("no_custom_head")==0 ) //{ // return photo; //}else{ // do{ // CCLOG("headPath=%s",CCHttpAgent::getInstance()->getImagePath(RoomScene::getRff()[seatid].user_id).c_str()); // // CCSize sc_sz = photo->getContentSize(); // CCSprite *header = CCSprite::create(CCHttpAgent::getInstance()->getImagePath(RoomScene::getRff()[seatid].user_id).c_str()); // CC_BREAK_IF(!header); // CCSize tx_sz = header->getContentSize(); // header->setScaleX(sc_sz.width/tx_sz.width); // header->setScaleY(sc_sz.height/tx_sz.height); // // return header; // }while(0); //} return NULL; } void RoomOtherPlayer::updateOtherPlayerUI(int seatid) { if (seatAction) return; int begin=seatid; int end=seatid+1; CCLOG("update UI"); if (seatid==10) //刷新全部ui { begin=0; end=9; } for (int i=begin;i<end;i++) { if (this->getChildByTag(i)) { this->removeChildByTag(i,true); } if (this->getChildByTag(100+i)) { this->removeChildByTag(100+i,true); } } if (seatid>=0 && seatid<9){ //清除操作警告! updateWarnning(seatid); } //for (int i=begin;i<end;i++) //{ // if ( RoomScene::getMySeatID()==-1 && RoomScene::getRff()[i].player_status==12) //12表示没人,则播放坐下动画 // { // Scale9Sprite* sitBtn_normal = Scale9Sprite::createWithSpriteFrameName("sit_down_frame.png"); // Scale9Sprite* sitBtn_selected = Scale9Sprite::createWithSpriteFrameName("sit_down_frame.png"); // Scale9Sprite* sitBtn_highLight = Scale9Sprite::createWithSpriteFrameName("sit_down_frame.png"); // Scale9Sprite* sitBtn_disabled = Scale9Sprite::createWithSpriteFrameName("sit_down_frame.png"); // // sitBtn_highLight->setColor(ccc3(131,131,131)); // CCSize sitBtn_size = sitBtn_normal->getContentSize(); // ControlButton* sitBtn = ControlButton::create(sitBtn_normal); // sitBtn->setPreferredSize(sitBtn_size); // // sitBtn->setZoomOnTouchDown(false); // sitBtn->setBackgroundSpriteForState(sitBtn_normal,CCControlStateNormal); // sitBtn->setBackgroundSpriteForState(sitBtn_selected,CCControlStateSelected); // sitBtn->setBackgroundSpriteForState(sitBtn_highLight,CCControlStateHighlighted); // sitBtn->setBackgroundSpriteForState(sitBtn_disabled,CCControlStateDisabled); // sitBtn->setAnchorPoint(ccp(0.5f,0.5f)); // sitBtn->setPosition(getPostBySeatID(i)); // sitBtn->setTag(100+i); // this->addChild(sitBtn,2); // sitBtn->addTargetWithActionForControlEvents(this, cccontrol_selector(RoomOtherPlayer::ctrlBtnCallback), CCControlEventTouchDown); // // CCLabelTTF *status_label = CCLabelTTF::create("","Arial-BoldMT",18); // status_label->setAnchorPoint(ccp(0.5f,0.5f)); // status_label->setPosition(ccp(sitBtn_size.width/2,78)); // sitBtn->addChild(status_label); // string title = "就坐"; // status_label->setString(title.c_str()); // } // else if (RoomScene::getRff()[i].player_status!=12 ) // { // if ( 13 == RoomScene::getRff()[i].player_status || 3 == RoomScene::getRff()[i].player_status ) //13等待下一场的玩家,3弃牌 // { // //头像框 // do{ // Scale9Sprite* player_icon_normal = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png"); // Scale9Sprite* player_icon_selected = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png"); // Scale9Sprite* player_icon_highLight = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png"); // Scale9Sprite* player_icon_disabled = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png"); // // player_icon_normal->setColor(ccc3(131,131,131)); // player_icon_highLight->setColor(ccc3(131,131,131)); // CCSize player_icon_size = player_icon_normal->getContentSize(); // ControlButton* player_icon = ControlButton::create(player_icon_normal); // CC_BREAK_IF(!player_icon); // player_icon->setPreferredSize(player_icon_size); // // player_icon->setZoomOnTouchDown(false); // player_icon->setBackgroundSpriteForState(player_icon_normal,CCControlStateNormal); // player_icon->setBackgroundSpriteForState(player_icon_selected,CCControlStateSelected); // player_icon->setBackgroundSpriteForState(player_icon_highLight,CCControlStateHighlighted); // player_icon->setBackgroundSpriteForState(player_icon_disabled,CCControlStateDisabled); // player_icon->setAnchorPoint(ccp(0.5f,0.5f)); // player_icon->setPosition(getPostBySeatID(i)); // player_icon->setTag(i); // this->addChild(player_icon,2); // player_icon->addTargetWithActionForControlEvents(this, cccontrol_selector(RoomOtherPlayer::ctrlBtnCallback), CCControlEventTouchDown); // CCLabelTTF *status_label = CCLabelTTF::create("","Arial-BoldMT",14); // CC_BREAK_IF(!status_label); // status_label->setAnchorPoint(ccp(0.5f,0.5f)); // status_label->setPosition(ccp(player_icon_size.width/2,player_icon_size.height-10)); // status_label->setTag(0); // player_icon->addChild(status_label); // string title = RoomPlayer::getTitleByStatus(RoomScene::getRff()[i].player_status,RoomScene::getRff()[i].name); // status_label->setString(title.c_str()); // // CCLabelTTF *chipNum = CCLabelTTF::create(Players::getInstance()->convertToChipNum(RoomScene::getRff()[i].own_gold),"Arial-BoldMT",14); // CC_BREAK_IF(!chipNum); // chipNum->setAnchorPoint(ccp(0.5f,0.5f)); // chipNum->setPosition(ccp(player_icon_size.width/2,10)); // chipNum->setTag(1); // player_icon->addChild(chipNum); // // CCSprite *photo = getPlayerAvatar(i); // CC_BREAK_IF(!photo); // photo->setColor(ccc3(131,131,131)); // photo->setPosition(ccp(player_icon_size.width/2, player_icon_size.height/2)); // player_icon->addChild(photo); // }while (0); // } // else // { // do{ // //头像 // Scale9Sprite* player_icon_normal = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png"); // Scale9Sprite* player_icon_selected = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png"); // Scale9Sprite* player_icon_highLight = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png"); // Scale9Sprite* player_icon_disabled = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png"); // // player_icon_highLight->setColor(ccc3(131,131,131)); // CCSize player_icon_size = player_icon_normal->getContentSize(); // ControlButton* player_icon = ControlButton::create(player_icon_normal); // CC_BREAK_IF(!player_icon); // player_icon->setPreferredSize(player_icon_size); // // player_icon->setZoomOnTouchDown(false); // player_icon->setBackgroundSpriteForState(player_icon_normal,CCControlStateNormal); // player_icon->setBackgroundSpriteForState(player_icon_selected,CCControlStateSelected); // player_icon->setBackgroundSpriteForState(player_icon_highLight,CCControlStateHighlighted); // player_icon->setBackgroundSpriteForState(player_icon_disabled,CCControlStateDisabled); // player_icon->setAnchorPoint(ccp(0.5f,0.5f)); // player_icon->setPosition(getPostBySeatID(i)); // player_icon->setTag(i); // this->addChild(player_icon,2); // player_icon->addTargetWithActionForControlEvents(this, cccontrol_selector(RoomOtherPlayer::ctrlBtnCallback), CCControlEventTouchDown); // // CCLabelTTF *status_label = CCLabelTTF::create("","Arial-BoldMT",14,CCSizeMake(80, 20) , kCCTextAlignmentCenter); // CC_BREAK_IF(!status_label); // status_label->setAnchorPoint(ccp(0.5f,0.5f)); // status_label->setPosition(ccp(player_icon_size.width/2,player_icon_size.height-10)); // status_label->setTag(0); // player_icon->addChild(status_label); // // if (RoomScene::getRff()[i].bborsb==0) // { // string title = RoomPlayer::getTitleByStatus(RoomScene::getRff()[i].player_status,RoomScene::getRff()[i].name); // status_label->setString(title.c_str()); // }else if (RoomScene::getRff()[i].bborsb==1){ // status_label->setString("小盲注"); // }else if (RoomScene::getRff()[i].bborsb==2){ // status_label->setString("大盲注"); // } // CCLabelTTF *chipNum = CCLabelTTF::create(Players::getInstance()->convertToChipNum(RoomScene::getRff()[i].own_gold),"Arial-BoldMT",14); // CC_BREAK_IF(!chipNum); // chipNum->setAnchorPoint(ccp(0.5f,0.5f)); // chipNum->setPosition(ccp(player_icon_size.width/2,10)); // chipNum->setTag(1); // player_icon->addChild(chipNum); // // //玩家头像 // CCSprite *photo = getPlayerAvatar(i); // CC_BREAK_IF(!photo); // photo->setPosition(ccp(player_icon_size.width/2, player_icon_size.height/2)); // player_icon->addChild(photo); // // // if ( 10 == RoomScene::getRff()[i].player_status ) // { // status_label->setString("下注中.."); // // m_index = i; // CCSprite *time_sp = CCSprite::createWithSpriteFrameName("player_frame_3.png"); // time_bar = CusProgressTimer::createWith(time_sp , 20.0f); // CC_BREAK_IF(!time_bar); // time_bar->setPosition(ccp(player_icon_size.width/2, player_icon_size.height/2)); // float left_time = RoomScene::getRff()[i].left_time-getServerTime()>20? 20:RoomScene::getRff()[i].left_time-getServerTime(); // time_bar->setLeftTime(left_time); // time_bar->setSelector(this, common_selector(RoomOtherPlayer::updateStatus)); // time_bar->setSelector3(this, common_selector(RoomOtherPlayer::timeWarnning)); // player_icon->addChild(time_bar); // // if (i==RoomScene::getMySeatID()){ // time_bar->setSelector2(this, common_selector(RoomOtherPlayer::cardCallBack)); // } // } // }while(0); // } // } //} } void RoomOtherPlayer::ctrlBtnCallback(CCObject *sender,cocos2d::extension::Control::EventType controlEvent) { ControlButton* ctrl_btn = (ControlButton*)sender; int btn_tag = ctrl_btn->getTag(); //if (PlayerModel::getInstance()->money<RoomInfo::getInstance()->min_take && btn_tag>=100) //{ // //自身筹码小于最小携带 // if (RoomScene::isExistPromote()) // { // return; // } // // CCString *str = CCString::createWithFormat("很遗憾,筹码达不到该房间的最小限制,当然您也可以充值获得更多筹码。"); // // CCScene *scene = CCDirector::sharedDirector()->getRunningScene(); // RoomPopFrame *popFrame = RoomPopFrame::create(); // popFrame->setAnchorPoint(ccp(0,0)); // popFrame->setAnchorPoint(ccp(0,0)); // scene->addChild(popFrame,6); // // popFrame->createDialog(str->getCString(),"继续旁观","进入房间"); // popFrame->setClickOnce(true); // popFrame->setReturnSelector(this, common_selector(RoomOtherPlayer::quicklyEnterRoom)); // // return; //} // //if (RoomInfo::getInstance()->max_limit!=-1) //{ // if (PlayerModel::getInstance()->money>RoomInfo::getInstance()->max_limit && btn_tag>=100) // { // //自身筹码大于最大携带 // if (RoomScene::isExistPromote()) // { // return; // } // // CCString *str = CCString::createWithFormat("你的筹码已超过该场的最大上限,可以去更高档的桌子比赛了!"); // // CCScene *scene = CCDirector::sharedDirector()->getRunningScene(); // RoomPopFrame *popFrame = RoomPopFrame::create(); // popFrame->setAnchorPoint(ccp(0,0)); // popFrame->setAnchorPoint(ccp(0,0)); // scene->addChild(popFrame,6); // // popFrame->createDialog(str->getCString(),"继续旁观","进入房间"); // popFrame->setClickOnce(true); // popFrame->setReturnSelector(this, common_selector(RoomOtherPlayer::quicklyEnterRoom)); // // return; // } //} // // //if (btn_tag>=100) //{ // CCScene *scene = CCDirector::sharedDirector()->getRunningScene(); // if (!scene->getChildByTag(10)) // { // return; // } // RoomFastBuy *roomFastBuy = (RoomFastBuy*)scene->getChildByTag(10)->getChildByTag(4); // if (roomFastBuy) // { // roomFastBuy->openDialog(btn_tag-100,"携带筹码"); // } //}else{ // // CCScene *scene = CCDirector::sharedDirector()->getRunningScene(); // // int index=-1; // for (int i=0;i<50;i++) // { // if (Players::getInstance()[i].seatid==btn_tag) // { // index=i; // break; // } // } // if (index==-1) // return; // RoomOtherInfo *otherPlayerInfo = RoomOtherInfo::create(); // otherPlayerInfo->setAnchorPoint(CCPointZero); // otherPlayerInfo->setPosition(CCPointZero); // otherPlayerInfo->initUI(index); // scene->addChild(otherPlayerInfo,5); //} } void RoomOtherPlayer::ctrlbtn_scheduler(float dt) { ControlButton *player = dynamic_cast<ControlButton*>(getChildByTag(click_index)); player->setTouchEnabled(true); } void RoomOtherPlayer::quicklyEnterRoom(bool bvar) { this->getParent()->unscheduleAllSelectors(); //RoomScene::setIsExit(true); // //JPacket jpacket; //jpacket.val["cmd"] = CMD_LOGOUT_REQUEST; //jpacket.end(); //CCTcpClient::getInstance()->send_data(jpacket.tostring()); for (int i=0;i<50;i++) { Players::getInstance()[i].init(); } for (int i=0;i<9;i++) { //RoomScene::getRff()[i].reset(); } //RoomInfo::getInstance()->init(); //初始化房间 enterOtherRoom(); Sound::getInstance()->playEffect("sound/sound_gangjinru.ogg"); } void RoomOtherPlayer::enterOtherRoom() { std::vector<Venue> allList; for (int i=1; i<=5; ++i) { std::vector<Venue> tempList; if (i==1) { tempList = PlayerModel::getInstance()->venueList_1; } else if (i==2) { tempList = PlayerModel::getInstance()->venueList_2; } else if (i==3) { tempList = PlayerModel::getInstance()->venueList_3; } else if (i==4) { tempList = PlayerModel::getInstance()->venueList_4; } else if (i==5) { tempList = PlayerModel::getInstance()->venueList_5; } for (std::vector<Venue>::iterator iter=tempList.begin(); iter!=tempList.end(); ++iter) { allList.push_back(*iter); } } //用于保存可以进入的桌子id std::vector<int> room_id; room_id.clear(); for (std::vector<Venue>::iterator iter=allList.begin(); iter!=allList.end(); ++iter) { if (PlayerModel::getInstance()->money>=(*iter).min_money) { if ((*iter).limit==-1){ room_id.push_back((*iter).room_id); }else if (PlayerModel::getInstance()->money<=(*iter).limit) { room_id.push_back((*iter).room_id); } } } if (room_id.empty()) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) showToast("筹码不足,没有可进入的房间!"); #else //CCMessageBox("筹码不足,没有可进入的房间!","错误提示"); #endif return; } //随机一个桌子id int index = rand()%room_id.size(); int table_id = room_id[index]; //取出房间信息 for (std::vector<Venue>::iterator iter=allList.begin(); iter!=allList.end(); ++iter) { if ((*iter).room_id==table_id) { //RoomInfo::getInstance()->s_bet=(*iter).sblind; //RoomInfo::getInstance()->b_bet=(*iter).bblind; //RoomInfo::getInstance()->min_take=(*iter).min_money; //RoomInfo::getInstance()->max_take=(*iter).max_money; //RoomInfo::getInstance()->port = (*iter).port; //RoomInfo::getInstance()->ip = (*iter).ip; //RoomInfo::getInstance()->max_limit = (*iter).limit; //RoomInfo::getInstance()->tid = 0; //RoomInfo::getInstance()->rmid = (*iter).showVenueId; CCArray* vect = CCArray::create(); StringFormat::Split((*iter).quickRefuelItems.c_str(), ",", vect); for (int i=0; i<vect->count(); ++i) { //RoomInfo::getInstance()->quick_addBet[i] = StringFormat::strToInt(((CCString*)vect->objectAtIndex(i))->getCString()); //DLog::showLog("-------quick_addBet[%d]: %d",i,RoomInfo::getInstance()->quick_addBet[i]); } break; } } CCTextureCache::purgeSharedTextureCache(); CCSpriteFrameCache::purgeSharedSpriteFrameCache(); //CCTransitionScene* reScene = CCTransitionFade::create(0.5f, RoomScene::scene(),ccBLACK); //CCDirector::sharedDirector()->replaceScene(reScene); } void RoomOtherPlayer::timer_bar_scheduler(float dt) { } void RoomOtherPlayer::updateStatus(int status) { //RoomScene::getRff()[m_index].player_status = status; //RoomScene::getRff()[m_index].bborsb = 0; } void RoomOtherPlayer::timeWarnning(float dt) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) if (CCUserDefault::sharedUserDefault()->getBoolForKey(SYSTEM_VOLUME_SNAKE_SWITCH_KEY,false)) { setVibrate(); } #endif //RoomWarnning *roomWarnning = dynamic_cast<RoomWarnning*>(this->getParent()->getChildByTag(7)); //do{ // CC_BREAK_IF(!roomWarnning); // roomWarnning->addWarnning(m_index); // // if(m_index==RoomScene::getMySeatID()){ // my_sound_id=Sound::getInstance()->playEffect("sound/sound_daojishi.ogg",true); // } //}while (0); } void RoomOtherPlayer::updateWarnning(int seatid) { //RoomWarnning *roomWarnning = dynamic_cast<RoomWarnning*>(this->getParent()->getChildByTag(7)); //do{ // CC_BREAK_IF(!roomWarnning); // roomWarnning->removeWarnning(seatid); // // CC_BREAK_IF(my_sound_id==-1); // Sound::getInstance()->stopEffect(my_sound_id); //}while (0); } void RoomOtherPlayer::cardCallBack(float dt) { //int mySeatID =0;//RoomScene::getMySeatID(); //RoomCardAction* roomCardAction = dynamic_cast<RoomCardAction*>(this->getParent()->getChildByTag(2)); //roomCardAction->cardAction(10*mySeatID+1); //roomCardAction->cardAction(10*mySeatID+2); } int RoomOtherPlayer::getNextPlayerSeatidOfGaming(int seatid) { int nextSeatid; int index=0; for (int i=0;i<9;i++) { //if ( RoomScene::getRff()[i].player_status<=11 && RoomScene::getRff()[i].player_status!=3 ) //{ // index++; //} } if ( 1==index ) { return -1; } for (int i=seatid+1;i<9;i++) { //if (RoomScene::getRff()[i].player_status<=11 && RoomScene::getRff()[i].player_status!=3 ) //{ // nextSeatid = i; // return nextSeatid; //} } for (int i=0;i<seatid;i++) { //if (RoomScene::getRff()[i].player_status<=11 && RoomScene::getRff()[i].player_status!=3 ) //{ // nextSeatid = i; // return nextSeatid; //} } return -1; } void RoomOtherPlayer::sitAction(int seatid) { int index = seatid; for (int i=100 ; i<109;i++) { if (this->getChildByTag(i)) { this->removeChildByTag(i,true); } } for (int i=0;i!=9;++i){ if (getChildByTag(i)){ ControlButton *palyer = dynamic_cast<ControlButton*>(getChildByTag(i)); palyer->setTouchEnabled(false); } } CCScene *scene = CCDirector::sharedDirector()->getRunningScene(); if (!scene->getChildByTag(10)) { return; } //RoomCardAction *roomCardAction = (RoomCardAction*)scene->getChildByTag(10)->getChildByTag(2); //RoomTag *roomTag = (RoomTag*)scene->getChildByTag(10)->getChildByTag(5); //RoomChip *roomChip = (RoomChip*)scene->getChildByTag(10)->getChildByTag(3); //RoomWarnning *roomWarnning = (RoomWarnning*)scene->getChildByTag(10)->getChildByTag(7); //RoomLight *roomLight = (RoomLight*)scene->getChildByTag(10)->getChildByTag(8); if (index==0) { } else if (index<5) { seatAction=true; //if (roomCardAction) //{ // roomCardAction->hidePlayerCards(); //} //if (roomTag) //{ // roomTag->hideTag(); //} //if (roomChip) //{ // roomChip->hideAllChips(); //} //if (roomWarnning) //{ // roomWarnning->hideWarnning(); //} //if (roomLight) { // roomLight->hideLight(); //} int controlNum = index+1; for (int i=0;i<9;i++) { if (this->getChildByTag(i)) { CCPointArray *array = CCPointArray::create(10); int seat_id_pos = i; for (int j=i;j<i+controlNum;j++) { array->addControlPoint(getPostBySeatID(seat_id_pos,true)); seat_id_pos--; if (seat_id_pos<0) { seat_id_pos=8; } } CCCatmullRomTo *action = CCCatmullRomTo::create(1, array); this->getChildByTag(i)->runAction(action); } } }else{ seatAction=true; //if (roomCardAction) //{ // roomCardAction->hidePlayerCards(); //} //if (roomTag) //{ // roomTag->hideTag(); //} //if (roomChip) //{ // roomChip->hideAllChips(); //} //if (roomWarnning) //{ // roomWarnning->hideWarnning(); //} //if (roomLight) { // roomLight->hideLight(); //} int controlNum = 10-index; for (int i=0;i<9;i++) { if (this->getChildByTag(i)) { CCPointArray *array = CCPointArray::create(10); int seat_id_pos = i; for (int j=i;j<i+controlNum;j++) { array->addControlPoint(getPostBySeatID(seat_id_pos,true)); seat_id_pos++; if (seat_id_pos>8) { seat_id_pos=0; } } CCCatmullRomTo *action = CCCatmullRomTo::create(1, array); this->getChildByTag(i)->runAction(action); } } } CCCallFuncN *cf = CCCallFuncN::create(this, callfuncN_selector(RoomOtherPlayer::showActionTag)); this->runAction(CCSequence::create(CCDelayTime::create(1.0f),cf,NULL)); if (!scene->getChildByTag(10)) { return; } //RoomBottom *roomBottom = (RoomBottom*)scene->getChildByTag(10)->getChildByTag(1); //roomBottom->updateMyPlayerUI(seatid); //坐下音效 Sound::getInstance()->playEffect("sound/sound_gangjinru.ogg"); } void RoomOtherPlayer::showActionTag(CCNode *pSender) { for (int i=0; i!=9; ++i) { if (getChildByTag(i)){ ControlButton *palyer = dynamic_cast<ControlButton*>(getChildByTag(i)); palyer->setTouchEnabled(true); } } CCScene *scene = CCDirector::sharedDirector()->getRunningScene(); if (!scene->getChildByTag(10)) { return; } //RoomCardAction *roomCardAction = (RoomCardAction*)scene->getChildByTag(10)->getChildByTag(2); //if (roomCardAction) //{ // roomCardAction->showPlayerCards(); //} if (!scene->getChildByTag(10)) { return; } //RoomTag *roomTag = (RoomTag*)scene->getChildByTag(10)->getChildByTag(5); //if (roomTag) //{ // roomTag->showTag(); //} if (!scene->getChildByTag(10)) { return; } //RoomChip *roomChip = (RoomChip*)scene->getChildByTag(10)->getChildByTag(3); //if (roomChip) //{ // roomChip->showAllChips(); //} if (!scene->getChildByTag(10)) { return; } //RoomWarnning *roomWarnning = (RoomWarnning*)scene->getChildByTag(10)->getChildByTag(7); //if (roomWarnning) //{ // roomWarnning->showWarnning(); //} if (!scene->getChildByTag(10)) { return; } //RoomLight *roomLight = (RoomLight*)scene->getChildByTag(10)->getChildByTag(8); //if (roomLight) { // roomLight->showLight(); //} if (seatAction){ seatAction=false; updateOtherPlayerUI(10); } } void RoomOtherPlayer::addWinFrame(int seatid) { do{ CC_BREAK_IF(!getChildByTag(seatid)); CC_BREAK_IF(getChildByTag(seatid)->getChildByTag(321)); CCSprite *frame = CCSprite::createWithSpriteFrameName("room_win_frame.png"); CC_BREAK_IF(!frame); frame->setPosition(ccp(getChildByTag(seatid)->getContentSize().width/2, getChildByTag(seatid)->getContentSize().height/2)); frame->setTag(321); getChildByTag(seatid)->addChild(frame,5); vector<CCPoint> vecPos; vecPos.push_back(ccp(21,3)); vecPos.push_back(ccp(3,107)); vecPos.push_back(ccp(65,117)); vecPos.push_back(ccp(83,13)); float delay=0.5f; CCCallFuncN *cf = CCCallFuncN::create(this, callfuncN_selector(RoomOtherPlayer::removeWinStar)); for (int i=0; i!=4; ++i) { CCSprite *star = CCSprite::createWithSpriteFrameName("room_win_star.png"); star->setPosition(vecPos[i]); star->setOpacity(0); frame->addChild(star); star->runAction(CCSequence::create(CCDelayTime::create(delay),CCFadeIn::create(0.5f),CCFadeOut::create(0.5f),cf,NULL)); delay+=1.0f; } }while(0); } void RoomOtherPlayer::removeWinStar(CCNode *pSender) { do{ CCSprite *sp = dynamic_cast<CCSprite*>(pSender); CC_BREAK_IF(!sp); sp->removeFromParentAndCleanup(true); }while (0); }
83466580cca2ad63126661a09ee4acecd135c2d8
8bb53a4764186cca14296b405fbced488b303794
/Course.cpp
9b7e9cf156ac33610149386b9d27498a4051bb95
[]
no_license
mbooali/CourseManagementSystem_Simulation
62f7c32dbc54e990f66f319fb8268e0cd0353aef
198ecb9e5a542b555dfb7898e0e431c48db21278
refs/heads/master
2021-01-17T11:58:12.973362
2015-03-15T05:00:06
2015-03-15T05:00:06
32,245,814
0
0
null
null
null
null
UTF-8
C++
false
false
736
cpp
// ourse.cpp: implementation of the Course class. // ////////////////////////////////////////////////////////////////////// #include "Course.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// string Course::GiveName() { return name; } Course::Course () //class Constructor for Course { zarfiat = vahed = term = status = mark = 0; } void Course::SetVars( int v, int z, string n ) { vahed = v; zarfiat = z; name = n; } Course* Course::Next() { return next; } void Course::SetNext( Course *next2 ) { next = next2; } void Course::Show() { cout << name << endl << vahed<< endl << zarfiat << endl; }
dc909a351ca0af697fe3deac85749d2fc944eaea
b7e66b2c0b9bb14dbf4ae5aa587335c63c5586d7
/Chapter1/problem1.cpp
f83f5275663a018334fe28fc850e58573c6734cd
[]
no_license
howardwang15/Cracking-the-coding-interview
232c80847deac1f69f51413615025f7b2a7742d8
895dd6d4b6e72e6527cf68e02b3ddc54398142dc
refs/heads/master
2018-11-17T17:42:16.977785
2018-09-03T02:44:22
2018-09-03T02:44:22
116,181,757
0
0
null
null
null
null
UTF-8
C++
false
false
251
cpp
#include <iostream> using namespace std; bool isUnique(string s) { int frequencies[256] = { 0 }; for (char c: s) { int val = c; if (frequencies[val] != 0) return false; frequencies[val]++; } return true; } int main () { }
9bc30c12f83dfa8069cd310bb9c438256011d791
9f520bcbde8a70e14d5870fd9a88c0989a8fcd61
/pitzDaily/389/uniform/functionObjects/functionObjectProperties
15b5c580dadf831388e52cb2b659b89fef46566a
[]
no_license
asAmrita/adjoinShapOptimization
6d47c89fb14d090941da706bd7c39004f515cfea
079cbec87529be37f81cca3ea8b28c50b9ceb8c5
refs/heads/master
2020-08-06T21:32:45.429939
2019-10-06T09:58:20
2019-10-06T09:58:20
213,144,901
1
0
null
null
null
null
UTF-8
C++
false
false
897
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1806 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "389/uniform/functionObjects"; object functionObjectProperties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // ************************************************************************* //
e0358987eede4c99a9a2465dc5b9a203004b586e
696bc51f1a05101252b0a25782f915ea28ad548d
/DreamWarcraft/RTTIHelper.h
f7f29147659cef5c201a4a602b27eca297672b5d
[ "MIT" ]
permissive
ruijiexie/dreamdota
4ae9a685960bb67c2511699868f7ca42a16803dd
2d71c5ebe1b3fb2726bf20e514025dbe28152a35
refs/heads/master
2021-06-09T05:25:35.045791
2016-12-12T16:40:51
2016-12-12T16:40:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,175
h
#include "stdafx.h" #ifndef RTTIHELPER_INCLUDED #define RTTIHELPER_INCLUDED #include <fp_call.h> namespace RTTIHelper { struct TypeDescriptor { DWORD pVFTable; DWORD spare; char name[]; }; /* RTTI (Run-Time Type Identification) is special compiler-generated information which is used to support C++ operators like dynamic_cast<> and typeid(), and also for C++ exceptions. Due to its nature, RTTI is only required (and generated) for polymorphic classes, i.e. classes with virtual functions. MSVC compiler puts a pointer to the structure called "Complete Object Locator" just before the vftable. The structure is called so because it allows compiler to find the location of the complete object from a specific vftable pointer (since a class can have several of them). COL looks like following: */ struct RTTICompleteObjectLocator { DWORD signature; //always zero ? DWORD offset; //offset of this vtable in the complete class DWORD cdOffset; //constructor displacement offset struct TypeDescriptor* pTypeDescriptor; //TypeDescriptor of the complete class struct RTTIClassHierarchyDescriptor* pClassDescriptor; //describes inheritance hierarchy }; /* Class Hierarchy Descriptor describes the inheritance hierarchy of the class. It is shared by all COLs for a class. */ struct RTTIClassHierarchyDescriptor { DWORD signature; //always zero? DWORD attributes; //bit 0 set = multiple inheritance, bit 1 set = virtual inheritance DWORD numBaseClasses; //number of classes in pBaseClassArray struct RTTIBaseClassArray* pBaseClassArray; }; struct PMD { int mdisp; //member displacement int pdisp; //vbtable displacement int vdisp; //displacement inside vbtable }; /* Base Class Array describes all base classes together with information which allows compiler to cast the derived class to any of them during execution of the _dynamic_cast_ operator. Each entry (Base Class Descriptor) has the following structure: */ struct RTTIBaseClassDescriptor { struct TypeDescriptor* pTypeDescriptor; //type descriptor of the class DWORD numContainedBases; //number of nested classes following in the Base Class Array struct PMD where; //pointer-to-member displacement info DWORD attributes; //flags, usually 0 }; inline void** vtable(void* obj) {return *(void***)obj;} inline const char* className(void* obj) { RTTICompleteObjectLocator* col = *aero::pointer_calc<RTTICompleteObjectLocator**>(vtable(obj), -4); return &(col->pTypeDescriptor->name[4]); } /* bool isInstanceOf(void* obj, const char* parentName) { bool rv = false; RTTICompleteObjectLocator* col = *aero::pointer_calc<RTTICompleteObjectLocator**>(vtable(obj), -4); uint32_t parent_count = col->pClassDescriptor->numBaseClasses; size_t name_len = strlen(parentName); const char* object_class_name = &(col->pTypeDescriptor->name[4]); if (parent_count && name_len) { for (uint32_t i = 0; i < parent_count; ++i) { const char* parent_name = col->pClassDescriptor->pBaseClassArray if (strstr(object_class_name, parentName) != NULL && strlen()) return true; } } return rv; } */ }; #endif
6dfd68acdbd618e2b2d723e5472cb499abcec932
cae01d285dbd8bbebd7b48b95efa483ae6b4a2c5
/Intermediate/Build/Win64/UE4Editor/Inc/VehicleTemplate/Checkpoints.generated.h
12757ce519347866731717ca9fa903cab1ef5d18
[]
no_license
AliHasl/UnrealVehicleProject
24f148f487b56c8a40ce0313bcf1a12294a7834b
592f743cb05977ce7265506f7348f6c35e57e63c
refs/heads/master
2020-04-10T05:41:48.065440
2018-12-07T14:30:36
2018-12-07T14:30:36
160,834,796
0
0
null
null
null
null
UTF-8
C++
false
false
4,149
h
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "ObjectMacros.h" #include "ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef VEHICLETEMPLATE_Checkpoints_generated_h #error "Checkpoints.generated.h already included, missing '#pragma once' in Checkpoints.h" #endif #define VEHICLETEMPLATE_Checkpoints_generated_h #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_RPC_WRAPPERS #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_RPC_WRAPPERS_NO_PURE_DECLS #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesACheckpoints(); \ friend VEHICLETEMPLATE_API class UClass* Z_Construct_UClass_ACheckpoints(); \ public: \ DECLARE_CLASS(ACheckpoints, AActor, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/VehicleTemplate"), NO_API) \ DECLARE_SERIALIZER(ACheckpoints) \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_INCLASS \ private: \ static void StaticRegisterNativesACheckpoints(); \ friend VEHICLETEMPLATE_API class UClass* Z_Construct_UClass_ACheckpoints(); \ public: \ DECLARE_CLASS(ACheckpoints, AActor, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/VehicleTemplate"), NO_API) \ DECLARE_SERIALIZER(ACheckpoints) \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API ACheckpoints(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ACheckpoints) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ACheckpoints); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ACheckpoints); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API ACheckpoints(ACheckpoints&&); \ NO_API ACheckpoints(const ACheckpoints&); \ public: #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API ACheckpoints(ACheckpoints&&); \ NO_API ACheckpoints(const ACheckpoints&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ACheckpoints); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ACheckpoints); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(ACheckpoints) #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_PRIVATE_PROPERTY_OFFSET #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_12_PROLOG #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_PRIVATE_PROPERTY_OFFSET \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_RPC_WRAPPERS \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_INCLASS \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_PRIVATE_PROPERTY_OFFSET \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_RPC_WRAPPERS_NO_PURE_DECLS \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_INCLASS_NO_PURE_DECLS \ VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h_15_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID VehicleTemplate_04_12_2018_Source_VehicleTemplate_Checkpoints_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
5edd2152d39d3a90650a8398593b0ddb571c9a56
8c953249a62367a8f0138eff488ce5d510e65620
/cs109/lab4og/src/comply.cc
5b61a7f4c7c67392bf0a348fddea0430171eed89
[]
no_license
nahawtho/cs109copy
5ce87799eb09ac22b38f63b8d77b3878f8b5b001
66e2b2be6adf54bf724a437f2a32090a1d834cba
refs/heads/master
2020-04-05T06:50:35.063576
2018-11-08T05:10:56
2018-11-08T05:10:56
156,653,424
0
0
null
null
null
null
UTF-8
C++
false
false
2,890
cc
/* * Copyright (C) 2018 David C. Harrison. All right reserved. * * You may not use, distribute, publish, or modify this code without * the express written permission of the copyright holder. */ /****************** DO NOT MODIFY THIS FILE **************************** * * It is not included in the subission archive ceated by 'make submit' . * * If you modify it and your code relies on those modifications, your code * will not compile in the automated test harness and will be unable to * execute any tests. * * To put it another way, if you modify this file, you will get a big fat * ZERO on this lab. * ************************************************************************/ #include <iostream> #include "circle.h" #include "polygon.h" #include "reuleaux.h" #include "sphere.h" static void twodim() { Point p1 = Point(); Point p2 = Point(0.0, 0.0); Point p3 = Point(p2); Circle circle = Circle(Point(0.0,0.0), 0.0); double x = circle.center().x; double r = circle.radius(); ConvexPolygon polygon = ConvexPolygon({Point(0,0), Point(0,0), Point(0,0)}); polygon.vertices().size(); RegularConvexPolygon regular = RegularConvexPolygon({Point(0,0), Point(0,0), Point(0,0)}); regular.vertices().size(); Point vertices[3] = {Point(0,0), Point(0,0), Point(0,0)}; ReuleauxTriangle reuleaux = ReuleauxTriangle(vertices); reuleaux.vertices().size(); circle.containedBy(circle); circle.containedBy(polygon); circle.containedBy(regular); circle.containedBy(reuleaux); polygon.containedBy(circle); polygon.containedBy(polygon); polygon.containedBy(regular); polygon.containedBy(reuleaux); regular.containedBy(circle); regular.containedBy(polygon); regular.containedBy(regular); regular.containedBy(reuleaux); reuleaux.containedBy(circle); reuleaux.containedBy(polygon); reuleaux.containedBy(regular); reuleaux.containedBy(reuleaux); } static void threedim() { Point3D p1 = Point3D(); Point3D p2 = Point3D(0.0, 0.0, 0.0); Point3D p3 = Point3D(p2); Sphere sphere = Sphere(Point3D(0.0,0.0,0.0), 0.0); Point3D upper[4] = {Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0)}; Point3D lower[4] = {Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0)}; Cube cube = Cube(upper, lower); Point3D vertices[4] = {Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0), Point3D(0,0,0)}; ReuleauxTetrahedron reuleaux = ReuleauxTetrahedron(vertices); cube.containedBy(cube); cube.containedBy(sphere); cube.containedBy(reuleaux); sphere.containedBy(cube); sphere.containedBy(sphere); sphere.containedBy(reuleaux); reuleaux.containedBy(cube); reuleaux.containedBy(sphere); reuleaux.containedBy(reuleaux); } int main(int argc, char *argv[]) { twodim(); threedim(); }
4e8213aa94d1e02c6254898794a4c0f7c40095fe
c022ac5523662a3022e220beef041268b11103f4
/DS-malik-cpp/namespaceEg1.cpp
2b4d6c7989ed8cac7189d88c0aa2ebf75f1cfb49
[]
no_license
Otumian-empire/DS-malik-cpp
780194091ddd013ed6f5286a79278cc3f0eeb9ed
aa2273b88dab69b267ffb1cab76e5c562fc28de7
refs/heads/master
2020-06-13T03:36:48.184918
2020-04-26T09:46:08
2020-04-26T09:46:08
194,520,519
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
 namespace otu { string author = "Otumian Empire"; string expertise = "Die hard programmer"; } namespace globalType { const int N = 10; const double RATE = 7.50; int count = 0; void printResult(); } #include <iostream>z using namespace std; // using namespace otu; using namespace globalType; int main() { // cout << otu::author << endl << expertise << endl; cout << N << endl; cout << RATE << endl; return 0; }
95002ba9a183a5a01ea48372d05aceb0a90a39d6
f6e5e55a6e206a850ee5382fb420aa5ae2dc4c7b
/25_1_Template/25_1_Template/Pessoa.cpp
2fada3ab4e36830fffb8646d29b4630b8fdaa69c
[]
no_license
rodrigo-prado/CursoCPlusPlus
a76f672152eb6111a643f6d2ff1030e7e04a167e
784890712d6041414d37c294a54e18eea7ce7dea
refs/heads/master
2023-01-22T14:33:44.738964
2020-11-27T22:01:57
2020-11-27T22:01:57
315,754,784
2
0
null
null
null
null
UTF-8
C++
false
false
490
cpp
#include "Pessoa.h" #include <iostream> using namespace std; Pessoa::Pessoa(string first,string last, int arbitrary) : primeiro_nome_(first),ultimo_nome_(last), idade_(arbitrary) { } Pessoa::~Pessoa() { } string Pessoa::GetName() { return primeiro_nome_ + " " + ultimo_nome_; } bool Pessoa::operator<(Pessoa const& p) const { return idade_ < p.idade_; } bool Pessoa::operator<(int i) const { return idade_ < i; } bool operator<(int i, Pessoa const& p) { return i < p.idade_; }
23bb7c0023ab0d19e14718cb92e52a5c74663292
7e2f4649977299d392d6fedd08156232d62bd216
/src/controls/sdbrowserwidget.h
366ea2b95faed6832f485ed90a07af9c5cdb32ab
[ "MIT" ]
permissive
AhmadPanogari/Phoenard-Toolkit
cadd1d26649f7877ff87fc2791d32e8c9d06fbe1
395ce79a3c56701073531cb2caad3637312d906c
refs/heads/master
2021-06-04T17:47:43.102820
2016-07-11T14:42:53
2016-07-11T14:42:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,830
h
#ifndef SDBROWSERWIDGET_H #define SDBROWSERWIDGET_H #include <QTreeWidget> #include <QResizeEvent> #include <QDragEnterEvent> #include <QDragMoveEvent> #include <QDragLeaveEvent> #include <QDropEvent> #include "mainmenutab.h" #include "../imaging/phniconprovider.h" class SDBrowserWidget : public QTreeWidget, public MainMenuTab { Q_OBJECT public: SDBrowserWidget(QWidget *parent = 0); void refreshFiles(); void deleteFiles(); void saveFilesTo(); void importFiles(); void importFiles(QStringList filePaths); void importFiles(QStringList filePaths, QString destFolder); void createNew(QString fileName, bool isDirectory); void keyPressEvent(QKeyEvent *ev); bool hasSelection(); QTreeWidgetItem* getSelectedFolder(); QString volumeName(); protected: void dragEnterEvent(QDragEnterEvent *event); void dragMoveEvent(QDragMoveEvent *event); void dragLeaveEvent(QDragLeaveEvent *event); void dropEvent(QDropEvent *event); void itemExpanded(QTreeWidgetItem *item); void refreshItem(QTreeWidgetItem *item); void refreshItem(QTreeWidgetItem *item, QList<DirectoryInfo> subFiles); void setupItemName(QTreeWidgetItem *item, QString name); void addExpandedListTasks(QTreeWidgetItem *item, QList<stk500Task*> *tasks); QString getPath(QTreeWidgetItem *item); QTreeWidgetItem *getItemAtPath(QString path); bool itemHasSelectedParent(QTreeWidgetItem *item); bool itemIsFolder(QTreeWidgetItem *item); void updateItemIcon(QTreeWidgetItem *item); private slots: void on_itemExpanded(QTreeWidgetItem *item); void on_itemChanged(QTreeWidgetItem *item, int column); void on_itemDoubleClicked(QTreeWidgetItem *item, int column); private: bool _isRefreshing; PHNIconProvider iconProvider; }; #endif // SDBROWSERWIDGET_H
6cdf6bdd52ff7a0d8f30d45dbc4bac4c28880324
63e3ec9a6849b10dc743b191a62649c954831d06
/Tester/main.cpp
e0791ff35004ab5b558141ef4bc581cfd09d9451
[ "Apache-2.0" ]
permissive
amj55/CPP
b89f1bfafd7595f47689c3c8502f2a3ae380c267
993fdfa8e1878c2033ad78070d55442f4c15393a
refs/heads/master
2021-08-28T09:33:35.491890
2017-12-11T21:17:15
2017-12-11T21:17:15
114,029,061
1
0
null
null
null
null
UTF-8
C++
false
false
409
cpp
#include <iostream> #include <vector> using namespace std; int main() { vector<int> test; test.push_back(5); test.push_back(10); test.push_back(100); test.insert(test.begin(), 1); cout << test.back() << " " << test.front() << " " << test[0] << endl; return 0; } void disp(vector<con> items) { for(int i = 0; i < items.size(); i++) { cout << items[1] << " "; } }
547d777962fb28b2c7f4e4c8ef43132d3e6a009a
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_5/WWC+poonceonce+ctrlonceonce+Release.c.cbmc.cpp
bab1de600e14ef3935676eed5dae25374028b0c9
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
35,227
cpp
// Global variabls: // 3:atom_2_X0_1:1 // 0:vars:2 // 2:atom_1_X0_2:1 // Local global variabls: // 0:thr0:1 // 1:thr1:1 // 2:thr2:1 #define ADDRSIZE 4 #define LOCALADDRSIZE 3 #define NTHREAD 4 #define NCONTEXT 5 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // Declare arrays for intial value version in contexts int local_mem[LOCALADDRSIZE]; // Dumping initializations local_mem[0+0] = 0; local_mem[1+0] = 0; local_mem[2+0] = 0; int cstart[NTHREAD]; int creturn[NTHREAD]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NTHREAD*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NTHREAD*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NTHREAD*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NTHREAD*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NTHREAD*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NTHREAD*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NTHREAD*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NTHREAD*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NTHREAD*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NTHREAD]; int cdy[NTHREAD]; int cds[NTHREAD]; int cdl[NTHREAD]; int cisb[NTHREAD]; int caddr[NTHREAD]; int cctrl[NTHREAD]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(3+0,0) = 0; mem(0+0,0) = 0; mem(0+1,0) = 0; mem(2+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; mem(0,1) = meminit(0,1); co(0,1) = coinit(0,1); delta(0,1) = deltainit(0,1); mem(0,2) = meminit(0,2); co(0,2) = coinit(0,2); delta(0,2) = deltainit(0,2); mem(0,3) = meminit(0,3); co(0,3) = coinit(0,3); delta(0,3) = deltainit(0,3); mem(0,4) = meminit(0,4); co(0,4) = coinit(0,4); delta(0,4) = deltainit(0,4); co(1,0) = 0; delta(1,0) = -1; mem(1,1) = meminit(1,1); co(1,1) = coinit(1,1); delta(1,1) = deltainit(1,1); mem(1,2) = meminit(1,2); co(1,2) = coinit(1,2); delta(1,2) = deltainit(1,2); mem(1,3) = meminit(1,3); co(1,3) = coinit(1,3); delta(1,3) = deltainit(1,3); mem(1,4) = meminit(1,4); co(1,4) = coinit(1,4); delta(1,4) = deltainit(1,4); co(2,0) = 0; delta(2,0) = -1; mem(2,1) = meminit(2,1); co(2,1) = coinit(2,1); delta(2,1) = deltainit(2,1); mem(2,2) = meminit(2,2); co(2,2) = coinit(2,2); delta(2,2) = deltainit(2,2); mem(2,3) = meminit(2,3); co(2,3) = coinit(2,3); delta(2,3) = deltainit(2,3); mem(2,4) = meminit(2,4); co(2,4) = coinit(2,4); delta(2,4) = deltainit(2,4); co(3,0) = 0; delta(3,0) = -1; mem(3,1) = meminit(3,1); co(3,1) = coinit(3,1); delta(3,1) = deltainit(3,1); mem(3,2) = meminit(3,2); co(3,2) = coinit(3,2); delta(3,2) = deltainit(3,2); mem(3,3) = meminit(3,3); co(3,3) = coinit(3,3); delta(3,3) = deltainit(3,3); mem(3,4) = meminit(3,4); co(3,4) = coinit(3,4); delta(3,4) = deltainit(3,4); // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !36, metadata !DIExpression()), !dbg !42 // br label %label_1, !dbg !43 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !41), !dbg !44 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !37, metadata !DIExpression()), !dbg !45 // call void @llvm.dbg.value(metadata i64 2, metadata !40, metadata !DIExpression()), !dbg !45 // store atomic i64 2, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !46 // ST: Guess // : Release iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l20_c3 old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l20_c3 // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); ASSUME(cw(1,0) >= cr(1,3+0)); ASSUME(cw(1,0) >= cr(1,0+0)); ASSUME(cw(1,0) >= cr(1,0+1)); ASSUME(cw(1,0) >= cr(1,2+0)); ASSUME(cw(1,0) >= cw(1,3+0)); ASSUME(cw(1,0) >= cw(1,0+0)); ASSUME(cw(1,0) >= cw(1,0+1)); ASSUME(cw(1,0) >= cw(1,2+0)); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 2; mem(0,cw(1,0)) = 2; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; is(1,0) = iw(1,0); cs(1,0) = cw(1,0); ASSUME(creturn[1] >= cw(1,0)); // ret i8* null, !dbg !47 ret_thread_1 = (- 1); goto T1BLOCK_END; T1BLOCK_END: // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !50, metadata !DIExpression()), !dbg !60 // br label %label_2, !dbg !48 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !59), !dbg !62 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !52, metadata !DIExpression()), !dbg !63 // %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !51 // LD: Guess old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l26_c15 // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); // Update creg_r0 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r0 = buff(2,0); ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r0 = mem(0,cr(2,0)); } ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %0, metadata !54, metadata !DIExpression()), !dbg !63 // %conv = trunc i64 %0 to i32, !dbg !52 // call void @llvm.dbg.value(metadata i32 %conv, metadata !51, metadata !DIExpression()), !dbg !60 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !55, metadata !DIExpression()), !dbg !66 // call void @llvm.dbg.value(metadata i64 1, metadata !57, metadata !DIExpression()), !dbg !66 // store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !54 // ST: Guess iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l27_c3 old_cw = cw(2,0+1*1); cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l27_c3 // Check ASSUME(active[iw(2,0+1*1)] == 2); ASSUME(active[cw(2,0+1*1)] == 2); ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(cw(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cw(2,0+1*1) >= old_cw); ASSUME(cw(2,0+1*1) >= cr(2,0+1*1)); ASSUME(cw(2,0+1*1) >= cl[2]); ASSUME(cw(2,0+1*1) >= cisb[2]); ASSUME(cw(2,0+1*1) >= cdy[2]); ASSUME(cw(2,0+1*1) >= cdl[2]); ASSUME(cw(2,0+1*1) >= cds[2]); ASSUME(cw(2,0+1*1) >= cctrl[2]); ASSUME(cw(2,0+1*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+1*1) = 1; mem(0+1*1,cw(2,0+1*1)) = 1; co(0+1*1,cw(2,0+1*1))+=1; delta(0+1*1,cw(2,0+1*1)) = -1; ASSUME(creturn[2] >= cw(2,0+1*1)); // %cmp = icmp eq i32 %conv, 2, !dbg !55 creg__r0__2_ = max(0,creg_r0); // %conv1 = zext i1 %cmp to i32, !dbg !55 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !58, metadata !DIExpression()), !dbg !60 // store i32 %conv1, i32* @atom_1_X0_2, align 4, !dbg !56, !tbaa !57 // ST: Guess iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l29_c15 old_cw = cw(2,2); cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l29_c15 // Check ASSUME(active[iw(2,2)] == 2); ASSUME(active[cw(2,2)] == 2); ASSUME(sforbid(2,cw(2,2))== 0); ASSUME(iw(2,2) >= creg__r0__2_); ASSUME(iw(2,2) >= 0); ASSUME(cw(2,2) >= iw(2,2)); ASSUME(cw(2,2) >= old_cw); ASSUME(cw(2,2) >= cr(2,2)); ASSUME(cw(2,2) >= cl[2]); ASSUME(cw(2,2) >= cisb[2]); ASSUME(cw(2,2) >= cdy[2]); ASSUME(cw(2,2) >= cdl[2]); ASSUME(cw(2,2) >= cds[2]); ASSUME(cw(2,2) >= cctrl[2]); ASSUME(cw(2,2) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,2) = (r0==2); mem(2,cw(2,2)) = (r0==2); co(2,cw(2,2))+=1; delta(2,cw(2,2)) = -1; ASSUME(creturn[2] >= cw(2,2)); // ret i8* null, !dbg !61 ret_thread_2 = (- 1); goto T2BLOCK_END; T2BLOCK_END: // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !77, metadata !DIExpression()), !dbg !89 // br label %label_3, !dbg !50 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !87), !dbg !91 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !79, metadata !DIExpression()), !dbg !92 // %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !53 // LD: Guess old_cr = cr(3,0+1*1); cr(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l35_c15 // Check ASSUME(active[cr(3,0+1*1)] == 3); ASSUME(cr(3,0+1*1) >= iw(3,0+1*1)); ASSUME(cr(3,0+1*1) >= 0); ASSUME(cr(3,0+1*1) >= cdy[3]); ASSUME(cr(3,0+1*1) >= cisb[3]); ASSUME(cr(3,0+1*1) >= cdl[3]); ASSUME(cr(3,0+1*1) >= cl[3]); // Update creg_r1 = cr(3,0+1*1); crmax(3,0+1*1) = max(crmax(3,0+1*1),cr(3,0+1*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+1*1) < cw(3,0+1*1)) { r1 = buff(3,0+1*1); ASSUME((!(( (cw(3,0+1*1) < 1) && (1 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(3,0+1*1) < 2) && (2 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(3,0+1*1) < 3) && (3 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(3,0+1*1) < 4) && (4 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(3,0+1*1) != co(0+1*1,cr(3,0+1*1))) { ASSUME(cr(3,0+1*1) >= old_cr); } pw(3,0+1*1) = co(0+1*1,cr(3,0+1*1)); r1 = mem(0+1*1,cr(3,0+1*1)); } ASSUME(creturn[3] >= cr(3,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !81, metadata !DIExpression()), !dbg !92 // %conv = trunc i64 %0 to i32, !dbg !54 // call void @llvm.dbg.value(metadata i32 %conv, metadata !78, metadata !DIExpression()), !dbg !89 // %cmp = icmp eq i32 %conv, 0, !dbg !55 creg__r1__0_ = max(0,creg_r1); // %conv1 = zext i1 %cmp to i32, !dbg !55 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !82, metadata !DIExpression()), !dbg !89 // %tobool = icmp ne i32 %conv1, 0, !dbg !56 creg___r1__0___0_ = max(0,creg__r1__0_); // br i1 %tobool, label %if.then, label %if.else, !dbg !58 old_cctrl = cctrl[3]; cctrl[3] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[3] >= old_cctrl); ASSUME(cctrl[3] >= creg___r1__0___0_); if(((r1==0)!=0)) { goto T3BLOCK2; } else { goto T3BLOCK3; } T3BLOCK2: // br label %lbl_label195, !dbg !59 goto T3BLOCK4; T3BLOCK3: // br label %lbl_label195, !dbg !60 goto T3BLOCK4; T3BLOCK4: // call void @llvm.dbg.label(metadata !88), !dbg !101 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !83, metadata !DIExpression()), !dbg !102 // call void @llvm.dbg.value(metadata i64 1, metadata !85, metadata !DIExpression()), !dbg !102 // store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !63 // ST: Guess iw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l39_c3 old_cw = cw(3,0); cw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l39_c3 // Check ASSUME(active[iw(3,0)] == 3); ASSUME(active[cw(3,0)] == 3); ASSUME(sforbid(0,cw(3,0))== 0); ASSUME(iw(3,0) >= 0); ASSUME(iw(3,0) >= 0); ASSUME(cw(3,0) >= iw(3,0)); ASSUME(cw(3,0) >= old_cw); ASSUME(cw(3,0) >= cr(3,0)); ASSUME(cw(3,0) >= cl[3]); ASSUME(cw(3,0) >= cisb[3]); ASSUME(cw(3,0) >= cdy[3]); ASSUME(cw(3,0) >= cdl[3]); ASSUME(cw(3,0) >= cds[3]); ASSUME(cw(3,0) >= cctrl[3]); ASSUME(cw(3,0) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,0) = 1; mem(0,cw(3,0)) = 1; co(0,cw(3,0))+=1; delta(0,cw(3,0)) = -1; ASSUME(creturn[3] >= cw(3,0)); // %cmp2 = icmp eq i32 %conv, 1, !dbg !64 creg__r1__1_ = max(0,creg_r1); // %conv3 = zext i1 %cmp2 to i32, !dbg !64 // call void @llvm.dbg.value(metadata i32 %conv3, metadata !86, metadata !DIExpression()), !dbg !89 // store i32 %conv3, i32* @atom_2_X0_1, align 4, !dbg !65, !tbaa !66 // ST: Guess iw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l41_c15 old_cw = cw(3,3); cw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l41_c15 // Check ASSUME(active[iw(3,3)] == 3); ASSUME(active[cw(3,3)] == 3); ASSUME(sforbid(3,cw(3,3))== 0); ASSUME(iw(3,3) >= creg__r1__1_); ASSUME(iw(3,3) >= 0); ASSUME(cw(3,3) >= iw(3,3)); ASSUME(cw(3,3) >= old_cw); ASSUME(cw(3,3) >= cr(3,3)); ASSUME(cw(3,3) >= cl[3]); ASSUME(cw(3,3) >= cisb[3]); ASSUME(cw(3,3) >= cdy[3]); ASSUME(cw(3,3) >= cdl[3]); ASSUME(cw(3,3) >= cds[3]); ASSUME(cw(3,3) >= cctrl[3]); ASSUME(cw(3,3) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,3) = (r1==1); mem(3,cw(3,3)) = (r1==1); co(3,cw(3,3))+=1; delta(3,cw(3,3)) = -1; ASSUME(creturn[3] >= cw(3,3)); // ret i8* null, !dbg !70 ret_thread_3 = (- 1); goto T3BLOCK_END; T3BLOCK_END: // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !114, metadata !DIExpression()), !dbg !137 // call void @llvm.dbg.value(metadata i8** %argv, metadata !115, metadata !DIExpression()), !dbg !137 // %0 = bitcast i64* %thr0 to i8*, !dbg !64 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !64 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !116, metadata !DIExpression()), !dbg !139 // %1 = bitcast i64* %thr1 to i8*, !dbg !66 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !66 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !120, metadata !DIExpression()), !dbg !141 // %2 = bitcast i64* %thr2 to i8*, !dbg !68 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !68 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !121, metadata !DIExpression()), !dbg !143 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !122, metadata !DIExpression()), !dbg !144 // call void @llvm.dbg.value(metadata i64 0, metadata !124, metadata !DIExpression()), !dbg !144 // store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !71 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l50_c3 old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l50_c3 // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !125, metadata !DIExpression()), !dbg !146 // call void @llvm.dbg.value(metadata i64 0, metadata !127, metadata !DIExpression()), !dbg !146 // store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !73 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l51_c3 old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l51_c3 // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // store i32 0, i32* @atom_1_X0_2, align 4, !dbg !74, !tbaa !75 // ST: Guess iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l52_c15 old_cw = cw(0,2); cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l52_c15 // Check ASSUME(active[iw(0,2)] == 0); ASSUME(active[cw(0,2)] == 0); ASSUME(sforbid(2,cw(0,2))== 0); ASSUME(iw(0,2) >= 0); ASSUME(iw(0,2) >= 0); ASSUME(cw(0,2) >= iw(0,2)); ASSUME(cw(0,2) >= old_cw); ASSUME(cw(0,2) >= cr(0,2)); ASSUME(cw(0,2) >= cl[0]); ASSUME(cw(0,2) >= cisb[0]); ASSUME(cw(0,2) >= cdy[0]); ASSUME(cw(0,2) >= cdl[0]); ASSUME(cw(0,2) >= cds[0]); ASSUME(cw(0,2) >= cctrl[0]); ASSUME(cw(0,2) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,2) = 0; mem(2,cw(0,2)) = 0; co(2,cw(0,2))+=1; delta(2,cw(0,2)) = -1; ASSUME(creturn[0] >= cw(0,2)); // store i32 0, i32* @atom_2_X0_1, align 4, !dbg !79, !tbaa !75 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l53_c15 old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l53_c15 // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !80 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call3 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !81 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call4 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !82 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !83, !tbaa !84 r3 = local_mem[0]; // %call5 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !86 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !87, !tbaa !84 r4 = local_mem[1]; // %call6 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !88 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !89, !tbaa !84 r5 = local_mem[2]; // %call7 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !90 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !129, metadata !DIExpression()), !dbg !161 // %6 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !92 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l63_c12 // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r6 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r6 = buff(0,0); ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r6 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %6, metadata !131, metadata !DIExpression()), !dbg !161 // %conv = trunc i64 %6 to i32, !dbg !93 // call void @llvm.dbg.value(metadata i32 %conv, metadata !128, metadata !DIExpression()), !dbg !137 // %cmp = icmp eq i32 %conv, 2, !dbg !94 creg__r6__2_ = max(0,creg_r6); // %conv8 = zext i1 %cmp to i32, !dbg !94 // call void @llvm.dbg.value(metadata i32 %conv8, metadata !132, metadata !DIExpression()), !dbg !137 // %7 = load i32, i32* @atom_1_X0_2, align 4, !dbg !95, !tbaa !75 // LD: Guess old_cr = cr(0,2); cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l65_c13 // Check ASSUME(active[cr(0,2)] == 0); ASSUME(cr(0,2) >= iw(0,2)); ASSUME(cr(0,2) >= 0); ASSUME(cr(0,2) >= cdy[0]); ASSUME(cr(0,2) >= cisb[0]); ASSUME(cr(0,2) >= cdl[0]); ASSUME(cr(0,2) >= cl[0]); // Update creg_r7 = cr(0,2); crmax(0,2) = max(crmax(0,2),cr(0,2)); caddr[0] = max(caddr[0],0); if(cr(0,2) < cw(0,2)) { r7 = buff(0,2); ASSUME((!(( (cw(0,2) < 1) && (1 < crmax(0,2)) )))||(sforbid(2,1)> 0)); ASSUME((!(( (cw(0,2) < 2) && (2 < crmax(0,2)) )))||(sforbid(2,2)> 0)); ASSUME((!(( (cw(0,2) < 3) && (3 < crmax(0,2)) )))||(sforbid(2,3)> 0)); ASSUME((!(( (cw(0,2) < 4) && (4 < crmax(0,2)) )))||(sforbid(2,4)> 0)); } else { if(pw(0,2) != co(2,cr(0,2))) { ASSUME(cr(0,2) >= old_cr); } pw(0,2) = co(2,cr(0,2)); r7 = mem(2,cr(0,2)); } ASSUME(creturn[0] >= cr(0,2)); // call void @llvm.dbg.value(metadata i32 %7, metadata !133, metadata !DIExpression()), !dbg !137 // %8 = load i32, i32* @atom_2_X0_1, align 4, !dbg !96, !tbaa !75 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l66_c13 // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r8 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r8 = buff(0,3); ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0)); ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0)); ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0)); ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0)); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r8 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i32 %8, metadata !134, metadata !DIExpression()), !dbg !137 // %and = and i32 %7, %8, !dbg !97 creg_r9 = max(creg_r7,creg_r8); r9 = r7 & r8; // call void @llvm.dbg.value(metadata i32 %and, metadata !135, metadata !DIExpression()), !dbg !137 // %and9 = and i32 %conv8, %and, !dbg !98 creg_r10 = max(creg__r6__2_,creg_r9); r10 = (r6==2) & r9; // call void @llvm.dbg.value(metadata i32 %and9, metadata !136, metadata !DIExpression()), !dbg !137 // %cmp10 = icmp eq i32 %and9, 1, !dbg !99 creg__r10__1_ = max(0,creg_r10); // br i1 %cmp10, label %if.then, label %if.end, !dbg !101 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg__r10__1_); if((r10==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([120 x i8], [120 x i8]* @.str.1, i64 0, i64 0), i32 noundef 69, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !102 // unreachable, !dbg !102 r11 = 1; goto T0BLOCK_END; T0BLOCK2: // %9 = bitcast i64* %thr2 to i8*, !dbg !105 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !105 // %10 = bitcast i64* %thr1 to i8*, !dbg !105 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !105 // %11 = bitcast i64* %thr0 to i8*, !dbg !105 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !105 // ret i32 0, !dbg !106 ret_thread_0 = 0; goto T0BLOCK_END; T0BLOCK_END: ASSUME(meminit(0,1) == mem(0,0)); ASSUME(coinit(0,1) == co(0,0)); ASSUME(deltainit(0,1) == delta(0,0)); ASSUME(meminit(0,2) == mem(0,1)); ASSUME(coinit(0,2) == co(0,1)); ASSUME(deltainit(0,2) == delta(0,1)); ASSUME(meminit(0,3) == mem(0,2)); ASSUME(coinit(0,3) == co(0,2)); ASSUME(deltainit(0,3) == delta(0,2)); ASSUME(meminit(0,4) == mem(0,3)); ASSUME(coinit(0,4) == co(0,3)); ASSUME(deltainit(0,4) == delta(0,3)); ASSUME(meminit(1,1) == mem(1,0)); ASSUME(coinit(1,1) == co(1,0)); ASSUME(deltainit(1,1) == delta(1,0)); ASSUME(meminit(1,2) == mem(1,1)); ASSUME(coinit(1,2) == co(1,1)); ASSUME(deltainit(1,2) == delta(1,1)); ASSUME(meminit(1,3) == mem(1,2)); ASSUME(coinit(1,3) == co(1,2)); ASSUME(deltainit(1,3) == delta(1,2)); ASSUME(meminit(1,4) == mem(1,3)); ASSUME(coinit(1,4) == co(1,3)); ASSUME(deltainit(1,4) == delta(1,3)); ASSUME(meminit(2,1) == mem(2,0)); ASSUME(coinit(2,1) == co(2,0)); ASSUME(deltainit(2,1) == delta(2,0)); ASSUME(meminit(2,2) == mem(2,1)); ASSUME(coinit(2,2) == co(2,1)); ASSUME(deltainit(2,2) == delta(2,1)); ASSUME(meminit(2,3) == mem(2,2)); ASSUME(coinit(2,3) == co(2,2)); ASSUME(deltainit(2,3) == delta(2,2)); ASSUME(meminit(2,4) == mem(2,3)); ASSUME(coinit(2,4) == co(2,3)); ASSUME(deltainit(2,4) == delta(2,3)); ASSUME(meminit(3,1) == mem(3,0)); ASSUME(coinit(3,1) == co(3,0)); ASSUME(deltainit(3,1) == delta(3,0)); ASSUME(meminit(3,2) == mem(3,1)); ASSUME(coinit(3,2) == co(3,1)); ASSUME(deltainit(3,2) == delta(3,1)); ASSUME(meminit(3,3) == mem(3,2)); ASSUME(coinit(3,3) == co(3,2)); ASSUME(deltainit(3,3) == delta(3,2)); ASSUME(meminit(3,4) == mem(3,3)); ASSUME(coinit(3,4) == co(3,3)); ASSUME(deltainit(3,4) == delta(3,3)); ASSERT(r11== 0); }
f3499235c1299d4bc284deb36518a466f36274bf
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/Qt/Components/moc_pqStringVectorPropertyWidget.cxx
ec134e8372774ae2c8e9d04920dba9af3c476a00
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
2,679
cxx
/**************************************************************************** ** Meta object code from reading C++ file 'pqStringVectorPropertyWidget.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../ParaView/Qt/Components/pqStringVectorPropertyWidget.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'pqStringVectorPropertyWidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.6. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_pqStringVectorPropertyWidget[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_pqStringVectorPropertyWidget[] = { "pqStringVectorPropertyWidget\0" }; void pqStringVectorPropertyWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObjectExtraData pqStringVectorPropertyWidget::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject pqStringVectorPropertyWidget::staticMetaObject = { { &pqPropertyWidget::staticMetaObject, qt_meta_stringdata_pqStringVectorPropertyWidget, qt_meta_data_pqStringVectorPropertyWidget, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &pqStringVectorPropertyWidget::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *pqStringVectorPropertyWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *pqStringVectorPropertyWidget::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_pqStringVectorPropertyWidget)) return static_cast<void*>(const_cast< pqStringVectorPropertyWidget*>(this)); return pqPropertyWidget::qt_metacast(_clname); } int pqStringVectorPropertyWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = pqPropertyWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
697e691d13515b02d37cce2ac7290dba54adf47d
b1ee6b1a8b616c3e2692a426d4e59b8a508cd6c3
/Robot/Robot.ip_user_files/bd/base/ip/base_constant_tkeep_tstrb_1/sim/base_constant_tkeep_tstrb_1.h
59cc2887cf546a3587b23354959360c8139fe323
[ "MIT" ]
permissive
junhongmit/PYNQ_Car
5c9157bc42680c897c828ba6539800b066d6888f
c4600f270c56c819e6b3e3e357b44081ee5ddce5
refs/heads/master
2022-03-01T12:44:03.589295
2019-10-21T16:43:33
2019-10-21T16:43:33
165,031,312
1
0
null
null
null
null
UTF-8
C++
false
false
2,689
h
// (c) Copyright 1995-2014 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. // IP VLNV: xilinx.com:ip:xlconstant:1.1 // IP Revision: 1 #ifndef _base_constant_tkeep_tstrb_1_H_ #define _base_constant_tkeep_tstrb_1_H_ #include "xlconstant_v1_1.h" #include "systemc.h" class base_constant_tkeep_tstrb_1 : public sc_module { public: xlconstant_v1_1_5<4,15> mod; sc_out< sc_bv<4> > dout; base_constant_tkeep_tstrb_1 (sc_core::sc_module_name name) :sc_module(name), mod("mod") { mod.dout(dout); } }; #endif
7440b24ea9e26820cf09a065a704bccd9e0110c4
959af614f695a948ae2c899f1e9a6c8163c80e00
/samples/core/sample_core_benchmark_disk.cpp
abfd69eb7210700193f120cb835cc69b5763b33c
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Paul-Hi/saiga
cacf1d8537096df871fafa06e755b4e9908672f3
1b843bf7800f7113e7bd4d709fc965088078702d
refs/heads/master
2023-06-19T22:18:24.752565
2021-06-29T15:06:25
2021-06-29T15:06:25
289,020,555
0
0
MIT
2020-08-20T13:58:07
2020-08-20T13:58:06
null
UTF-8
C++
false
false
1,195
cpp
/** * Copyright (c) 2017 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "saiga/core/Core.h" #include "saiga/core/time/all.h" #include "saiga/core/util/Thread/omp.h" using namespace Saiga; int sizeMB = 1000 * 1; size_t blockSize = sizeMB * 1000UL * 1000UL; double blockSizeGB = (blockSize / (1000.0 * 1000.0 * 1000.0)); void write(const std::string& file, const std::vector<char>& data) { FILE* dest = fopen(file.c_str(), "wb"); if (dest == 0) { return; } auto written = fwrite(0, 1, data.size(), dest); SAIGA_ASSERT(written == data.size()); fclose(dest); } void write2(const std::string& file, const std::vector<char>& data) { std::ofstream is(file, std::ios::binary | std::ios::out); if (!is.is_open()) { std::cout << "File not found " << file << std::endl; return; } is.write(data.data(), data.size()); is.close(); } int main(int, char**) { catchSegFaults(); std::vector<char> data(blockSize); { SAIGA_BLOCK_TIMER(); write2("test.dat", data); } std::cout << "Done." << std::endl; return 0; }
42f0b1c94b78719dc6a409d2c51f79d2d01764a5
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/crypto/ec_signature_creator_impl.cc
2870310dd1c0d30880412a0a05bd87ac978da063
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
2,343
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crypto/ec_signature_creator_impl.h" #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/evp.h> #include <openssl/sha.h> #include <stddef.h> #include <stdint.h> #include "base/logging.h" #include "crypto/ec_private_key.h" #include "crypto/openssl_util.h" namespace crypto { ECSignatureCreatorImpl::ECSignatureCreatorImpl(ECPrivateKey* key) : key_(key) { EnsureOpenSSLInit(); } ECSignatureCreatorImpl::~ECSignatureCreatorImpl() {} bool ECSignatureCreatorImpl::Sign(const uint8_t* data, int data_len, std::vector<uint8_t>* signature) { OpenSSLErrStackTracer err_tracer(FROM_HERE); bssl::ScopedEVP_MD_CTX ctx; size_t sig_len = 0; if (!ctx.get() || !EVP_DigestSignInit(ctx.get(), nullptr, EVP_sha256(), nullptr, key_->key()) || !EVP_DigestSignUpdate(ctx.get(), data, data_len) || !EVP_DigestSignFinal(ctx.get(), nullptr, &sig_len)) { return false; } signature->resize(sig_len); if (!EVP_DigestSignFinal(ctx.get(), &signature->front(), &sig_len)) return false; // NOTE: A call to EVP_DigestSignFinal() with a nullptr second parameter // returns a maximum allocation size, while the call without a nullptr // returns the real one, which may be smaller. signature->resize(sig_len); return true; } bool ECSignatureCreatorImpl::DecodeSignature( const std::vector<uint8_t>& der_sig, std::vector<uint8_t>* out_raw_sig) { OpenSSLErrStackTracer err_tracer(FROM_HERE); // Create ECDSA_SIG object from DER-encoded data. bssl::UniquePtr<ECDSA_SIG> ecdsa_sig( ECDSA_SIG_from_bytes(der_sig.data(), der_sig.size())); if (!ecdsa_sig.get()) return false; // The result is made of two 32-byte vectors. const size_t kMaxBytesPerBN = 32; std::vector<uint8_t> result(2 * kMaxBytesPerBN); if (!BN_bn2bin_padded(&result[0], kMaxBytesPerBN, ecdsa_sig->r) || !BN_bn2bin_padded(&result[kMaxBytesPerBN], kMaxBytesPerBN, ecdsa_sig->s)) { return false; } out_raw_sig->swap(result); return true; } } // namespace crypto
c7ad667771f2737d87dc1bcbb1062bb791a32891
39e9e8c8d4ca4e97c87f35670e0774920a2abe45
/Viscous/viscous_explicit.cpp
f68f3576d94040890d6259110772a44f661caa48
[]
no_license
aditya12398/QKFVS_2D
a15de68d4759c36fe6e19c995004aa6b39fe64fa
9d80d5f64f25f9235ab61d2c78333165473787e6
refs/heads/master
2020-06-14T13:46:01.679637
2019-08-09T02:38:01
2019-08-09T02:38:01
195,017,837
2
0
null
null
null
null
UTF-8
C++
false
false
26,153
cpp
/* This code is a solver for 2D Euler equations for compressible domain. It uses `Kinetic Flux Vector Splitting(KFVS)` to calculate fluxes across the edges of a cell and conserve them. The related equations can be found in the Reference: "J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations" at location ../References/Kinetic_Flux_Vector_Splitting Strongly Recommended: Use Visual Studio Code(text editor) while understanding the code. The comments are coupled appropriately with the functions and variables for easier understanding. */ #include <fstream> #include <iostream> #include <cmath> using namespace std; int max_edges, max_cells, max_iters; double Mach, aoa, cfl, limiter_const; double gma = 1.4, R = 287, Prandtl_number = 0.72; //Flow and material parameters double residue, max_res; //RMS Residue and maximum residue in the fluid domain int max_res_cell; //Cell number with maximum residue double pi = 4.0 * atan(1.0); //Structure to store edge data struct Edge { int lcell, rcell; //Holds cell numbers on either side of the edge. Prefix l stands for left and r for right. double nx, ny, mx, my; //Hold point data. Prefix m stands for midpoint and n for edge normal. double length; //Holds edge length data char status; //Specifies whether the edge is Internal(f), Wall(w) or Outer Boundary(o). }; //Structure to store cell data struct Cell { int *edge, noe, nbhs, *conn; //Holds enclosing edges and neighbour cell data. double area, cx, cy; //Area of the cell and cell centre coordinates double rho, u1, u2, pr, tp; //Values of density, x - velocity, y - velocity, pressure and temperature of the cell double u1x, u2x, u1y, u2y; //Velocity derivatives double tpx, tpy; //Temperature derivatives double flux[5]; //Kinetic Fluxes. Reference: See function `void KFVS_pos_flux(...)` double Unew[5], Uold[5]; //Corresponds to void backward_sweep() double q[5], qx[5], qy[5]; //Entropy Variables. Reference: See Boltzmann Equations }; struct Edge *edge; struct Cell *cell; //--------------------------Main function starts-------------------------- int main(int arg, char *argv[]) { void input_data(); void initial_conditions(); void q_variables(); void q_derivatives(); void f_derivatives(); void evaluate_flux(); void state_update(); void print_output(); ofstream outfile("./Output/Residue"); double res_old; input_data(); int T = 2; for (int t = 1; t <= max_iters; t++) { initial_conditions(); q_variables(); q_derivatives(); f_derivatives(); evaluate_flux(); state_update(); if (t == 1) res_old = residue; residue = log10(residue / res_old); if ((max_res) < -12 && (residue) < -12) { cout << "Convergence criteria reached.\n"; break; } cout << t << "\t" << residue << "\t" << max_res << "\t" << max_res_cell << endl; outfile << t << "\t" << residue << "\t" << max_res << "\t" << max_res_cell << endl; if (t == T) { T = T + 2; print_output(); } } print_output(); } //End of the main function /* This function reads flow and grid data from the files: Grid data: ogrid_viscous_dim Flow Parameters: fp_viscous */ void input_data() { ifstream infile("ogrid_viscous_dim"); ifstream infile2("fp_viscous"); //Input Flow Parameters infile2 >> Mach >> aoa >> cfl >> max_iters >> limiter_const; //Input Edge data infile >> max_edges; edge = new Edge[max_edges + 1]; for (int k = 1; k <= max_edges; k++) { infile >> edge[k].mx >> edge[k].my >> edge[k].lcell >> edge[k].rcell >> edge[k].status >> edge[k].nx >> edge[k].ny >> edge[k].length; } //Input Cell data infile >> max_cells; cell = new Cell[max_cells + 1]; for (int k = 1; k <= max_cells; k++) { infile >> cell[k].cx >> cell[k].cy >> cell[k].rho >> cell[k].u1 >> cell[k].u2 >> cell[k].pr >> cell[k].area >> cell[k].noe; cell[k].tp = cell[k].pr / (R * cell[k].rho); //Set enclosing edges cell[k].edge = new int[cell[k].noe + 1]; for (int r = 1; r <= cell[k].noe; r++) infile >> cell[k].edge[r]; //Set neighbours infile >> cell[k].nbhs; cell[k].conn = new int[cell[k].nbhs]; for (int r = 0; r < cell[k].nbhs; r++) infile >> cell[k].conn[r]; } infile.close(); infile2.close(); } //End of the function double *gauss_elimination(double matrix[5][(6)]) { int i, j, k; double *solution = new double[5]; double swap; //Pivot the matrix for diagonal dominance for (i = 0; i < 5; i++) { solution[i] = 0; double max = fabs(matrix[i][i]); int pos = i; for (j = i; j < 5; j++) { if (fabs(matrix[j][i]) > max) { pos = j; max = fabs(matrix[j][i]); } } //Swap the elements for (k = 0; k <= 5; k++) { swap = matrix[i][k]; matrix[i][k] = matrix[pos][k]; matrix[pos][k] = swap; } } //Convert the matrix to a lower triangle matrix for (i = 4; i > 0; i--) { for (j = i - 1; j >= 0; j--) { double d = (matrix[j][i] / matrix[i][i]); for (k = 5; k >= 0; k--) { matrix[j][k] -= d * matrix[i][k]; } } } solution[0] = matrix[0][5] / matrix[0][0]; for (i = 1; i < 5; i++) { solution[i] = matrix[i][5]; for (j = i - 1; j >= 0; j--) { solution[i] -= (solution[j] * matrix[i][j]); } solution[i] = solution[i] / matrix[i][i]; } return solution; } void construct_equation(int k, char var, double matrix[5][6]) { double sig_dxdx, sig_dydy, sig_dxdy; double sig_dxdxdx, sig_dydydy, sig_dxdxdy, sig_dxdydy; double sig_dxdxdxdx, sig_dydydydy, sig_dxdxdxdy, sig_dxdxdydy, sig_dxdydydy; double sig_dfdx, sig_dfdy, sig_dfdxdx, sig_dfdydy, sig_dfdxdy; double dx, dy, df; sig_dxdx = sig_dydy = sig_dxdy = sig_dxdxdx = sig_dydydy = sig_dxdxdy = sig_dxdydy = sig_dxdxdxdx = sig_dydydydy = sig_dxdxdxdy = sig_dxdxdydy = sig_dxdydydy = sig_dfdx = sig_dfdy = sig_dfdxdx = sig_dfdydy = sig_dfdxdy = 0; for (int i = 0; i < cell[k].nbhs; i++) { int p = cell[k].conn[i]; dx = cell[p].cx - cell[k].cx; dy = cell[p].cy - cell[k].cy; double dist = sqrt(dx * dx + dy * dy); //Distance between cell and edge midpoint double w = 1 / pow(dist, 2.0); //Least Squares weight if (var == 'u') df = cell[p].u1 - cell[k].u1; else if (var == 'v') df = cell[p].u2 - cell[k].u2; else if (var == 't') df = cell[p].tp - cell[k].tp; sig_dfdx += w * df * dx; sig_dfdy += w * df * dy; sig_dfdxdx += w * df * dx * dx; sig_dfdydy += w * df * dy * dy; sig_dfdxdy += w * df * dx * dy; sig_dxdx += w * dx * dx; sig_dxdy += w * dx * dy; sig_dydy += w * dy * dy; sig_dxdxdx += w * dx * dx * dx; sig_dxdxdy += w * dx * dx * dy; sig_dxdydy += w * dx * dy * dy; sig_dydydy += w * dy * dy * dy; sig_dxdxdxdx += w * dx * dx * dx * dx; sig_dxdxdxdy += w * dx * dx * dx * dy; sig_dxdxdydy += w * dx * dx * dy * dy; sig_dxdydydy += w * dx * dy * dy * dy; sig_dydydydy += w * dy * dy * dy * dy; } matrix[0][5] = sig_dfdx; matrix[1][5] = sig_dfdy; matrix[2][5] = sig_dfdxdx / 2; matrix[3][5] = sig_dfdydy / 2; matrix[4][5] = sig_dfdxdy; matrix[0][0] = sig_dxdx; matrix[1][1] = sig_dydy; matrix[2][2] = sig_dxdxdxdx / 4; matrix[3][3] = sig_dydydydy / 4; matrix[4][4] = sig_dxdxdydy; matrix[0][1] = matrix[1][0] = sig_dxdy; matrix[0][2] = matrix[2][0] = sig_dxdxdx / 2; matrix[0][3] = matrix[3][0] = sig_dxdydy / 2; matrix[0][4] = matrix[4][0] = sig_dxdxdy; matrix[1][2] = matrix[2][1] = sig_dxdxdy / 2; matrix[1][3] = matrix[3][1] = sig_dydydy / 2; matrix[1][4] = matrix[4][1] = sig_dxdydy; matrix[2][3] = matrix[3][2] = sig_dxdxdydy / 4; matrix[2][4] = matrix[4][2] = sig_dxdxdxdy / 2; matrix[3][4] = matrix[4][3] = sig_dxdydydy / 2; } void f_derivatives() { for (int k = 1; k <= max_cells; k++) { double matrix[5][6], *solution; //Derivative of velocity construct_equation(k, 'u', matrix); solution = gauss_elimination(matrix); cell[k].u1x = solution[0]; cell[k].u1y = solution[1]; delete[] solution; construct_equation(k, 'v', matrix); solution = gauss_elimination(matrix); cell[k].u2x = solution[0]; cell[k].u2y = solution[1]; delete[] solution; construct_equation(k, 't', matrix); solution = gauss_elimination(matrix); cell[k].tpx = solution[0]; cell[k].tpy = solution[1]; delete[] solution; } } void viscous_flux(double *G, int e, double nx, double ny, int CELL, double rho_ref, double u1_ref, double u2_ref, double pr_ref) { double u_dash[5], tp_dash[3]; double tauxx, tauyy, tauxy, t_ref, mu, kappa; t_ref = pr_ref / (R * rho_ref); mu = 1.458E-6 * pow(t_ref, 1.5) / (t_ref + 110.4); kappa = mu * (gma * R) / (Prandtl_number * (gma - 1)); u_dash[1] = (cell[CELL].u1x); u_dash[2] = (cell[CELL].u1y); u_dash[3] = (cell[CELL].u2x); u_dash[4] = (cell[CELL].u2y); tp_dash[1] = cell[CELL].tpx; tp_dash[2] = cell[CELL].tpy; tauxx = mu * (4 / 3 * u_dash[1] - 2 / 3 * u_dash[4]); tauyy = mu * (4 / 3 * u_dash[4] - 2 / 3 * u_dash[1]); tauxy = mu * (u_dash[2] + u_dash[3]); //Storing viscous fluxes if (edge[e].status == 'w') { tp_dash[1] = tp_dash[2] = 0; } G[1] = 0; G[2] = -(tauxx * nx + tauxy * ny); G[3] = -(tauxy * nx + tauyy * ny); G[4] = -((u1_ref * tauxx + u2_ref * tauxy + kappa * tp_dash[1]) * nx) + ((u1_ref * tauxy + u2_ref * tauyy + kappa * tp_dash[2]) * ny); } //Fluxes are evaluated in this function void evaluate_flux() { //Function Prototypes void linear_reconstruction(double *, int, int); void KFVS_pos_flux(double *, double, double, double, double, double, double); void KFVS_neg_flux(double *, double, double, double, double, double, double); void KFVS_wall_flux(double *, double, double, double, double, double, double); void KFVS_outer_flux(double *, double, double, double, double, double, double); double u_dash[5]; int lcell, rcell; double nx, ny, s; double Gp[5], Gn[5], Gd[5]; double Gwall[5], Gout[5]; double lprim[5], rprim[5]; char status; double rhol, u1l, u2l, prl; //Left Cell Data double rhor, u1r, u2r, prr; //Right Cell Data for (int k = 1; k <= max_edges; k++) { lcell = edge[k].lcell; rcell = edge[k].rcell; nx = edge[k].nx; ny = edge[k].ny; s = edge[k].length; status = edge[k].status; if (status == 'f') //Flux across interior edges { linear_reconstruction(lprim, lcell, k); linear_reconstruction(rprim, rcell, k); rhol = lprim[1]; u1l = lprim[2]; u2l = lprim[3]; prl = lprim[4]; rhor = rprim[1]; u1r = rprim[2]; u2r = rprim[3]; prr = rprim[4]; KFVS_pos_flux(Gp, nx, ny, rhol, u1l, u2l, prl); KFVS_neg_flux(Gn, nx, ny, rhor, u1r, u2r, prr); viscous_flux(Gd, k, nx, ny, lcell, rhol, u1l, u2l, prl); viscous_flux(Gd, k, nx, ny, rcell, rhor, u1r, u2r, prr); for (int r = 1; r <= 4; r++) { cell[lcell].flux[r] = cell[lcell].flux[r] + s * (*(Gp + r) + *(Gn + r) + *(Gd + r)); cell[rcell].flux[r] = cell[rcell].flux[r] - s * (*(Gp + r) + *(Gn + r) + *(Gd + r)); } } if (status == 'w') //Flux across wall edge { if (lcell == 0) { nx = -nx; ny = -ny; lcell = rcell; } linear_reconstruction(lprim, lcell, k); rhol = lprim[1]; u1l = lprim[2]; u2l = lprim[3]; prl = lprim[4]; KFVS_wall_flux(Gwall, nx, ny, rhol, u1l, u2l, prl); viscous_flux(Gd, k, nx, ny, lcell, rhol, 0, 0, prl); for (int r = 1; r <= 4; r++) cell[lcell].flux[r] = cell[lcell].flux[r] + s * (*(Gwall + r) + *(Gd + r)); } if (status == 'o') //Flux across outer boundary edge { if (lcell == 0) { nx = -nx; ny = -ny; lcell = rcell; } linear_reconstruction(lprim, lcell, k); rhol = lprim[1]; u1l = lprim[2]; u2l = lprim[3]; prl = lprim[4]; KFVS_outer_flux(Gout, nx, ny, rhol, u1l, u2l, prl); viscous_flux(Gd, k, nx, ny, lcell, rhol, u1l, u2l, prl); for (int r = 1; r <= 4; r++) cell[lcell].flux[r] = cell[lcell].flux[r] + s * (*(Gout + r) + *(Gd + r)); } } //End of k loop } //End of the flux function //Expressions for the kfvs - fluxes /* Function to find the kfvs - positive flux The following function uses the G Flux equations. Reference: J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations; Page 7 of 32; Book Page Number 453 Reference Location: ../References/Kinetic_Flux_Vector_Splitting/ */ void KFVS_pos_flux(double *G, double nx, double ny, double rho, double u1, double u2, double pr) { double tx, ty; tx = ny; ty = -nx; double un = u1 * nx + u2 * ny; double ut = u1 * tx + u2 * ty; double beta = 0.5 * rho / pr; double S = un * sqrt(beta); double A = 0.5 * (1 + erf(S)); double B = 0.5 * exp(-S * S) / sqrt(pi * beta); *(G + 1) = rho * (un * A + B); double temp1 = (pr + rho * un * un) * A + rho * un * B; double temp2 = rho * (un * ut * A + ut * B); *(G + 2) = -ty * temp1 + ny * temp2; *(G + 3) = tx * temp1 - nx * temp2; temp1 = 0.5 * rho * (un * un + ut * ut); *(G + 4) = ((gma / (gma - 1)) * pr + temp1) * un * A + (((gma + 1) / (2 * (gma - 1))) * pr + temp1) * B; } //End of G-positive flux /* Function to find the kfvs - negative flux The following function uses the G Flux equations. Reference: J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations; Page 7 of 32; Book Page Number 453 Reference Location: ../References/Kinetic_Flux_Vector_Splitting/ */ void KFVS_neg_flux(double *G, double nx, double ny, double rho, double u1, double u2, double pr) { double tx, ty; tx = ny; ty = -nx; double un = u1 * nx + u2 * ny; double ut = u1 * tx + u2 * ty; double beta = 0.5 * rho / pr; double S = un * sqrt(beta); double A = 0.5 * (1 - erf(S)); double B = 0.5 * exp(-S * S) / sqrt(pi * beta); *(G + 1) = rho * (un * A - B); double temp1 = (pr + rho * un * un) * A - rho * un * B; double temp2 = rho * (un * ut * A - ut * B); *(G + 2) = -ty * temp1 + ny * temp2; *(G + 3) = tx * temp1 - nx * temp2; temp1 = 0.5 * rho * (un * un + ut * ut); *(G + 4) = ((gma / (gma - 1)) * pr + temp1) * un * A - (((gma + 1) / (2 * (gma - 1))) * pr + temp1) * B; } //End of G-negative flux /* Function to find the kfvs - wall boundary flux The following function uses the G Flux equations. Reference: J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations; Page 7 of 32; Book Page Number 453 Reference Location: ../References/Kinetic_Flux_Vector_Splitting/ */ void KFVS_wall_flux(double *G, double nx, double ny, double rho, double u1, double u2, double pr) { double un, ut; ut = 0.0; //No slip boundary condition un = 0.0; double beta = 0.5 * rho / pr; double Sw = un * sqrt(beta); double Aw = 0.5 * (1 + erf(Sw)); double Bw = 0.5 * exp(-Sw * Sw) / sqrt(pi * beta); double temp = (pr + rho * un * un) * Aw + rho * un * Bw; temp = 2.0 * temp; *(G + 1) = 0.0; *(G + 2) = nx * temp; *(G + 3) = ny * temp; *(G + 4) = 0.0; } //End of the wall flux function /* Function to find the kfvs - outer boundary flux The following function uses the G Flux equations. Reference: J. C. Mandal, S. M. Deshpande - Kinetic Flux Vector Splitting For Euler Equations; Page 7 of 32; Book Page Number 453 Reference Location: ../References/Kinetic_Flux_Vector_Splitting/ */ void KFVS_outer_flux(double *Gout, double nx, double ny, double rho, double u1, double u2, double pr) { void KFVS_pos_flux(double *, double, double, double, double, double, double); void KFVS_neg_flux(double *, double, double, double, double, double, double); double Gp[5]; double Gn_inf[5]; double rho_inf, u1_inf, u2_inf, pr_inf, u_ref; u_ref = sqrt(gma * R * 288.20); double theta = aoa * pi / 180; rho_inf = 1.225; u1_inf = u_ref * Mach * cos(theta); u2_inf = u_ref * Mach * sin(theta); pr_inf = 101325.0; KFVS_pos_flux(Gp, nx, ny, rho, u1, u2, pr); KFVS_neg_flux(Gn_inf, nx, ny, rho_inf, u1_inf, u2_inf, pr_inf); for (int r = 1; r <= 4; r++) *(Gout + r) = *(Gp + r) + *(Gn_inf + r); } //End of the function //Function to find the conserved vector from the given primitive vector void prim_to_conserved(double *U, int k) { double rho, u1, u2, pr, e; rho = cell[k].rho; u1 = cell[k].u1; u2 = cell[k].u2; pr = cell[k].pr; e = (1 / (gma - 1)) * pr / rho + 0.5 * (u1 * u1 + u2 * u2); *(U + 1) = rho; *(U + 2) = rho * u1; *(U + 3) = rho * u2; *(U + 4) = rho * e; } //End of the function //Function to get the primitive vector from the given conserved vector void conserved_to_primitive(double *U, int k) { double U1 = *(U + 1); double U2 = *(U + 2); double U3 = *(U + 3); double U4 = *(U + 4); cell[k].rho = U1; double temp = 1 / U1; cell[k].u1 = U2 * temp; cell[k].u2 = U3 * temp; temp = U4 - (0.5 * temp) * (U2 * U2 + U3 * U3); cell[k].pr = 0.4 * temp; cell[k].tp = cell[k].pr / (R * cell[k].rho); } //End of the function //Function to find the delt (delta t) for each cell double func_delt(int k) { double smallest_dist(int); double rho, u1, u2, pr; double area, temp1, smin; int edges, e; double nx, ny, delt_inv = 0.0, delt_visc = 0.0; area = cell[k].area; u1 = cell[k].u1; u2 = cell[k].u2; rho = cell[k].rho; pr = cell[k].pr; smin = smallest_dist(k); edges = cell[k].noe; temp1 = 3.0 * sqrt(pr / rho); for (int r = 1; r <= edges; r++) { e = cell[k].edge[r]; double length = edge[e].length; nx = edge[e].nx; ny = edge[e].ny; if (edge[e].rcell == k) { nx = -nx; ny = -ny; } double un = u1 * nx + u2 * ny; double temp2 = (fabs(un) + temp1); temp2 = length * temp2; delt_inv = delt_inv + temp2; } double mu = 1.458E-6 * pow(cell[k].tp, 1.5) / (cell[k].tp + 110.4); delt_inv = 2.0 * area / delt_inv; delt_visc = rho * Prandtl_number * smin * smin / (4 * mu * gma); double delt = 1 / ((1 / delt_inv) + (1 / delt_visc)); return (cfl * delt); } //End of the function //Function to give the initial conditions void initial_conditions() { double rho, u1, u2, pr, e, U[5]; for (int k = 1; k <= max_cells; k++) { rho = cell[k].rho; u1 = cell[k].u1; u2 = cell[k].u2; pr = cell[k].pr; e = (1 / (gma - 1)) * pr / rho + 0.5 * (u1 * u1 + u2 * u2); U[1] = rho; U[2] = rho * u1; U[3] = rho * u2; U[4] = rho * e; for (int r = 1; r <= 4; r++) { cell[k].flux[r] = 0.0; cell[k].Uold[r] = U[r]; cell[k].Unew[r] = U[r]; } } } //End of the function void state_update() { void prim_to_conserved(double *, int); void conserved_to_primitive(double *, int); residue = 0.0; max_res = 0.0; double U[5]; for (int k = 1; k <= max_cells; k++) { prim_to_conserved(U, k); double temp = U[1]; for (int r = 1; r <= 4; r++) { cell[k].Unew[r] = cell[k].Uold[r] - func_delt(k) * cell[k].flux[r] / cell[k].area; U[r] = cell[k].Unew[r]; cell[k].Uold[r] = cell[k].Unew[r]; } residue = residue + (temp - U[1]) * (temp - U[1]); temp = fabs(temp - U[1]); if (max_res < temp) { max_res = temp; max_res_cell = k; } conserved_to_primitive(U, k); } residue = residue / max_cells; residue = sqrt(residue); } //End of the function //Function writes the data in supported tecplot format void write_tecplot() { static int count = 1; string title =to_string(count++) + "_Solution_Tecplot_Explicit.dat"; ofstream tecplotfile("./Output/" + title); tecplotfile << "TITLE: \"QKFVS Viscous Code - NAL\"\n"; tecplotfile << "VARIABLES= \"X\", \"Y\", \"Density\", \"Pressure\", \"x-velocity\", \"y-velocity\", \"Velocity Magnitude\", \"Temperature\"\n"; tecplotfile << "ZONE I= 298 J= 179, DATAPACKING=BLOCK\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].cx << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].cy << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].rho << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].pr << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].u1 << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].u2 << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << sqrt(pow(cell[k].u1, 2) + pow(cell[k].u2, 2)) << "\n"; } } tecplotfile << "\n"; for (int j = 1; j < 180; j++) { for (int i = 1; i <= 298; i++) { int k = (j - 1) * 298 + i; tecplotfile << cell[k].tp << "\n"; } } tecplotfile << "\n"; tecplotfile.close(); } //Function which prints the final primitive vector into the file "primitive-vector.dat" void print_output() { ofstream outfile("./Output/Primitive-Vector.dat"); for (int k = 1; k <= max_cells; k++) { outfile << k << "\t" << cell[k].rho << "\t" << cell[k].u1 << "\t" << cell[k].u2 << "\t" << cell[k].pr << endl; } write_tecplot(); } //End of the function /* Second order part of the code starts from here Second order accuracy is achieved via linear reconstruction with q-variables */ //Function to calculate the q-variables for all the nodes void q_variables() { int i; double rho, u1, u2, pr, beta; for (i = 1; i <= max_cells; i++) { rho = cell[i].rho; u1 = cell[i].u1; u2 = cell[i].u2; pr = cell[i].pr; beta = 0.5 * rho / pr; cell[i].q[1] = log(rho) + (log(beta) * (1 / (gma - 1))) - beta * (u1 * u1 + u2 * u2); cell[i].q[2] = 2 * beta * u1; cell[i].q[3] = 2 * beta * u2; cell[i].q[4] = -2 * beta; } } //End of the function //Function to convert q-varibales to primitive variables void func_qtilde_to_prim_variables(double *prim, double *qtilde) { double q1, q2, q3, q4, beta, u1, u2; q1 = *(qtilde + 1); q2 = *(qtilde + 2); q3 = *(qtilde + 3); q4 = *(qtilde + 4); beta = -q4 * 0.5; double temp = 0.5 / beta; *(prim + 2) = q2 * temp; *(prim + 3) = q3 * temp; u1 = *(prim + 2); u2 = *(prim + 3); double temp1 = q1 + beta * (u1 * u1 + u2 * u2); //double temp2 = temp1 - (log(beta)/(gma-1)); temp1 = temp1 - (log(beta) * (1 / (gma - 1))); *(prim + 1) = exp(temp1); *(prim + 4) = *(prim + 1) * temp; } //End of the function //Function to find q-derivatives using the method of least squares void q_derivatives() { //double power = 2.0; for (int k = 1; k <= max_cells; k++) { //Initialise the sigma values double sig_dxdx = 0.0; double sig_dydy = 0.0; double sig_dxdy = 0.0; double sig_dxdq[5], sig_dydq[5]; for (int r = 1; r <= 4; r++) { sig_dxdq[r] = 0.0; sig_dydq[r] = 0.0; } for (int j = 0; j < cell[k].nbhs; j++) { int p = cell[k].conn[j]; double delx = cell[p].cx - cell[k].cx; double dely = cell[p].cy - cell[k].cy; double dist = sqrt(delx * delx + dely * dely); double w = 1 / pow(dist, 2.0); sig_dxdx = sig_dxdx + w * delx * delx; sig_dydy = sig_dydy + w * dely * dely; sig_dxdy = sig_dxdy + w * delx * dely; for (int r = 1; r <= 4; r++) { double delq = cell[p].q[r] - cell[k].q[r]; sig_dxdq[r] = sig_dxdq[r] + w * delx * delq; sig_dydq[r] = sig_dydq[r] + w * dely * delq; } } double det = sig_dxdx * sig_dydy - sig_dxdy * sig_dxdy; for (int r = 1; r <= 4; r++) { double detx = sig_dydy * sig_dxdq[r] - sig_dxdy * sig_dydq[r]; double dety = sig_dxdx * sig_dydq[r] - sig_dxdy * sig_dxdq[r]; cell[k].qx[r] = detx / det; cell[k].qy[r] = dety / det; } } //End of k loop } //End of the function //Function to find the linear reconstruction values of primitive variables at the mid point of a given edge void linear_reconstruction(double *prim, int CELL, int edg) { void limiter(double *, double *, int); void func_qtilde_to_prim_variables(double *, double *); double delx, dely, phi[5], qtilde[5]; delx = edge[edg].mx - cell[CELL].cx; dely = edge[edg].my - cell[CELL].cy; for (int r = 1; r <= 4; r++) qtilde[r] = cell[CELL].q[r] + delx * cell[CELL].qx[r] + dely * cell[CELL].qy[r]; //limiter(qtilde, phi, CELL); /*for (int r = 1; r <= 4; r++) qtilde[r] = cell[CELL].q[r] + phi[r] * (delx * cell[CELL].qx[r] + dely * cell[CELL].qy[r]);*/ func_qtilde_to_prim_variables(prim, qtilde); } //End of the function //Function to find the limiter void limiter(double *qtilde, double *phi, int k) { double maximum(int, int); double minimum(int, int); double smallest_dist(int); double max_q, min_q, temp; double q, del_neg, del_pos; for (int r = 1; r <= 4; r++) { q = cell[k].q[r]; del_neg = qtilde[r] - q; if (fabs(del_neg) <= 10e-6) phi[r] = 1.0; else { if (del_neg > 0.0) { max_q = maximum(k, r); del_pos = max_q - q; } else if (del_neg < 0.0) { min_q = minimum(k, r); del_pos = min_q - q; } double num, den, ds; ds = smallest_dist(k); double epsi = limiter_const * ds; epsi = pow(epsi, 3.0); num = (del_pos * del_pos) + (epsi * epsi); num = num * del_neg + 2.0 * del_neg * del_neg * del_pos; den = del_pos * del_pos + 2.0 * del_neg * del_neg; den = den + del_neg * del_pos + epsi * epsi; den = den * del_neg; temp = num / den; if (temp < 1.0) phi[r] = temp; else phi[r] = 1.0; } } } //End of the function double maximum(int k, int r) { double max = cell[k].q[r]; for (int j = 0; j < cell[k].nbhs; j++) { int p = cell[k].conn[j]; if (cell[p].q[r] > max) max = cell[p].q[r]; } return (max); } //End of the function double minimum(int k, int r) { double min = cell[k].q[r]; for (int j = 0; j < cell[k].nbhs; j++) { int p = cell[k].conn[j]; if (cell[p].q[r] < min) min = cell[p].q[r]; } return (min); } //End of the function //Finding the dels; the smallest distance measured over the neighbours of a given cell double smallest_dist(int k) { int p; double dx, dy, ds, min; for (int j = 0; j < cell[k].nbhs; j++) { p = cell[k].conn[j]; dx = cell[p].cx - cell[k].cx; dy = cell[p].cy - cell[k].cy; ds = sqrt(dx * dx + dy * dy); if (j == 0) min = ds; if (ds < min) min = ds; } return (ds); } //End of the function
dd17aea02e2bcc6fc9c62ed475cbe61630ff9bd4
d017b807b3753800feef6b8077d084b460027e46
/cpp/AlignParametric/ParticleSurface.cpp
fe23b164543c2453c78ca40248b79256e1172a1e
[]
no_license
awturner/awturner-phd
de64cc0c23e1195df59ea9ac6ebfa8e24ee55f88
d8280b5602476565d97586854566c93fefe1d431
refs/heads/master
2016-09-06T04:47:14.802338
2011-06-02T22:33:27
2011-06-02T22:33:27
32,140,837
0
0
null
null
null
null
UTF-8
C++
false
false
8,158
cpp
/* * ################################################################################ * ### MIT License * ################################################################################ * * Copyright (c) 2006-2011 Andy Turner * * 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 "AlignParametric/ParticleSurface.h" #include "Mesh/TuplesImpl.h" #include "Mesh/MeshFunctions.h" #include "Mesh/TuplesFunctions.h" #include "MeshSearching/FacesNearestPointSearch.h" #include "Useful/Noise.h" #include "Useful/ColouredConsole.h" #include <vector> #include <algorithm> #include "vnl/vnl_matrix_fixed.h" #include "Useful/ArrayVectorFunctions.h" using namespace AWT; using namespace AWT::AlignParametric; AWT::AlignParametric::ParticleSurface::ParticleSurface(MeshType::P mesh, const TuplesType::P samples, const Idx _ntake) { // Keep a hold of the mesh this->mesh = mesh; calculateFaceNormals(); const Idx ntake = std::min<Idx>(_ntake, samples->getNumberOfPoints()); DEBUGMACRO("Only taking " << ntake); // Take just the first 10 samples this->samples = TuplesImpl<T>::getInstance(3, ntake); for (Idx i = 0; i < ntake; ++i) { T vtx[3]; samples->getPoint(i, vtx); this->samples->setPoint(i, vtx); } // Calculate the 5th-%ile triangle area, use this to avoid truncation error std::vector<T> areas; MESH_EACHFACE(mesh, f) areas.push_back(MeshFunctions<T>::getFaceArea(mesh, f)); sort(areas.begin(), areas.end()); maxMove = sqrt(areas[ areas.size() * 5 / 100 ]) / 2; PRINTVBL(maxMove); } void AWT::AlignParametric::ParticleSurface::initialize() { DEBUGLINE; setPointLocationsInitial(); } AWT::AlignParametric::ParticleSurface::~ParticleSurface() { } // Get the number of parameter components describing each sample Idx AWT::AlignParametric::ParticleSurface::getParameterDimensionality() const { return 3; } // Get the number of samples on the surface Idx AWT::AlignParametric::ParticleSurface::getNumberOfSamples() const { return samples->getNumberOfPoints(); } // Get the current sample locations // NOTE: This should be in HOMOGENEOUS form, i.e. samples.rows() = Dims + 1 // The last row should be all ones, or weird things will happen... void AWT::AlignParametric::ParticleSurface::getSamples(MatrixType& samples) const { if (samples.rows() != 4 || samples.cols() != getNumberOfSamples()) samples.set_size(4, getNumberOfSamples()); T vtx[4]; for (Idx i = 0, imax = getNumberOfSamples(); i < imax; ++i) { this->samples->getPoint(i, vtx); vtx[3] = 1; samples.set_column(i, vtx); } } T AWT::AlignParametric::ParticleSurface::getMaxMove() const { return maxMove; } // Get the number of parameters which control this sampling Idx AWT::AlignParametric::ParticleSurface::getNumberOfParameters() const { return samples->getNumberOfPoints(); } // Get the current set of control values void AWT::AlignParametric::ParticleSurface::getParameters(MatrixType& controls) const { if (controls.rows() != getNumberOfParameters() || controls.cols() != 3) controls.set_size(getNumberOfParameters(), 3); T vtx[3]; for (Idx i = 0, imax = getNumberOfParameters(); i < imax; ++i) { samples->getPoint(i,vtx); controls.set_row(i, vtx); } } void AWT::AlignParametric::ParticleSurface::jacobian(const Idx l, const Idx p, MatrixType& matrix) const { // Nice and easy Jacobian... if (l == p) { matrix.set_identity(); return; T nml[3]; faceNormals->getPoint(particleFace[l], nml); for (Idx r = 0; r < 3; ++r) for (Idx c = 0; c < 3; ++c) matrix(r,c) -= nml[r]*nml[c]; } else { matrix.fill(0); } } void AWT::AlignParametric::ParticleSurface::splitParticle(const Idx p, const T* theShift) { ColouredConsole cons(ColouredConsole::COL_YELLOW); FacesNearestPointSearch<T>::P searcher = FacesNearestPointSearch<T>::getInstance(); T vtx[4]; const T mults[] = { -0.5, 0.5 }; const Idx idxs[] = { p, samples->getNumberOfPoints() }; // Push back a face into the list (will be overwritten soon enough) particleFace.push_back(INVALID_INDEX); for (Idx i = 0; i < 2; ++i) { // Get the sample location samples->getPoint(p, vtx); FOREACHAXIS(ax) vtx[ax] += mults[i]*theShift[ax]; vtx[3] = 1; updatePointLocation(idxs[i], vtx, searcher); samples->getPoint(idxs[i], vtx); //PRINTVBL(idxs[i]); //PRINTVEC(vtx, 4); } modified(); } void AWT::AlignParametric::ParticleSurface::refine() { } // Iterator functions - allows you to skip all the zero jacobians // Takes the internal iterPtr back to the start void AWT::AlignParametric::ParticleSurface::resetIterator() { iterPtr = 0; } // Advances to the next non-zero jacobian pair bool AWT::AlignParametric::ParticleSurface::next(Idx& l, Idx& p) { bool ret = iterPtr < samples->getNumberOfPoints(); if (ret) l = p = iterPtr++; else l = p = INVALID_INDEX; return ret; } MeshType::P AWT::AlignParametric::ParticleSurface::getMesh() { return mesh; } TuplesType::P AWT::AlignParametric::ParticleSurface::getSamples() { return samples; } // Projects the point to the closest point on the mesh surface int AWT::AlignParametric::ParticleSurface::updatePointLocation(const Idx i, const T* vtx, FacesNearestPointSearch<T>::P searcher) { searcher->reset(); searcher->setTestPoint(vtx); mesh->searchFaces(searcher); T vtxNearest[3]; int np = searcher->getNearestPoint(vtxNearest); particleFace[i] = np; samples->setPoint(i, vtxNearest); return np; } void AWT::AlignParametric::ParticleSurface::calculateFaceNormals() { T vtx[3][3]; faceNormals = TuplesImpl<T>::getInstance(3, mesh->getNumberOfFaces()); MESH_EACHFACE(mesh, f) { mesh->getFace(f, vtx[0], vtx[1], vtx[2]); FOREACHAXIS(ax) { vtx[2][ax] -= vtx[0][ax]; vtx[1][ax] -= vtx[0][ax]; } cross<T>(vtx[1], vtx[2], vtx[0]); normalize<T>(vtx[0], 3); faceNormals->setPoint(f, vtx[0]); } } void AWT::AlignParametric::ParticleSurface::setPointLocationsInitial() { FacesNearestPointSearch<T>::P searcher = FacesNearestPointSearch<T>::getInstance(); T vtx[4]; // Make sure that the list of particleFaces is allocated particleFace.clear(); for (Idx i = 0, imax = samples->getNumberOfPoints(); i < imax; ++i) { // Get the sample location samples->getPoint(i, vtx); vtx[3] = 1; // Push back a face into the list (will be overwritten soon enough) particleFace.push_back(INVALID_INDEX); updatePointLocation(i, vtx, searcher); } } void AWT::AlignParametric::ParticleSurface::setParameters(MatrixType& controls) { FacesNearestPointSearch<T>::P searcher = FacesNearestPointSearch<T>::getInstance(); T vtx[3]; for (Idx i = 0, imax = samples->getNumberOfPoints(); i < imax; ++i) { vtx[0] = controls(i,0); vtx[1] = controls(i,1); vtx[2] = controls(i,2); updatePointLocation(i, vtx, searcher); } }
[ "[email protected]@8ccf9804-531a-5bdb-f4a8-09d094668cd7" ]
[email protected]@8ccf9804-531a-5bdb-f4a8-09d094668cd7
70e88be0e6d971d7e5b7e635de9ca1e355ae7bc5
cbd022378f8c657cef7f0d239707c0ac0b27118a
/src/npcclient/walkpoly.h
086682f6eb262d1af23613db499207e0fd45b057
[]
no_license
randomcoding/PlaneShift-PSAI
57d3c1a2accdef11d494c523f3e2e99142d213af
06c585452abf960e0fc964fe0b7502b9bd550d1f
refs/heads/master
2016-09-10T01:58:01.360365
2011-09-07T23:13:48
2011-09-07T23:13:48
2,336,981
0
0
null
null
null
null
UTF-8
C++
false
false
13,256
h
/* * walkpoly.h * * Copyright (C) 2005 Atomic Blue ([email protected], http://www.atomicblue.org) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation (version 2 * of the License). * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef ___WALKPOLY_HEADER___ #define ___WALKPOLY_HEADER___ #if USE_WALKPOLY //============================================================================= // Crystal Space Includes //============================================================================= #include <csgeom/vector3.h> #include <csgeom/box.h> #include <iutil/objreg.h> #include <csutil/array.h> #include <csutil/csstring.h> #include <csutil/list.h> //============================================================================= // Local Includes //============================================================================= #include "pathfind.h" class psNPCClient; void Dump3(const char * name, const csVector3 & p); void Dump(const char * name, const csBox3 & b); void Dump(const char * name, const csVector3 & p); float Calc2DDistance(const csVector3 & a, const csVector3 & b); float AngleDiff(float a1, float a2); /** Normal equation of a line in 2D space (the y coord is ignored) */ class ps2DLine { public: float a, b, c; void Dump(); void Calc(const csVector3 & p1, const csVector3 & p2); void CalcPerp(const csVector3 & begin, const csVector3 & end); float CalcDist(const csVector3 & point); float CalcRel(const csVector3 & point); void Copy(ps2DLine & dest); }; class psWalkPoly; class psMapWalker; struct iSector; class CelBase; struct iDocumentNode; struct iVFS; /************************************************************************** * psSpatialIndex is a tree-style data structure. * Its purpose is fast search of the psWalkPoly that is under your feet * or close to you. * It recursively splits the space into pairs of rectangular subspaces. * * Each subspace corresponds to one node of the tree. * Each node keeps list of psWalkPolys whose psWalkPoly::box * collides with the subspace of the node. ***************************************************************************/ class psSpatialIndexNode { friend class psSpatialIndex; public: psSpatialIndexNode(); /** Finds terminal node containing given point The point MUST be located in subtree of this node */ psSpatialIndexNode * FindNodeOfPoint(const csVector3 & p); /** Adds polygon to the right terminal nodes from the subtree */ void Add(psWalkPoly* poly); csBox3 & GetBBox() { return bbox; } csList<psWalkPoly*> * GetPolys() { return &polys; }; protected: /** Returns distance to root (root has 0) */ int GetTreeLevel(); /** Splits itself into two nodes */ void Split(); /** Chooses and sets appropriate splitAxis and splitValue */ void ChooseSplit(); psSpatialIndexNode * child1, * child2; psSpatialIndexNode * parent; csBox3 bbox; /** subspace of this node */ float splitValue; /** The border value of x or y or z which separates the subspaces of child1 and child2 ... used only if node has children */ char splitAxis; /** 0=x, 1=y, 2=z ... used only if node has children */ csList<psWalkPoly*> polys; /** Polygons whose "box" collides with this subspace */ int numPolys; /** Length of the list because csList lacks that */ }; class psSpatialIndex { public: psSpatialIndex(); /** Adds without balancing */ void Add(psWalkPoly* poly); /** Rebuilds the index from scratch so that it is more balanced */ void Rebuild(); /** Finds terminal node containing given point. 'hint' is an optional index node that could be the right node */ psSpatialIndexNode * FindNodeOfPoint(const csVector3 & p, psSpatialIndexNode * hint=NULL); //psSpatialIndexNode * FindNodeOfPoly(psWalkPoly * poly); /** Finds psWalkPoly whose "box" contains given point 'hint' is an optional index node that could be the right node */ psWalkPoly * FindPolyOfPoint(const csVector3 & p, psSpatialIndexNode * hint=NULL); psANode * FindNearbyANode(const csVector3 & pos); protected: psSpatialIndexNode root; }; class psSeed { public: psSeed(); psSeed(csVector3 pos, iSector * sector, float quality); psSeed(csVector3 edgePos, csVector3 pos, iSector * sector, float quality); void SaveToString(csString & str); void LoadFromXML(iDocumentNode * node, csRef<iEngine> engine); bool CheckValidity(psMapWalker * walker); bool edgeSeed; float quality; csVector3 pos, edgePos; iSector * sector; }; class psSeedSet { public: psSeedSet(iObjectRegistry * objReg); psSeed PickUpBestSeed(); void AddSeed(const psSeed & seed); bool IsEmpty() { return seeds.IsEmpty(); } bool LoadFromString(const csString & str); bool LoadFromFile(const csString & path); void SaveToString(csString & str); bool SaveToFile(const csString & path); protected: iObjectRegistry * objReg; csList<psSeed> seeds; }; /***************************************************************** * The areas of map that are without major obstacles are denoted * by set of polygons that cover these areas. This is used * to precisely calculate very short paths. Other paths * are calculated using A*, and later fine-tuned with this map. ******************************************************************/ /** This describes a contact of edge of one polygon with edge of another polygon */ class psWalkPolyCont { public: csVector3 begin, end; ///< what part of the edge psWalkPoly * poly; ///< the polygon that touches us }; /** Vertex of psWalkPoly, also containing info about edge to the next vertex. Contains list of contacts with neighbour psWalkPolys */ class psWalkPolyVert { public: csVector3 pos; ps2DLine line; ///< normal equation of edge from this vertex to the following one csArray<psWalkPolyCont> conts; csString info; ///< debug only bool touching, stuck; bool followingEdge; float angle; psWalkPolyVert(); psWalkPolyVert(const csVector3 & pos); /** Finds neighbour polygon that contacts with this edge at given point. Return NULL = there is no contact at this point */ psWalkPoly * FindCont(const csVector3 & point); void CalcLineTo(const csVector3 & point); }; /** This just keeps all polygons that we know and their index */ class psWalkPolyMap { friend class psWalkPoly; public: psWalkPolyMap(iObjectRegistry * objReg); psWalkPolyMap(); void SetObjReg(iObjectRegistry * objReg) { this->objReg=objReg; } /** Adds new polygon to map */ void AddPoly(psWalkPoly * ); /** Checks if you can go directly between two points without problems */ bool CheckDirectPath(csVector3 start, csVector3 goal); void Generate(psNPCClient * npcclient, psSeedSet & seeds, iSector * sector); void CalcConts(); csString DumpPolys(); void BuildBasicAMap(psAMap & AMap); void LoadFromXML(iDocumentNode * node); bool LoadFromString(const csString & str); bool LoadFromFile(const csString & path); void SaveToString(csString & str); bool SaveToFile(const csString & path); psANode * FindNearbyANode(const csVector3 & pos); psWalkPoly * FindPoly(int id); void PrunePolys(); void DeleteContsWith(psWalkPoly * poly); protected: csList<psWalkPoly*> polys; psSpatialIndex index; csHash<psWalkPoly*> polyByID; iObjectRegistry * objReg; csRef<iVFS> vfs; }; /******************************************************************** * A convex polygon that denotes area without major obstacles . * It is not necessarily a real polygon, because its vertices * do not have to be on the same 3D plane (just "roughly"). * The walkable area within the polygon borders is rarely flat, too. ********************************************************************/ class psWalkPoly { friend class psWalkPolyMap; public: psWalkPoly(); ~psWalkPoly(); /** Adds a new vertex to polygon - vertices must be added CLOCKWISE ! */ void AddVert(const csVector3 & pos, int beforeIndex=-1); size_t GetNumVerts() { return verts.GetSize(); } void AddNode(psANode * node); void DeleteNode(psANode * node); void SetSector(iSector * sector); /** Moves 'point' (which must be within our polygon) towards 'goal' until it reaches another polygon or dead end. Returns true, if it reached another polygon, false on dead end */ bool MoveToNextPoly(const csVector3 & goal, csVector3 & point, psWalkPoly * & nextPoly); void AddSeeds(psMapWalker * walker, psSeedSet & seeds); /** Checks if polygon is still convex after we moved vertex 'vertNum' */ bool CheckConvexity(int vertNum); void Clear(); //ignores y void Cut(const csVector3 & cut1, const csVector3 & cut2); //ignores y void Intersect(const psWalkPoly & other); float EstimateY(const csVector3 & point); void Dump(const char * name); void DumpJS(const char * name); void DumpPureJS(); void DumpPolyJS(const char * name); int Stretch(psMapWalker & walker, psWalkPolyMap & map, float stepSize); void GlueToNeighbours(psMapWalker & walker, psWalkPolyMap & map); float GetBoxSize(); float GetArea(); float GetTriangleArea(int vertNum); float GetLengthOfEdges(); void GetShape(float & min, float & max); float GetNarrowness(); void PruneUnboundVerts(psMapWalker & walker); void PruneInLineVerts(); bool IsNearWalls(psMapWalker & walker, int vertNum); /** returns true if it moved at least a bit */ bool StretchVert(psMapWalker & walker, psWalkPolyMap & map, int vertNum, const csVector3 & newPos, float stepSize); void SetMini(psMapWalker & walker, const csVector3 & pos, int numVerts); /** Calculates box of polygon */ void CalcBox(); csBox3 & GetBox() { return box; } bool IsInLine(); void ClearInfo(); bool CollidesWithPolys(psWalkPolyMap & map, csList<psWalkPoly*> * polys); void SaveToString(csString & str); void LoadFromXML(iDocumentNode * node, csRef<iEngine> engine); /** Populates the 'conts' array */ void CalcConts(psWalkPolyMap & map); void RecalcAllEdges(); void ConnectNodeToPoly(psANode * node, bool bidirectional); bool TouchesPoly(psWalkPoly * poly); bool NeighboursTouchEachOther(); psANode * GetFirstNode(); int GetID() { return id; } iSector * GetSector() { return sector; } bool PointIsIn(const csVector3 & p, float maxRel=0); csVector3 GetClosestPoint(const csVector3 & point, float & angle); int GetNumConts(); size_t GetNumNodes() { return nodes.GetSize(); } bool ReachableFromNeighbours(); psWalkPoly* GetNearNeighbour(const csVector3 & pos, float maxDist); void DeleteContsWith(psWalkPoly * poly); bool NeighbourSupsMe(psWalkPoly* neighbour); void MovePointInside(csVector3 & point, const csVector3 & goal); protected: void RecalcEdges(int vertNum); int FindClosestEdge(const csVector3 pos); /** Finds contact of this polygon with another polygon that is at given point and edge */ psWalkPoly * FindCont(const csVector3 & point, int edgeNum); /** Moves 'point' to the closest point in the direction of 'goal' that is within our polygon (some point on polygon border). 'edgeNum' is number of the edge where the new point is */ bool MoveToBorder(const csVector3 & goal, csVector3 & point, int & edgeNum); /** Populates the 'edges' array according to 'verts' */ void CalcEdges(); int GetNeighbourIndex(int vertNum, int offset) const; bool HandleProblems(psMapWalker & walker, psWalkPolyMap & map, int vertNum, const csVector3 & oldPos); csVector3 GetClosestCollisionPoint(csList<psWalkPoly*> & collisions, ps2DLine & line); bool HandlePolyCollisions(psWalkPolyMap & map, int vertNum, const csVector3 & oldPos); int id; static int nextID; bool supl; csArray<psWalkPolyVert> verts; /** vertices of polygon */ iSector * sector; csBox3 box; /** box around polygon - taller than the real poly */ csArray<psANode*> nodes; }; #endif #endif
[ "whacko88@2752fbe2-5038-0410-9d0a-88578062bcef" ]
whacko88@2752fbe2-5038-0410-9d0a-88578062bcef