hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
329eae5447f0cd48d1e279aab3660dbbae09d470
1,092
cpp
C++
src/CubeSystem/CubeManagerInputs.cpp
frc2081/2018-RobotCode
6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019
[ "MIT" ]
null
null
null
src/CubeSystem/CubeManagerInputs.cpp
frc2081/2018-RobotCode
6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019
[ "MIT" ]
5
2018-01-18T03:25:07.000Z
2018-03-16T13:27:53.000Z
src/CubeSystem/CubeManagerInputs.cpp
frc2081/2018-RobotCode
6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019
[ "MIT" ]
null
null
null
/* * CubeManagerInputs.cpp * * Created on: Feb 2, 2018 * Author: wentzdr */ #include <CubeSystem/CubeManagerInputs.h> CubeManagerInputs::CubeManagerInputs() { intakeCubeSensor = CubeSensor::NO_CUBE_PRESENT; shooterCubeSensor = CubeSensor::NO_CUBE_PRESENT; shooterangleactualvalue = 0; armHomeSensor = false; } CubeManagerInputs::~CubeManagerInputs() { } CubeManagerInputs::CubeSensor CubeManagerInputs::getIntakeCubeSensor() { return intakeCubeSensor; } CubeManagerInputs::CubeSensor CubeManagerInputs::getShooterCubeSensor() { return shooterCubeSensor; } double CubeManagerInputs::getShooterAngleActualValue() { return shooterangleactualvalue; } void CubeManagerInputs::updateInputs(IO *Inputs){ if(Inputs->intakecubesensor->Get()) intakeCubeSensor = CubeSensor::NO_CUBE_PRESENT; else intakeCubeSensor = CubeSensor::CUBE_PRESENT; if(Inputs->cubechambersensor->Get()) shooterCubeSensor = CubeSensor::NO_CUBE_PRESENT; else shooterCubeSensor = CubeSensor::CUBE_PRESENT; armHomeSensor = Inputs->armhomeswitch->Get(); }
25.395349
87
0.757326
frc2081
329eb6c93a40cfd2e31b7eb5d6b0ae3c8a198775
5,881
cpp
C++
OpenSees/SRC/domain/groundMotion/InterpolatedGroundMotion.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
8
2019-03-05T16:25:10.000Z
2020-04-17T14:12:03.000Z
SRC/domain/groundMotion/InterpolatedGroundMotion.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
null
null
null
SRC/domain/groundMotion/InterpolatedGroundMotion.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
3
2019-09-21T03:11:11.000Z
2020-01-19T07:29:37.000Z
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // $Revision: 1.2 $ // $Date: 2003-02-14 23:00:57 $ // $Source: /usr/local/cvs/OpenSees/SRC/domain/groundMotion/InterpolatedGroundMotion.cpp,v $ // File: ~/earthquake/InterpolatedGroundMotion.C // // Written: fmk // Created: 11/00 // Revision: A // // Description: This file contains the class definition for // InterpolatedGroundMotion. // // What: "@(#) InterpolatedGroundMotion.C, revA" #include <InterpolatedGroundMotion.h> #include <stdlib.h> #include <math.h> #include <classTags.h> #include <Vector.h> #include <Channel.h> InterpolatedGroundMotion::InterpolatedGroundMotion() :GroundMotion(GROUND_MOTION_TAG_InterpolatedGroundMotion), theMotions(0), factors(0), destroyMotions(0), data(3), deltaPeak(0.0) { } InterpolatedGroundMotion::InterpolatedGroundMotion(GroundMotion **groundMotions, const Vector &fact, bool destroyMotions, double dT) :GroundMotion(GROUND_MOTION_TAG_InterpolatedGroundMotion), theMotions(0), factors(0), destroyMotions(0), data(3), deltaPeak(dT) { factors = new Vector(fact); theMotions = new GroundMotion *[fact.Size()]; for (int i=0; i<fact.Size(); i++) theMotions[i] = groundMotions[i]; if (destroyMotions == true) destroyMotions = 1; } InterpolatedGroundMotion::~InterpolatedGroundMotion() { if (destroyMotions == 1) { for (int i=0; i<factors->Size(); i++) delete theMotions[i]; } delete [] theMotions; delete factors; } double InterpolatedGroundMotion::getDuration(void) { double value = 0.0; int numMotions = factors->Size(); for (int i=0; i<numMotions; i++) { double motionValue = theMotions[i]->getDuration(); if (motionValue > value) value = motionValue; } return value; } double InterpolatedGroundMotion::getPeakAccel(void) { double value = 0.0; double duration = this->getDuration(); double time = 0.0; while (time < duration) { double accel = this->getAccel(time); if (accel > value) value = accel; time += deltaPeak; } return value; } double InterpolatedGroundMotion::getPeakVel(void) { double value = 0.0; double duration = this->getDuration(); double time = 0.0; while (time < duration) { double accel = this->getVel(time); if (accel > value) value = accel; time += deltaPeak; } return value; } double InterpolatedGroundMotion::getPeakDisp(void) { double value = 0.0; double duration = this->getDuration(); double time = 0.0; while (time < duration) { double accel = this->getDisp(time); if (accel > value) value = accel; time += deltaPeak; } return value; } double InterpolatedGroundMotion::getAccel(double time) { if (time < 0.0) return 0.0; double value = 0.0; int numMotions = factors->Size(); for (int i=0; i<numMotions; i++) { value += (*factors)(i) * theMotions[i]->getAccel(time); } return value; } double InterpolatedGroundMotion::getVel(double time) { if (time < 0.0) return 0.0; double value = 0.0; int numMotions = factors->Size(); for (int i=0; i<numMotions; i++) { value += (*factors)(i) * theMotions[i]->getVel(time); } return value; } double InterpolatedGroundMotion::getDisp(double time) { if (time < 0.0) return 0.0; double value = 0.0; int numMotions = factors->Size(); for (int i=0; i<numMotions; i++) { value += (*factors)(i) * theMotions[i]->getDisp(time); } return value; } const Vector & InterpolatedGroundMotion::getDispVelAccel(double time) { if (time < 0.0) { data(0) = 0.0; data(1) = 0.0; data(2) = 0.0; return data; } data.Zero(); static Vector motionData(3); int numMotions = factors->Size(); for (int i=0; i<numMotions; i++) { motionData = theMotions[i]->getDispVelAccel(time); motionData *= (*factors)(i); data += motionData; } return data; } int InterpolatedGroundMotion::sendSelf(int commitTag, Channel &theChannel) { opserr << "InterpolatedGroundMotion::sendSelf() -- not yet implemented" << endln; return -1; } int InterpolatedGroundMotion::recvSelf(int commitTag, Channel &theChannel, FEM_ObjectBroker &theBroker) { opserr << "InterpolatedGroundMotion::recvSelf() -- not yet impelemented" << endln; return -1; }
25.458874
92
0.558578
kuanshi
32a0c7754769a1c3f4cc12714467089ebc1be583
4,237
cpp
C++
Alien Engine/Alien Engine/ModuleAudio.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
7
2020-02-20T15:11:11.000Z
2020-05-19T00:29:04.000Z
Alien Engine/Alien Engine/ModuleAudio.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
125
2020-02-29T17:17:31.000Z
2020-05-06T19:50:01.000Z
Alien Engine/Alien Engine/ModuleAudio.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
1
2020-05-19T00:29:06.000Z
2020-05-19T00:29:06.000Z
#include "Application.h" #include "ModuleAudio.h" #include "ComponentAudioEmitter.h" #include "Event.h" #include "mmgr/mmgr.h" #include "Optick/include/optick.h" ModuleAudio::ModuleAudio(bool start_enabled) : Module(start_enabled) { name = "audio"; } ModuleAudio::~ModuleAudio() {} bool ModuleAudio::Start() { // Init wwise and audio banks bool ret = WwiseT::InitSoundEngine(); default_listener = CreateSoundEmitter("Listener"); SetListener(default_listener); for (auto i = banks.begin(); i != banks.end(); i++) { if (!(*i)->loaded) { WwiseT::LoadBank((std::to_string((*i)->id) + ".bnk").c_str()); (*i)->loaded = true; } } return ret; } void ModuleAudio::LoadBanksInfo() { auto j = App->LoadJSONFile("Assets/AudioBanks/SoundbanksInfo.json"); auto bank_arr = j->GetArray("SoundBanksInfo.SoundBanks"); bank_arr->GetFirstNode(); for (uint i = 0; i < bank_arr->GetArraySize(); ++i, bank_arr->GetAnotherNode()) { if (strcmp(bank_arr->GetString("ShortName"), "Init") != 0) { Bank* b = new Bank(); b->id = std::stoull(bank_arr->GetString("Id")); b->name = bank_arr->GetString("ShortName"); auto events = bank_arr->GetArray("IncludedEvents"); events->GetFirstNode(); for (uint e = 0; e < events->GetArraySize(); ++e, events->GetAnotherNode()) { b->events[std::stoull(events->GetString("Id"))] = events->GetString("Name"); } auto aud = bank_arr->GetArray("IncludedMemoryFiles"); for (uint a = 0; a < aud->GetArraySize(); ++a) { b->audios[std::stoull(aud->GetString("Id"))] = aud->GetString("ShortName"); } banks.push_back(b); } } } update_status ModuleAudio::Update(float dt) { OPTICK_EVENT(); return UPDATE_CONTINUE; } update_status ModuleAudio::PostUpdate(float dt) { OPTICK_EVENT(); if (listener != nullptr) WwiseT::ProcessAudio(); return UPDATE_CONTINUE; } bool ModuleAudio::CleanUp() { OPTICK_EVENT(); for (auto i = emitters.begin(); i != emitters.end(); i++) { if((*i)) delete* i; } emitters.clear(); WwiseT::StopAllEvents(); UnloadAllBanksFromWwise(); for (auto b = banks.begin(); b != banks.end(); b++) { if ((*b)) delete* b; } banks.clear(); delete default_listener; default_listener = nullptr; return WwiseT::CloseSoundEngine(); } bool ModuleAudio::UnloadAllBanksFromWwise() { OPTICK_EVENT(); for (auto it = banks.begin(); it != banks.end(); it++) { if ((*it)) { if ((*it)->loaded) { WwiseT::UnLoadBank(std::to_string((*it)->id).c_str()); (*it)->loaded = false; } } } return true; } void ModuleAudio::AddBank(Bank* bk) { banks.push_back(bk); } WwiseT::AudioSource * ModuleAudio::CreateSoundEmitter(const char * name) { return WwiseT::CreateAudSource(name); } const std::vector<Bank*> ModuleAudio::GetBanks() const { return banks; } const Bank* ModuleAudio::GetBankByName(const char* name) const { Bank* bk = nullptr; for (int i = 0; i < banks.size(); ++i) { if (App->StringCmp(name, App->audio->GetBanks()[i]->name.c_str())) bk = App->audio->GetBanks()[i]; } return bk; } Bank* ModuleAudio::GetBankByID(const u64& id) const { for (auto i = banks.begin(); i != banks.end(); ++i) { if ((*i)->id == id) return *i; } return nullptr; } const char* ModuleAudio::GetEventNameByID(const u64& id) const { for (auto i = banks.begin(); i != banks.end(); ++i) { for (auto j = (*i)->events.begin(); j != (*i)->events.end(); ++j) { if ((*j).first == id) return (*j).second.c_str(); } } return ""; } void ModuleAudio::HandleEvent(EventType eventType) { switch (eventType) { case EventType::ON_PAUSE: //Pause(); break; case EventType::ON_STOP: Stop(); break; } } void ModuleAudio::Play() { OPTICK_EVENT(); for (auto iterator = emitters.begin(); iterator != App->audio->emitters.end(); ++iterator) { (*iterator)->StartSound(); } is_playing = true; } void ModuleAudio::Stop() { WwiseT::StopAllEvents(); } void ModuleAudio::Pause() const { WwiseT::PauseAll(); } void ModuleAudio::Resume() const { WwiseT::ResumeAll(); } void ModuleAudio::SetListener(WwiseT::AudioSource* new_listener) { if (new_listener == nullptr) listener = default_listener; else listener = new_listener; WwiseT::SetDefaultListener(new_listener->GetID()); }
19.892019
91
0.648808
OverPowered-Team
32a1f95935e11bdf24d984a323691566858ebe80
3,199
cpp
C++
tooling/showinshell_win.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
54
2015-09-13T07:29:52.000Z
2022-03-16T07:43:50.000Z
tooling/showinshell_win.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
null
null
null
tooling/showinshell_win.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
31
2016-08-26T13:35:01.000Z
2022-03-13T16:43:12.000Z
// https://github.com/KubaO/stackoverflown/tree/master/tooling #include "tooling.h" #ifdef Q_OS_WIN32 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <QAxObject> #include <QCoreApplication> #include <QDebug> #include <QDir> #include <QFileInfo> #include <QTextBrowser> #include <QUuid> #include <ShObjIdl.h> #include <ShlDisp.h> #include <Windows.h> namespace tooling { static void showDoc(QAxObject *obj) { if (!obj) return; auto *br = new QTextBrowser; br->setText(obj->generateDocumentation()); br->show(); } static QStringList getVerbNames(QAxBase *obj) { QStringList names; auto *verbs = obj->querySubObject("Verbs()"); verbs->disableMetaObject(); auto count = verbs->dynamicCall("Count()").toInt(); for (int i = 0; i < count; ++i) { auto verb = verbs->querySubObject("Item(QVariant)", i); verb->disableMetaObject(); names.push_back(verb->dynamicCall("Name()").toString()); } return names; } namespace detail { bool showInWindowsShell(const QString &filePath, bool deselect) { QFileInfo appFI(filePath); auto matchPath = appFI.dir().path().toLower(); auto matchName = appFI.fileName().toLower(); QAxObject shellApp("Shell.Application"); QAxObject *windows = shellApp.querySubObject("Windows()"); windows->disableMetaObject(); auto count = windows->dynamicCall("Count()").toInt(); qDebug() << count; for (int i = 0; i < count; ++i) { QAxObject *win = windows->querySubObject("Item(QVariant)", {i}); win->disableMetaObject(); auto program = win->dynamicCall("FullName()").toString(); QFileInfo programFI(program); if (programFI.baseName().toLower() != "explorer") continue; auto url = win->dynamicCall("LocationURL()").toUrl(); if (!url.isLocalFile()) continue; auto path = url.path().mid(1).toLower(); if (path != matchPath) continue; QAxObject *doc = win->querySubObject("Document()"); QAxObject *folder = doc->querySubObject("Folder()"); folder->disableMetaObject(); QAxObject *folderItems = folder->querySubObject("Items()"); folderItems->disableMetaObject(); QAxObject *ourEntry = {}; int count = folderItems->dynamicCall("Count()").toInt(); for (int j = 0; j < count; j++) { QAxObject *entry = folderItems->querySubObject("Item(QVariant)", j); entry->disableMetaObject(); auto name = entry->dynamicCall("Name()").toString().toLower(); if (name == matchName) ourEntry = entry; } if (ourEntry) { if (false) ourEntry->dynamicCall("InvokeVerb(QVariant)", QVariant()); // open etc. auto rc = doc->dynamicCall("SelectItem(QVariant, int)", ourEntry->asVariant(), SVSI_SELECT | (deselect ? SVSI_DESELECTOTHERS : 0)); auto hwnd = win->dynamicCall("HWND()").toLongLong(); BringWindowToTop(HWND(hwnd)); return true; } } return false; } } // namespace detail } // namespace tooling #else namespace tooling { namespace detail { bool showInWindowsShell(const QString &, bool) { return false; } } // namespace detail } // namespace tooling #endif
31.058252
88
0.641763
SammyEnigma
32a4a11ad05be2aba57383316057873d2484b831
1,974
cpp
C++
src/filter/filterset.cpp
ikitayama/cobi
e9bc4a5675ead1874ad9ffa953de8edb3a763479
[ "BSD-3-Clause" ]
null
null
null
src/filter/filterset.cpp
ikitayama/cobi
e9bc4a5675ead1874ad9ffa953de8edb3a763479
[ "BSD-3-Clause" ]
null
null
null
src/filter/filterset.cpp
ikitayama/cobi
e9bc4a5675ead1874ad9ffa953de8edb3a763479
[ "BSD-3-Clause" ]
1
2018-12-14T02:45:41.000Z
2018-12-14T02:45:41.000Z
/***************************************************************************** ** Cobi http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 2009-2010 ** ** Forschungszentrum Juelich, Juelich Supercomputing Centre ** ** ** ** See the file COPYRIGHT in the base directory for details ** *****************************************************************************/ /** * @file filterset.cpp * @author Jan Mussler * @brief Implementation of filterset class * * a filterset is a set of filters, represtens the filters tag containing * all filters defined in one filter specification */ #include "filters.h" using namespace gi::filter; FilterSet::FilterSet() { } FilterSet::~FilterSet() { for (mapStringIFilter::iterator i = filters.begin(); i != filters.end(); i++) { delete (*i).second; } filters.clear(); } void FilterSet::addFilter(std::string aName, IFilter* aFilter) { filters[aName] = aFilter; } set<string> FilterSet::getFilterNames() { set<string> names; for (mapStringIFilter::iterator i = filters.begin(); i != filters.end(); i++) { names.insert(i->first); } return names; } IFilter* FilterSet::getFilterByName(std::string aName) { if (filters.find(aName) != filters.end()) { return filters[aName]; } throw ex::ReferencingUndefinedFilter(); } vector<IFilter*> FilterSet::getInstrumentingFilters() { vector<IFilter*> result; for (mapStringIFilter::iterator i = filters.begin(); i != filters.end(); i++) { if ((*i).second->isInstrumenting()) { result.push_back((*i).second); } } return result; }
28.608696
79
0.479737
ikitayama
32aa6b720a4b042b5e509e70837b9ec33b9d9ed4
13,994
cc
C++
ppapi/proxy/ppb_audio_input_proxy.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
ppapi/proxy/ppb_audio_input_proxy.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
ppapi/proxy/ppb_audio_input_proxy.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// 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 "ppapi/proxy/ppb_audio_input_proxy.h" #include "base/compiler_specific.h" #include "ppapi/c/dev/ppb_audio_input_dev.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppb_audio_config.h" #include "ppapi/proxy/enter_proxy.h" #include "ppapi/proxy/plugin_dispatcher.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/shared_impl/api_id.h" #include "ppapi/shared_impl/platform_file.h" #include "ppapi/shared_impl/ppapi_globals.h" #include "ppapi/shared_impl/ppb_audio_input_shared.h" #include "ppapi/shared_impl/ppb_device_ref_shared.h" #include "ppapi/shared_impl/tracked_callback.h" #include "ppapi/thunk/enter.h" #include "ppapi/thunk/resource_creation_api.h" #include "ppapi/thunk/thunk.h" using ppapi::IntToPlatformFile; using ppapi::thunk::PPB_AudioInput_API; namespace ppapi { namespace proxy { class AudioInput : public PPB_AudioInput_Shared { public: explicit AudioInput(const HostResource& audio_input); virtual ~AudioInput(); // Implementation of PPB_AudioInput_API trusted methods. virtual int32_t OpenTrusted( const std::string& device_id, PP_Resource config, const PP_CompletionCallback& create_callback) OVERRIDE; virtual int32_t GetSyncSocket(int* sync_socket) OVERRIDE; virtual int32_t GetSharedMemory(int* shm_handle, uint32_t* shm_size) OVERRIDE; virtual const std::vector<DeviceRefData>& GetDeviceRefData() const OVERRIDE; private: // PPB_AudioInput_Shared implementation. virtual int32_t InternalEnumerateDevices( PP_Resource* devices, PP_CompletionCallback callback) OVERRIDE; virtual int32_t InternalOpen(const std::string& device_id, PP_AudioSampleRate sample_rate, uint32_t sample_frame_count, PP_CompletionCallback callback) OVERRIDE; virtual PP_Bool InternalStartCapture() OVERRIDE; virtual PP_Bool InternalStopCapture() OVERRIDE; virtual void InternalClose() OVERRIDE; PluginDispatcher* GetDispatcher() const { return PluginDispatcher::GetForResource(this); } DISALLOW_COPY_AND_ASSIGN(AudioInput); }; AudioInput::AudioInput(const HostResource& audio_input) : PPB_AudioInput_Shared(audio_input) { } AudioInput::~AudioInput() { Close(); } int32_t AudioInput::OpenTrusted(const std::string& device_id, PP_Resource config, const PP_CompletionCallback& create_callback) { return PP_ERROR_NOTSUPPORTED; // Don't proxy the trusted interface. } int32_t AudioInput::GetSyncSocket(int* sync_socket) { return PP_ERROR_NOTSUPPORTED; // Don't proxy the trusted interface. } int32_t AudioInput::GetSharedMemory(int* shm_handle, uint32_t* shm_size) { return PP_ERROR_NOTSUPPORTED; // Don't proxy the trusted interface. } const std::vector<DeviceRefData>& AudioInput::GetDeviceRefData() const { // Don't proxy the trusted interface. static std::vector<DeviceRefData> result; return result; } int32_t AudioInput::InternalEnumerateDevices(PP_Resource* devices, PP_CompletionCallback callback) { devices_ = devices; enumerate_devices_callback_ = new TrackedCallback(this, callback); GetDispatcher()->Send(new PpapiHostMsg_PPBAudioInput_EnumerateDevices( API_ID_PPB_AUDIO_INPUT_DEV, host_resource())); return PP_OK_COMPLETIONPENDING; } int32_t AudioInput::InternalOpen(const std::string& device_id, PP_AudioSampleRate sample_rate, uint32_t sample_frame_count, PP_CompletionCallback callback) { open_callback_ = new TrackedCallback(this, callback); GetDispatcher()->Send(new PpapiHostMsg_PPBAudioInput_Open( API_ID_PPB_AUDIO_INPUT_DEV, host_resource(), device_id, sample_rate, sample_frame_count)); return PP_OK_COMPLETIONPENDING; } PP_Bool AudioInput::InternalStartCapture() { SetStartCaptureState(); GetDispatcher()->Send(new PpapiHostMsg_PPBAudioInput_StartOrStop( API_ID_PPB_AUDIO_INPUT_DEV, host_resource(), true)); return PP_TRUE; } PP_Bool AudioInput::InternalStopCapture() { GetDispatcher()->Send(new PpapiHostMsg_PPBAudioInput_StartOrStop( API_ID_PPB_AUDIO_INPUT_DEV, host_resource(), false)); SetStopCaptureState(); return PP_TRUE; } void AudioInput::InternalClose() { GetDispatcher()->Send(new PpapiHostMsg_PPBAudioInput_Close( API_ID_PPB_AUDIO_INPUT_DEV, host_resource())); } PPB_AudioInput_Proxy::PPB_AudioInput_Proxy(Dispatcher* dispatcher) : InterfaceProxy(dispatcher), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { } PPB_AudioInput_Proxy::~PPB_AudioInput_Proxy() { } // static PP_Resource PPB_AudioInput_Proxy::CreateProxyResource0_1( PP_Instance instance, PP_Resource config, PPB_AudioInput_Callback audio_input_callback, void* user_data) { PluginDispatcher* dispatcher = PluginDispatcher::GetForInstance(instance); if (!dispatcher) return 0; HostResource result; dispatcher->Send(new PpapiHostMsg_PPBAudioInput_Create( API_ID_PPB_AUDIO_INPUT_DEV, instance, &result)); if (result.is_null()) return 0; AudioInput* audio_input = new AudioInput(result); int32_t open_result = audio_input->Open("", config, audio_input_callback, user_data, AudioInput::MakeIgnoredCompletionCallback()); if (open_result != PP_OK && open_result != PP_OK_COMPLETIONPENDING) { delete audio_input; return 0; } return audio_input->GetReference(); } // static PP_Resource PPB_AudioInput_Proxy::CreateProxyResource( PP_Instance instance) { PluginDispatcher* dispatcher = PluginDispatcher::GetForInstance(instance); if (!dispatcher) return 0; HostResource result; dispatcher->Send(new PpapiHostMsg_PPBAudioInput_Create( API_ID_PPB_AUDIO_INPUT_DEV, instance, &result)); if (result.is_null()) return 0; return (new AudioInput(result))->GetReference(); } bool PPB_AudioInput_Proxy::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PPB_AudioInput_Proxy, msg) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBAudioInput_Create, OnMsgCreate) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBAudioInput_EnumerateDevices, OnMsgEnumerateDevices) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBAudioInput_Open, OnMsgOpen) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBAudioInput_StartOrStop, OnMsgStartOrStop) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBAudioInput_Close, OnMsgClose) IPC_MESSAGE_HANDLER(PpapiMsg_PPBAudioInput_EnumerateDevicesACK, OnMsgEnumerateDevicesACK) IPC_MESSAGE_HANDLER(PpapiMsg_PPBAudioInput_OpenACK, OnMsgOpenACK) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() // TODO(brettw) handle bad messages! return handled; } void PPB_AudioInput_Proxy::OnMsgCreate(PP_Instance instance, HostResource* result) { thunk::EnterResourceCreation resource_creation(instance); if (resource_creation.succeeded()) { result->SetHostResource( instance, resource_creation.functions()->CreateAudioInput(instance)); } } void PPB_AudioInput_Proxy::OnMsgEnumerateDevices( const ppapi::HostResource& audio_input) { EnterHostFromHostResourceForceCallback<PPB_AudioInput_API> enter( audio_input, callback_factory_, &PPB_AudioInput_Proxy::EnumerateDevicesACKInHost, audio_input); if (enter.succeeded()) enter.SetResult(enter.object()->EnumerateDevices(NULL, enter.callback())); } void PPB_AudioInput_Proxy::OnMsgOpen(const ppapi::HostResource& audio_input, const std::string& device_id, int32_t sample_rate, uint32_t sample_frame_count) { // The ...ForceCallback class will help ensure the callback is always called. // All error cases must call SetResult on this class. EnterHostFromHostResourceForceCallback<PPB_AudioInput_API> enter( audio_input, callback_factory_, &PPB_AudioInput_Proxy::OpenACKInHost, audio_input); if (enter.failed()) return; // When enter fails, it will internally schedule the callback. thunk::EnterResourceCreation resource_creation(audio_input.instance()); // Make an audio config object. PP_Resource audio_config_res = resource_creation.functions()->CreateAudioConfig( audio_input.instance(), static_cast<PP_AudioSampleRate>(sample_rate), sample_frame_count); if (!audio_config_res) { enter.SetResult(PP_ERROR_FAILED); return; } // Initiate opening the audio object. enter.SetResult(enter.object()->OpenTrusted( device_id, audio_config_res, enter.callback())); // Clean up the temporary audio config resource we made. const PPB_Core* core = static_cast<const PPB_Core*>( dispatcher()->local_get_interface()(PPB_CORE_INTERFACE)); core->ReleaseResource(audio_config_res); } void PPB_AudioInput_Proxy::OnMsgStartOrStop(const HostResource& audio_input, bool capture) { EnterHostFromHostResource<PPB_AudioInput_API> enter(audio_input); if (enter.failed()) return; if (capture) enter.object()->StartCapture(); else enter.object()->StopCapture(); } void PPB_AudioInput_Proxy::OnMsgClose(const ppapi::HostResource& audio_input) { EnterHostFromHostResource<PPB_AudioInput_API> enter(audio_input); if (enter.succeeded()) enter.object()->Close(); } // Processed in the plugin (message from host). void PPB_AudioInput_Proxy::OnMsgEnumerateDevicesACK( const ppapi::HostResource& audio_input, int32_t result, const std::vector<ppapi::DeviceRefData>& devices) { EnterPluginFromHostResource<PPB_AudioInput_API> enter(audio_input); if (enter.succeeded()) { static_cast<AudioInput*>(enter.object())->OnEnumerateDevicesComplete( result, devices); } } void PPB_AudioInput_Proxy::OnMsgOpenACK( const HostResource& audio_input, int32_t result, IPC::PlatformFileForTransit socket_handle, base::SharedMemoryHandle handle, uint32_t length) { EnterPluginFromHostResource<PPB_AudioInput_API> enter(audio_input); if (enter.failed()) { // The caller may still have given us these handles in the failure case. // The easiest way to clean these up is to just put them in the objects // and then close them. This failure case is not performance critical. base::SyncSocket temp_socket( IPC::PlatformFileForTransitToPlatformFile(socket_handle)); base::SharedMemory temp_mem(handle, false); } else { static_cast<AudioInput*>(enter.object())->OnOpenComplete( result, handle, length, IPC::PlatformFileForTransitToPlatformFile(socket_handle)); } } void PPB_AudioInput_Proxy::EnumerateDevicesACKInHost( int32_t result, const HostResource& audio_input) { EnterHostFromHostResource<PPB_AudioInput_API> enter(audio_input); dispatcher()->Send(new PpapiMsg_PPBAudioInput_EnumerateDevicesACK( API_ID_PPB_AUDIO_INPUT_DEV, audio_input, result, enter.succeeded() && result == PP_OK ? enter.object()->GetDeviceRefData() : std::vector<DeviceRefData>())); } void PPB_AudioInput_Proxy::OpenACKInHost(int32_t result, const HostResource& audio_input) { IPC::PlatformFileForTransit socket_handle = IPC::InvalidPlatformFileForTransit(); base::SharedMemoryHandle shared_memory = IPC::InvalidPlatformFileForTransit(); uint32_t shared_memory_length = 0; if (result == PP_OK) { result = GetAudioInputConnectedHandles(audio_input, &socket_handle, &shared_memory, &shared_memory_length); } // Send all the values, even on error. This simplifies some of our cleanup // code since the handles will be in the other process and could be // inconvenient to clean up. Our IPC code will automatically handle this for // us, as long as the remote side always closes the handles it receives // (in OnMsgOpenACK), even in the failure case. dispatcher()->Send(new PpapiMsg_PPBAudioInput_OpenACK( API_ID_PPB_AUDIO_INPUT_DEV, audio_input, result, socket_handle, shared_memory, shared_memory_length)); } int32_t PPB_AudioInput_Proxy::GetAudioInputConnectedHandles( const HostResource& resource, IPC::PlatformFileForTransit* foreign_socket_handle, base::SharedMemoryHandle* foreign_shared_memory_handle, uint32_t* shared_memory_length) { // Get the audio interface which will give us the handles. EnterHostFromHostResource<PPB_AudioInput_API> enter(resource); if (enter.failed()) return PP_ERROR_NOINTERFACE; // Get the socket handle for signaling. int32_t socket_handle; int32_t result = enter.object()->GetSyncSocket(&socket_handle); if (result != PP_OK) return result; // socket_handle doesn't belong to us: don't close it. *foreign_socket_handle = dispatcher()->ShareHandleWithRemote( IntToPlatformFile(socket_handle), false); if (*foreign_socket_handle == IPC::InvalidPlatformFileForTransit()) return PP_ERROR_FAILED; // Get the shared memory for the buffer. int shared_memory_handle; result = enter.object()->GetSharedMemory(&shared_memory_handle, shared_memory_length); if (result != PP_OK) return result; // shared_memory_handle doesn't belong to us: don't close it. *foreign_shared_memory_handle = dispatcher()->ShareHandleWithRemote( IntToPlatformFile(shared_memory_handle), false); if (*foreign_shared_memory_handle == IPC::InvalidPlatformFileForTransit()) return PP_ERROR_FAILED; return PP_OK; } } // namespace proxy } // namespace ppapi
37.119363
80
0.732242
Scopetta197
32acc95ad00e98ee8b0be47a27d1fd28e7963ef7
1,073
cpp
C++
leetcode/60. Permutation Sequence.cpp
chamow97/Interview-Prep
9ce13afef6090b1604f72bf5f80a6e1df65be24f
[ "MIT" ]
1
2018-09-13T12:16:42.000Z
2018-09-13T12:16:42.000Z
leetcode/60. Permutation Sequence.cpp
chamow97/Interview-Prep
9ce13afef6090b1604f72bf5f80a6e1df65be24f
[ "MIT" ]
null
null
null
leetcode/60. Permutation Sequence.cpp
chamow97/Interview-Prep
9ce13afef6090b1604f72bf5f80a6e1df65be24f
[ "MIT" ]
null
null
null
class Solution { public: int perm(int n) { int curr = 1; for(int i = 2; i <= n; i++) { curr *= i; } return curr; } string getPermutation(int n, int k) { set<int> s; string ans = ""; for(int i = 1; i <= n; i++) { s.insert(i); } int tot = n; while(tot > 0) { int currPerm = perm(tot - 1); int newK = k / currPerm; if(currPerm * newK < k) { newK++; } else if(newK == 0) { newK = tot; } int test = (k / currPerm) * currPerm; if(test != 0) { k = k % test; } int index = 1; for(set<int> :: iterator it = s.begin(); it != s.end(); it++) { if(index == newK) { ans += (char(*it + '0')); s.erase(it); break; } index++; } tot--; } return ans; } };
24.953488
75
0.321528
chamow97
32ae93de04e4ee99e86e2c39c1712e06c1835e29
10,433
cpp
C++
vendor/android-tools/init/util.cpp
dylanh333/android-unmkbootimg
7c30a58b5bc3d208fbbbbc713717e2aae98df699
[ "MIT" ]
3
2018-04-01T18:35:29.000Z
2020-12-18T21:09:53.000Z
vendor/android-tools/init/util.cpp
dylanh333/android-unmkbootimg
7c30a58b5bc3d208fbbbbc713717e2aae98df699
[ "MIT" ]
2
2017-04-24T12:29:05.000Z
2017-05-09T12:27:10.000Z
vendor/android-tools/init/util.cpp
dylanh333/android-unmkbootimg
7c30a58b5bc3d208fbbbbc713717e2aae98df699
[ "MIT" ]
null
null
null
/* * Copyright (C) 2008 The Android Open Source Project * * 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 "util.h" #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <pwd.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <time.h> #include <unistd.h> #include <thread> #include <android-base/file.h> #include <android-base/logging.h> #include <android-base/properties.h> #include <android-base/stringprintf.h> #include <android-base/strings.h> #include <android-base/unique_fd.h> #include <cutils/android_reboot.h> #include <cutils/sockets.h> #include <selinux/android.h> #include <selinux/label.h> #include "init.h" #include "reboot.h" using android::base::boot_clock; static unsigned int do_decode_uid(const char *s) { unsigned int v; if (!s || *s == '\0') return UINT_MAX; if (isalpha(s[0])) { struct passwd* pwd = getpwnam(s); if (!pwd) return UINT_MAX; return pwd->pw_uid; } errno = 0; v = (unsigned int) strtoul(s, 0, 0); if (errno) return UINT_MAX; return v; } /* * decode_uid - decodes and returns the given string, which can be either the * numeric or name representation, into the integer uid or gid. Returns * UINT_MAX on error. */ unsigned int decode_uid(const char *s) { unsigned int v = do_decode_uid(s); if (v == UINT_MAX) { LOG(ERROR) << "decode_uid: Unable to find UID for '" << s << "'; returning UINT_MAX"; } return v; } /* * create_socket - creates a Unix domain socket in ANDROID_SOCKET_DIR * ("/dev/socket") as dictated in init.rc. This socket is inherited by the * daemon. We communicate the file descriptor's value via the environment * variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo"). */ int create_socket(const char *name, int type, mode_t perm, uid_t uid, gid_t gid, const char *socketcon) { if (socketcon) { if (setsockcreatecon(socketcon) == -1) { PLOG(ERROR) << "setsockcreatecon(\"" << socketcon << "\") failed"; return -1; } } android::base::unique_fd fd(socket(PF_UNIX, type, 0)); if (fd < 0) { PLOG(ERROR) << "Failed to open socket '" << name << "'"; return -1; } if (socketcon) setsockcreatecon(NULL); struct sockaddr_un addr; memset(&addr, 0 , sizeof(addr)); addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s", name); if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) { PLOG(ERROR) << "Failed to unlink old socket '" << name << "'"; return -1; } char *filecon = NULL; if (sehandle) { if (selabel_lookup(sehandle, &filecon, addr.sun_path, S_IFSOCK) == 0) { setfscreatecon(filecon); } } int ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr)); int savederrno = errno; setfscreatecon(NULL); freecon(filecon); if (ret) { errno = savederrno; PLOG(ERROR) << "Failed to bind socket '" << name << "'"; goto out_unlink; } if (lchown(addr.sun_path, uid, gid)) { PLOG(ERROR) << "Failed to lchown socket '" << addr.sun_path << "'"; goto out_unlink; } if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) { PLOG(ERROR) << "Failed to fchmodat socket '" << addr.sun_path << "'"; goto out_unlink; } LOG(INFO) << "Created socket '" << addr.sun_path << "'" << ", mode " << std::oct << perm << std::dec << ", user " << uid << ", group " << gid; return fd.release(); out_unlink: unlink(addr.sun_path); return -1; } bool read_file(const std::string& path, std::string* content) { content->clear(); android::base::unique_fd fd( TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC))); if (fd == -1) { return false; } // For security reasons, disallow world-writable // or group-writable files. struct stat sb; if (fstat(fd, &sb) == -1) { PLOG(ERROR) << "fstat failed for '" << path << "'"; return false; } if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) { LOG(ERROR) << "skipping insecure file '" << path << "'"; return false; } return android::base::ReadFdToString(fd, content); } bool write_file(const std::string& path, const std::string& content) { android::base::unique_fd fd(TEMP_FAILURE_RETRY( open(path.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600))); if (fd == -1) { PLOG(ERROR) << "write_file: Unable to open '" << path << "'"; return false; } bool success = android::base::WriteStringToFd(content, fd); if (!success) { PLOG(ERROR) << "write_file: Unable to write to '" << path << "'"; } return success; } int mkdir_recursive(const std::string& path, mode_t mode) { std::string::size_type slash = 0; while ((slash = path.find('/', slash + 1)) != std::string::npos) { auto directory = path.substr(0, slash); struct stat info; if (stat(directory.c_str(), &info) != 0) { auto ret = make_dir(directory.c_str(), mode); if (ret && errno != EEXIST) return ret; } } auto ret = make_dir(path.c_str(), mode); if (ret && errno != EEXIST) return ret; return 0; } int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) { boot_clock::time_point timeout_time = boot_clock::now() + timeout; while (boot_clock::now() < timeout_time) { struct stat sb; if (stat(filename, &sb) != -1) return 0; std::this_thread::sleep_for(10ms); } return -1; } void import_kernel_cmdline(bool in_qemu, const std::function<void(const std::string&, const std::string&, bool)>& fn) { std::string cmdline; android::base::ReadFileToString("/proc/cmdline", &cmdline); for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) { std::vector<std::string> pieces = android::base::Split(entry, "="); if (pieces.size() == 2) { fn(pieces[0], pieces[1], in_qemu); } } } int make_dir(const char *path, mode_t mode) { int rc; char *secontext = NULL; if (sehandle) { selabel_lookup(sehandle, &secontext, path, mode); setfscreatecon(secontext); } rc = mkdir(path, mode); if (secontext) { int save_errno = errno; freecon(secontext); setfscreatecon(NULL); errno = save_errno; } return rc; } int restorecon(const char* pathname, int flags) { return selinux_android_restorecon(pathname, flags); } /* * Writes hex_len hex characters (1/2 byte) to hex from bytes. */ std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) { std::string hex("0x"); for (size_t i = 0; i < bytes_len; i++) android::base::StringAppendF(&hex, "%02x", bytes[i]); return hex; } /* * Returns true is pathname is a directory */ bool is_dir(const char* pathname) { struct stat info; if (stat(pathname, &info) == -1) { return false; } return S_ISDIR(info.st_mode); } bool expand_props(const std::string& src, std::string* dst) { const char* src_ptr = src.c_str(); if (!dst) { return false; } /* - variables can either be $x.y or ${x.y}, in case they are only part * of the string. * - will accept $$ as a literal $. * - no nested property expansion, i.e. ${foo.${bar}} is not supported, * bad things will happen * - ${x.y:-default} will return default value if property empty. */ while (*src_ptr) { const char* c; c = strchr(src_ptr, '$'); if (!c) { dst->append(src_ptr); return true; } dst->append(src_ptr, c); c++; if (*c == '$') { dst->push_back(*(c++)); src_ptr = c; continue; } else if (*c == '\0') { return true; } std::string prop_name; std::string def_val; if (*c == '{') { c++; const char* end = strchr(c, '}'); if (!end) { // failed to find closing brace, abort. LOG(ERROR) << "unexpected end of string in '" << src << "', looking for }"; return false; } prop_name = std::string(c, end); c = end + 1; size_t def = prop_name.find(":-"); if (def < prop_name.size()) { def_val = prop_name.substr(def + 2); prop_name = prop_name.substr(0, def); } } else { prop_name = c; LOG(ERROR) << "using deprecated syntax for specifying property '" << c << "', use ${name} instead"; c += prop_name.size(); } if (prop_name.empty()) { LOG(ERROR) << "invalid zero-length property name in '" << src << "'"; return false; } std::string prop_val = android::base::GetProperty(prop_name, ""); if (prop_val.empty()) { if (def_val.empty()) { LOG(ERROR) << "property '" << prop_name << "' doesn't exist while expanding '" << src << "'"; return false; } prop_val = def_val; } dst->append(prop_val); src_ptr = c; } return true; } void panic() { LOG(ERROR) << "panic: rebooting to bootloader"; DoReboot(ANDROID_RB_RESTART2, "reboot", "bootloader", false); } std::ostream& operator<<(std::ostream& os, const Timer& t) { os << t.duration_s() << " seconds"; return os; }
28.045699
111
0.571456
dylanh333
32aee2b886c19799dabedf608ef816901dc70716
88,230
cpp
C++
printscan/wia/test/wiatest2/wiatestview.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/wia/test/wiatest2/wiatestview.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/wia/test/wiatest2/wiatestview.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// wiatestView.cpp : implementation of the CWiatestView class // #include "stdafx.h" #include "wiatest.h" #include "wiatestDoc.h" #include "wiatestView.h" #include "wiaeditpropdlg.h" #include "wiacapdlg.h" #include "wiaacquiredlg.h" #include "wiadatacallback.h" #include "wiadocacqsettings.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CWiatestView IMPLEMENT_DYNCREATE(CWiatestView, CFormView) BEGIN_MESSAGE_MAP(CWiatestView, CFormView) //{{AFX_MSG_MAP(CWiatestView) ON_NOTIFY(TVN_SELCHANGED, IDC_ITEM_TREECTRL, OnSelchangedItemTreectrl) ON_WM_SIZE() ON_NOTIFY(NM_DBLCLK, IDC_ITEMPROPERTIES_LISTCTRL, OnDblclkItempropertiesListctrl) ON_COMMAND(IDM_ACQUIREIMAGE, OnAcquireimage) ON_COMMAND(IDM_LOAD_WIAPROPERTYSTREAM, OnLoadWiapropertystream) ON_COMMAND(IDM_SAVE_WIAPROPERTYSTREAM, OnSaveWiapropertystream) ON_NOTIFY(NM_RCLICK, IDC_ITEMPROPERTIES_LISTCTRL, OnRclickItempropertiesListctrl) ON_COMMAND(ID_PROPERTYEDITPOPUPMENU_EDITPROPERTYVALUE, OnPropertyeditpopupmenuEditpropertyvalue) ON_COMMAND(IDM_VIEW_CAPABILITIES, OnViewCapabilities) ON_NOTIFY(NM_RCLICK, IDC_ITEM_TREECTRL, OnRclickItemTreectrl) ON_COMMAND(IDM_DELETE_ITEM, OnDeleteItem) ON_COMMAND(IDM_ACQUIREIMAGE_COMMONUI, OnAcquireimageCommonui) ON_COMMAND(IDM_EDIT_DEBUGOUT, OnEditDebugout) ON_UPDATE_COMMAND_UI(IDM_EDIT_DEBUGOUT, OnUpdateEditDebugout) ON_WM_SHOWWINDOW() ON_COMMAND(IDM_DOCUMENT_ACQUISITION_SETTINGS, OnDocumentAcquisitionSettings) ON_UPDATE_COMMAND_UI(IDM_DOCUMENT_ACQUISITION_SETTINGS, OnUpdateDocumentAcquisitionSettings) ON_LBN_SELCHANGE(IDC_SUPPORTED_TYMED_AND_FORMAT_LISTBOX, OnSelchangeSupportedTymedAndFormatListbox) ON_BN_CLICKED(IDC_THUMBNAIL_PREVIEW, OnThumbnailPreview) //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CFormView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CFormView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CFormView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CWiatestView construction/destruction CWiatestView::CWiatestView() : CFormView(CWiatestView::IDD) { m_bOutputToDebuggerON = FALSE; m_hThumbNailBitmap = NULL; m_bHasDocumentFeeder = FALSE; //{{AFX_DATA_INIT(CWiatestView) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // TODO: add construction code here } CWiatestView::~CWiatestView() { } void CWiatestView::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); //{{AFX_DATA_MAP(CWiatestView) DDX_Control(pDX, IDC_SUPPORTED_TYMED_AND_FORMAT_LISTBOX, m_SupportedTymedAndFormatsListBox); DDX_Control(pDX, IDC_THUMBNAIL_PREVIEW, m_ThumbnailPreviewWindow); DDX_Control(pDX, IDC_ITEMPROPERTIES_LISTCTRL, m_ItemPropertiesListCtrl); DDX_Control(pDX, IDC_ITEM_TREECTRL, m_ItemTreeCtrl); //}}AFX_DATA_MAP } BOOL CWiatestView::PreCreateWindow(CREATESTRUCT& cs) { return CFormView::PreCreateWindow(cs); } void CWiatestView::OnInitialUpdate() { CFormView::OnInitialUpdate(); GetParentFrame()->RecalcLayout(); ResizeParentToFit(FALSE); // get associated document CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ // initialize item tree control AddWiaItemsToTreeControl(TVI_ROOT, pDocument->m_pIRootItem); // initialize property list control m_ItemPropertiesListCtrl.SetupColumnHeaders(); // initialize supported TYMED and formats list box AddSupportedTYMEDAndFormatsToListBox(pDocument->m_pIRootItem); // initialize device type specifics for UI AdjustViewForDeviceType(); // register for events RegisterForEvents(); // maximize window CWnd* Parent = GetParent(); Parent->ShowWindow(SW_SHOWMAXIMIZED); } } ///////////////////////////////////////////////////////////////////////////// // CWiatestView printing BOOL CWiatestView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CWiatestView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CWiatestView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } void CWiatestView::OnPrint(CDC* pDC, CPrintInfo* /*pInfo*/) { // TODO: add customized printing code here } ///////////////////////////////////////////////////////////////////////////// // CWiatestView diagnostics #ifdef _DEBUG void CWiatestView::AssertValid() const { CFormView::AssertValid(); } void CWiatestView::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } CWiatestDoc* CWiatestView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CWiatestDoc))); return (CWiatestDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CWiatestView message handlers void CWiatestView::AddWiaItemsToTreeControl(HTREEITEM hParent, IWiaItem *pIWiaItem) { if(hParent == TVI_ROOT){ // delete any old items in tree m_ItemTreeCtrl.DeleteAllItems(); } TV_INSERTSTRUCT tv; HRESULT hr = S_OK; IEnumWiaItem* pIEnumWiaItem = NULL; LONG lItemType = 0; HTREEITEM hNewParent = NULL; TCHAR szItemName[MAX_PATH]; CWiahelper WIA; memset(szItemName,0,sizeof(szItemName)); tv.hParent = hParent; tv.hInsertAfter = TVI_LAST; tv.item.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT | TVIF_PARAM; tv.item.hItem = NULL; tv.item.state = TVIS_EXPANDED; tv.item.stateMask = TVIS_STATEIMAGEMASK; tv.item.cchTextMax = 6; tv.item.cChildren = 0; tv.item.lParam = 0; // get item's full name WIA.SetIWiaItem(pIWiaItem); WIA.ReadPropertyString(WIA_IPA_FULL_ITEM_NAME,szItemName); tv.item.pszText = szItemName; // insert item into tree hNewParent = m_ItemTreeCtrl.InsertItem(&tv); // check item type to see if it is a parent hr = pIWiaItem->GetItemType(&lItemType); if(SUCCEEDED(hr)){ if(lItemType & (WiaItemTypeFolder | WiaItemTypeHasAttachments)){ // we have a potential parent hr = pIWiaItem->EnumChildItems(&pIEnumWiaItem); if(S_OK == hr){ ULONG ulFetched = 0; IWiaItem *pFoundIWiaItem = NULL; // we have a parent with children hr = pIEnumWiaItem->Next(1,&pFoundIWiaItem,&ulFetched); while(S_OK == hr){ // add item to tree AddWiaItemsToTreeControl(hNewParent,pFoundIWiaItem); // release enumerated item pFoundIWiaItem->Release(); hr = pIEnumWiaItem->Next(1,&pFoundIWiaItem,&ulFetched); } } } } } void CWiatestView::OnSelchangedItemTreectrl(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; HTREEITEM hTreeItem = NULL; hTreeItem = m_ItemTreeCtrl.GetSelectedItem(); if(hTreeItem){ CString cszItemName = m_ItemTreeCtrl.GetItemText(hTreeItem); if(cszItemName.GetLength() > 0){ CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ BSTR bstrFullItemName = NULL; bstrFullItemName = cszItemName.AllocSysString(); if(bstrFullItemName){ HRESULT hr = S_OK; IWiaItem *pFoundIWiaItem = NULL; hr = pDocument->m_pIRootItem->FindItemByName(0,bstrFullItemName,&pFoundIWiaItem); if(SUCCEEDED(hr)){ if(NULL != pFoundIWiaItem){ hr = pDocument->SetCurrentIWiaItem(pFoundIWiaItem); if(SUCCEEDED(hr)){ // update list control with properties of the selected (found) item AddWiaItemPropertiesToListControl(pDocument->m_pICurrentItem); // update valid TYMED/Formats listbox selections AddSupportedTYMEDAndFormatsToListBox(pDocument->m_pICurrentItem); // disable supported TYMED and format selection if the item selected // is a root item. if(pDocument->m_pICurrentItem == pDocument->m_pIRootItem){ m_SupportedTymedAndFormatsListBox.SetCurSel(-1); m_SupportedTymedAndFormatsListBox.EnableWindow(FALSE); } else { m_SupportedTymedAndFormatsListBox.EnableWindow(TRUE); // set current selection for TYMED and format listbox SetCurrentSelectionForTYMEDAndFormat(); } // display thumbnail if one exists DisplayThumbnail(pDocument->m_pICurrentItem); // release IWiaItem pFoundIWiaItem->Release(); pFoundIWiaItem = NULL; } } else { ErrorMessageBox(IDS_WIATESTERROR_ITEMNOTFOUND,hr); } } else { ErrorMessageBox(IDS_WIATESTERROR_ITEMNOTFOUND,hr); } SysFreeString(bstrFullItemName); bstrFullItemName = NULL; } } } } *pResult = 0; } void CWiatestView::AddWiaItemPropertiesToListControl(IWiaItem *pIWiaItem) { // erase any old properties m_ItemPropertiesListCtrl.DeleteAllItems(); // insert new properties HRESULT hr = S_OK; IWiaPropertyStorage *pIWiaPropStg = NULL; INT ItemNumber = 0; hr = pIWiaItem->QueryInterface(IID_IWiaPropertyStorage,(void **)&pIWiaPropStg); if(hr == S_OK) { IEnumSTATPROPSTG *pIPropEnum = NULL; hr = pIWiaPropStg->Enum(&pIPropEnum); if(hr == S_OK) { STATPROPSTG StatPropStg; memset(&StatPropStg,0,sizeof(StatPropStg)); do { hr = pIPropEnum->Next(1,&StatPropStg,NULL); if (hr == S_OK) { if (StatPropStg.lpwstrName != NULL) { // read property value PROPSPEC PropSpec; PROPVARIANT PropVar; PropSpec.ulKind = PRSPEC_PROPID; PropSpec.propid = StatPropStg.propid; hr = pIWiaPropStg->ReadMultiple(1,&PropSpec,&PropVar); if (hr == S_OK) { TCHAR szPropName[MAX_PATH]; memset(szPropName,0,sizeof(szPropName)); TCHAR szValue[MAX_PATH]; memset(szValue,0,sizeof(szValue)); TCHAR szText[MAX_PATH]; memset(szText,0,sizeof(szText)); LV_ITEM lvitem; lvitem.mask = LVIF_TEXT | LVIF_PARAM; lvitem.iItem = ItemNumber; lvitem.iSubItem = 0; lvitem.pszText = szText; lvitem.iImage = NULL; lvitem.lParam = StatPropStg.propid; // Write property name to list control if (WideCharToMultiByte(CP_ACP, 0,StatPropStg.lpwstrName,-1, szPropName, MAX_PATH,NULL,NULL) > 0) { lstrcpy(szText,szPropName); // insert name into list control m_ItemPropertiesListCtrl.InsertItem(&lvitem); // move to next column for setting the value lvitem.mask = LVIF_TEXT; lvitem.iSubItem = 1; } else { lstrcpy(szPropName,TEXT("<MISSING NAME>")); } // Write property value to list control PROPVAR2TSTR(&PropVar,szText); m_ItemPropertiesListCtrl.SetItem(&lvitem); // display access flags and var type ULONG AccessFlags = 0; ULONG VarType = 0; PROPVARIANT AttrPropVar; // not used at this time hr = pIWiaPropStg->GetPropertyAttributes(1, &PropSpec,&AccessFlags,&AttrPropVar); if (hr != S_OK) { hr = S_OK; // do this to continue property traversal } else { // display access flags lvitem.mask = LVIF_TEXT; lvitem.iSubItem = 3; memset(lvitem.pszText,0,sizeof(szText)); AccessFlags2TSTR(lvitem.pszText,AccessFlags); m_ItemPropertiesListCtrl.SetItem(&lvitem); } // display var type lvitem.mask = LVIF_TEXT; lvitem.iSubItem = 2; VT2TSTR(lvitem.pszText,PropVar.vt); m_ItemPropertiesListCtrl.SetItem(&lvitem); // increment Row counter ItemNumber++; } } else { } } // clean up property name CoTaskMemFree(StatPropStg.lpwstrName); } while (hr == S_OK); pIPropEnum->Release(); } else { ErrorMessageBox(IDS_WIATESTERROR_ENUMERATE_PROPERTIES,hr); } pIWiaPropStg->Release(); } else { ErrorMessageBox(IDS_WIATESTERROR_WIAPROPERTYSTORAGE,hr); } // auto resize columns for (int Col = 0; Col <4;Col++){ m_ItemPropertiesListCtrl.SetColumnWidth(Col, LVSCW_AUTOSIZE); } } void CWiatestView::VT2TSTR(TCHAR *pszText,ULONG VarType) { if (pszText == NULL) return; switch (VarType) { case VT_EMPTY: // nothing lstrcpy(pszText,TEXT("VT_EMPTY")); break; case VT_NULL: // SQL style Null lstrcpy(pszText,TEXT("VT_NULL")); break; case VT_I2: // 2 byte signed int lstrcpy(pszText,TEXT("VT_I2")); break; case VT_I4: // 4 byte signed int lstrcpy(pszText,TEXT("VT_I4")); break; case VT_R4: // 4 byte real lstrcpy(pszText,TEXT("VT_R4")); break; case VT_R8: // 8 byte real lstrcpy(pszText,TEXT("VT_R8")); break; case VT_CY: // currency lstrcpy(pszText,TEXT("VT_CY")); break; case VT_DATE: // date lstrcpy(pszText,TEXT("VT_DATE")); break; case VT_BSTR: // OLE Automation string lstrcpy(pszText,TEXT("VT_BSTR")); break; case VT_DISPATCH: // IDispatch * lstrcpy(pszText,TEXT("VT_DISPATCH")); break; case VT_ERROR: // SCODE lstrcpy(pszText,TEXT("VT_ERROR")); break; case VT_BOOL: // True=-1, False=0 lstrcpy(pszText,TEXT("VT_BOOL")); break; case VT_VARIANT: // VARIANT * lstrcpy(pszText,TEXT("VT_VARIANT")); break; case VT_UNKNOWN: // IUnknown * lstrcpy(pszText,TEXT("VT_UNKNOWN")); break; case VT_DECIMAL: // 16 byte fixed point lstrcpy(pszText,TEXT("VT_DECIMAL")); break; case VT_RECORD: // user defined type lstrcpy(pszText,TEXT("VT_RECORD")); break; case VT_I1: // signed char lstrcpy(pszText,TEXT("VT_I1")); break; case VT_UI1: // unsigned char lstrcpy(pszText,TEXT("VT_UI1")); break; case VT_UI2: // unsigned short lstrcpy(pszText,TEXT("VT_UI2")); break; case VT_UI4: // unsigned short lstrcpy(pszText,TEXT("VT_UI4")); break; case VT_I8: // signed 64-bit int lstrcpy(pszText,TEXT("VT_I8")); break; case VT_UI8: // unsigned 64-bit int lstrcpy(pszText,TEXT("VT_UI8")); break; case VT_INT: // signed machine int lstrcpy(pszText,TEXT("VT_INT")); break; case VT_UINT: // unsigned machine int lstrcpy(pszText,TEXT("VT_UINT")); break; case VT_VOID: // C style void lstrcpy(pszText,TEXT("VT_VOID")); break; case VT_HRESULT: // Standard return type lstrcpy(pszText,TEXT("VT_HRESULT")); break; case VT_PTR: // pointer type lstrcpy(pszText,TEXT("VT_PTR")); break; case VT_SAFEARRAY: // (use VT_ARRAY in VARIANT) lstrcpy(pszText,TEXT("VT_SAFEARRAY")); break; case VT_CARRAY: // C style array lstrcpy(pszText,TEXT("VT_CARRAY")); break; case VT_USERDEFINED: // user defined type lstrcpy(pszText,TEXT("VT_USERDEFINED")); break; case VT_LPSTR: // null terminated string lstrcpy(pszText,TEXT("VT_LPSTR")); break; case VT_LPWSTR: // wide null terminated string lstrcpy(pszText,TEXT("VT_LPWSTR")); break; case VT_FILETIME: // FILETIME lstrcpy(pszText,TEXT("VT_FILETIME")); break; case VT_BLOB: // Length prefixed bytes lstrcpy(pszText,TEXT("VT_BLOB")); break; case VT_STREAM: // Name of the stream follows lstrcpy(pszText,TEXT("VT_STREAM")); break; case VT_STORAGE: // Name of the storage follows lstrcpy(pszText,TEXT("VT_STORAGE")); break; case VT_STREAMED_OBJECT: // Stream contains an object lstrcpy(pszText,TEXT("VT_STREAMED_OBJECT")); break; case VT_STORED_OBJECT: // Storage contains an object lstrcpy(pszText,TEXT("VT_STORED_OBJECT")); break; case VT_VERSIONED_STREAM: // Stream with a GUID version lstrcpy(pszText,TEXT("VT_VERSIONED_STREAM")); break; case VT_BLOB_OBJECT: // Blob contains an object lstrcpy(pszText,TEXT("VT_BLOB_OBJECT")); break; case VT_CF: // Clipboard format lstrcpy(pszText,TEXT("VT_CF")); break; case VT_CLSID: // A Class ID lstrcpy(pszText,TEXT("VT_CLSID")); break; case VT_VECTOR: // simple counted array lstrcpy(pszText,TEXT("VT_VECTOR")); break; case VT_ARRAY: // SAFEARRAY* lstrcpy(pszText,TEXT("VT_ARRAY")); break; case VT_BYREF: // void* for local use lstrcpy(pszText,TEXT("VT_BYREF")); break; case VT_BSTR_BLOB: // Reserved for system use lstrcpy(pszText,TEXT("VT_BSTR_BLOB")); break; case VT_VECTOR|VT_I4: lstrcpy(pszText,TEXT("VT_VECTOR | VT_I4")); break; case VT_VECTOR | VT_UI1: lstrcpy(pszText,TEXT("VT_VECTOR | VT_UI1")); break; case VT_VECTOR | VT_UI2: lstrcpy(pszText,TEXT("VT_VECTOR | VT_UI2")); break; case VT_VECTOR | VT_UI4: lstrcpy(pszText,TEXT("VT_VECTOR | VT_UI4")); break; default: // unknown type detected!! lstrcpy(pszText,TEXT("VT_UNKNOWNTYPE")); break; } } void CWiatestView::AccessFlags2TSTR(TCHAR *pszText,ULONG AccessFlags) { if (pszText == NULL) return; if ((AccessFlags & WIA_PROP_READ) == WIA_PROP_READ){ lstrcat(pszText,TEXT("WIA_PROP_READ | ")); } if ((AccessFlags & WIA_PROP_WRITE) == WIA_PROP_WRITE){ lstrcat(pszText,TEXT("WIA_PROP_WRITE | ")); } if (lstrcmp(pszText,TEXT("WIA_PROP_READ | WIA_PROP_WRITE | ")) == 0){ lstrcpy(pszText,TEXT("WIA_PROP_RW | ")); } if ((AccessFlags & WIA_PROP_NONE) == WIA_PROP_NONE){ lstrcat(pszText,TEXT("WIA_PROP_NONE | ")); } if ((AccessFlags & WIA_PROP_RANGE) == WIA_PROP_RANGE){ lstrcat(pszText,TEXT("WIA_PROP_RANGE | ")); } if ((AccessFlags & WIA_PROP_LIST) == WIA_PROP_LIST){ lstrcat(pszText,TEXT("WIA_PROP_LIST | ")); } if ((AccessFlags & WIA_PROP_FLAG) == WIA_PROP_FLAG){ lstrcat(pszText,TEXT("WIA_PROP_FLAG | ")); } LONG lLen = 0; lLen = lstrlen(pszText); // check for unknown access flags if (lLen == 0){ TSPRINTF(pszText,TEXT("WIA_PROP_UNKNOWN = %d "),AccessFlags); return; } pszText[lLen - (2 * sizeof(TCHAR))] = 0; } void CWiatestView::PROPVAR2TSTR(PROPVARIANT *pPropVar,TCHAR *szValue) { SYSTEMTIME *pSystemTime = NULL; switch (pPropVar->vt) { case VT_I1: TSPRINTF(szValue,TEXT("%d"),pPropVar->cVal); break; case VT_UI1: TSPRINTF(szValue,TEXT("%d"),pPropVar->bVal); break; case VT_I2: TSPRINTF(szValue,TEXT("%d"),pPropVar->iVal); break; case VT_UI2: TSPRINTF(szValue,TEXT("%d"),pPropVar->uiVal); break; case VT_UI4: TSPRINTF(szValue,TEXT("%d"),pPropVar->ulVal); break; case VT_UI8: TSPRINTF(szValue,TEXT("%d"),pPropVar->lVal); break; case VT_INT: TSPRINTF(szValue,TEXT("%d"),pPropVar->intVal); break; case VT_I4: TSPRINTF(szValue,TEXT("%d"),pPropVar->lVal); break; case VT_R4: TSPRINTF(szValue,TEXT("%2.5f"),pPropVar->fltVal); break; case VT_R8: TSPRINTF(szValue,TEXT("%2.5f"),pPropVar->dblVal); break; case VT_BSTR: #ifndef UNICODE WideCharToMultiByte(CP_ACP, 0,pPropVar->bstrVal, -1, szValue, MAX_PATH,NULL,NULL); #else TSPRINTF(szValue,TEXT("%ws"),pPropVar->bstrVal); #endif break; case VT_LPWSTR: { //TSPRINTF(szValue,TEXT("%ws"),pPropVar->pwszVal); CString TempString = pPropVar->pwszVal; lstrcpy(szValue,TempString); } break; case VT_UINT: TSPRINTF(szValue,TEXT("%d"),pPropVar->uintVal); break; case VT_CLSID: { UCHAR *pwszUUID = NULL; long lErrorCode = UuidToString(pPropVar->puuid,&pwszUUID); if(NULL != pwszUUID){ //TSPRINTF(szValue,TEXT("%s"),pwszUUID); lstrcpy(szValue,(LPCTSTR)pwszUUID); // free allocated string RpcStringFree(&pwszUUID); } } break; case VT_VECTOR | VT_UI2: pSystemTime = (SYSTEMTIME*)pPropVar->caui.pElems; if(NULL != pSystemTime){ // ( YYYY:MM:W:DD:HH:MM:SS:ms ) TSPRINTF(szValue,TEXT("%d:%d:%d:%d:%d:%d:%d:%d"),pSystemTime->wYear, pSystemTime->wMonth, pSystemTime->wDay, pSystemTime->wDayOfWeek, pSystemTime->wHour, pSystemTime->wMinute, pSystemTime->wSecond, pSystemTime->wMilliseconds); } break; default: TSPRINTF(szValue,TEXT("%d"),pPropVar->lVal); break; } } void CWiatestView::TSTR2PROPVAR(TCHAR *szValue, PROPVARIANT *pPropVar) { WCHAR wszbuffer[MAX_PATH]; CHAR szbuffer[MAX_PATH]; memset(wszbuffer,0,sizeof(wszbuffer)); memset(szbuffer,0,sizeof(szbuffer)); int iErrorCode = 0; long lErrorCode = 0; switch (pPropVar->vt) { case VT_I1: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->cVal); break; case VT_I2: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->bVal); break; case VT_I4: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->lVal); break; case VT_I8: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->hVal); break; case VT_UI1: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->bVal); break; case VT_UI2: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->uiVal); break; case VT_UI4: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->ulVal); break; case VT_UI8: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->lVal); break; case VT_INT: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->intVal); break; case VT_R4: iErrorCode = TSSCANF(szValue,TEXT("%f"),&pPropVar->fltVal); break; case VT_R8: iErrorCode = TSSCANF(szValue,TEXT("%f"),&pPropVar->fltVal); break; case VT_BSTR: #ifndef UNICODE MultiByteToWideChar(CP_ACP, 0,szValue,-1,wszbuffer,MAX_PATH); pPropVar->bstrVal = SysAllocString(wszbuffer); #else pPropVar->bstrVal = SysAllocString(szValue); #endif break; case VT_CLSID: #ifndef UNICODE pPropVar->puuid = (GUID*)CoTaskMemAlloc(sizeof(UUID)); lErrorCode = UuidFromString((UCHAR*)szValue,pPropVar->puuid); #else pPropVar->puuid = CoTaskMemAlloc(sizeof(UUID)); WideCharToMultiByte(CP_ACP, 0,szValue,-1,szbuffer,MAX_PATH,NULL,NULL); UuidFromString((UCHAR*)szbuffer,pPropVar->puuid); #endif break; case VT_UINT: iErrorCode = TSSCANF(szValue,TEXT("%li"),&pPropVar->uintVal); break; case VT_VECTOR | VT_UI2: { TCHAR *psz = NULL; // is this a SYSTEMTIME formatted string? psz = TSTRSTR(szValue,TEXT(":")); if(NULL != psz){ SYSTEMTIME *pSystemTime = NULL; pSystemTime = (SYSTEMTIME*)CoTaskMemAlloc(sizeof(SYSTEMTIME)); if(pSystemTime){ memset(pSystemTime,0,sizeof(SYSTEMTIME)); // fill out SYSTEMTIME structure iErrorCode = TSSCANF(szValue,TEXT("%hd:%hd:%hd:%hd:%hd:%hd:%hd:%hd"),&pSystemTime->wYear, &pSystemTime->wMonth, &pSystemTime->wDay, &pSystemTime->wDayOfWeek, &pSystemTime->wHour, &pSystemTime->wMinute, &pSystemTime->wSecond, &pSystemTime->wMilliseconds); // set count pPropVar->caui.cElems = (sizeof(SYSTEMTIME) / sizeof(WORD)); // set pointer (array of WORD values) pPropVar->caui.pElems = (WORD*)pSystemTime; } } } break; default: iErrorCode = TSSCANF(szValue,"%li",&pPropVar->lVal); break; } } void CWiatestView::OnSize(UINT nType, int cx, int cy) { CFormView::OnSize(nType, cx, cy); CRect ParentWindowRect; LONG lOffset = 0; // get parent window rect GetWindowRect(ParentWindowRect); ScreenToClient(ParentWindowRect); // resize property list control if(NULL != m_ItemPropertiesListCtrl.m_hWnd){ CRect ListBoxRect; // get list control rect m_ItemPropertiesListCtrl.GetWindowRect(ListBoxRect); ScreenToClient(ListBoxRect); // adjust width ListBoxRect.right = ParentWindowRect.right - 10; lOffset = ListBoxRect.right; // adjust height ListBoxRect.bottom = ParentWindowRect.bottom - 10; m_ItemPropertiesListCtrl.MoveWindow(ListBoxRect); } if(GET_STIDEVICE_TYPE(m_lDeviceType) == StiDeviceTypeDigitalCamera){ // move thumbnail control if(NULL != m_ThumbnailPreviewWindow.m_hWnd){ CRect ThumbnailRect; // get thumbnail rect m_ThumbnailPreviewWindow.GetWindowRect(ThumbnailRect); ScreenToClient(ThumbnailRect); // adjust position INT iWidth = ThumbnailRect.Width(); ThumbnailRect.right = lOffset; ThumbnailRect.left = (ThumbnailRect.right - iWidth); m_ThumbnailPreviewWindow.MoveWindow(ThumbnailRect); } // resize supported TYMED and Format listbox if(NULL != m_SupportedTymedAndFormatsListBox.m_hWnd){ CRect ListBoxRect; CRect ThumbnailRect; // get list box rect m_SupportedTymedAndFormatsListBox.GetWindowRect(ListBoxRect); ScreenToClient(ListBoxRect); // get thumbnail rect m_ThumbnailPreviewWindow.GetWindowRect(ThumbnailRect); ScreenToClient(ThumbnailRect); // adjust width ListBoxRect.right = ThumbnailRect.left - 10; m_SupportedTymedAndFormatsListBox.MoveWindow(ListBoxRect); } } else { // resize supported TYMED listbox if(NULL != m_SupportedTymedAndFormatsListBox.m_hWnd){ CRect ListBoxRect; CRect ThumbnailRect; // get list box rect m_SupportedTymedAndFormatsListBox.GetWindowRect(ListBoxRect); ScreenToClient(ListBoxRect); // adjust width ListBoxRect.right = lOffset; m_SupportedTymedAndFormatsListBox.MoveWindow(ListBoxRect); } } } void CWiatestView::OnDblclkItempropertiesListctrl(NMHDR* pNMHDR, LRESULT* pResult) { // find out what property is selected HD_NOTIFY* phdn = (HD_NOTIFY *) pNMHDR; TCHAR pszPropertyName[MAX_PATH]; memset(pszPropertyName,0,sizeof(pszPropertyName)); TCHAR pszPropertyValue[MAX_PATH]; memset(pszPropertyValue,0,sizeof(pszPropertyValue)); LV_ITEM lvitem; lvitem.mask = LVIF_PARAM; lvitem.iItem = phdn->iItem; lvitem.iSubItem = ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYNAME; lvitem.pszText = NULL; // is an item selected? if (phdn->iItem < ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYNAME) return; m_ItemPropertiesListCtrl.GetItem(&lvitem); // get stored property ID LONG iProp = 0; iProp = (LONG)lvitem.lParam; m_ItemPropertiesListCtrl.GetItemText(phdn->iItem, ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYNAME, pszPropertyName, sizeof(pszPropertyName)); m_ItemPropertiesListCtrl.GetItemText(phdn->iItem, ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYVALUE, pszPropertyValue, sizeof(pszPropertyValue)); // get document CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ IWiaPropertyStorage *pIWiaPropStg = NULL; HRESULT hr = S_OK; hr = pDocument->m_pICurrentItem->QueryInterface(IID_IWiaPropertyStorage,(void **)&pIWiaPropStg); if(SUCCEEDED(hr)) { // read property value for type and current value PROPVARIANT PropVar[1]; PROPVARIANT AttrPropVar[1]; PROPSPEC PropSpec[1]; PropSpec[0].ulKind = PRSPEC_PROPID; PropSpec[0].propid = iProp; ULONG ulAttributes = 0; CWiaeditpropDlg PropertyEditDlg; hr = pIWiaPropStg->ReadMultiple(1,PropSpec,PropVar); if (S_OK == hr) { PropertyEditDlg.SetVarType(PropVar[0].vt); // clear variant PropVariantClear(PropVar); hr = pIWiaPropStg->GetPropertyAttributes(1, PropSpec,&ulAttributes,AttrPropVar); if(S_OK == hr){ PropertyEditDlg.SetAttributes(ulAttributes, (PROPVARIANT*)AttrPropVar); BOOL bRefreshCurrentTYMEDAndFormatSelection = FALSE; if((lstrcmp(pszPropertyName,TEXT("Format")) == 0) || (lstrcmp(pszPropertyName,TEXT("Media Type")) == 0)){ bRefreshCurrentTYMEDAndFormatSelection = TRUE; } if(PropertyEditDlg.DoModal(pszPropertyName,pszPropertyValue) == IDOK){ memset(pszPropertyValue,0,sizeof(pszPropertyValue)); PropertyEditDlg.GetPropertyValue(pszPropertyValue); PropVar[0].vt = PropertyEditDlg.GetVarType(); TSTR2PROPVAR(pszPropertyValue,(PROPVARIANT*)PropVar); hr = pIWiaPropStg->WriteMultiple(1,PropSpec,PropVar,MIN_PROPID); if(S_OK == hr){ // get current document, and refresh the property list with the current // selected item CWiatestDoc* pCurrentDocument = NULL; pCurrentDocument = (CWiatestDoc*)m_pDocument; if(pCurrentDocument){ // update list control with properties AddWiaItemPropertiesToListControl(pCurrentDocument->m_pICurrentItem); if(bRefreshCurrentTYMEDAndFormatSelection){ SetCurrentSelectionForTYMEDAndFormat(); } } } else if FAILED(hr){ // failure ErrorMessageBox(IDS_WIATESTERROR_WRITING_PROPERTY,hr); } else { // S_FALSE ErrorMessageBox(IDS_WIATESTWARNING_ADDITIONAL_PROPERTY); } // clear variant PropVariantClear(PropVar); } else { // user decided not to write the property } } } // release property storage pIWiaPropStg->Release(); pIWiaPropStg = NULL; } } *pResult = 0; } void CWiatestView::AddSupportedTYMEDAndFormatsToListBox(IWiaItem *pIWiaItem) { m_SupportedTymedAndFormatsListBox.ResetContent(); HRESULT hr = S_OK; IWiaDataTransfer *pIWiaDataTransfer = NULL; hr = pIWiaItem->QueryInterface(IID_IWiaDataTransfer, (void **)&pIWiaDataTransfer); if (S_OK == hr) { IEnumWIA_FORMAT_INFO *pIEnumWIA_FORMAT_INFO = NULL; WIA_FORMAT_INFO pfe; hr = pIWiaDataTransfer->idtEnumWIA_FORMAT_INFO(&pIEnumWIA_FORMAT_INFO); if (SUCCEEDED(hr)) { do { memset(&pfe,0,sizeof(pfe)); hr = pIEnumWIA_FORMAT_INFO->Next(1, &pfe, NULL); if (hr == S_OK) { TCHAR szFormat[MAX_PATH]; TCHAR szGuid[MAX_PATH]; TCHAR szTYMED[MAX_PATH]; memset(szFormat,0,sizeof(szFormat)); memset(szGuid,0,sizeof(szGuid)); memset(szTYMED,0,sizeof(szTYMED)); if(!WIACONSTANT2TSTR(TEXT("Media Type"),(LONG)pfe.lTymed,szTYMED)){ lstrcpy(szTYMED,TEXT("TYMED_UNKNOWN")); } FORMAT2TSTR(pfe.guidFormatID,szGuid); TSPRINTF(szFormat,TEXT("%s - %s"),szTYMED,szGuid); m_SupportedTymedAndFormatsListBox.AddString(szFormat); } else { if (FAILED(hr)) { ErrorMessageBox(IDS_WIATESTERROR_ENUMFORMATS,hr); } } } while (hr == S_OK); pIEnumWIA_FORMAT_INFO->Release(); pIEnumWIA_FORMAT_INFO = NULL; } else { ErrorMessageBox(IDS_WIATESTERROR_ENUMFORMATS,hr); } pIWiaDataTransfer->Release(); pIWiaDataTransfer = NULL; } else { ErrorMessageBox(IDS_WIATESTERROR_IWIADATATRANSFER,hr); } } void CWiatestView::FORMAT2TSTR(GUID guidFormat, TCHAR *pszFormat) { if(guidFormat == WiaImgFmt_UNDEFINED) lstrcpy(pszFormat,TEXT("WiaImgFmt_UNDEFINED:")); else if(guidFormat == WiaImgFmt_MEMORYBMP) lstrcpy(pszFormat,TEXT("WiaImgFmt_MEMORYBMP:")); else if(guidFormat == WiaImgFmt_BMP) lstrcpy(pszFormat,TEXT("WiaImgFmt_BMP:")); else if(guidFormat == WiaImgFmt_EMF) lstrcpy(pszFormat,TEXT("WiaImgFmt_EMF:")); else if(guidFormat == WiaImgFmt_WMF) lstrcpy(pszFormat,TEXT("WiaImgFmt_WMF:")); else if(guidFormat == WiaImgFmt_JPEG) lstrcpy(pszFormat,TEXT("WiaImgFmt_JPEG:")); else if(guidFormat == WiaImgFmt_PNG) lstrcpy(pszFormat,TEXT("WiaImgFmt_PNG:")); else if(guidFormat == WiaImgFmt_GIF) lstrcpy(pszFormat,TEXT("WiaImgFmt_GIF:")); else if(guidFormat == WiaImgFmt_TIFF) lstrcpy(pszFormat,TEXT("WiaImgFmt_TIFF:")); else if(guidFormat == WiaImgFmt_EXIF) lstrcpy(pszFormat,TEXT("WiaImgFmt_EXIF:")); else if(guidFormat == WiaImgFmt_PHOTOCD) lstrcpy(pszFormat,TEXT("WiaImgFmt_PHOTOCD:")); else if(guidFormat == WiaImgFmt_FLASHPIX) lstrcpy(pszFormat,TEXT("WiaImgFmt_FLASHPIX:")); else { lstrcpy(pszFormat,TEXT("Custom Format:")); } TCHAR szGUID[MAX_PATH]; memset(szGUID,0,sizeof(szGUID)); UCHAR *pwszUUID = NULL; long lErrorCode = UuidToString(&guidFormat,&pwszUUID); TSPRINTF(szGUID," (%s)",pwszUUID); lstrcat(pszFormat,szGUID); // free allocated string RpcStringFree(&pwszUUID); } void CWiatestView::OnAcquireimage() { // delete old temp image files DeleteTempDataTransferFiles(); CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ if(pDocument->m_pICurrentItem == pDocument->m_pIRootItem){ // use the common UI, because we can not transfer from the root item OnAcquireimageCommonui(); return; } TCHAR szFileName[MAX_PATH]; TCHAR szTempFile[MAX_PATH]; memset(szFileName,0,sizeof(szFileName)); memset(szTempFile,0,sizeof(szTempFile)); CWiahelper WIA; HRESULT hr = S_OK; LONG lTymed = 0; hr = WIA.SetIWiaItem(pDocument->m_pICurrentItem); if (SUCCEEDED(hr)) { hr = WIA.ReadPropertyLong(WIA_IPA_TYMED,&lTymed); if (S_OK == hr) { switch (lTymed) { case TYMED_CALLBACK: case TYMED_MULTIPAGE_CALLBACK: GetTempPath(sizeof(szFileName),szFileName); RC2TSTR(IDS_WIATEST_MEMORYTRANSFER_FILENAME,szTempFile,sizeof(szTempFile)); lstrcat(szFileName,szTempFile); hr = TransferToMemory(szFileName, pDocument->m_pICurrentItem); break; case TYMED_FILE: case TYMED_MULTIPAGE_FILE: GetTempPath(sizeof(szFileName),szFileName); RC2TSTR(IDS_WIATEST_FILETRANSFER_FILENAME,szTempFile,sizeof(szTempFile)); lstrcat(szFileName,szTempFile); hr = TransferToFile(szFileName,pDocument->m_pICurrentItem); break; default: ErrorMessageBox(IDS_WIATESTERROR_UNSUPPORTEDTYMED); break; } } else if (S_FALSE == hr) { ErrorMessageBox(IDS_WIATESTERROR_READINGTYMED_EXIST,hr); } else { ErrorMessageBox(IDS_WIATESTERROR_READINGTYMED,hr); } } else { ErrorMessageBox(IDS_WIATESTERROR_READINGTYMED,hr); } if ((hr == S_OK)||(WIA_STATUS_END_OF_MEDIA == hr)) { CWiahelper WIA; WIA.SetIWiaItem(pDocument->m_pICurrentItem); GUID guidFormat; memset(&guidFormat,0,sizeof(guidFormat)); hr = WIA.ReadPropertyGUID(WIA_IPA_FORMAT,&guidFormat); if(S_OK == hr){ RenameTempDataTransferFilesAndLaunchViewer(guidFormat,lTymed); } } } } HRESULT CWiatestView::TransferToFile(TCHAR *szFileName, IWiaItem *pIWiaItem) { STGMEDIUM StgMedium; HRESULT hr = S_OK; // get IWiaDatatransfer interface IWiaDataTransfer *pIWiaDataTransfer = NULL; hr = pIWiaItem->QueryInterface(IID_IWiaDataTransfer, (void **)&pIWiaDataTransfer); if (SUCCEEDED(hr)) { WCHAR wszFileName[MAX_PATH]; memset(wszFileName,0,sizeof(wszFileName)); #ifndef UNICODE MultiByteToWideChar(CP_ACP, 0,szFileName,-1,wszFileName,MAX_PATH); #else lstrcpy(wszFileName,szFileName); #endif CWiahelper WIA; LONG lTymed = TYMED_FILE; WIA.SetIWiaItem(pIWiaItem); hr = WIA.ReadPropertyLong(WIA_IPA_TYMED, &lTymed); if (SUCCEEDED(hr)) { StgMedium.tymed = lTymed; StgMedium.pUnkForRelease = NULL; StgMedium.hGlobal = NULL; StgMedium.lpszFileName = wszFileName; IWiaDataCallback* pIWiaDataCallback = NULL; CWiaDataCallback WiaDataCallback; hr = WiaDataCallback.QueryInterface(IID_IWiaDataCallback,(void **)&pIWiaDataCallback); if (hr == S_OK) { hr = pIWiaDataTransfer->idtGetData(&StgMedium,pIWiaDataCallback); if ((hr == S_OK)||(WIA_STATUS_END_OF_MEDIA == hr)) { // successful transfer } else if (S_FALSE == hr) { ErrorMessageBox(IDS_WIATESTERROR_CANCEL_ACQUISITION); } else { ErrorMessageBox(IDS_WIATESTERROR_ACQUISITION,hr); } pIWiaDataTransfer->Release(); //WiaDataCallback.Release(); } } } return hr; } HRESULT CWiatestView::TransferToMemory(TCHAR *szFileName, IWiaItem *pIWiaItem) { HRESULT hr = S_OK; // get IWiaDatatransfer interface IWiaDataTransfer *pIWiaDataTransfer = NULL; hr = pIWiaItem->QueryInterface(IID_IWiaDataTransfer, (void **)&pIWiaDataTransfer); if (SUCCEEDED(hr)) { WIA_DATA_TRANSFER_INFO WiaDataTransferInformation; memset(&WiaDataTransferInformation,0,sizeof(WiaDataTransferInformation)); WiaDataTransferInformation.ulSize = sizeof(WiaDataTransferInformation); WiaDataTransferInformation.ulBufferSize = (ReadMinBufferSizeProperty(pIWiaItem) * MIN_BUFFER_FACTOR); IWiaDataCallback* pIWiaDataCallback = NULL; CWiaDataCallback WiaDataCallback; hr = WiaDataCallback.QueryInterface(IID_IWiaDataCallback,(void **)&pIWiaDataCallback); if (hr == S_OK) { hr = pIWiaDataTransfer->idtGetBandedData(&WiaDataTransferInformation,pIWiaDataCallback); if ((hr == S_OK)||(WIA_STATUS_END_OF_MEDIA == hr)) { HANDLE hMemoryDataFile = NULL; hMemoryDataFile = CreateFile(szFileName, GENERIC_WRITE,FILE_SHARE_READ,NULL, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); if (hMemoryDataFile != INVALID_HANDLE_VALUE && hMemoryDataFile != NULL) { LONG lDataSize = 0; BYTE *pData = WiaDataCallback.GetCallbackMemoryPtr(&lDataSize); DWORD dwBytesWritten = 0; if (lDataSize > 0) { // handle BITMAP DATA (special case) if (WiaDataCallback.IsBITMAPDATA()) { // we need to adjust any headers, because the height and image size information // could be incorrect. (this will handle infinite page length devices) BITMAPFILEHEADER bmfh; BITMAPINFOHEADER *pbmh = NULL; pbmh = (BITMAPINFOHEADER*)pData; if(pbmh->biHeight < 0){ StatusMessageBox(IDS_WIATESTWARNING_NEGATIVE_HEIGHTBITMAP); pbmh->biHeight = abs(pbmh->biHeight); } LONG lPaletteSize = pbmh->biClrUsed * sizeof(RGBQUAD); bmfh.bfType = BMPFILE_HEADER_MARKER; bmfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + lPaletteSize; bmfh.bfSize = sizeof(BITMAPFILEHEADER) + lDataSize; bmfh.bfReserved1 = 0; bmfh.bfReserved2 = 0; // only fix the BITMAPINFOHEADER if height needs to be calculated if (pbmh->biHeight == 0) { StatusMessageBox(IDS_WIATESTWARNING_ZERO_HEIGHTBITMAP); LONG lWidthBytes = CalculateWidthBytes(pbmh->biWidth,pbmh->biBitCount); pbmh->biSizeImage = lDataSize - lPaletteSize - sizeof(BITMAPINFOHEADER); pbmh->biHeight = LONG(pbmh->biSizeImage/lWidthBytes); pbmh->biXPelsPerMeter = 0; // zero out pbmh->biYPelsPerMeter = 0; // zero out } WriteFile(hMemoryDataFile,&bmfh,sizeof(bmfh),&dwBytesWritten,NULL); } // write data to disk WriteFile(hMemoryDataFile,pData,lDataSize,&dwBytesWritten,NULL); } // flush and close FlushFileBuffers(hMemoryDataFile); CloseHandle(hMemoryDataFile); } } else if (S_FALSE == hr) { ErrorMessageBox(IDS_WIATESTERROR_CANCEL_ACQUISITION); } else { ErrorMessageBox(IDS_WIATESTERROR_ACQUISITION,hr); } pIWiaDataTransfer->Release(); //WiaDataCallback.Release(); } } return hr; } void CWiatestView::OnLoadWiapropertystream() { CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ CWiahelper WIA; WIA.SetIWiaItem(pDocument->m_pICurrentItem); HRESULT hr = S_OK; TCHAR szPropertyStreamFile[MAX_PATH]; memset(szPropertyStreamFile,0,sizeof(szPropertyStreamFile)); // select saving location OPENFILENAME ofn; // common dialog box structure TCHAR szLoadPropStreamTitle[MAX_PATH]; memset(szLoadPropStreamTitle,0,sizeof(szLoadPropStreamTitle)); RC2TSTR(IDS_WIATESTLOADPROPSTREAM_DIALOGTITLE,szLoadPropStreamTitle,sizeof(szLoadPropStreamTitle)); memset(&ofn,0,sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = m_hWnd; ofn.lpstrFile = szPropertyStreamFile; ofn.nMaxFile = sizeof(szPropertyStreamFile); ofn.lpstrFilter = "*.wia\0*.wia\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.lpstrTitle = szLoadPropStreamTitle; ofn.Flags = 0; ofn.lpstrDefExt = "wia"; if (!GetOpenFileName(&ofn)) { return; } hr = WIA.ReadPropertyStreamFile(szPropertyStreamFile); if(FAILED(hr)){ ErrorMessageBox(IDS_WIATESTERROR_READPROPERTYSTREAMFILE,hr); } else { // refresh the item tree AddWiaItemsToTreeControl(TVI_ROOT,pDocument->m_pIRootItem); // refresh the properties AddWiaItemPropertiesToListControl(pDocument->m_pIRootItem); } } } void CWiatestView::OnSaveWiapropertystream() { CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ CWiahelper WIA; WIA.SetIWiaItem(pDocument->m_pICurrentItem); HRESULT hr = S_OK; TCHAR szPropertyStreamFile[MAX_PATH]; memset(szPropertyStreamFile,0,sizeof(szPropertyStreamFile)); // select saving location OPENFILENAME ofn; // common dialog box structure TCHAR szSavePropStreamTitle[MAX_PATH]; memset(szSavePropStreamTitle,0,sizeof(szSavePropStreamTitle)); RC2TSTR(IDS_WIATESTSAVEPROPSTREAM_DIALOGTITLE,szSavePropStreamTitle,sizeof(szSavePropStreamTitle)); memset(&ofn,0,sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = m_hWnd; ofn.lpstrFile = szPropertyStreamFile; ofn.nMaxFile = sizeof(szPropertyStreamFile); ofn.lpstrFilter = "*.wia\0*.wia\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.lpstrTitle = szSavePropStreamTitle; ofn.Flags = 0; ofn.lpstrDefExt = "wia"; if (!GetSaveFileName(&ofn)) { return; } hr = WIA.WritePropertyStreamFile(szPropertyStreamFile); if(FAILED(hr)){ ErrorMessageBox(IDS_WIATESTERROR_WRITEPROPERTYSTREAMFILE,hr); } } } void CWiatestView::OnRclickItempropertiesListctrl(NMHDR* pNMHDR, LRESULT* pResult) { POINT MousePos; CMenu PopupMenu; CMenu *pEditMenu = NULL; if(PopupMenu.LoadMenu(IDR_PROPERTY_EDIT_POPUPMENU)){ GetCursorPos(&MousePos); pEditMenu = PopupMenu.GetSubMenu(0); if(pEditMenu){ pEditMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON, MousePos.x, MousePos.y, this); } } *pResult = 0; } void CWiatestView::OnPropertyeditpopupmenuEditpropertyvalue() { PROPVARIANT *pPropertyVariants = NULL; PROPSPEC *pPropertySpecs = NULL; UINT uiNumProperties = m_ItemPropertiesListCtrl.GetSelectedCount(); if(uiNumProperties <=0){ return; } BOOL bWriteProperties = TRUE; IWiaPropertyStorage *pIWiaPropStg = NULL; HRESULT hr = S_OK; UINT iPropertyIndex = 0; pPropertyVariants = new PROPVARIANT[uiNumProperties]; if(pPropertyVariants){ pPropertySpecs = new PROPSPEC[uiNumProperties]; if(pPropertySpecs){ POSITION pos = NULL; pos = m_ItemPropertiesListCtrl.GetFirstSelectedItemPosition(); if (NULL != pos){ while (pos && bWriteProperties){ int iItem = m_ItemPropertiesListCtrl.GetNextSelectedItem(pos); // find out what property is selected TCHAR pszPropertyName[MAX_PATH]; memset(pszPropertyName,0,sizeof(pszPropertyName)); TCHAR pszPropertyValue[MAX_PATH]; memset(pszPropertyValue,0,sizeof(pszPropertyValue)); LV_ITEM lvitem; lvitem.mask = LVIF_PARAM; lvitem.iItem = iItem; lvitem.iSubItem = ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYNAME; lvitem.pszText = NULL; // is an item selected? if (iItem < ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYNAME) return; m_ItemPropertiesListCtrl.GetItem(&lvitem); // get stored property ID LONG iProp = 0; iProp = (LONG)lvitem.lParam; m_ItemPropertiesListCtrl.GetItemText(iItem, ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYNAME, pszPropertyName, sizeof(pszPropertyName)); m_ItemPropertiesListCtrl.GetItemText(iItem, ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYVALUE, pszPropertyValue, sizeof(pszPropertyValue)); // get document CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ hr = pDocument->m_pICurrentItem->QueryInterface(IID_IWiaPropertyStorage,(void **)&pIWiaPropStg); if(SUCCEEDED(hr)) { // read property value for type and current value PROPVARIANT PropVar[1]; PROPVARIANT AttrPropVar[1]; PROPSPEC PropSpec[1]; PropSpec[0].ulKind = PRSPEC_PROPID; PropSpec[0].propid = iProp; // set propspec pPropertySpecs[iPropertyIndex].ulKind = PRSPEC_PROPID; pPropertySpecs[iPropertyIndex].propid = iProp; ULONG ulAttributes = 0; CWiaeditpropDlg PropertyEditDlg; hr = pIWiaPropStg->ReadMultiple(1,PropSpec,PropVar); if (S_OK == hr) { PropertyEditDlg.SetVarType(PropVar[0].vt); // clear variant PropVariantClear(PropVar); hr = pIWiaPropStg->GetPropertyAttributes(1, PropSpec,&ulAttributes,AttrPropVar); if(S_OK == hr){ PropertyEditDlg.SetAttributes(ulAttributes, (PROPVARIANT*)AttrPropVar); if(PropertyEditDlg.DoModal(pszPropertyName,pszPropertyValue) == IDOK){ memset(pszPropertyValue,0,sizeof(pszPropertyValue)); PropertyEditDlg.GetPropertyValue(pszPropertyValue); // set variant pPropertyVariants[iPropertyIndex].vt = PropertyEditDlg.GetVarType(); TSTR2PROPVAR(pszPropertyValue,(PROPVARIANT*)&pPropertyVariants[iPropertyIndex]); iPropertyIndex++; } else { // user decided not to write the property bWriteProperties = FALSE; } } } // release property storage pIWiaPropStg->Release(); pIWiaPropStg = NULL; } } } } } if(bWriteProperties){ // get current document, and refresh the property list with the current // selected item CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ hr = pDocument->m_pICurrentItem->QueryInterface(IID_IWiaPropertyStorage,(void **)&pIWiaPropStg); if(SUCCEEDED(hr)) { hr = pIWiaPropStg->WriteMultiple(uiNumProperties,pPropertySpecs,pPropertyVariants,MIN_PROPID); if(S_OK == hr){ // success } else if FAILED(hr){ // failure ErrorMessageBox(IDS_WIATESTERROR_WRITING_PROPERTY,hr); } else { // S_FALSE ErrorMessageBox(IDS_WIATESTWARNING_ADDITIONAL_PROPERTY); } pIWiaPropStg->Release(); pIWiaPropStg = NULL; } // update list control with properties AddWiaItemPropertiesToListControl(pDocument->m_pICurrentItem); // update TYMED and format selection listbox SetCurrentSelectionForTYMEDAndFormat(); } } if(pPropertyVariants){ PropVariantClear(pPropertyVariants); delete [] pPropertyVariants; pPropertyVariants = NULL; } if(pPropertySpecs){ delete [] pPropertySpecs; pPropertySpecs = NULL; } } } void CWiatestView::OnViewCapabilities() { CWiacapDlg CapabilitiesDlg; CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ CapabilitiesDlg.SetIWiaItem(pDocument->m_pIRootItem); CapabilitiesDlg.DoModal(); #ifdef FORCE_UPDATE if(CapabilitiesDlg.m_bCommandSent){ // refresh the item tree AddWiaItemsToTreeControl(TVI_ROOT,pDocument->m_pIRootItem); // refresh the properties AddWiaItemPropertiesToListControl(pDocument->m_pIRootItem); } #endif } } void CWiatestView::OnRclickItemTreectrl(NMHDR* pNMHDR, LRESULT* pResult) { POINT MousePos; CMenu PopupMenu; CMenu *pEditMenu = NULL; if(PopupMenu.LoadMenu(IDR_ITEMTREE_POPUPMENU)){ GetCursorPos(&MousePos); pEditMenu = PopupMenu.GetSubMenu(0); if(pEditMenu){ CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ if(pDocument->m_pICurrentItem == pDocument->m_pIRootItem){ pEditMenu->EnableMenuItem(IDM_DELETE_ITEM,MF_BYCOMMAND|MF_GRAYED); pEditMenu->RemoveMenu(IDM_ACQUIREIMAGE,MF_BYCOMMAND); } else { pEditMenu->RemoveMenu(IDM_ACQUIREIMAGE_COMMONUI,MF_BYCOMMAND); } pEditMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON, MousePos.x, MousePos.y, this); } } } *pResult = 0; } ULONG CWiatestView::ReadMinBufferSizeProperty(IWiaItem *pIWiaItem) { LONG lMinBufferSize = 0; CWiahelper WIA; WIA.SetIWiaItem(pIWiaItem); HRESULT hr = S_OK; hr = WIA.ReadPropertyLong(WIA_IPA_MIN_BUFFER_SIZE,&lMinBufferSize); if(FAILED(hr)){ ErrorMessageBox(IDS_WIATESTERROR_READINGMINBUFFERSIZE,hr); } return lMinBufferSize; } void CWiatestView::SetCurrentSelectionForTYMEDAndFormat() { TCHAR szTymed[MAX_PATH]; memset(szTymed,0,sizeof(szTymed)); TCHAR szFormat[MAX_PATH]; memset(szFormat,0,sizeof(szFormat)); INT iItem = 0; LVFINDINFO info; info.flags = LVFI_PARTIAL|LVFI_STRING; // find current TYMED setting info.psz = TEXT("Media Type"); iItem = m_ItemPropertiesListCtrl.FindItem(&info,-1); if(iItem != -1){ // item Found // get current value from control m_ItemPropertiesListCtrl.GetItemText(iItem,ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYVALUE, szTymed, sizeof(szTymed)); LONG lTymed = 0; int iErrorCode = TSSCANF(szTymed,"%d",&lTymed); WIACONSTANT2TSTR(TEXT("Media Type"), lTymed, szTymed); } // find current Format setting info.psz = TEXT("Format"); iItem = m_ItemPropertiesListCtrl.FindItem(&info,-1); if(iItem != -1){ // item Found // get current value from control m_ItemPropertiesListCtrl.GetItemText(iItem,ITEMPROPERTYLISTCTRL_COLUMN_PROPERTYVALUE, szFormat, sizeof(szFormat)); } // find and select the current TYMED / format pair in the selection control. INT iNumListBoxItems = 0; iNumListBoxItems = m_SupportedTymedAndFormatsListBox.GetCount(); if(iNumListBoxItems > 0){ for(INT i = 0; i < iNumListBoxItems; i++){ TCHAR szText[MAX_PATH]; memset(szText,0,sizeof(szText)); m_SupportedTymedAndFormatsListBox.GetText(i,szText); if(TSTRSTR(szText,szTymed) != NULL){ // found TYMED if(TSTRSTR(szText,szFormat) != NULL){ // found format m_SupportedTymedAndFormatsListBox.SetCurSel(i); // exit loop i = iNumListBoxItems; } } } } } void CWiatestView::DeleteTempDataTransferFiles() { } void CWiatestView::RenameTempDataTransferFilesAndLaunchViewer(GUID guidFormat, LONG lTymed) { TCHAR *pszFileExt = NULL; TCHAR szOriginalFileName[MAX_PATH]; TCHAR szFileName[MAX_PATH]; TCHAR szTempPath[MAX_PATH]; TCHAR szFullLaunchPath[MAX_PATH]; TCHAR szOriginalFullLaunchPath[MAX_PATH]; memset(szFileName,0,sizeof(szFileName)); memset(szTempPath,0,sizeof(szTempPath)); memset(szFullLaunchPath,0,sizeof(szFullLaunchPath)); memset(szOriginalFileName,0,sizeof(szOriginalFileName)); memset(szOriginalFullLaunchPath,0,sizeof(szOriginalFullLaunchPath)); GetTempPath(sizeof(szTempPath),szTempPath); BOOL bKnownFormat = TRUE; switch(lTymed){ case TYMED_CALLBACK: case TYMED_MULTIPAGE_CALLBACK: RC2TSTR(IDS_WIATEST_MEMORYTRANSFER_FILENAME,szOriginalFileName,sizeof(szOriginalFileName)); lstrcpy(szFileName,szOriginalFileName); pszFileExt = TSTRSTR(szFileName,TEXT("mem")); break; case TYMED_FILE: case TYMED_MULTIPAGE_FILE: RC2TSTR(IDS_WIATEST_FILETRANSFER_FILENAME,szOriginalFileName,sizeof(szOriginalFileName)); lstrcpy(szFileName,szOriginalFileName); pszFileExt = TSTRSTR(szFileName,TEXT("fil")); break; default: break; } if(lstrlen(szFileName) > 0){ if(pszFileExt){ // rename to known image formats if(guidFormat == WiaImgFmt_UNDEFINED) lstrcpy(pszFileExt,TEXT("bmp")); else if(guidFormat == WiaImgFmt_MEMORYBMP) lstrcpy(pszFileExt,TEXT("bmp")); else if(guidFormat == WiaImgFmt_BMP) lstrcpy(pszFileExt,TEXT("bmp")); else if(guidFormat == WiaImgFmt_EMF) lstrcpy(pszFileExt,TEXT("emf")); else if(guidFormat == WiaImgFmt_WMF) lstrcpy(pszFileExt,TEXT("wmf")); else if(guidFormat == WiaImgFmt_JPEG) lstrcpy(pszFileExt,TEXT("jpg")); else if(guidFormat == WiaImgFmt_PNG) lstrcpy(pszFileExt,TEXT("png")); else if(guidFormat == WiaImgFmt_GIF) lstrcpy(pszFileExt,TEXT("gif")); else if(guidFormat == WiaImgFmt_TIFF) lstrcpy(pszFileExt,TEXT("tif")); else if(guidFormat == WiaImgFmt_EXIF) lstrcpy(pszFileExt,TEXT("jpg")); else if(guidFormat == WiaImgFmt_PHOTOCD) lstrcpy(pszFileExt,TEXT("pcd")); else if(guidFormat == WiaImgFmt_FLASHPIX) lstrcpy(pszFileExt,TEXT("fpx")); else { TCHAR szValue[MAX_PATH]; memset(szValue,0,sizeof(szValue)); UCHAR *pwszUUID = NULL; long lErrorCode = UuidToString(&guidFormat,&pwszUUID); //TSPRINTF(szValue,TEXT("%s"),pwszUUID); lstrcpy(szValue,(LPCTSTR)pwszUUID); // (TEXT("(Unknown Image type) GUID: %s"),pwszUUID); // free allocated string RpcStringFree(&pwszUUID); bKnownFormat = FALSE; } } } if(bKnownFormat){ // launch viewer lstrcpy(szFullLaunchPath,szTempPath); lstrcat(szFullLaunchPath,szFileName); lstrcpy(szOriginalFullLaunchPath,szTempPath); lstrcat(szOriginalFullLaunchPath,szOriginalFileName); // delete any duplicates DeleteFile(szFullLaunchPath); // rename file MoveFile(szOriginalFullLaunchPath,szFullLaunchPath); HINSTANCE hInst = NULL; hInst = ShellExecute(m_hWnd,NULL,szFullLaunchPath,NULL,szTempPath,SW_SHOW); } else { ErrorMessageBox(IDS_WIATESTERROR_UNKNOWN_IMAGEFORMAT); } } LONG CWiatestView::CalculateWidthBytes(LONG lWidthPixels, LONG lbpp) { LONG lWidthBytes = 0; lWidthBytes = (lWidthPixels * lbpp) + 31; lWidthBytes = ((lWidthBytes/8) & 0xfffffffc); return lWidthBytes; } void CWiatestView::OnDeleteItem() { HRESULT hr = S_OK; CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ if(pDocument->m_pICurrentItem != pDocument->m_pIRootItem){ pDocument->m_pICurrentItem->DeleteItem(0); pDocument->m_pICurrentItem->Release(); pDocument->m_pICurrentItem = NULL; // refresh the item tree AddWiaItemsToTreeControl(TVI_ROOT,pDocument->m_pIRootItem); // refresh the properties AddWiaItemPropertiesToListControl(pDocument->m_pIRootItem); } else { ErrorMessageBox(IDS_WIATESTERROR_DELETEROOTITEM); } } } void CWiatestView::OnAcquireimageCommonui() { // delete old temp image files DeleteTempDataTransferFiles(); HRESULT hr = S_OK; IWiaItem **pIWiaItemArray = NULL; LONG lItemCount = 0; CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ hr = pDocument->m_pIRootItem->DeviceDlg(m_hWnd,0,WIA_INTENT_MINIMIZE_SIZE,&lItemCount,&pIWiaItemArray); if(S_OK == hr){ // get temp file name TCHAR szTempFile[MAX_PATH]; memset(szTempFile,0,sizeof(szTempFile)); RC2TSTR(IDS_WIATEST_FILETRANSFER_FILENAME,szTempFile,sizeof(szTempFile)); for(LONG lItem = 0; lItem < lItemCount; lItem++){ // get temp path TCHAR szFileName[MAX_PATH]; memset(szFileName,0,sizeof(szFileName)); GetTempPath(sizeof(szFileName),szFileName); // create new temp file with image index number TCHAR szFinalFileName[MAX_PATH]; memset(szFinalFileName,0,sizeof(szFinalFileName)); TSPRINTF(szFinalFileName,TEXT("%d%s"),lItem,szTempFile); // add new temp file to temp path lstrcat(szFileName,szFinalFileName); // set TYMED_FILE CWiahelper WIA; WIA.SetIWiaItem(pIWiaItemArray[lItem]); hr = WIA.WritePropertyLong(WIA_IPA_TYMED,TYMED_FILE); if (S_OK == hr) { // transfer to this file hr = TransferToFile(szFileName,pIWiaItemArray[lItem]); if ((hr == S_OK)||(WIA_STATUS_END_OF_MEDIA == hr)) { GUID guidFormat; memset(&guidFormat,0,sizeof(guidFormat)); hr = WIA.ReadPropertyGUID(WIA_IPA_FORMAT,&guidFormat); if (S_OK == hr) { RenameTempDataTransferFilesAndLaunchViewer(szFileName,guidFormat,TYMED_FILE); } else { ErrorMessageBox(IDS_WIATESTERROR_READINGFORMAT,hr); } } else if (FAILED(hr)) { ErrorMessageBox(IDS_WIATESTERROR_ACQUISITION,hr); } } else { ErrorMessageBox(IDS_WIATESTERROR_WRITINGTYMED,hr); } // release item after acquisition pIWiaItemArray[lItem]->Release(); } } } } void CWiatestView::OnEditDebugout() { } void CWiatestView::OnUpdateEditDebugout(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_bOutputToDebuggerON); } void CWiatestView::RenameTempDataTransferFilesAndLaunchViewer(TCHAR *szFileName, GUID guidFormat, LONG lTymed) { if(!szFileName) return; TCHAR *pszFileExt = NULL; TCHAR szOriginalFileName[MAX_PATH]; TCHAR szTempPath[MAX_PATH]; memset(szTempPath,0,sizeof(szTempPath)); memset(szOriginalFileName,0,sizeof(szOriginalFileName)); // copy original filename lstrcpy(szOriginalFileName,szFileName); // get temp launch path GetTempPath(sizeof(szTempPath),szTempPath); BOOL bKnownFormat = TRUE; switch(lTymed){ case TYMED_CALLBACK: case TYMED_MULTIPAGE_CALLBACK: pszFileExt = TSTRSTR(szFileName,TEXT("mem")); break; case TYMED_FILE: case TYMED_MULTIPAGE_FILE: pszFileExt = TSTRSTR(szFileName,TEXT("fil")); break; default: break; } if(lstrlen(szFileName) > 0){ if(pszFileExt){ // rename to known image formats if(guidFormat == WiaImgFmt_UNDEFINED) lstrcpy(pszFileExt,TEXT("bmp")); else if(guidFormat == WiaImgFmt_MEMORYBMP) lstrcpy(pszFileExt,TEXT("bmp")); else if(guidFormat == WiaImgFmt_BMP) lstrcpy(pszFileExt,TEXT("bmp")); else if(guidFormat == WiaImgFmt_EMF) lstrcpy(pszFileExt,TEXT("emf")); else if(guidFormat == WiaImgFmt_WMF) lstrcpy(pszFileExt,TEXT("wmf")); else if(guidFormat == WiaImgFmt_JPEG) lstrcpy(pszFileExt,TEXT("jpg")); else if(guidFormat == WiaImgFmt_PNG) lstrcpy(pszFileExt,TEXT("png")); else if(guidFormat == WiaImgFmt_GIF) lstrcpy(pszFileExt,TEXT("gif")); else if(guidFormat == WiaImgFmt_TIFF) lstrcpy(pszFileExt,TEXT("tif")); else if(guidFormat == WiaImgFmt_EXIF) lstrcpy(pszFileExt,TEXT("jpg")); else if(guidFormat == WiaImgFmt_PHOTOCD) lstrcpy(pszFileExt,TEXT("pcd")); else if(guidFormat == WiaImgFmt_FLASHPIX) lstrcpy(pszFileExt,TEXT("fpx")); else { TCHAR szValue[MAX_PATH]; memset(szValue,0,sizeof(szValue)); UCHAR *pwszUUID = NULL; long lErrorCode = UuidToString(&guidFormat,&pwszUUID); //TSPRINTF(szValue,TEXT("%s"),pwszUUID); lstrcpy(szValue,(LPCTSTR)pwszUUID); // (TEXT("(Unknown Image type) GUID: %s"),pwszUUID); // free allocated string RpcStringFree(&pwszUUID); bKnownFormat = FALSE; } } } if(bKnownFormat){ // delete any duplicates DeleteFile(szFileName); // rename file MoveFile(szOriginalFileName,szFileName); HINSTANCE hInst = NULL; hInst = ShellExecute(m_hWnd,NULL,szFileName,NULL,szTempPath,SW_SHOW); } else { ErrorMessageBox(IDS_WIATESTERROR_UNKNOWN_IMAGEFORMAT); } } void CWiatestView::DisplayMissingThumbnail() { //m_hThumbNailBitmap = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_THUMBNAIL_MISSING_BITMAP)); //if(m_hThumbNailBitmap){ // display thumbnail(deleting any old one) HBITMAP hPreviousBitmap = NULL; //hPreviousBitmap = m_ThumbnailPreviewWindow.SetBitmap(m_hThumbNailBitmap); hPreviousBitmap = m_ThumbnailPreviewWindow.GetBitmap(); if(hPreviousBitmap){ DeleteObject(hPreviousBitmap); hPreviousBitmap = NULL; } m_ThumbnailPreviewWindow.Invalidate(); Invalidate(); //} } void CWiatestView::DisplayThumbnail(IWiaItem *pIWiaItem) { if(GET_STIDEVICE_TYPE(m_lDeviceType) == StiDeviceTypeDigitalCamera){ HRESULT hr = S_OK; BYTE *pThumbNail = NULL; CWiahelper WIA; WIA.SetIWiaItem(pIWiaItem); long lThumbNailHeight = 0; long lThumbNailWidth = 0; long lThumbNailSize = 0; // // read thumbnail height // hr = WIA.ReadPropertyLong(WIA_IPC_THUMB_HEIGHT,&lThumbNailHeight); if(hr != S_OK){ if(FAILED(hr)){ ErrorMessageBox(IDS_WIATESTERROR_THUMBNAILHEIGHT,hr); } DisplayMissingThumbnail(); return; } // // read thumbnail width // hr = WIA.ReadPropertyLong(WIA_IPC_THUMB_WIDTH,&lThumbNailWidth); if(hr != S_OK){ if(FAILED(hr)){ ErrorMessageBox(IDS_WIATESTERROR_THUMBNAILWIDTH,hr); } DisplayMissingThumbnail(); return; } // // read thumbnail data // LONG lDataSize = 0; BYTE *pData = NULL; hr = WIA.ReadPropertyData(WIA_IPC_THUMBNAIL,&pData,&lDataSize); if (hr == S_OK) { lThumbNailSize = lThumbNailWidth * lThumbNailHeight * 3; if (lThumbNailSize != lDataSize) { TCHAR szErrorResourceText[MAX_PATH]; memset(szErrorResourceText,0,sizeof(szErrorResourceText)); TCHAR szErrorText[MAX_PATH]; memset(szErrorText,0,sizeof(szErrorText)); RC2TSTR(IDS_WIATESTERROR_PROCESSING_THUMBNAILDATA,szErrorResourceText,sizeof(szErrorResourceText)); TSPRINTF(szErrorText,szErrorResourceText,lThumbNailSize,lDataSize); ErrorMessageBox(szErrorText); // free temp memory if(pData){ GlobalFree(pData); pData = NULL; } DisplayMissingThumbnail(); return; } BITMAPINFO bmi; memset(&bmi,0,sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = lThumbNailWidth; bmi.bmiHeader.biHeight = lThumbNailHeight; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 24; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = 0; bmi.bmiHeader.biXPelsPerMeter = 0; bmi.bmiHeader.biYPelsPerMeter = 0; bmi.bmiHeader.biClrUsed = 0; bmi.bmiHeader.biClrImportant = 0; PBYTE pThumbNailData = NULL; HDC hdc = ::GetDC(NULL); if(hdc){ HDC hdcm = CreateCompatibleDC(hdc); } m_hThumbNailBitmap = CreateDIBSection(hdc,&bmi,DIB_RGB_COLORS,(void **)&pThumbNailData,NULL,0); if(m_hThumbNailBitmap){ memcpy(pThumbNailData,pData,lDataSize); } // free temp memory if(pData){ GlobalFree(pData); pData = NULL; } // display thumbnail(deleting any old one) HBITMAP hPreviousBitmap = NULL; hPreviousBitmap = m_ThumbnailPreviewWindow.SetBitmap(m_hThumbNailBitmap); if(hPreviousBitmap){ DeleteObject(hPreviousBitmap); hPreviousBitmap = NULL; } m_ThumbnailPreviewWindow.Invalidate(); } else if(hr != S_OK){ if(FAILED(hr)){ ErrorMessageBox(IDS_WIATESTERROR_THUMBNAILDATA,hr); } DisplayMissingThumbnail(); return; } } } void CWiatestView::AdjustViewForDeviceType() { // get associated document CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ m_lDeviceType = 0; CWiahelper WIA; HRESULT hr = S_OK; WIA.SetIWiaItem(pDocument->m_pIRootItem); hr = WIA.ReadPropertyLong(WIA_DIP_DEV_TYPE,&m_lDeviceType); if(S_OK == hr){ if(GET_STIDEVICE_TYPE(m_lDeviceType) == StiDeviceTypeScanner){ // disable thumbnail preview window m_ThumbnailPreviewWindow.ShowWindow(SW_HIDE); LONG lDocHandlingSelect = 0; hr = WIA.ReadPropertyLong(WIA_DPS_DOCUMENT_HANDLING_SELECT,&lDocHandlingSelect); if(S_OK == hr){ // enable Document Acquisition settings menu option, and toolbar m_bHasDocumentFeeder = TRUE; } } } else { // error? } } } void CWiatestView::RegisterForEvents() { HRESULT hr = S_OK; IWiaDevMgr *pIWiaDevMgr = NULL; hr = CoCreateInstance(CLSID_WiaDevMgr, NULL, CLSCTX_LOCAL_SERVER, IID_IWiaDevMgr,(void**)&pIWiaDevMgr); if(FAILED(hr)){ // creation of device manager failed, so we can not continue ErrorMessageBox(IDS_WIATESTERROR_COCREATEWIADEVMGR,hr); return; } CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if (pDocument) { // read device ID CWiahelper WIA; WIA.SetIWiaItem(pDocument->m_pIRootItem); BSTR bstrDeviceID = NULL; hr = WIA.ReadPropertyBSTR(WIA_DIP_DEV_ID,&bstrDeviceID); if (FAILED(hr)) { ErrorMessageBox(IDS_WIATESTERROR_DEVICEID,hr); return; } WIA_DEV_CAP DevCap; IEnumWIA_DEV_CAPS* pIEnumWiaDevCaps = NULL; // enumerate all device events supported hr = pDocument->m_pIRootItem->EnumDeviceCapabilities(WIA_DEVICE_EVENTS,&pIEnumWiaDevCaps); if (S_OK == hr) { LONG lEventIndex = 0; IWiaEventCallback* pIWiaEventCallback = NULL; hr = m_WiaEventCallback.QueryInterface(IID_IWiaEventCallback,(void **)&pIWiaEventCallback); if (SUCCEEDED(hr)) { do { memset(&DevCap,0,sizeof(DevCap)); hr = pIEnumWiaDevCaps->Next(1,&DevCap,NULL); if (S_OK == hr) { // DevCap.ulFlags; // DevCap.bstrIcon; // DevCap.bstrCommanline; // DevCap.guid; hr = pIWiaDevMgr->RegisterEventCallbackInterface(0, bstrDeviceID, &DevCap.guid, pIWiaEventCallback, &m_WiaEventCallback.m_pIUnkRelease[lEventIndex]); if (FAILED(hr)) { ErrorMessageBox(IDS_WIATESTERROR_REGISTER_EVENT_CALLBACK,hr); } else { // increment index lEventIndex++; } // free allocated strings if (DevCap.bstrName) { SysFreeString(DevCap.bstrName); } if (DevCap.bstrDescription) { SysFreeString(DevCap.bstrDescription); } } }while (hr == S_OK); } pIEnumWiaDevCaps->Release(); pIEnumWiaDevCaps = NULL; } } pIWiaDevMgr->Release(); pIWiaDevMgr = NULL; //CWnd* pParent = GetParent(); m_WiaEventCallback.SetViewWindowHandle(m_hWnd); } LRESULT CWiatestView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { BOOL bProcessMessage = FALSE; // is it one of the user defined messages?? switch (message) { case WM_DEVICE_DISCONNECTED: case WM_DEVICE_CONNECTED: case WM_ITEM_DELETED: case WM_ITEM_CREATED: case WM_TREE_UPDATED: case WM_STORAGE_CREATED: case WM_STORAGE_DELETED: bProcessMessage = TRUE; break; default: break; } // if it is process it... if (bProcessMessage) { HRESULT hr = S_OK; CWnd *pParent = GetParent(); if (pParent) { CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if (pDocument) { switch (message) { case WM_DEVICE_DISCONNECTED: return pParent->PostMessage(WM_CLOSE,0,0); break; case WM_DEVICE_CONNECTED: break; case WM_ITEM_DELETED: case WM_ITEM_CREATED: case WM_TREE_UPDATED: case WM_STORAGE_CREATED: case WM_STORAGE_DELETED: // refresh the item tree AddWiaItemsToTreeControl(TVI_ROOT,pDocument->m_pIRootItem); // refresh the properties AddWiaItemPropertiesToListControl(pDocument->m_pIRootItem); break; default: break; } } } } // do default processing return CFormView::WindowProc(message, wParam, lParam); } void CWiatestView::OnShowWindow(BOOL bShow, UINT nStatus) { CFormView::OnShowWindow(bShow, nStatus); } void CWiatestView::OnDocumentAcquisitionSettings() { CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if (pDocument) { CWiaDocAcqSettings DocumentAcquisitionSettingsDlg(IDS_WIATEST_DOCUMENT_SETTINGS_TITLE, pDocument->m_pIRootItem); if (DocumentAcquisitionSettingsDlg.DoModal() != IDCANCEL) { // refresh the item tree AddWiaItemsToTreeControl(TVI_ROOT,pDocument->m_pIRootItem); // refresh the properties AddWiaItemPropertiesToListControl(pDocument->m_pIRootItem); } } } void CWiatestView::OnUpdateDocumentAcquisitionSettings(CCmdUI* pCmdUI) { pCmdUI->Enable(m_bHasDocumentFeeder); } void CWiatestView::OnSelchangeSupportedTymedAndFormatListbox() { CWiatestDoc* pDocument = NULL; pDocument = (CWiatestDoc*)m_pDocument; if(pDocument){ TCHAR szTymedAndFormat[MAX_PATH]; memset(szTymedAndFormat,0,sizeof(szTymedAndFormat)); INT iCurrentSelection = 0; iCurrentSelection = m_SupportedTymedAndFormatsListBox.GetCurSel(); if(iCurrentSelection != -1){ m_SupportedTymedAndFormatsListBox.GetText(iCurrentSelection,szTymedAndFormat); // find current TYMED selection (located in selected string) LONG lTymed = TYMED_CALLBACK; if(TSTRSTR(szTymedAndFormat,TEXT("TYMED_CALLBACK")) != NULL){ lTymed = TYMED_CALLBACK; } if(TSTRSTR(szTymedAndFormat,TEXT("TYMED_FILE")) != NULL){ lTymed = TYMED_FILE; } if(TSTRSTR(szTymedAndFormat,TEXT("TYMED_MULTIPAGE_CALLBACK")) != NULL){ lTymed = TYMED_MULTIPAGE_CALLBACK; } if(TSTRSTR(szTymedAndFormat,TEXT("TYMED_MULTIPAGE_FILE")) != NULL){ lTymed = TYMED_MULTIPAGE_FILE; } HRESULT hr = S_OK; CWiahelper WIA; WIA.SetIWiaItem(pDocument->m_pICurrentItem); // write TYMED to device hr = WIA.WritePropertyLong(WIA_IPA_TYMED,lTymed); if (FAILED(hr)){ ErrorMessageBox(IDS_WIATESTERROR_WRITINGTYMED,hr); return; } // find current format selection TCHAR *pszGUID = NULL; // trim off trailing ')' on guid string LONG lLen = 0; lLen = lstrlen(szTymedAndFormat); szTymedAndFormat[(lLen * sizeof(TCHAR)) - sizeof(TCHAR)] = 0; pszGUID = TSTRSTR(szTymedAndFormat,TEXT("(")); if(pszGUID){ pszGUID+=sizeof(TCHAR); // we are on the GUID GUID guidFormat = GUID_NULL; memset(&guidFormat,0,sizeof(guidFormat)); #ifndef UNICODE long lErrorCode = UuidFromString((UCHAR*)pszGUID,&guidFormat); #else WideCharToMultiByte(CP_ACP, 0,pszGUID,-1,szbuffer,MAX_PATH,NULL,NULL); UuidFromString((UCHAR*)szbuffer,&guidFormat); #endif if(guidFormat != GUID_NULL){ hr = WIA.WritePropertyGUID(WIA_IPA_FORMAT,guidFormat); if(SUCCEEDED(hr)){ AddWiaItemPropertiesToListControl(pDocument->m_pICurrentItem); } else { ErrorMessageBox(IDS_WIATESTERROR_WRITINGFORMAT,hr); } } } } } } void CWiatestView::OnThumbnailPreview() { }
38.731343
126
0.547002
npocmaka
32af3355a38b4aaf5e250e11dc330039addb0cf9
2,095
cpp
C++
powermode.cpp
eddiejames/openpower-occ-control-1
bc2f68b9a5cabbdedd988ac14e010d651c685601
[ "Apache-2.0" ]
1
2021-08-10T21:50:06.000Z
2021-08-10T21:50:06.000Z
powermode.cpp
eddiejames/openpower-occ-control-1
bc2f68b9a5cabbdedd988ac14e010d651c685601
[ "Apache-2.0" ]
1
2021-10-19T19:47:53.000Z
2021-10-19T19:47:53.000Z
powermode.cpp
eddiejames/openpower-occ-control-1
bc2f68b9a5cabbdedd988ac14e010d651c685601
[ "Apache-2.0" ]
2
2019-07-16T16:13:01.000Z
2021-10-20T21:41:02.000Z
#include <fmt/core.h> #include <phosphor-logging/log.hpp> #include <powermode.hpp> #include <xyz/openbmc_project/Control/Power/Mode/server.hpp> #include <cassert> #include <regex> namespace open_power { namespace occ { namespace powermode { using namespace phosphor::logging; using Mode = sdbusplus::xyz::openbmc_project::Control::Power::server::Mode; void PowerMode::modeChanged(sdbusplus::message::message& msg) { if (!occStatus.occActive()) { // Nothing to do return; } SysPwrMode pmode = SysPwrMode::NO_CHANGE; std::map<std::string, std::variant<std::string>> properties{}; std::string interface; std::string propVal; msg.read(interface, properties); const auto modeEntry = properties.find(POWER_MODE_PROP); if (modeEntry != properties.end()) { auto modeEntryValue = modeEntry->second; propVal = std::get<std::string>(modeEntryValue); pmode = convertStringToMode(propVal); if (pmode != SysPwrMode::NO_CHANGE) { log<level::INFO>( fmt::format("Power Mode Change Requested: {}", propVal) .c_str()); // Trigger mode change to OCC occStatus.sendModeChange(); } } return; } // Convert PowerMode string to OCC SysPwrMode SysPwrMode convertStringToMode(const std::string& i_modeString) { SysPwrMode pmode = SysPwrMode::NO_CHANGE; Mode::PowerMode mode = Mode::convertPowerModeFromString(i_modeString); if (mode == Mode::PowerMode::MaximumPerformance) { pmode = SysPwrMode::MAX_PERF; } else if (mode == Mode::PowerMode::PowerSaving) { pmode = SysPwrMode::POWER_SAVING; } else if (mode == Mode::PowerMode::Static) { pmode = SysPwrMode::DISABLE; } else { log<level::ERR>( fmt::format("convertStringToMode: Invalid Power Mode specified: {}", i_modeString) .c_str()); } return pmode; } } // namespace powermode } // namespace occ } // namespace open_power
23.539326
80
0.623389
eddiejames
32b0095056c444d81f3846253150025d0ec460d9
1,673
hpp
C++
util/logging.hpp
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
util/logging.hpp
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
util/logging.hpp
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
1
2020-10-04T22:14:55.000Z
2020-10-04T22:14:55.000Z
#pragma once /* Logging functions and macros used by all rsked applications. */ /* Part of the rsked package. * * Copyright 2020 Steven A. Harp * * 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. * */ /// Load this before any other boost logging headers /// must define this to use the shared lib #define BOOST_LOG_DYN_LINK 1 #include <boost/log/trivial.hpp> #include <boost/log/sources/severity_logger.hpp> namespace lt = boost::log::trivial; using rsked_logger_t=boost::log::sources::severity_logger<lt::severity_level>; extern rsked_logger_t Lgr; // global log source #define LOG_DEBUG(_logger) BOOST_LOG_SEV(_logger,lt::debug) #define LOG_INFO(_logger) BOOST_LOG_SEV(_logger,lt::info) #define LOG_WARNING(_logger) BOOST_LOG_SEV(_logger,lt::warning) #define LOG_ERROR(_logger) BOOST_LOG_SEV(_logger,lt::error) /* Bit flags to pass init_logging to enable FILE and/or CONSOLE backends * and to enable debug messages. */ #define LF_FILE 1 #define LF_CONSOLE 2 #define LF_DEBUG 4 void init_logging(const char* /*appname*/, const char* /* "rsked_%5N.log" */, int flags=LF_FILE); void finish_logging();
30.981481
78
0.73162
farlies
32b0d7ad2c5ae1910e4a9e345a6279e42bae61d6
669
cpp
C++
test/forty_two.cpp
vinniefalco/library-template
8fa8395d917163c29b9ecc21145ba78028b724da
[ "BSL-1.0" ]
6
2020-03-02T22:40:17.000Z
2020-03-09T20:49:24.000Z
test/forty_two.cpp
vinniefalco/library-template
8fa8395d917163c29b9ecc21145ba78028b724da
[ "BSL-1.0" ]
1
2020-12-01T20:01:36.000Z
2020-12-01T20:01:36.000Z
test/forty_two.cpp
vinniefalco/library-template
8fa8395d917163c29b9ecc21145ba78028b724da
[ "BSL-1.0" ]
1
2020-11-30T22:29:51.000Z
2020-11-30T22:29:51.000Z
// // Copyright (c) 2020 Vinnie Falco (vinnie.falco@gmail.com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/vinniefalco/library_template // // Test that header file is self-contained. #include <boost/library_template/forty_two.hpp> #include "test_suite.hpp" namespace boost { namespace library_template { class forty_two_test { public: void run() { BOOST_TEST(forty_two() == 42); } }; TEST_SUITE(forty_two_test, "boost.library_template.forty_two"); } // library_template } // boost
20.90625
79
0.718984
vinniefalco
32b3ed3d609f2e874e79a1eb38b24d97ab1952fe
839
cpp
C++
C/common/string_utils.cpp
ashish-ScaleDB/FogLAMP
fd52bc53f6a10752acdb1c549279dcaa406893a5
[ "Apache-2.0" ]
1
2020-09-10T11:34:04.000Z
2020-09-10T11:34:04.000Z
C/common/string_utils.cpp
YashTatkondawar/FogLAMP
6a3a6d45db9c9f0058110252202826e9859ccfa1
[ "Apache-2.0" ]
1
2017-09-06T14:05:21.000Z
2017-09-06T14:05:21.000Z
C/common/string_utils.cpp
YashTatkondawar/FogLAMP
6a3a6d45db9c9f0058110252202826e9859ccfa1
[ "Apache-2.0" ]
null
null
null
/* * FogLAMP utilities functions for handling JSON document * * Copyright (c) 2018 Dianomic Systems * * Released under the Apache 2.0 Licence * * Author: Stefano Simonelli */ #include <iostream> #include <string> #include "string_utils.h" using namespace std; /** * Search and replace a string * * @param out StringToManage string in which apply the search and replacement * @param StringToSearch string to search and replace * @param StringToReplace substitution string * */ void StringReplace(std::string& StringToManage, const std::string& StringToSearch, const std::string& StringReplacement) { if (StringToManage.find(StringToSearch) != string::npos) { StringToManage.replace(StringToManage.find(StringToSearch), StringToSearch.length(), StringReplacement); } }
22.675676
80
0.709178
ashish-ScaleDB
32be67a5dc1a4a37e175de639614a6c71929c546
2,995
cpp
C++
Algorithms/0576.OutOfBoundaryPaths/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0576.OutOfBoundaryPaths/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0576.OutOfBoundaryPaths/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> #include "gtest/gtest.h" namespace { class Solution { public: int findPaths(int m, int n, int N, int i, int j) const { if (N == 0) return 0; size_t outPathsCount = 0; const size_t storageSize = static_cast<size_t>(m) * n; std::vector<size_t> current(storageSize, 0); // first step initStorage(m, n, i, j, current, outPathsCount); if (N == 1) return static_cast<int>(outPathsCount); std::vector<size_t> next(storageSize, 0); for (size_t step = 2; step <= static_cast<size_t>(N); ++step) { std::fill(next.begin(), next.end(), 0); for (size_t index = 0; index < current.size(); ++index) { const size_t row = index / n; const size_t column = index % n; if (current[index] != 0) processCell(m, n, row, column, current, next, outPathsCount); } std::swap(current, next); } return static_cast<int>(outPathsCount); } private: constexpr static size_t ModValue = 1000000007; void initStorage(size_t m, size_t n, size_t i, size_t j, std::vector<size_t> &current, size_t &outPathsCount) const { if (i > 0) current[(i - 1) * n + j] = 1; else ++outPathsCount; if (i < (m - 1)) current[(i + 1) * n + j] = 1; else ++outPathsCount; if (j > 0) current[i * n + (j - 1)] = 1; else ++outPathsCount; if (j < (n - 1)) current[i * n + (j + 1)] = 1; else ++outPathsCount; } void processCell(size_t m, size_t n, size_t i, size_t j, std::vector<size_t> const &current, std::vector<size_t> &next, size_t&outPathsCount) const { const size_t currentPathsCount = current[i * n + j]; if (i > 0) next[(i - 1) * n + j] = (next[(i - 1) * n + j] + currentPathsCount) % ModValue; else outPathsCount = (outPathsCount + currentPathsCount) % ModValue; if (i < (m - 1)) next[(i + 1) * n + j] = (next[(i + 1) * n + j] + currentPathsCount) % ModValue; else outPathsCount = (outPathsCount + currentPathsCount) % ModValue; if (j > 0) next[i * n + (j - 1)] = (next[i * n + (j - 1)] + currentPathsCount) % ModValue; else outPathsCount = (outPathsCount + currentPathsCount) % ModValue; if (j < (n - 1)) next[i * n + (j + 1)] = (next[i * n + (j + 1)] + currentPathsCount) % ModValue; else outPathsCount = (outPathsCount + currentPathsCount) % ModValue; } }; } namespace OutOfBoundaryPathsTask { TEST(OutOfBoundaryPathsTaskTests, Examples) { const Solution solution; ASSERT_EQ(6, solution.findPaths(2, 2, 2, 0, 0)); ASSERT_EQ(12, solution.findPaths(1, 3, 3, 0, 1)); } }
31.197917
151
0.52187
stdstring
32c39ab5131ad707f6a922aff6697cbd0ace3949
2,732
cpp
C++
PATA1017.cpp
Geeks-Z/PAT-Advanced-Level-Practice
6b25d07ae602310215e46c951638b93080b382bf
[ "MIT" ]
null
null
null
PATA1017.cpp
Geeks-Z/PAT-Advanced-Level-Practice
6b25d07ae602310215e46c951638b93080b382bf
[ "MIT" ]
null
null
null
PATA1017.cpp
Geeks-Z/PAT-Advanced-Level-Practice
6b25d07ae602310215e46c951638b93080b382bf
[ "MIT" ]
null
null
null
/* * @Descripttion: * @version: 1.0 * @Author: Geeks_Z * @Date: 2021-05-13 10:20:55 * @LastEditors: Geeks_Z * @LastEditTime: 2021-05-30 21:33:19 */ #include <cstdio> #include <iostream> #include <vector> using namespace std; const int MAXN = 501; const int INF = 100010; bool vis[MAXN] = {false}; //连接矩阵 起点到该点最短距离 点权 station数量 自行车数量 第二标尺最优值 int G[MAXN][MAXN], dis[MAXN], weight[MAXN], n, minNeed = INF, capacity, minBack = INF; //最优路径 临时路径 vector<int> path[MAXN], tempPath, bestPath; void dijkstra(int s) { fill(dis, dis + n + 1, INF); dis[s] = 0; for (int i = 0; i < n + 1; i++) { //找到最小的u int u = -1, min = INF; for (int j = 0; j < n + 1; j++) { if (vis[j] == false && dis[j] < min) { u = j; min = dis[j]; } } if (u == -1) { return; } vis[u] = true; for (int v = 0; v < n + 1; v++) { if (vis[v] == false && G[u][v] != INF) { if (dis[u] + G[u][v] < dis[v]) { dis[v] = dis[u] + G[u][v]; path[v].clear(); path[v].push_back(u); } else if (dis[u] + G[u][v] == dis[v]) { path[v].push_back(u); } } } } } /** * @Descripttion: 输出路径 * @param {int} s 起点 * @param {int} v 当前访问的结点 * @return {*} */ void DFS(int v) { tempPath.push_back(v); if (v == 0) { int need = 0, back = 0; for (int i = tempPath.size() - 1; i >= 0; i--) { int id = tempPath[i]; if (weight[id] > 0) { back += weight[id]; } else { //携带的数量能够满足当前station的需求 if (back > (0 - weight[id])) { back += weight[id]; } else { //出去目前携带的 还应该携带的 need += ((0 - weight[id]) - back); back = 0; } } } if (need < minNeed) { minNeed = need; minBack = back; bestPath = tempPath; } else if (need == minNeed && back < minBack) { minBack = back; bestPath = tempPath; } tempPath.pop_back(); return; } for (int i = 0; i < path[v].size(); i++) { DFS(path[v][i]); } tempPath.pop_back(); } int main() { // freopen("input.txt", "r", stdin); fill(G[0], G[0] + MAXN * MAXN, INF); int sp, m; cin >> capacity >> n >> sp >> m; for (int i = 1; i <= n; i++) { scanf("%d", &weight[i]); weight[i] = weight[i] - capacity / 2; } int s1, s2, time; for (int i = 0; i < m; i++) { cin >> s1 >> s2 >> time; G[s1][s2] = G[s2][s1] = time; } dijkstra(0); DFS(sp); printf("%d 0", minNeed); for (int i = bestPath.size() - 2; i >= 0; i--) printf("->%d", bestPath[i]); printf(" %d", minBack); return 0; }
18.841379
86
0.453148
Geeks-Z
32c49cffb08f92d04c4f2794fcc658344e531edf
695
hpp
C++
NWNXLib/API/Linux/API/CExoLinkedListTemplatedCERFRes.hpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
1
2019-06-04T04:30:24.000Z
2019-06-04T04:30:24.000Z
NWNXLib/API/Linux/API/CExoLinkedListTemplatedCERFRes.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
null
null
null
NWNXLib/API/Linux/API/CExoLinkedListTemplatedCERFRes.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
1
2019-10-20T07:54:45.000Z
2019-10-20T07:54:45.000Z
#pragma once #include <cstdint> namespace NWNXLib { namespace API { // Forward class declarations (defined in the source file) struct CExoLinkedListInternal; struct CExoLinkedListTemplatedCERFRes { CExoLinkedListInternal* m_pcExoLinkedListInternal; // The below are auto generated stubs. CExoLinkedListTemplatedCERFRes() = default; CExoLinkedListTemplatedCERFRes(const CExoLinkedListTemplatedCERFRes&) = default; CExoLinkedListTemplatedCERFRes& operator=(const CExoLinkedListTemplatedCERFRes&) = default; ~CExoLinkedListTemplatedCERFRes(); }; void CExoLinkedListTemplatedCERFRes__CExoLinkedListTemplatedCERFResDtor(CExoLinkedListTemplatedCERFRes* thisPtr); } }
23.965517
113
0.811511
acaos
32c5d68b9d08b4efec7cf2a0bf90bc9ea057716c
4,024
cpp
C++
wpimath/src/test/native/cpp/geometry/Translation3dTest.cpp
frc1418/allwpilib
a4787130f4434f00f4800b23e815105b022c4783
[ "BSD-3-Clause" ]
null
null
null
wpimath/src/test/native/cpp/geometry/Translation3dTest.cpp
frc1418/allwpilib
a4787130f4434f00f4800b23e815105b022c4783
[ "BSD-3-Clause" ]
null
null
null
wpimath/src/test/native/cpp/geometry/Translation3dTest.cpp
frc1418/allwpilib
a4787130f4434f00f4800b23e815105b022c4783
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include <cmath> #include "frc/geometry/Translation3d.h" #include "gtest/gtest.h" using namespace frc; static constexpr double kEpsilon = 1E-9; TEST(Translation3dTest, Sum) { const Translation3d one{1_m, 3_m, 5_m}; const Translation3d two{2_m, 5_m, 8_m}; const auto sum = one + two; EXPECT_NEAR(3.0, sum.X().value(), kEpsilon); EXPECT_NEAR(8.0, sum.Y().value(), kEpsilon); EXPECT_NEAR(13.0, sum.Z().value(), kEpsilon); } TEST(Translation3dTest, Difference) { const Translation3d one{1_m, 3_m, 5_m}; const Translation3d two{2_m, 5_m, 8_m}; const auto difference = one - two; EXPECT_NEAR(difference.X().value(), -1.0, kEpsilon); EXPECT_NEAR(difference.Y().value(), -2.0, kEpsilon); EXPECT_NEAR(difference.Z().value(), -3.0, kEpsilon); } TEST(Translation3dTest, RotateBy) { Eigen::Vector3d xAxis{1.0, 0.0, 0.0}; Eigen::Vector3d yAxis{0.0, 1.0, 0.0}; Eigen::Vector3d zAxis{0.0, 0.0, 1.0}; const Translation3d translation{1_m, 2_m, 3_m}; const auto rotated1 = translation.RotateBy(Rotation3d{xAxis, 90_deg}); EXPECT_NEAR(rotated1.X().value(), 1.0, kEpsilon); EXPECT_NEAR(rotated1.Y().value(), -3.0, kEpsilon); EXPECT_NEAR(rotated1.Z().value(), 2.0, kEpsilon); const auto rotated2 = translation.RotateBy(Rotation3d{yAxis, 90_deg}); EXPECT_NEAR(rotated2.X().value(), 3.0, kEpsilon); EXPECT_NEAR(rotated2.Y().value(), 2.0, kEpsilon); EXPECT_NEAR(rotated2.Z().value(), -1.0, kEpsilon); const auto rotated3 = translation.RotateBy(Rotation3d{zAxis, 90_deg}); EXPECT_NEAR(rotated3.X().value(), -2.0, kEpsilon); EXPECT_NEAR(rotated3.Y().value(), 1.0, kEpsilon); EXPECT_NEAR(rotated3.Z().value(), 3.0, kEpsilon); } TEST(Translation3dTest, ToTranslation2d) { Translation3d translation{1_m, 2_m, 3_m}; Translation2d expected{1_m, 2_m}; EXPECT_EQ(expected, translation.ToTranslation2d()); } TEST(Translation3dTest, Multiplication) { const Translation3d original{3_m, 5_m, 7_m}; const auto mult = original * 3; EXPECT_NEAR(mult.X().value(), 9.0, kEpsilon); EXPECT_NEAR(mult.Y().value(), 15.0, kEpsilon); EXPECT_NEAR(mult.Z().value(), 21.0, kEpsilon); } TEST(Translation3dTest, Division) { const Translation3d original{3_m, 5_m, 7_m}; const auto div = original / 2; EXPECT_NEAR(div.X().value(), 1.5, kEpsilon); EXPECT_NEAR(div.Y().value(), 2.5, kEpsilon); EXPECT_NEAR(div.Z().value(), 3.5, kEpsilon); } TEST(Translation3dTest, Norm) { const Translation3d one{3_m, 5_m, 7_m}; EXPECT_NEAR(one.Norm().value(), std::hypot(3, 5, 7), kEpsilon); } TEST(Translation3dTest, Distance) { const Translation3d one{1_m, 1_m, 1_m}; const Translation3d two{6_m, 6_m, 6_m}; EXPECT_NEAR(one.Distance(two).value(), 5 * std::sqrt(3), kEpsilon); } TEST(Translation3dTest, UnaryMinus) { const Translation3d original{-4.5_m, 7_m, 9_m}; const auto inverted = -original; EXPECT_NEAR(inverted.X().value(), 4.5, kEpsilon); EXPECT_NEAR(inverted.Y().value(), -7, kEpsilon); EXPECT_NEAR(inverted.Z().value(), -9, kEpsilon); } TEST(Translation3dTest, Equality) { const Translation3d one{9_m, 5.5_m, 3.5_m}; const Translation3d two{9_m, 5.5_m, 3.5_m}; EXPECT_TRUE(one == two); } TEST(Translation3dTest, Inequality) { const Translation3d one{9_m, 5.5_m, 3.5_m}; const Translation3d two{9_m, 5.7_m, 3.5_m}; EXPECT_TRUE(one != two); } TEST(Translation3dTest, PolarConstructor) { Eigen::Vector3d zAxis{0.0, 0.0, 1.0}; Translation3d one{std::sqrt(2) * 1_m, Rotation3d(zAxis, 45_deg)}; EXPECT_NEAR(one.X().value(), 1.0, kEpsilon); EXPECT_NEAR(one.Y().value(), 1.0, kEpsilon); EXPECT_NEAR(one.Z().value(), 0.0, kEpsilon); Translation3d two{2_m, Rotation3d(zAxis, 60_deg)}; EXPECT_NEAR(two.X().value(), 1.0, kEpsilon); EXPECT_NEAR(two.Y().value(), std::sqrt(3.0), kEpsilon); EXPECT_NEAR(two.Z().value(), 0.0, kEpsilon); }
31.193798
74
0.694583
frc1418
32c781b3614915d5dd36d907d45946d4e230d68e
2,403
cpp
C++
NULL Engine/Source/R_Texture.cpp
BarcinoLechiguino/NULL_Engine
f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3
[ "MIT" ]
4
2020-11-29T12:28:31.000Z
2021-06-08T17:32:56.000Z
NULL Engine/Source/R_Texture.cpp
BarcinoLechiguino/NULL_Engine
f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3
[ "MIT" ]
null
null
null
NULL Engine/Source/R_Texture.cpp
BarcinoLechiguino/NULL_Engine
f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3
[ "MIT" ]
4
2020-11-01T17:06:32.000Z
2021-01-09T16:58:50.000Z
#include "OpenGL.h" #include "VariableTypedefs.h" #include "JSONParser.h" #include "R_Texture.h" R_Texture::R_Texture() : Resource(RESOURCE_TYPE::TEXTURE) { } R_Texture::~R_Texture() { } bool R_Texture::CleanUp() { bool ret = true; glDeleteTextures(1, (GLuint*)&tex_data.id); return ret; } bool R_Texture::SaveMeta(ParsonNode& meta_root) const { bool ret = true; ParsonArray contained_array = meta_root.SetArray("ContainedResources"); ParsonNode settings = meta_root.SetNode("ImportSettings"); texture_settings.Save(settings); return ret; } bool R_Texture::LoadMeta(const ParsonNode& meta_root) { bool ret = true; return ret; } // --- R_TEXTURE METHODS --- Texture R_Texture::GetTextureData() const { return tex_data; } void R_Texture::SetTextureData(uint id, uint width, uint height, uint depth, uint bpp, uint bytes, TEXTURE_FORMAT format, bool compressed) { tex_data.id = id; tex_data.width = width; tex_data.height = height; tex_data.depth = depth; tex_data.bpp = bpp; tex_data.bytes = bytes; tex_data.format = format; tex_data.compressed = compressed; } uint R_Texture::GetTextureID() const { return tex_data.id; } uint R_Texture::GetTextureWidth() const { return tex_data.width; } uint R_Texture::GetTextureHeight() const { return tex_data.height; } uint R_Texture::GetTextureDepth() const { return tex_data.depth; } uint R_Texture::GetTextureBpp() const { return tex_data.bpp; } uint R_Texture::GetTextureBytes() const { return tex_data.bytes; } TEXTURE_FORMAT R_Texture::GetTextureFormat() const { return tex_data.format; } bool R_Texture::TextureIsCompressed() const { return tex_data.compressed; } const char* R_Texture::GetTextureFormatString() const { switch (tex_data.format) { case TEXTURE_FORMAT::UNKNOWN: { return "UNKNOWN"; } break; case TEXTURE_FORMAT::COLOUR_INDEX: { return "COLOUR_INDEX"; } break; case TEXTURE_FORMAT::RGB: { return "RGB"; } break; case TEXTURE_FORMAT::RGBA: { return "RGBA"; } break; case TEXTURE_FORMAT::BGR: { return "BGR"; } break; case TEXTURE_FORMAT::BGRA: { return "BGRA"; } break; case TEXTURE_FORMAT::LUMINANCE: { return "LUMINANCE"; } break; } return "NONE"; } // --- TEXTURE STRUCT METHODS --- Texture::Texture() { id = 0; width = 0; height = 0; depth = 0; bpp = 0; bytes = 0; format = TEXTURE_FORMAT::UNKNOWN; compressed = true; }
17.8
138
0.707033
BarcinoLechiguino
32cd47a750a6e5e362d342f372e5150b3d689d2d
248,622
cc
C++
runtime/verifier/method_verifier.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
20
2021-06-24T16:38:42.000Z
2022-01-20T16:15:57.000Z
runtime/verifier/method_verifier.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
null
null
null
runtime/verifier/method_verifier.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
4
2021-11-03T06:01:12.000Z
2022-02-24T02:57:31.000Z
/* * Copyright (C) 2011 The Android Open Source Project * * 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 "method_verifier-inl.h" #include <ostream> #include "android-base/stringprintf.h" #include "art_field-inl.h" #include "art_method-inl.h" #include "base/aborting.h" #include "base/enums.h" #include "base/leb128.h" #include "base/indenter.h" #include "base/logging.h" // For VLOG. #include "base/mutex-inl.h" #include "base/sdk_version.h" #include "base/stl_util.h" #include "base/systrace.h" #include "base/time_utils.h" #include "base/utils.h" #include "class_linker.h" #include "class_root.h" #include "compiler_callbacks.h" #include "dex/class_accessor-inl.h" #include "dex/descriptors_names.h" #include "dex/dex_file-inl.h" #include "dex/dex_file_exception_helpers.h" #include "dex/dex_instruction-inl.h" #include "dex/dex_instruction_utils.h" #include "experimental_flags.h" #include "gc/accounting/card_table-inl.h" #include "handle_scope-inl.h" #include "intern_table.h" #include "mirror/class-inl.h" #include "mirror/class.h" #include "mirror/class_loader.h" #include "mirror/dex_cache-inl.h" #include "mirror/method_handle_impl.h" #include "mirror/method_type.h" #include "mirror/object-inl.h" #include "mirror/object_array-inl.h" #include "mirror/var_handle.h" #include "obj_ptr-inl.h" #include "reg_type-inl.h" #include "register_line-inl.h" #include "runtime.h" #include "scoped_newline.h" #include "scoped_thread_state_change-inl.h" #include "stack.h" #include "vdex_file.h" #include "verifier_compiler_binding.h" #include "verifier_deps.h" namespace art { namespace verifier { using android::base::StringPrintf; static constexpr bool kTimeVerifyMethod = !kIsDebugBuild; PcToRegisterLineTable::PcToRegisterLineTable(ScopedArenaAllocator& allocator) : register_lines_(allocator.Adapter(kArenaAllocVerifier)) {} void PcToRegisterLineTable::Init(RegisterTrackingMode mode, InstructionFlags* flags, uint32_t insns_size, uint16_t registers_size, ScopedArenaAllocator& allocator, RegTypeCache* reg_types) { DCHECK_GT(insns_size, 0U); register_lines_.resize(insns_size); for (uint32_t i = 0; i < insns_size; i++) { bool interesting = false; switch (mode) { case kTrackRegsAll: interesting = flags[i].IsOpcode(); break; case kTrackCompilerInterestPoints: interesting = flags[i].IsCompileTimeInfoPoint() || flags[i].IsBranchTarget(); break; case kTrackRegsBranches: interesting = flags[i].IsBranchTarget(); break; default: break; } if (interesting) { register_lines_[i].reset(RegisterLine::Create(registers_size, allocator, reg_types)); } } } PcToRegisterLineTable::~PcToRegisterLineTable() {} namespace impl { namespace { enum class CheckAccess { kYes, kNo, }; enum class FieldAccessType { kAccGet, kAccPut }; template <bool kVerifierDebug> class MethodVerifier final : public ::art::verifier::MethodVerifier { public: bool IsInstanceConstructor() const { return IsConstructor() && !IsStatic(); } const RegType& ResolveCheckedClass(dex::TypeIndex class_idx) override REQUIRES_SHARED(Locks::mutator_lock_) { DCHECK(!HasFailures()); const RegType& result = ResolveClass<CheckAccess::kYes>(class_idx); DCHECK(!HasFailures()); return result; } void FindLocksAtDexPc() REQUIRES_SHARED(Locks::mutator_lock_); private: MethodVerifier(Thread* self, const DexFile* dex_file, Handle<mirror::DexCache> dex_cache, Handle<mirror::ClassLoader> class_loader, const dex::ClassDef& class_def, const dex::CodeItem* code_item, uint32_t method_idx, ArtMethod* method, uint32_t access_flags, bool can_load_classes, bool allow_soft_failures, bool need_precise_constants, bool verify_to_dump, bool allow_thread_suspension, uint32_t api_level) REQUIRES_SHARED(Locks::mutator_lock_); void UninstantiableError(const char* descriptor) { Fail(VerifyError::VERIFY_ERROR_NO_CLASS) << "Could not create precise reference for " << "non-instantiable klass " << descriptor; } static bool IsInstantiableOrPrimitive(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) { return klass->IsInstantiable() || klass->IsPrimitive(); } // Is the method being verified a constructor? See the comment on the field. bool IsConstructor() const { return is_constructor_; } // Is the method verified static? bool IsStatic() const { return (method_access_flags_ & kAccStatic) != 0; } // Adds the given string to the beginning of the last failure message. void PrependToLastFailMessage(std::string); // Adds the given string to the end of the last failure message. void AppendToLastFailMessage(const std::string& append); /* * Compute the width of the instruction at each address in the instruction stream, and store it in * insn_flags_. Addresses that are in the middle of an instruction, or that are part of switch * table data, are not touched (so the caller should probably initialize "insn_flags" to zero). * * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are also set. * * Performs some static checks, notably: * - opcode of first instruction begins at index 0 * - only documented instructions may appear * - each instruction follows the last * - last byte of last instruction is at (code_length-1) * * Logs an error and returns "false" on failure. */ bool ComputeWidthsAndCountOps(); /* * Set the "in try" flags for all instructions protected by "try" statements. Also sets the * "branch target" flags for exception handlers. * * Call this after widths have been set in "insn_flags". * * Returns "false" if something in the exception table looks fishy, but we're expecting the * exception table to be somewhat sane. */ bool ScanTryCatchBlocks() REQUIRES_SHARED(Locks::mutator_lock_); /* * Perform static verification on all instructions in a method. * * Walks through instructions in a method calling VerifyInstruction on each. */ template <bool kAllowRuntimeOnlyInstructions> bool VerifyInstructions(); /* * Perform static verification on an instruction. * * As a side effect, this sets the "branch target" flags in InsnFlags. * * "(CF)" items are handled during code-flow analysis. * * v3 4.10.1 * - target of each jump and branch instruction must be valid * - targets of switch statements must be valid * - operands referencing constant pool entries must be valid * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid * - (CF) operands of method invocation instructions must be valid * - (CF) only invoke-direct can call a method starting with '<' * - (CF) <clinit> must never be called explicitly * - operands of instanceof, checkcast, new (and variants) must be valid * - new-array[-type] limited to 255 dimensions * - can't use "new" on an array class * - (?) limit dimensions in multi-array creation * - local variable load/store register values must be in valid range * * v3 4.11.1.2 * - branches must be within the bounds of the code array * - targets of all control-flow instructions are the start of an instruction * - register accesses fall within range of allocated registers * - (N/A) access to constant pool must be of appropriate type * - code does not end in the middle of an instruction * - execution cannot fall off the end of the code * - (earlier) for each exception handler, the "try" area must begin and * end at the start of an instruction (end can be at the end of the code) * - (earlier) for each exception handler, the handler must start at a valid * instruction */ template <bool kAllowRuntimeOnlyInstructions> bool VerifyInstruction(const Instruction* inst, uint32_t code_offset); /* Ensure that the register index is valid for this code item. */ bool CheckRegisterIndex(uint32_t idx); /* Ensure that the wide register index is valid for this code item. */ bool CheckWideRegisterIndex(uint32_t idx); // Perform static checks on an instruction referencing a CallSite. All we do here is ensure that // the call site index is in the valid range. bool CheckCallSiteIndex(uint32_t idx); // Perform static checks on a field Get or set instruction. All we do here is ensure that the // field index is in the valid range. bool CheckFieldIndex(uint32_t idx); // Perform static checks on a method invocation instruction. All we do here is ensure that the // method index is in the valid range. bool CheckMethodIndex(uint32_t idx); // Perform static checks on an instruction referencing a constant method handle. All we do here // is ensure that the method index is in the valid range. bool CheckMethodHandleIndex(uint32_t idx); // Perform static checks on a "new-instance" instruction. Specifically, make sure the class // reference isn't for an array class. bool CheckNewInstance(dex::TypeIndex idx); // Perform static checks on a prototype indexing instruction. All we do here is ensure that the // prototype index is in the valid range. bool CheckPrototypeIndex(uint32_t idx); /* Ensure that the string index is in the valid range. */ bool CheckStringIndex(uint32_t idx); // Perform static checks on an instruction that takes a class constant. Ensure that the class // index is in the valid range. bool CheckTypeIndex(dex::TypeIndex idx); // Perform static checks on a "new-array" instruction. Specifically, make sure they aren't // creating an array of arrays that causes the number of dimensions to exceed 255. bool CheckNewArray(dex::TypeIndex idx); // Verify an array data table. "cur_offset" is the offset of the fill-array-data instruction. bool CheckArrayData(uint32_t cur_offset); // Verify that the target of a branch instruction is valid. We don't expect code to jump directly // into an exception handler, but it's valid to do so as long as the target isn't a // "move-exception" instruction. We verify that in a later stage. // The dex format forbids certain instructions from branching to themselves. // Updates "insn_flags_", setting the "branch target" flag. bool CheckBranchTarget(uint32_t cur_offset); // Verify a switch table. "cur_offset" is the offset of the switch instruction. // Updates "insn_flags_", setting the "branch target" flag. bool CheckSwitchTargets(uint32_t cur_offset); // Check the register indices used in a "vararg" instruction, such as invoke-virtual or // filled-new-array. // - vA holds word count (0-5), args[] have values. // There are some tests we don't do here, e.g. we don't try to verify that invoking a method that // takes a double is done with consecutive registers. This requires parsing the target method // signature, which we will be doing later on during the code flow analysis. bool CheckVarArgRegs(uint32_t vA, uint32_t arg[]); // Check the register indices used in a "vararg/range" instruction, such as invoke-virtual/range // or filled-new-array/range. // - vA holds word count, vC holds index of first reg. bool CheckVarArgRangeRegs(uint32_t vA, uint32_t vC); // Checks the method matches the expectations required to be signature polymorphic. bool CheckSignaturePolymorphicMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_); // Checks the invoked receiver matches the expectations for signature polymorphic methods. bool CheckSignaturePolymorphicReceiver(const Instruction* inst) REQUIRES_SHARED(Locks::mutator_lock_); // Extract the relative offset from a branch instruction. // Returns "false" on failure (e.g. this isn't a branch instruction). bool GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional, bool* selfOkay); /* Perform detailed code-flow analysis on a single method. */ bool VerifyCodeFlow() REQUIRES_SHARED(Locks::mutator_lock_); // Set the register types for the first instruction in the method based on the method signature. // This has the side-effect of validating the signature. bool SetTypesFromSignature() REQUIRES_SHARED(Locks::mutator_lock_); /* * Perform code flow on a method. * * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit on the first * instruction, process it (setting additional "changed" bits), and repeat until there are no * more. * * v3 4.11.1.1 * - (N/A) operand stack is always the same size * - operand stack [registers] contain the correct types of values * - local variables [registers] contain the correct types of values * - methods are invoked with the appropriate arguments * - fields are assigned using values of appropriate types * - opcodes have the correct type values in operand registers * - there is never an uninitialized class instance in a local variable in code protected by an * exception handler (operand stack is okay, because the operand stack is discarded when an * exception is thrown) [can't know what's a local var w/o the debug info -- should fall out of * register typing] * * v3 4.11.1.2 * - execution cannot fall off the end of the code * * (We also do many of the items described in the "static checks" sections, because it's easier to * do them here.) * * We need an array of RegType values, one per register, for every instruction. If the method uses * monitor-enter, we need extra data for every register, and a stack for every "interesting" * instruction. In theory this could become quite large -- up to several megabytes for a monster * function. * * NOTE: * The spec forbids backward branches when there's an uninitialized reference in a register. The * idea is to prevent something like this: * loop: * move r1, r0 * new-instance r0, MyClass * ... * if-eq rN, loop // once * initialize r0 * * This leaves us with two different instances, both allocated by the same instruction, but only * one is initialized. The scheme outlined in v3 4.11.1.4 wouldn't catch this, so they work around * it by preventing backward branches. We achieve identical results without restricting code * reordering by specifying that you can't execute the new-instance instruction if a register * contains an uninitialized instance created by that same instruction. */ bool CodeFlowVerifyMethod() REQUIRES_SHARED(Locks::mutator_lock_); /* * Perform verification for a single instruction. * * This requires fully decoding the instruction to determine the effect it has on registers. * * Finds zero or more following instructions and sets the "changed" flag if execution at that * point needs to be (re-)evaluated. Register changes are merged into "reg_types_" at the target * addresses. Does not set or clear any other flags in "insn_flags_". */ bool CodeFlowVerifyInstruction(uint32_t* start_guess) REQUIRES_SHARED(Locks::mutator_lock_); // Perform verification of a new array instruction void VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range) REQUIRES_SHARED(Locks::mutator_lock_); // Helper to perform verification on puts of primitive type. void VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type, const uint32_t vregA) REQUIRES_SHARED(Locks::mutator_lock_); // Perform verification of an aget instruction. The destination register's type will be set to // be that of component type of the array unless the array type is unknown, in which case a // bottom type inferred from the type of instruction is used. is_primitive is false for an // aget-object. void VerifyAGet(const Instruction* inst, const RegType& insn_type, bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_); // Perform verification of an aput instruction. void VerifyAPut(const Instruction* inst, const RegType& insn_type, bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_); // Lookup instance field and fail for resolution violations ArtField* GetInstanceField(const RegType& obj_type, int field_idx) REQUIRES_SHARED(Locks::mutator_lock_); // Lookup static field and fail for resolution violations ArtField* GetStaticField(int field_idx) REQUIRES_SHARED(Locks::mutator_lock_); // Perform verification of an iget/sget/iput/sput instruction. template <FieldAccessType kAccType> void VerifyISFieldAccess(const Instruction* inst, const RegType& insn_type, bool is_primitive, bool is_static) REQUIRES_SHARED(Locks::mutator_lock_); // Resolves a class based on an index and, if C is kYes, performs access checks to ensure // the referrer can access the resolved class. template <CheckAccess C> const RegType& ResolveClass(dex::TypeIndex class_idx) REQUIRES_SHARED(Locks::mutator_lock_); /* * For the "move-exception" instruction at "work_insn_idx_", which must be at an exception handler * address, determine the Join of all exceptions that can land here. Fails if no matching * exception handler can be found or if the Join of exception types fails. */ const RegType& GetCaughtExceptionType() REQUIRES_SHARED(Locks::mutator_lock_); /* * Resolves a method based on an index and performs access checks to ensure * the referrer can access the resolved method. * Does not throw exceptions. */ ArtMethod* ResolveMethodAndCheckAccess(uint32_t method_idx, MethodType method_type) REQUIRES_SHARED(Locks::mutator_lock_); /* * Verify the arguments to a method. We're executing in "method", making * a call to the method reference in vB. * * If this is a "direct" invoke, we allow calls to <init>. For calls to * <init>, the first argument may be an uninitialized reference. Otherwise, * calls to anything starting with '<' will be rejected, as will any * uninitialized reference arguments. * * For non-static method calls, this will verify that the method call is * appropriate for the "this" argument. * * The method reference is in vBBBB. The "is_range" parameter determines * whether we use 0-4 "args" values or a range of registers defined by * vAA and vCCCC. * * Widening conversions on integers and references are allowed, but * narrowing conversions are not. * * Returns the resolved method on success, null on failure (with *failure * set appropriately). */ ArtMethod* VerifyInvocationArgs(const Instruction* inst, MethodType method_type, bool is_range) REQUIRES_SHARED(Locks::mutator_lock_); // Similar checks to the above, but on the proto. Will be used when the method cannot be // resolved. void VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, MethodType method_type, bool is_range) REQUIRES_SHARED(Locks::mutator_lock_); template <class T> ArtMethod* VerifyInvocationArgsFromIterator(T* it, const Instruction* inst, MethodType method_type, bool is_range, ArtMethod* res_method) REQUIRES_SHARED(Locks::mutator_lock_); /* * Verify the arguments present for a call site. Returns "true" if all is well, "false" otherwise. */ bool CheckCallSite(uint32_t call_site_idx); /* * Verify that the target instruction is not "move-exception". It's important that the only way * to execute a move-exception is as the first instruction of an exception handler. * Returns "true" if all is well, "false" if the target instruction is move-exception. */ bool CheckNotMoveException(const uint16_t* insns, int insn_idx) { if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-exception"; return false; } return true; } /* * Verify that the target instruction is not "move-result". It is important that we cannot * branch to move-result instructions, but we have to make this a distinct check instead of * adding it to CheckNotMoveException, because it is legal to continue into "move-result" * instructions - as long as the previous instruction was an invoke, which is checked elsewhere. */ bool CheckNotMoveResult(const uint16_t* insns, int insn_idx) { if (((insns[insn_idx] & 0xff) >= Instruction::MOVE_RESULT) && ((insns[insn_idx] & 0xff) <= Instruction::MOVE_RESULT_OBJECT)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-result*"; return false; } return true; } /* * Verify that the target instruction is not "move-result" or "move-exception". This is to * be used when checking branch and switch instructions, but not instructions that can * continue. */ bool CheckNotMoveExceptionOrMoveResult(const uint16_t* insns, int insn_idx) { return (CheckNotMoveException(insns, insn_idx) && CheckNotMoveResult(insns, insn_idx)); } /* * Control can transfer to "next_insn". Merge the registers from merge_line into the table at * next_insn, and set the changed flag on the target address if any of the registers were changed. * In the case of fall-through, update the merge line on a change as its the working line for the * next instruction. * Returns "false" if an error is encountered. */ bool UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line, bool update_merge_line) REQUIRES_SHARED(Locks::mutator_lock_); // Return the register type for the method. const RegType& GetMethodReturnType() REQUIRES_SHARED(Locks::mutator_lock_); // Get a type representing the declaring class of the method. const RegType& GetDeclaringClass() REQUIRES_SHARED(Locks::mutator_lock_); InstructionFlags* CurrentInsnFlags() { return &GetModifiableInstructionFlags(work_insn_idx_); } const RegType& DetermineCat1Constant(int32_t value, bool precise) REQUIRES_SHARED(Locks::mutator_lock_); // Try to create a register type from the given class. In case a precise type is requested, but // the class is not instantiable, a soft error (of type NO_CLASS) will be enqueued and a // non-precise reference will be returned. // Note: we reuse NO_CLASS as this will throw an exception at runtime, when the failing class is // actually touched. const RegType& FromClass(const char* descriptor, ObjPtr<mirror::Class> klass, bool precise) REQUIRES_SHARED(Locks::mutator_lock_); ALWAYS_INLINE bool FailOrAbort(bool condition, const char* error_msg, uint32_t work_insn_idx); ALWAYS_INLINE InstructionFlags& GetModifiableInstructionFlags(size_t index) { return insn_flags_[index]; } // Returns the method index of an invoke instruction. uint16_t GetMethodIdxOfInvoke(const Instruction* inst) REQUIRES_SHARED(Locks::mutator_lock_); // Returns the field index of a field access instruction. uint16_t GetFieldIdxOfFieldAccess(const Instruction* inst, bool is_static) REQUIRES_SHARED(Locks::mutator_lock_); // Run verification on the method. Returns true if verification completes and false if the input // has an irrecoverable corruption. bool Verify() override REQUIRES_SHARED(Locks::mutator_lock_); // Dump the failures encountered by the verifier. std::ostream& DumpFailures(std::ostream& os); // Dump the state of the verifier, namely each instruction, what flags are set on it, register // information void Dump(std::ostream& os) REQUIRES_SHARED(Locks::mutator_lock_) { VariableIndentationOutputStream vios(&os); Dump(&vios); } void Dump(VariableIndentationOutputStream* vios) REQUIRES_SHARED(Locks::mutator_lock_); ArtMethod* method_being_verified_; // Its ArtMethod representation if known. const uint32_t method_access_flags_; // Method's access flags. const RegType* return_type_; // Lazily computed return type of the method. // The dex_cache for the declaring class of the method. Handle<mirror::DexCache> dex_cache_ GUARDED_BY(Locks::mutator_lock_); // The class loader for the declaring class of the method. Handle<mirror::ClassLoader> class_loader_ GUARDED_BY(Locks::mutator_lock_); const dex::ClassDef& class_def_; // The class def of the declaring class of the method. const RegType* declaring_class_; // Lazily computed reg type of the method's declaring class. // The dex PC of a FindLocksAtDexPc request, -1 otherwise. uint32_t interesting_dex_pc_; // The container into which FindLocksAtDexPc should write the registers containing held locks, // null if we're not doing FindLocksAtDexPc. std::vector<DexLockInfo>* monitor_enter_dex_pcs_; // An optimization where instead of generating unique RegTypes for constants we use imprecise // constants that cover a range of constants. This isn't good enough for deoptimization that // avoids loading from registers in the case of a constant as the dex instruction set lost the // notion of whether a value should be in a floating point or general purpose register file. const bool need_precise_constants_; // Indicates whether we verify to dump the info. In that case we accept quickened instructions // even though we might detect to be a compiler. Should only be set when running // VerifyMethodAndDump. const bool verify_to_dump_; // Whether or not we call AllowThreadSuspension periodically, we want a way to disable this for // thread dumping checkpoints since we may get thread suspension at an inopportune time due to // FindLocksAtDexPC, resulting in deadlocks. const bool allow_thread_suspension_; // Whether the method seems to be a constructor. Note that this field exists as we can't trust // the flags in the dex file. Some older code does not mark methods named "<init>" and "<clinit>" // correctly. // // Note: this flag is only valid once Verify() has started. bool is_constructor_; // API level, for dependent checks. Note: we do not use '0' for unset here, to simplify checks. // Instead, unset level should correspond to max(). const uint32_t api_level_; friend class ::art::verifier::MethodVerifier; DISALLOW_COPY_AND_ASSIGN(MethodVerifier); }; // Note: returns true on failure. template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::FailOrAbort(bool condition, const char* error_msg, uint32_t work_insn_idx) { if (kIsDebugBuild) { // In a debug build, abort if the error condition is wrong. Only warn if // we are already aborting (as this verification is likely run to print // lock information). if (LIKELY(gAborting == 0)) { DCHECK(condition) << error_msg << work_insn_idx << " " << dex_file_->PrettyMethod(dex_method_idx_); } else { if (!condition) { LOG(ERROR) << error_msg << work_insn_idx; Fail(VERIFY_ERROR_BAD_CLASS_HARD) << error_msg << work_insn_idx; return true; } } } else { // In a non-debug build, just fail the class. if (!condition) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << error_msg << work_insn_idx; return true; } } return false; } static bool IsLargeMethod(const CodeItemDataAccessor& accessor) { if (!accessor.HasCodeItem()) { return false; } uint16_t registers_size = accessor.RegistersSize(); uint32_t insns_size = accessor.InsnsSizeInCodeUnits(); return registers_size * insns_size > 4*1024*1024; } template <bool kVerifierDebug> MethodVerifier<kVerifierDebug>::MethodVerifier(Thread* self, const DexFile* dex_file, Handle<mirror::DexCache> dex_cache, Handle<mirror::ClassLoader> class_loader, const dex::ClassDef& class_def, const dex::CodeItem* code_item, uint32_t dex_method_idx, ArtMethod* method, uint32_t method_access_flags, bool can_load_classes, bool allow_soft_failures, bool need_precise_constants, bool verify_to_dump, bool allow_thread_suspension, uint32_t api_level) : art::verifier::MethodVerifier(self, dex_file, code_item, dex_method_idx, can_load_classes, allow_thread_suspension, allow_soft_failures), method_being_verified_(method), method_access_flags_(method_access_flags), return_type_(nullptr), dex_cache_(dex_cache), class_loader_(class_loader), class_def_(class_def), declaring_class_(nullptr), interesting_dex_pc_(-1), monitor_enter_dex_pcs_(nullptr), need_precise_constants_(need_precise_constants), verify_to_dump_(verify_to_dump), allow_thread_suspension_(allow_thread_suspension), is_constructor_(false), api_level_(api_level == 0 ? std::numeric_limits<uint32_t>::max() : api_level) { } template <bool kVerifierDebug> void MethodVerifier<kVerifierDebug>::FindLocksAtDexPc() { CHECK(monitor_enter_dex_pcs_ != nullptr); CHECK(code_item_accessor_.HasCodeItem()); // This only makes sense for methods with code. // Quick check whether there are any monitor_enter instructions before verifying. for (const DexInstructionPcPair& inst : code_item_accessor_) { if (inst->Opcode() == Instruction::MONITOR_ENTER) { // Strictly speaking, we ought to be able to get away with doing a subset of the full method // verification. In practice, the phase we want relies on data structures set up by all the // earlier passes, so we just run the full method verification and bail out early when we've // got what we wanted. Verify(); return; } } } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::Verify() { // Some older code doesn't correctly mark constructors as such. Test for this case by looking at // the name. const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); const char* method_name = dex_file_->StringDataByIdx(method_id.name_idx_); bool instance_constructor_by_name = strcmp("<init>", method_name) == 0; bool static_constructor_by_name = strcmp("<clinit>", method_name) == 0; bool constructor_by_name = instance_constructor_by_name || static_constructor_by_name; // Check that only constructors are tagged, and check for bad code that doesn't tag constructors. if ((method_access_flags_ & kAccConstructor) != 0) { if (!constructor_by_name) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "method is marked as constructor, but not named accordingly"; return false; } is_constructor_ = true; } else if (constructor_by_name) { LOG(WARNING) << "Method " << dex_file_->PrettyMethod(dex_method_idx_) << " not marked as constructor."; is_constructor_ = true; } // If it's a constructor, check whether IsStatic() matches the name. // This should have been rejected by the dex file verifier. Only do in debug build. if (kIsDebugBuild) { if (IsConstructor()) { if (IsStatic() ^ static_constructor_by_name) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "constructor name doesn't match static flag"; return false; } } } // Methods may only have one of public/protected/private. // This should have been rejected by the dex file verifier. Only do in debug build. if (kIsDebugBuild) { size_t access_mod_count = (((method_access_flags_ & kAccPublic) == 0) ? 0 : 1) + (((method_access_flags_ & kAccProtected) == 0) ? 0 : 1) + (((method_access_flags_ & kAccPrivate) == 0) ? 0 : 1); if (access_mod_count > 1) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "method has more than one of public/protected/private"; return false; } } // If there aren't any instructions, make sure that's expected, then exit successfully. if (!code_item_accessor_.HasCodeItem()) { // Only native or abstract methods may not have code. if ((method_access_flags_ & (kAccNative | kAccAbstract)) == 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "zero-length code in concrete non-native method"; return false; } // This should have been rejected by the dex file verifier. Only do in debug build. // Note: the above will also be rejected in the dex file verifier, starting in dex version 37. if (kIsDebugBuild) { if ((method_access_flags_ & kAccAbstract) != 0) { // Abstract methods are not allowed to have the following flags. static constexpr uint32_t kForbidden = kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized; if ((method_access_flags_ & kForbidden) != 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "method can't be abstract and private/static/final/native/strict/synchronized"; return false; } } if ((class_def_.GetJavaAccessFlags() & kAccInterface) != 0) { // Interface methods must be public and abstract (if default methods are disabled). uint32_t kRequired = kAccPublic; if ((method_access_flags_ & kRequired) != kRequired) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface methods must be public"; return false; } // In addition to the above, interface methods must not be protected. static constexpr uint32_t kForbidden = kAccProtected; if ((method_access_flags_ & kForbidden) != 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface methods can't be protected"; return false; } } // We also don't allow constructors to be abstract or native. if (IsConstructor()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "constructors can't be abstract or native"; return false; } } return true; } // This should have been rejected by the dex file verifier. Only do in debug build. if (kIsDebugBuild) { // When there's code, the method must not be native or abstract. if ((method_access_flags_ & (kAccNative | kAccAbstract)) != 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "non-zero-length code in abstract or native method"; return false; } if ((class_def_.GetJavaAccessFlags() & kAccInterface) != 0) { // Interfaces may always have static initializers for their fields. If we are running with // default methods enabled we also allow other public, static, non-final methods to have code. // Otherwise that is the only type of method allowed. if (!(IsConstructor() && IsStatic())) { if (IsInstanceConstructor()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interfaces may not have non-static constructor"; return false; } else if (method_access_flags_ & kAccFinal) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interfaces may not have final methods"; return false; } else { uint32_t access_flag_options = kAccPublic; if (dex_file_->SupportsDefaultMethods()) { access_flag_options |= kAccPrivate; } if (!(method_access_flags_ & access_flag_options)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interfaces may not have protected or package-private members"; return false; } } } } // Instance constructors must not be synchronized. if (IsInstanceConstructor()) { static constexpr uint32_t kForbidden = kAccSynchronized; if ((method_access_flags_ & kForbidden) != 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "constructors can't be synchronized"; return false; } } } // Sanity-check the register counts. ins + locals = registers, so make sure that ins <= registers. if (code_item_accessor_.InsSize() > code_item_accessor_.RegistersSize()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad register counts (ins=" << code_item_accessor_.InsSize() << " regs=" << code_item_accessor_.RegistersSize(); return false; } // Allocate and initialize an array to hold instruction data. insn_flags_.reset(allocator_.AllocArray<InstructionFlags>( code_item_accessor_.InsnsSizeInCodeUnits())); DCHECK(insn_flags_ != nullptr); std::uninitialized_fill_n(insn_flags_.get(), code_item_accessor_.InsnsSizeInCodeUnits(), InstructionFlags()); // Run through the instructions and see if the width checks out. bool result = ComputeWidthsAndCountOps(); bool allow_runtime_only_instructions = !Runtime::Current()->IsAotCompiler() || verify_to_dump_; // Flag instructions guarded by a "try" block and check exception handlers. result = result && ScanTryCatchBlocks(); // Perform static instruction verification. result = result && (allow_runtime_only_instructions ? VerifyInstructions<true>() : VerifyInstructions<false>()); // Perform code-flow analysis and return. result = result && VerifyCodeFlow(); return result; } template <bool kVerifierDebug> void MethodVerifier<kVerifierDebug>::PrependToLastFailMessage(std::string prepend) { size_t failure_num = failure_messages_.size(); DCHECK_NE(failure_num, 0U); std::ostringstream* last_fail_message = failure_messages_[failure_num - 1]; prepend += last_fail_message->str(); failure_messages_[failure_num - 1] = new std::ostringstream(prepend, std::ostringstream::ate); delete last_fail_message; } template <bool kVerifierDebug> void MethodVerifier<kVerifierDebug>::AppendToLastFailMessage(const std::string& append) { size_t failure_num = failure_messages_.size(); DCHECK_NE(failure_num, 0U); std::ostringstream* last_fail_message = failure_messages_[failure_num - 1]; (*last_fail_message) << append; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::ComputeWidthsAndCountOps() { // We can't assume the instruction is well formed, handle the case where calculating the size // goes past the end of the code item. SafeDexInstructionIterator it(code_item_accessor_.begin(), code_item_accessor_.end()); for ( ; !it.IsErrorState() && it < code_item_accessor_.end(); ++it) { // In case the instruction goes past the end of the code item, make sure to not process it. SafeDexInstructionIterator next = it; ++next; if (next.IsErrorState()) { break; } Instruction::Code opcode = it->Opcode(); switch (opcode) { case Instruction::APUT_OBJECT: case Instruction::CHECK_CAST: has_check_casts_ = true; break; default: break; } GetModifiableInstructionFlags(it.DexPc()).SetIsOpcode(); } if (it != code_item_accessor_.end()) { const size_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits(); Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "code did not end where expected (" << it.DexPc() << " vs. " << insns_size << ")"; return false; } return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::ScanTryCatchBlocks() { const uint32_t tries_size = code_item_accessor_.TriesSize(); if (tries_size == 0) { return true; } const uint32_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits(); for (const dex::TryItem& try_item : code_item_accessor_.TryItems()) { const uint32_t start = try_item.start_addr_; const uint32_t end = start + try_item.insn_count_; if ((start >= end) || (start >= insns_size) || (end > insns_size)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad exception entry: startAddr=" << start << " endAddr=" << end << " (size=" << insns_size << ")"; return false; } if (!GetInstructionFlags(start).IsOpcode()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'try' block starts inside an instruction (" << start << ")"; return false; } DexInstructionIterator end_it(code_item_accessor_.Insns(), end); for (DexInstructionIterator it(code_item_accessor_.Insns(), start); it < end_it; ++it) { GetModifiableInstructionFlags(it.DexPc()).SetInTry(); } } // Iterate over each of the handlers to verify target addresses. const uint8_t* handlers_ptr = code_item_accessor_.GetCatchHandlerData(); const uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); ClassLinker* linker = Runtime::Current()->GetClassLinker(); for (uint32_t idx = 0; idx < handlers_size; idx++) { CatchHandlerIterator iterator(handlers_ptr); for (; iterator.HasNext(); iterator.Next()) { uint32_t dex_pc = iterator.GetHandlerAddress(); if (!GetInstructionFlags(dex_pc).IsOpcode()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "exception handler starts at bad address (" << dex_pc << ")"; return false; } if (!CheckNotMoveResult(code_item_accessor_.Insns(), dex_pc)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "exception handler begins with move-result* (" << dex_pc << ")"; return false; } GetModifiableInstructionFlags(dex_pc).SetBranchTarget(); // Ensure exception types are resolved so that they don't need resolution to be delivered, // unresolved exception types will be ignored by exception delivery if (iterator.GetHandlerTypeIndex().IsValid()) { ObjPtr<mirror::Class> exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), dex_cache_, class_loader_); if (exception_type == nullptr) { DCHECK(self_->IsExceptionPending()); self_->ClearException(); } } } handlers_ptr = iterator.EndDataPointer(); } return true; } template <bool kVerifierDebug> template <bool kAllowRuntimeOnlyInstructions> bool MethodVerifier<kVerifierDebug>::VerifyInstructions() { /* Flag the start of the method as a branch target, and a GC point due to stack overflow errors */ GetModifiableInstructionFlags(0).SetBranchTarget(); GetModifiableInstructionFlags(0).SetCompileTimeInfoPoint(); for (const DexInstructionPcPair& inst : code_item_accessor_) { const uint32_t dex_pc = inst.DexPc(); if (!VerifyInstruction<kAllowRuntimeOnlyInstructions>(&inst.Inst(), dex_pc)) { DCHECK_NE(failures_.size(), 0U); return false; } /* Flag instructions that are garbage collection points */ // All invoke points are marked as "Throw" points already. // We are relying on this to also count all the invokes as interesting. if (inst->IsBranch()) { GetModifiableInstructionFlags(dex_pc).SetCompileTimeInfoPoint(); // The compiler also needs safepoints for fall-through to loop heads. // Such a loop head must be a target of a branch. int32_t offset = 0; bool cond, self_ok; bool target_ok = GetBranchOffset(dex_pc, &offset, &cond, &self_ok); DCHECK(target_ok); GetModifiableInstructionFlags(dex_pc + offset).SetCompileTimeInfoPoint(); } else if (inst->IsSwitch() || inst->IsThrow()) { GetModifiableInstructionFlags(dex_pc).SetCompileTimeInfoPoint(); } else if (inst->IsReturn()) { GetModifiableInstructionFlags(dex_pc).SetCompileTimeInfoPointAndReturn(); } } return true; } template <bool kVerifierDebug> template <bool kAllowRuntimeOnlyInstructions> bool MethodVerifier<kVerifierDebug>::VerifyInstruction(const Instruction* inst, uint32_t code_offset) { if (Instruction::kHaveExperimentalInstructions && UNLIKELY(inst->IsExperimental())) { // Experimental instructions don't yet have verifier support implementation. // While it is possible to use them by themselves, when we try to use stable instructions // with a virtual register that was created by an experimental instruction, // the data flow analysis will fail. Fail(VERIFY_ERROR_FORCE_INTERPRETER) << "experimental instruction is not supported by verifier; skipping verification"; have_pending_experimental_failure_ = true; return false; } bool result = true; switch (inst->GetVerifyTypeArgumentA()) { case Instruction::kVerifyRegA: result = result && CheckRegisterIndex(inst->VRegA()); break; case Instruction::kVerifyRegAWide: result = result && CheckWideRegisterIndex(inst->VRegA()); break; } switch (inst->GetVerifyTypeArgumentB()) { case Instruction::kVerifyRegB: result = result && CheckRegisterIndex(inst->VRegB()); break; case Instruction::kVerifyRegBField: result = result && CheckFieldIndex(inst->VRegB()); break; case Instruction::kVerifyRegBMethod: result = result && CheckMethodIndex(inst->VRegB()); break; case Instruction::kVerifyRegBNewInstance: result = result && CheckNewInstance(dex::TypeIndex(inst->VRegB())); break; case Instruction::kVerifyRegBString: result = result && CheckStringIndex(inst->VRegB()); break; case Instruction::kVerifyRegBType: result = result && CheckTypeIndex(dex::TypeIndex(inst->VRegB())); break; case Instruction::kVerifyRegBWide: result = result && CheckWideRegisterIndex(inst->VRegB()); break; case Instruction::kVerifyRegBCallSite: result = result && CheckCallSiteIndex(inst->VRegB()); break; case Instruction::kVerifyRegBMethodHandle: result = result && CheckMethodHandleIndex(inst->VRegB()); break; case Instruction::kVerifyRegBPrototype: result = result && CheckPrototypeIndex(inst->VRegB()); break; } switch (inst->GetVerifyTypeArgumentC()) { case Instruction::kVerifyRegC: result = result && CheckRegisterIndex(inst->VRegC()); break; case Instruction::kVerifyRegCField: result = result && CheckFieldIndex(inst->VRegC()); break; case Instruction::kVerifyRegCNewArray: result = result && CheckNewArray(dex::TypeIndex(inst->VRegC())); break; case Instruction::kVerifyRegCType: result = result && CheckTypeIndex(dex::TypeIndex(inst->VRegC())); break; case Instruction::kVerifyRegCWide: result = result && CheckWideRegisterIndex(inst->VRegC()); break; } switch (inst->GetVerifyTypeArgumentH()) { case Instruction::kVerifyRegHPrototype: result = result && CheckPrototypeIndex(inst->VRegH()); break; } switch (inst->GetVerifyExtraFlags()) { case Instruction::kVerifyArrayData: result = result && CheckArrayData(code_offset); break; case Instruction::kVerifyBranchTarget: result = result && CheckBranchTarget(code_offset); break; case Instruction::kVerifySwitchTargets: result = result && CheckSwitchTargets(code_offset); break; case Instruction::kVerifyVarArgNonZero: // Fall-through. case Instruction::kVerifyVarArg: { // Instructions that can actually return a negative value shouldn't have this flag. uint32_t v_a = dchecked_integral_cast<uint32_t>(inst->VRegA()); if ((inst->GetVerifyExtraFlags() == Instruction::kVerifyVarArgNonZero && v_a == 0) || v_a > Instruction::kMaxVarArgRegs) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid arg count (" << v_a << ") in " "non-range invoke"; return false; } uint32_t args[Instruction::kMaxVarArgRegs]; inst->GetVarArgs(args); result = result && CheckVarArgRegs(v_a, args); break; } case Instruction::kVerifyVarArgRangeNonZero: // Fall-through. case Instruction::kVerifyVarArgRange: if (inst->GetVerifyExtraFlags() == Instruction::kVerifyVarArgRangeNonZero && inst->VRegA() <= 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid arg count (" << inst->VRegA() << ") in " "range invoke"; return false; } result = result && CheckVarArgRangeRegs(inst->VRegA(), inst->VRegC()); break; case Instruction::kVerifyError: Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected opcode " << inst->Name(); result = false; break; } if (!kAllowRuntimeOnlyInstructions && inst->GetVerifyIsRuntimeOnly()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "opcode only expected at runtime " << inst->Name(); result = false; } return result; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckRegisterIndex(uint32_t idx) { if (UNLIKELY(idx >= code_item_accessor_.RegistersSize())) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register index out of range (" << idx << " >= " << code_item_accessor_.RegistersSize() << ")"; return false; } return true; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckWideRegisterIndex(uint32_t idx) { if (UNLIKELY(idx + 1 >= code_item_accessor_.RegistersSize())) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "wide register index out of range (" << idx << "+1 >= " << code_item_accessor_.RegistersSize() << ")"; return false; } return true; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckCallSiteIndex(uint32_t idx) { uint32_t limit = dex_file_->NumCallSiteIds(); if (UNLIKELY(idx >= limit)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad call site index " << idx << " (max " << limit << ")"; return false; } return true; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckFieldIndex(uint32_t idx) { if (UNLIKELY(idx >= dex_file_->GetHeader().field_ids_size_)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad field index " << idx << " (max " << dex_file_->GetHeader().field_ids_size_ << ")"; return false; } return true; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckMethodIndex(uint32_t idx) { if (UNLIKELY(idx >= dex_file_->GetHeader().method_ids_size_)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad method index " << idx << " (max " << dex_file_->GetHeader().method_ids_size_ << ")"; return false; } return true; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckMethodHandleIndex(uint32_t idx) { uint32_t limit = dex_file_->NumMethodHandles(); if (UNLIKELY(idx >= limit)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad method handle index " << idx << " (max " << limit << ")"; return false; } return true; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckNewInstance(dex::TypeIndex idx) { if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx.index_ << " (max " << dex_file_->GetHeader().type_ids_size_ << ")"; return false; } // We don't need the actual class, just a pointer to the class name. const char* descriptor = dex_file_->StringByTypeIdx(idx); if (UNLIKELY(descriptor[0] != 'L')) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "can't call new-instance on type '" << descriptor << "'"; return false; } else if (UNLIKELY(strcmp(descriptor, "Ljava/lang/Class;") == 0)) { // An unlikely new instance on Class is not allowed. Fall back to interpreter to ensure an // exception is thrown when this statement is executed (compiled code would not do that). Fail(VERIFY_ERROR_INSTANTIATION); } return true; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckPrototypeIndex(uint32_t idx) { if (UNLIKELY(idx >= dex_file_->GetHeader().proto_ids_size_)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad prototype index " << idx << " (max " << dex_file_->GetHeader().proto_ids_size_ << ")"; return false; } return true; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckStringIndex(uint32_t idx) { if (UNLIKELY(idx >= dex_file_->GetHeader().string_ids_size_)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad string index " << idx << " (max " << dex_file_->GetHeader().string_ids_size_ << ")"; return false; } return true; } template <bool kVerifierDebug> inline bool MethodVerifier<kVerifierDebug>::CheckTypeIndex(dex::TypeIndex idx) { if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx.index_ << " (max " << dex_file_->GetHeader().type_ids_size_ << ")"; return false; } return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CheckNewArray(dex::TypeIndex idx) { if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx.index_ << " (max " << dex_file_->GetHeader().type_ids_size_ << ")"; return false; } int bracket_count = 0; const char* descriptor = dex_file_->StringByTypeIdx(idx); const char* cp = descriptor; while (*cp++ == '[') { bracket_count++; } if (UNLIKELY(bracket_count == 0)) { /* The given class must be an array type. */ Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "can't new-array class '" << descriptor << "' (not an array)"; return false; } else if (UNLIKELY(bracket_count > 255)) { /* It is illegal to create an array of more than 255 dimensions. */ Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "can't new-array class '" << descriptor << "' (exceeds limit)"; return false; } return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CheckArrayData(uint32_t cur_offset) { const uint32_t insn_count = code_item_accessor_.InsnsSizeInCodeUnits(); const uint16_t* insns = code_item_accessor_.Insns() + cur_offset; const uint16_t* array_data; int32_t array_data_offset; DCHECK_LT(cur_offset, insn_count); /* make sure the start of the array data table is in range */ array_data_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16); if (UNLIKELY(static_cast<int32_t>(cur_offset) + array_data_offset < 0 || cur_offset + array_data_offset + 2 >= insn_count)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid array data start: at " << cur_offset << ", data offset " << array_data_offset << ", count " << insn_count; return false; } /* offset to array data table is a relative branch-style offset */ array_data = insns + array_data_offset; // Make sure the table is at an even dex pc, that is, 32-bit aligned. if (UNLIKELY(!IsAligned<4>(array_data))) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unaligned array data table: at " << cur_offset << ", data offset " << array_data_offset; return false; } // Make sure the array-data is marked as an opcode. This ensures that it was reached when // traversing the code item linearly. It is an approximation for a by-spec padding value. if (UNLIKELY(!GetInstructionFlags(cur_offset + array_data_offset).IsOpcode())) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array data table at " << cur_offset << ", data offset " << array_data_offset << " not correctly visited, probably bad padding."; return false; } uint32_t value_width = array_data[1]; uint32_t value_count = *reinterpret_cast<const uint32_t*>(&array_data[2]); uint32_t table_size = 4 + (value_width * value_count + 1) / 2; /* make sure the end of the switch is in range */ if (UNLIKELY(cur_offset + array_data_offset + table_size > insn_count)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid array data end: at " << cur_offset << ", data offset " << array_data_offset << ", end " << cur_offset + array_data_offset + table_size << ", count " << insn_count; return false; } return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CheckBranchTarget(uint32_t cur_offset) { int32_t offset; bool isConditional, selfOkay; if (!GetBranchOffset(cur_offset, &offset, &isConditional, &selfOkay)) { return false; } if (UNLIKELY(!selfOkay && offset == 0)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "branch offset of zero not allowed at" << reinterpret_cast<void*>(cur_offset); return false; } // Check for 32-bit overflow. This isn't strictly necessary if we can depend on the runtime // to have identical "wrap-around" behavior, but it's unwise to depend on that. if (UNLIKELY(((int64_t) cur_offset + (int64_t) offset) != (int64_t) (cur_offset + offset))) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "branch target overflow " << reinterpret_cast<void*>(cur_offset) << " +" << offset; return false; } int32_t abs_offset = cur_offset + offset; if (UNLIKELY(abs_offset < 0 || (uint32_t) abs_offset >= code_item_accessor_.InsnsSizeInCodeUnits() || !GetInstructionFlags(abs_offset).IsOpcode())) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid branch target " << offset << " (-> " << reinterpret_cast<void*>(abs_offset) << ") at " << reinterpret_cast<void*>(cur_offset); return false; } GetModifiableInstructionFlags(abs_offset).SetBranchTarget(); return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional, bool* selfOkay) { const uint16_t* insns = code_item_accessor_.Insns() + cur_offset; *pConditional = false; *selfOkay = false; switch (*insns & 0xff) { case Instruction::GOTO: *pOffset = ((int16_t) *insns) >> 8; break; case Instruction::GOTO_32: *pOffset = insns[1] | (((uint32_t) insns[2]) << 16); *selfOkay = true; break; case Instruction::GOTO_16: *pOffset = (int16_t) insns[1]; break; case Instruction::IF_EQ: case Instruction::IF_NE: case Instruction::IF_LT: case Instruction::IF_GE: case Instruction::IF_GT: case Instruction::IF_LE: case Instruction::IF_EQZ: case Instruction::IF_NEZ: case Instruction::IF_LTZ: case Instruction::IF_GEZ: case Instruction::IF_GTZ: case Instruction::IF_LEZ: *pOffset = (int16_t) insns[1]; *pConditional = true; break; default: return false; } return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CheckSwitchTargets(uint32_t cur_offset) { const uint32_t insn_count = code_item_accessor_.InsnsSizeInCodeUnits(); DCHECK_LT(cur_offset, insn_count); const uint16_t* insns = code_item_accessor_.Insns() + cur_offset; /* make sure the start of the switch is in range */ int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16); if (UNLIKELY(static_cast<int32_t>(cur_offset) + switch_offset < 0 || cur_offset + switch_offset + 2 > insn_count)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch start: at " << cur_offset << ", switch offset " << switch_offset << ", count " << insn_count; return false; } /* offset to switch table is a relative branch-style offset */ const uint16_t* switch_insns = insns + switch_offset; // Make sure the table is at an even dex pc, that is, 32-bit aligned. if (UNLIKELY(!IsAligned<4>(switch_insns))) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unaligned switch table: at " << cur_offset << ", switch offset " << switch_offset; return false; } // Make sure the switch data is marked as an opcode. This ensures that it was reached when // traversing the code item linearly. It is an approximation for a by-spec padding value. if (UNLIKELY(!GetInstructionFlags(cur_offset + switch_offset).IsOpcode())) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "switch table at " << cur_offset << ", switch offset " << switch_offset << " not correctly visited, probably bad padding."; return false; } bool is_packed_switch = (*insns & 0xff) == Instruction::PACKED_SWITCH; uint32_t switch_count = switch_insns[1]; int32_t targets_offset; uint16_t expected_signature; if (is_packed_switch) { /* 0=sig, 1=count, 2/3=firstKey */ targets_offset = 4; expected_signature = Instruction::kPackedSwitchSignature; } else { /* 0=sig, 1=count, 2..count*2 = keys */ targets_offset = 2 + 2 * switch_count; expected_signature = Instruction::kSparseSwitchSignature; } uint32_t table_size = targets_offset + switch_count * 2; if (UNLIKELY(switch_insns[0] != expected_signature)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << StringPrintf("wrong signature for switch table (%x, wanted %x)", switch_insns[0], expected_signature); return false; } /* make sure the end of the switch is in range */ if (UNLIKELY(cur_offset + switch_offset + table_size > (uint32_t) insn_count)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch end: at " << cur_offset << ", switch offset " << switch_offset << ", end " << (cur_offset + switch_offset + table_size) << ", count " << insn_count; return false; } constexpr int32_t keys_offset = 2; if (switch_count > 1) { if (is_packed_switch) { /* for a packed switch, verify that keys do not overflow int32 */ int32_t first_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16); int32_t max_first_key = std::numeric_limits<int32_t>::max() - (static_cast<int32_t>(switch_count) - 1); if (UNLIKELY(first_key > max_first_key)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid packed switch: first_key=" << first_key << ", switch_count=" << switch_count; return false; } } else { /* for a sparse switch, verify the keys are in ascending order */ int32_t last_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16); for (uint32_t targ = 1; targ < switch_count; targ++) { int32_t key = static_cast<int32_t>(switch_insns[keys_offset + targ * 2]) | static_cast<int32_t>(switch_insns[keys_offset + targ * 2 + 1] << 16); if (UNLIKELY(key <= last_key)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid sparse switch: last key=" << last_key << ", this=" << key; return false; } last_key = key; } } } /* verify each switch target */ for (uint32_t targ = 0; targ < switch_count; targ++) { int32_t offset = static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) | static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16); int32_t abs_offset = cur_offset + offset; if (UNLIKELY(abs_offset < 0 || abs_offset >= static_cast<int32_t>(insn_count) || !GetInstructionFlags(abs_offset).IsOpcode())) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch target " << offset << " (-> " << reinterpret_cast<void*>(abs_offset) << ") at " << reinterpret_cast<void*>(cur_offset) << "[" << targ << "]"; return false; } GetModifiableInstructionFlags(abs_offset).SetBranchTarget(); } return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CheckVarArgRegs(uint32_t vA, uint32_t arg[]) { uint16_t registers_size = code_item_accessor_.RegistersSize(); for (uint32_t idx = 0; idx < vA; idx++) { if (UNLIKELY(arg[idx] >= registers_size)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid reg index (" << arg[idx] << ") in non-range invoke (>= " << registers_size << ")"; return false; } } return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CheckVarArgRangeRegs(uint32_t vA, uint32_t vC) { uint16_t registers_size = code_item_accessor_.RegistersSize(); // vA/vC are unsigned 8-bit/16-bit quantities for /range instructions, so there's no risk of // integer overflow when adding them here. if (UNLIKELY(vA + vC > registers_size)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid reg index " << vA << "+" << vC << " in range invoke (> " << registers_size << ")"; return false; } return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::VerifyCodeFlow() { const uint16_t registers_size = code_item_accessor_.RegistersSize(); /* Create and initialize table holding register status */ reg_table_.Init(kTrackCompilerInterestPoints, insn_flags_.get(), code_item_accessor_.InsnsSizeInCodeUnits(), registers_size, allocator_, GetRegTypeCache()); work_line_.reset(RegisterLine::Create(registers_size, allocator_, GetRegTypeCache())); saved_line_.reset(RegisterLine::Create(registers_size, allocator_, GetRegTypeCache())); /* Initialize register types of method arguments. */ if (!SetTypesFromSignature()) { DCHECK_NE(failures_.size(), 0U); std::string prepend("Bad signature in "); prepend += dex_file_->PrettyMethod(dex_method_idx_); PrependToLastFailMessage(prepend); return false; } // We may have a runtime failure here, clear. have_pending_runtime_throw_failure_ = false; /* Perform code flow verification. */ if (!CodeFlowVerifyMethod()) { DCHECK_NE(failures_.size(), 0U); return false; } return true; } template <bool kVerifierDebug> std::ostream& MethodVerifier<kVerifierDebug>::DumpFailures(std::ostream& os) { DCHECK_EQ(failures_.size(), failure_messages_.size()); for (size_t i = 0; i < failures_.size(); ++i) { os << failure_messages_[i]->str() << "\n"; } return os; } template <bool kVerifierDebug> void MethodVerifier<kVerifierDebug>::Dump(VariableIndentationOutputStream* vios) { if (!code_item_accessor_.HasCodeItem()) { vios->Stream() << "Native method\n"; return; } { vios->Stream() << "Register Types:\n"; ScopedIndentation indent1(vios); reg_types_.Dump(vios->Stream()); } vios->Stream() << "Dumping instructions and register lines:\n"; ScopedIndentation indent1(vios); for (const DexInstructionPcPair& inst : code_item_accessor_) { const size_t dex_pc = inst.DexPc(); // Might be asked to dump before the table is initialized. if (reg_table_.IsInitialized()) { RegisterLine* reg_line = reg_table_.GetLine(dex_pc); if (reg_line != nullptr) { vios->Stream() << reg_line->Dump(this) << "\n"; } } vios->Stream() << StringPrintf("0x%04zx", dex_pc) << ": " << GetInstructionFlags(dex_pc).ToString() << " "; const bool kDumpHexOfInstruction = false; if (kDumpHexOfInstruction) { vios->Stream() << inst->DumpHex(5) << " "; } vios->Stream() << inst->DumpString(dex_file_) << "\n"; } } static bool IsPrimitiveDescriptor(char descriptor) { switch (descriptor) { case 'I': case 'C': case 'S': case 'B': case 'Z': case 'F': case 'D': case 'J': return true; default: return false; } } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::SetTypesFromSignature() { RegisterLine* reg_line = reg_table_.GetLine(0); // Should have been verified earlier. DCHECK_GE(code_item_accessor_.RegistersSize(), code_item_accessor_.InsSize()); uint32_t arg_start = code_item_accessor_.RegistersSize() - code_item_accessor_.InsSize(); size_t expected_args = code_item_accessor_.InsSize(); /* long/double count as two */ // Include the "this" pointer. size_t cur_arg = 0; if (!IsStatic()) { if (expected_args == 0) { // Expect at least a receiver. Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected 0 args, but method is not static"; return false; } // If this is a constructor for a class other than java.lang.Object, mark the first ("this") // argument as uninitialized. This restricts field access until the superclass constructor is // called. const RegType& declaring_class = GetDeclaringClass(); if (IsConstructor()) { if (declaring_class.IsJavaLangObject()) { // "this" is implicitly initialized. reg_line->SetThisInitialized(); reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, declaring_class); } else { reg_line->SetRegisterType<LockOp::kClear>( this, arg_start + cur_arg, reg_types_.UninitializedThisArgument(declaring_class)); } } else { reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, declaring_class); } cur_arg++; } const dex::ProtoId& proto_id = dex_file_->GetMethodPrototype(dex_file_->GetMethodId(dex_method_idx_)); DexFileParameterIterator iterator(*dex_file_, proto_id); for (; iterator.HasNext(); iterator.Next()) { const char* descriptor = iterator.GetDescriptor(); if (descriptor == nullptr) { LOG(FATAL) << "Null descriptor"; } if (cur_arg >= expected_args) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args << " args, found more (" << descriptor << ")"; return false; } switch (descriptor[0]) { case 'L': case '[': // We assume that reference arguments are initialized. The only way it could be otherwise // (assuming the caller was verified) is if the current method is <init>, but in that case // it's effectively considered initialized the instant we reach here (in the sense that we // can return without doing anything or call virtual methods). { // Note: don't check access. No error would be thrown for declaring or passing an // inaccessible class. Only actual accesses to fields or methods will. const RegType& reg_type = ResolveClass<CheckAccess::kNo>(iterator.GetTypeIdx()); if (!reg_type.IsNonZeroReferenceTypes()) { DCHECK(HasFailures()); return false; } reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_type); } break; case 'Z': reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Boolean()); break; case 'C': reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Char()); break; case 'B': reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Byte()); break; case 'I': reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Integer()); break; case 'S': reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Short()); break; case 'F': reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Float()); break; case 'J': case 'D': { if (cur_arg + 1 >= expected_args) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args << " args, found more (" << descriptor << ")"; return false; } const RegType* lo_half; const RegType* hi_half; if (descriptor[0] == 'J') { lo_half = &reg_types_.LongLo(); hi_half = &reg_types_.LongHi(); } else { lo_half = &reg_types_.DoubleLo(); hi_half = &reg_types_.DoubleHi(); } reg_line->SetRegisterTypeWide(this, arg_start + cur_arg, *lo_half, *hi_half); cur_arg++; break; } default: Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected signature type char '" << descriptor << "'"; return false; } cur_arg++; } if (cur_arg != expected_args) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args << " arguments, found " << cur_arg; return false; } const char* descriptor = dex_file_->GetReturnTypeDescriptor(proto_id); // Validate return type. We don't do the type lookup; just want to make sure that it has the right // format. Only major difference from the method argument format is that 'V' is supported. bool result; if (IsPrimitiveDescriptor(descriptor[0]) || descriptor[0] == 'V') { result = descriptor[1] == '\0'; } else if (descriptor[0] == '[') { // single/multi-dimensional array of object/primitive size_t i = 0; do { i++; } while (descriptor[i] == '['); // process leading [ if (descriptor[i] == 'L') { // object array do { i++; // find closing ; } while (descriptor[i] != ';' && descriptor[i] != '\0'); result = descriptor[i] == ';'; } else { // primitive array result = IsPrimitiveDescriptor(descriptor[i]) && descriptor[i + 1] == '\0'; } } else if (descriptor[0] == 'L') { // could be more thorough here, but shouldn't be required size_t i = 0; do { i++; } while (descriptor[i] != ';' && descriptor[i] != '\0'); result = descriptor[i] == ';'; } else { result = false; } if (!result) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected char in return type descriptor '" << descriptor << "'"; } return result; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CodeFlowVerifyMethod() { const uint16_t* insns = code_item_accessor_.Insns(); const uint32_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits(); /* Begin by marking the first instruction as "changed". */ GetModifiableInstructionFlags(0).SetChanged(); uint32_t start_guess = 0; /* Continue until no instructions are marked "changed". */ while (true) { if (allow_thread_suspension_) { self_->AllowThreadSuspension(); } // Find the first marked one. Use "start_guess" as a way to find one quickly. uint32_t insn_idx = start_guess; for (; insn_idx < insns_size; insn_idx++) { if (GetInstructionFlags(insn_idx).IsChanged()) break; } if (insn_idx == insns_size) { if (start_guess != 0) { /* try again, starting from the top */ start_guess = 0; continue; } else { /* all flags are clear */ break; } } // We carry the working set of registers from instruction to instruction. If this address can // be the target of a branch (or throw) instruction, or if we're skipping around chasing // "changed" flags, we need to load the set of registers from the table. // Because we always prefer to continue on to the next instruction, we should never have a // situation where we have a stray "changed" flag set on an instruction that isn't a branch // target. work_insn_idx_ = insn_idx; if (GetInstructionFlags(insn_idx).IsBranchTarget()) { work_line_->CopyFromLine(reg_table_.GetLine(insn_idx)); } else if (kIsDebugBuild) { /* * Sanity check: retrieve the stored register line (assuming * a full table) and make sure it actually matches. */ RegisterLine* register_line = reg_table_.GetLine(insn_idx); if (register_line != nullptr) { if (work_line_->CompareLine(register_line) != 0) { Dump(LOG_STREAM(FATAL_WITHOUT_ABORT)); LOG(FATAL_WITHOUT_ABORT) << info_messages_.str(); LOG(FATAL) << "work_line diverged in " << dex_file_->PrettyMethod(dex_method_idx_) << "@" << reinterpret_cast<void*>(work_insn_idx_) << "\n" << " work_line=" << work_line_->Dump(this) << "\n" << " expected=" << register_line->Dump(this); } } } if (!CodeFlowVerifyInstruction(&start_guess)) { std::string prepend(dex_file_->PrettyMethod(dex_method_idx_)); prepend += " failed to verify: "; PrependToLastFailMessage(prepend); return false; } /* Clear "changed" and mark as visited. */ GetModifiableInstructionFlags(insn_idx).SetVisited(); GetModifiableInstructionFlags(insn_idx).ClearChanged(); } if (kVerifierDebug) { /* * Scan for dead code. There's nothing "evil" about dead code * (besides the wasted space), but it indicates a flaw somewhere * down the line, possibly in the verifier. * * If we've substituted "always throw" instructions into the stream, * we are almost certainly going to have some dead code. */ int dead_start = -1; for (const DexInstructionPcPair& inst : code_item_accessor_) { const uint32_t insn_idx = inst.DexPc(); /* * Switch-statement data doesn't get "visited" by scanner. It * may or may not be preceded by a padding NOP (for alignment). */ if (insns[insn_idx] == Instruction::kPackedSwitchSignature || insns[insn_idx] == Instruction::kSparseSwitchSignature || insns[insn_idx] == Instruction::kArrayDataSignature || (insns[insn_idx] == Instruction::NOP && (insn_idx + 1 < insns_size) && (insns[insn_idx + 1] == Instruction::kPackedSwitchSignature || insns[insn_idx + 1] == Instruction::kSparseSwitchSignature || insns[insn_idx + 1] == Instruction::kArrayDataSignature))) { GetModifiableInstructionFlags(insn_idx).SetVisited(); } if (!GetInstructionFlags(insn_idx).IsVisited()) { if (dead_start < 0) { dead_start = insn_idx; } } else if (dead_start >= 0) { LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start) << "-" << reinterpret_cast<void*>(insn_idx - 1); dead_start = -1; } } if (dead_start >= 0) { LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start) << "-" << reinterpret_cast<void*>(code_item_accessor_.InsnsSizeInCodeUnits() - 1); } // To dump the state of the verify after a method, do something like: // if (dex_file_->PrettyMethod(dex_method_idx_) == // "boolean java.lang.String.equals(java.lang.Object)") { // LOG(INFO) << info_messages_.str(); // } } return true; } // Returns the index of the first final instance field of the given class, or kDexNoIndex if there // is no such field. static uint32_t GetFirstFinalInstanceFieldIndex(const DexFile& dex_file, dex::TypeIndex type_idx) { const dex::ClassDef* class_def = dex_file.FindClassDef(type_idx); DCHECK(class_def != nullptr); ClassAccessor accessor(dex_file, *class_def); for (const ClassAccessor::Field& field : accessor.GetInstanceFields()) { if (field.IsFinal()) { return field.GetIndex(); } } return dex::kDexNoIndex; } // Setup a register line for the given return instruction. template <bool kVerifierDebug> static void AdjustReturnLine(MethodVerifier<kVerifierDebug>* verifier, const Instruction* ret_inst, RegisterLine* line) { Instruction::Code opcode = ret_inst->Opcode(); switch (opcode) { case Instruction::RETURN_VOID: case Instruction::RETURN_VOID_NO_BARRIER: if (verifier->IsInstanceConstructor()) { // Before we mark all regs as conflicts, check that we don't have an uninitialized this. line->CheckConstructorReturn(verifier); } line->MarkAllRegistersAsConflicts(verifier); break; case Instruction::RETURN: case Instruction::RETURN_OBJECT: line->MarkAllRegistersAsConflictsExcept(verifier, ret_inst->VRegA_11x()); break; case Instruction::RETURN_WIDE: line->MarkAllRegistersAsConflictsExceptWide(verifier, ret_inst->VRegA_11x()); break; default: LOG(FATAL) << "Unknown return opcode " << opcode; UNREACHABLE(); } } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CodeFlowVerifyInstruction(uint32_t* start_guess) { // If we're doing FindLocksAtDexPc, check whether we're at the dex pc we care about. // We want the state _before_ the instruction, for the case where the dex pc we're // interested in is itself a monitor-enter instruction (which is a likely place // for a thread to be suspended). if (monitor_enter_dex_pcs_ != nullptr && work_insn_idx_ == interesting_dex_pc_) { monitor_enter_dex_pcs_->clear(); // The new work line is more accurate than the previous one. std::map<uint32_t, DexLockInfo> depth_to_lock_info; auto collector = [&](uint32_t dex_reg, uint32_t depth) { auto insert_pair = depth_to_lock_info.emplace(depth, DexLockInfo(depth)); auto it = insert_pair.first; auto set_insert_pair = it->second.dex_registers.insert(dex_reg); DCHECK(set_insert_pair.second); }; work_line_->IterateRegToLockDepths(collector); for (auto& pair : depth_to_lock_info) { monitor_enter_dex_pcs_->push_back(pair.second); // Map depth to dex PC. (*monitor_enter_dex_pcs_)[monitor_enter_dex_pcs_->size() - 1].dex_pc = work_line_->GetMonitorEnterDexPc(pair.second.dex_pc); } } /* * Once we finish decoding the instruction, we need to figure out where * we can go from here. There are three possible ways to transfer * control to another statement: * * (1) Continue to the next instruction. Applies to all but * unconditional branches, method returns, and exception throws. * (2) Branch to one or more possible locations. Applies to branches * and switch statements. * (3) Exception handlers. Applies to any instruction that can * throw an exception that is handled by an encompassing "try" * block. * * We can also return, in which case there is no successor instruction * from this point. * * The behavior can be determined from the opcode flags. */ const uint16_t* insns = code_item_accessor_.Insns() + work_insn_idx_; const Instruction* inst = Instruction::At(insns); int opcode_flags = Instruction::FlagsOf(inst->Opcode()); int32_t branch_target = 0; bool just_set_result = false; if (kVerifierDebug) { // Generate processing back trace to debug verifier LogVerifyInfo() << "Processing " << inst->DumpString(dex_file_) << std::endl << work_line_->Dump(this); } /* * Make a copy of the previous register state. If the instruction * can throw an exception, we will copy/merge this into the "catch" * address rather than work_line, because we don't want the result * from the "successful" code path (e.g. a check-cast that "improves" * a type) to be visible to the exception handler. */ if ((opcode_flags & Instruction::kThrow) != 0 && CurrentInsnFlags()->IsInTry()) { saved_line_->CopyFromLine(work_line_.get()); } else if (kIsDebugBuild) { saved_line_->FillWithGarbage(); } DCHECK(!have_pending_runtime_throw_failure_); // Per-instruction flag, should not be set here. // We need to ensure the work line is consistent while performing validation. When we spot a // peephole pattern we compute a new line for either the fallthrough instruction or the // branch target. RegisterLineArenaUniquePtr branch_line; RegisterLineArenaUniquePtr fallthrough_line; switch (inst->Opcode()) { case Instruction::NOP: /* * A "pure" NOP has no effect on anything. Data tables start with * a signature that looks like a NOP; if we see one of these in * the course of executing code then we have a problem. */ if (inst->VRegA_10x() != 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "encountered data table in instruction stream"; } break; case Instruction::MOVE: work_line_->CopyRegister1(this, inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategory1nr); break; case Instruction::MOVE_FROM16: work_line_->CopyRegister1(this, inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategory1nr); break; case Instruction::MOVE_16: work_line_->CopyRegister1(this, inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategory1nr); break; case Instruction::MOVE_WIDE: work_line_->CopyRegister2(this, inst->VRegA_12x(), inst->VRegB_12x()); break; case Instruction::MOVE_WIDE_FROM16: work_line_->CopyRegister2(this, inst->VRegA_22x(), inst->VRegB_22x()); break; case Instruction::MOVE_WIDE_16: work_line_->CopyRegister2(this, inst->VRegA_32x(), inst->VRegB_32x()); break; case Instruction::MOVE_OBJECT: work_line_->CopyRegister1(this, inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategoryRef); break; case Instruction::MOVE_OBJECT_FROM16: work_line_->CopyRegister1(this, inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategoryRef); break; case Instruction::MOVE_OBJECT_16: work_line_->CopyRegister1(this, inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategoryRef); break; /* * The move-result instructions copy data out of a "pseudo-register" * with the results from the last method invocation. In practice we * might want to hold the result in an actual CPU register, so the * Dalvik spec requires that these only appear immediately after an * invoke or filled-new-array. * * These calls invalidate the "result" register. (This is now * redundant with the reset done below, but it can make the debug info * easier to read in some cases.) */ case Instruction::MOVE_RESULT: work_line_->CopyResultRegister1(this, inst->VRegA_11x(), false); break; case Instruction::MOVE_RESULT_WIDE: work_line_->CopyResultRegister2(this, inst->VRegA_11x()); break; case Instruction::MOVE_RESULT_OBJECT: work_line_->CopyResultRegister1(this, inst->VRegA_11x(), true); break; case Instruction::MOVE_EXCEPTION: { // We do not allow MOVE_EXCEPTION as the first instruction in a method. This is a simple case // where one entrypoint to the catch block is not actually an exception path. if (work_insn_idx_ == 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "move-exception at pc 0x0"; break; } /* * This statement can only appear as the first instruction in an exception handler. We verify * that as part of extracting the exception type from the catch block list. */ const RegType& res_type = GetCaughtExceptionType(); work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_11x(), res_type); break; } case Instruction::RETURN_VOID: if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) { if (!GetMethodReturnType().IsConflict()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void not expected"; } } break; case Instruction::RETURN: if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) { /* check the method signature */ const RegType& return_type = GetMethodReturnType(); if (!return_type.IsCategory1Types()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected non-category 1 return type " << return_type; } else { // Compilers may generate synthetic functions that write byte values into boolean fields. // Also, it may use integer values for boolean, byte, short, and character return types. const uint32_t vregA = inst->VRegA_11x(); const RegType& src_type = work_line_->GetRegisterType(this, vregA); bool use_src = ((return_type.IsBoolean() && src_type.IsByte()) || ((return_type.IsBoolean() || return_type.IsByte() || return_type.IsShort() || return_type.IsChar()) && src_type.IsInteger())); /* check the register contents */ bool success = work_line_->VerifyRegisterType(this, vregA, use_src ? src_type : return_type); if (!success) { AppendToLastFailMessage(StringPrintf(" return-1nr on invalid register v%d", vregA)); } } } break; case Instruction::RETURN_WIDE: if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) { /* check the method signature */ const RegType& return_type = GetMethodReturnType(); if (!return_type.IsCategory2Types()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-wide not expected"; } else { /* check the register contents */ const uint32_t vregA = inst->VRegA_11x(); bool success = work_line_->VerifyRegisterType(this, vregA, return_type); if (!success) { AppendToLastFailMessage(StringPrintf(" return-wide on invalid register v%d", vregA)); } } } break; case Instruction::RETURN_OBJECT: if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) { const RegType& return_type = GetMethodReturnType(); if (!return_type.IsReferenceTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object not expected"; } else { /* return_type is the *expected* return type, not register value */ DCHECK(!return_type.IsZeroOrNull()); DCHECK(!return_type.IsUninitializedReference()); const uint32_t vregA = inst->VRegA_11x(); const RegType& reg_type = work_line_->GetRegisterType(this, vregA); // Disallow returning undefined, conflict & uninitialized values and verify that the // reference in vAA is an instance of the "return_type." if (reg_type.IsUndefined()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning undefined register"; } else if (reg_type.IsConflict()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning register with conflict"; } else if (reg_type.IsUninitializedTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning uninitialized object '" << reg_type << "'"; } else if (!reg_type.IsReferenceTypes()) { // We really do expect a reference here. Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object returns a non-reference type " << reg_type; } else if (!return_type.IsAssignableFrom(reg_type, this)) { if (reg_type.IsUnresolvedTypes() || return_type.IsUnresolvedTypes()) { Fail(VERIFY_ERROR_NO_CLASS) << " can't resolve returned type '" << return_type << "' or '" << reg_type << "'"; } else { bool soft_error = false; // Check whether arrays are involved. They will show a valid class status, even // if their components are erroneous. if (reg_type.IsArrayTypes() && return_type.IsArrayTypes()) { return_type.CanAssignArray(reg_type, reg_types_, class_loader_, this, &soft_error); if (soft_error) { Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "array with erroneous component type: " << reg_type << " vs " << return_type; } } if (!soft_error) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning '" << reg_type << "', but expected from declaration '" << return_type << "'"; } } } } } break; /* could be boolean, int, float, or a null reference */ case Instruction::CONST_4: { int32_t val = static_cast<int32_t>(inst->VRegB_11n() << 28) >> 28; work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_11n(), DetermineCat1Constant(val, need_precise_constants_)); break; } case Instruction::CONST_16: { int16_t val = static_cast<int16_t>(inst->VRegB_21s()); work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_21s(), DetermineCat1Constant(val, need_precise_constants_)); break; } case Instruction::CONST: { int32_t val = inst->VRegB_31i(); work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_31i(), DetermineCat1Constant(val, need_precise_constants_)); break; } case Instruction::CONST_HIGH16: { int32_t val = static_cast<int32_t>(inst->VRegB_21h() << 16); work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_21h(), DetermineCat1Constant(val, need_precise_constants_)); break; } /* could be long or double; resolved upon use */ case Instruction::CONST_WIDE_16: { int64_t val = static_cast<int16_t>(inst->VRegB_21s()); const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); work_line_->SetRegisterTypeWide(this, inst->VRegA_21s(), lo, hi); break; } case Instruction::CONST_WIDE_32: { int64_t val = static_cast<int32_t>(inst->VRegB_31i()); const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); work_line_->SetRegisterTypeWide(this, inst->VRegA_31i(), lo, hi); break; } case Instruction::CONST_WIDE: { int64_t val = inst->VRegB_51l(); const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); work_line_->SetRegisterTypeWide(this, inst->VRegA_51l(), lo, hi); break; } case Instruction::CONST_WIDE_HIGH16: { int64_t val = static_cast<uint64_t>(inst->VRegB_21h()) << 48; const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); work_line_->SetRegisterTypeWide(this, inst->VRegA_21h(), lo, hi); break; } case Instruction::CONST_STRING: work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_21c(), reg_types_.JavaLangString()); break; case Instruction::CONST_STRING_JUMBO: work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_31c(), reg_types_.JavaLangString()); break; case Instruction::CONST_CLASS: { // Get type from instruction if unresolved then we need an access check // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved const RegType& res_type = ResolveClass<CheckAccess::kYes>(dex::TypeIndex(inst->VRegB_21c())); // Register holds class, ie its type is class, on error it will hold Conflict. work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_21c(), res_type.IsConflict() ? res_type : reg_types_.JavaLangClass()); break; } case Instruction::CONST_METHOD_HANDLE: work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_21c(), reg_types_.JavaLangInvokeMethodHandle()); break; case Instruction::CONST_METHOD_TYPE: work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_21c(), reg_types_.JavaLangInvokeMethodType()); break; case Instruction::MONITOR_ENTER: work_line_->PushMonitor(this, inst->VRegA_11x(), work_insn_idx_); // Check whether the previous instruction is a move-object with vAA as a source, creating // untracked lock aliasing. if (0 != work_insn_idx_ && !GetInstructionFlags(work_insn_idx_).IsBranchTarget()) { uint32_t prev_idx = work_insn_idx_ - 1; while (0 != prev_idx && !GetInstructionFlags(prev_idx).IsOpcode()) { prev_idx--; } const Instruction& prev_inst = code_item_accessor_.InstructionAt(prev_idx); switch (prev_inst.Opcode()) { case Instruction::MOVE_OBJECT: case Instruction::MOVE_OBJECT_16: case Instruction::MOVE_OBJECT_FROM16: if (prev_inst.VRegB() == inst->VRegA_11x()) { // Redo the copy. This won't change the register types, but update the lock status // for the aliased register. work_line_->CopyRegister1(this, prev_inst.VRegA(), prev_inst.VRegB(), kTypeCategoryRef); } break; // Catch a case of register aliasing when two registers are linked to the same // java.lang.Class object via two consequent const-class instructions immediately // preceding monitor-enter called on one of those registers. case Instruction::CONST_CLASS: { // Get the second previous instruction. if (prev_idx == 0 || GetInstructionFlags(prev_idx).IsBranchTarget()) { break; } prev_idx--; while (0 != prev_idx && !GetInstructionFlags(prev_idx).IsOpcode()) { prev_idx--; } const Instruction& prev2_inst = code_item_accessor_.InstructionAt(prev_idx); // Match the pattern "const-class; const-class; monitor-enter;" if (prev2_inst.Opcode() != Instruction::CONST_CLASS) { break; } // Ensure both const-classes are called for the same type_idx. if (prev_inst.VRegB_21c() != prev2_inst.VRegB_21c()) { break; } // Update the lock status for the aliased register. if (prev_inst.VRegA() == inst->VRegA_11x()) { work_line_->CopyRegister1(this, prev2_inst.VRegA(), inst->VRegA_11x(), kTypeCategoryRef); } else if (prev2_inst.VRegA() == inst->VRegA_11x()) { work_line_->CopyRegister1(this, prev_inst.VRegA(), inst->VRegA_11x(), kTypeCategoryRef); } break; } default: // Other instruction types ignored. break; } } break; case Instruction::MONITOR_EXIT: /* * monitor-exit instructions are odd. They can throw exceptions, * but when they do they act as if they succeeded and the PC is * pointing to the following instruction. (This behavior goes back * to the need to handle asynchronous exceptions, a now-deprecated * feature that Dalvik doesn't support.) * * In practice we don't need to worry about this. The only * exceptions that can be thrown from monitor-exit are for a * null reference and -exit without a matching -enter. If the * structured locking checks are working, the former would have * failed on the -enter instruction, and the latter is impossible. * * This is fortunate, because issue 3221411 prevents us from * chasing the "can throw" path when monitor verification is * enabled. If we can fully verify the locking we can ignore * some catch blocks (which will show up as "dead" code when * we skip them here); if we can't, then the code path could be * "live" so we still need to check it. */ opcode_flags &= ~Instruction::kThrow; work_line_->PopMonitor(this, inst->VRegA_11x()); break; case Instruction::CHECK_CAST: case Instruction::INSTANCE_OF: { /* * If this instruction succeeds, we will "downcast" register vA to the type in vB. (This * could be a "upcast" -- not expected, so we don't try to address it.) * * If it fails, an exception is thrown, which we deal with later by ignoring the update to * dec_insn.vA when branching to a handler. */ const bool is_checkcast = (inst->Opcode() == Instruction::CHECK_CAST); const dex::TypeIndex type_idx((is_checkcast) ? inst->VRegB_21c() : inst->VRegC_22c()); const RegType& res_type = ResolveClass<CheckAccess::kYes>(type_idx); if (res_type.IsConflict()) { // If this is a primitive type, fail HARD. ObjPtr<mirror::Class> klass = Runtime::Current()->GetClassLinker()->LookupResolvedType( type_idx, dex_cache_.Get(), class_loader_.Get()); if (klass != nullptr && klass->IsPrimitive()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "using primitive type " << dex_file_->StringByTypeIdx(type_idx) << " in instanceof in " << GetDeclaringClass(); break; } DCHECK_NE(failures_.size(), 0U); if (!is_checkcast) { work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_22c(), reg_types_.Boolean()); } break; // bad class } // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved uint32_t orig_type_reg = (is_checkcast) ? inst->VRegA_21c() : inst->VRegB_22c(); const RegType& orig_type = work_line_->GetRegisterType(this, orig_type_reg); if (!res_type.IsNonZeroReferenceTypes()) { if (is_checkcast) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on unexpected class " << res_type; } else { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on unexpected class " << res_type; } } else if (!orig_type.IsReferenceTypes()) { if (is_checkcast) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on non-reference in v" << orig_type_reg; } else { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on non-reference in v" << orig_type_reg; } } else if (orig_type.IsUninitializedTypes()) { if (is_checkcast) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on uninitialized reference in v" << orig_type_reg; } else { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on uninitialized reference in v" << orig_type_reg; } } else { if (is_checkcast) { work_line_->SetRegisterType<LockOp::kKeep>(this, inst->VRegA_21c(), res_type); } else { work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_22c(), reg_types_.Boolean()); } } break; } case Instruction::ARRAY_LENGTH: { const RegType& res_type = work_line_->GetRegisterType(this, inst->VRegB_12x()); if (res_type.IsReferenceTypes()) { if (!res_type.IsArrayTypes() && !res_type.IsZeroOrNull()) { // ie not an array or null Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type; } else { work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_12x(), reg_types_.Integer()); } } else { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type; } break; } case Instruction::NEW_INSTANCE: { const RegType& res_type = ResolveClass<CheckAccess::kYes>(dex::TypeIndex(inst->VRegB_21c())); if (res_type.IsConflict()) { DCHECK_NE(failures_.size(), 0U); break; // bad class } // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved // can't create an instance of an interface or abstract class */ if (!res_type.IsInstantiableTypes()) { Fail(VERIFY_ERROR_INSTANTIATION) << "new-instance on primitive, interface or abstract class" << res_type; // Soft failure so carry on to set register type. } const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_); // Any registers holding previous allocations from this address that have not yet been // initialized must be marked invalid. work_line_->MarkUninitRefsAsInvalid(this, uninit_type); // add the new uninitialized reference to the register state work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_21c(), uninit_type); break; } case Instruction::NEW_ARRAY: VerifyNewArray(inst, false, false); break; case Instruction::FILLED_NEW_ARRAY: VerifyNewArray(inst, true, false); just_set_result = true; // Filled new array sets result register break; case Instruction::FILLED_NEW_ARRAY_RANGE: VerifyNewArray(inst, true, true); just_set_result = true; // Filled new array range sets result register break; case Instruction::CMPL_FLOAT: case Instruction::CMPG_FLOAT: if (!work_line_->VerifyRegisterType(this, inst->VRegB_23x(), reg_types_.Float())) { break; } if (!work_line_->VerifyRegisterType(this, inst->VRegC_23x(), reg_types_.Float())) { break; } work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Integer()); break; case Instruction::CMPL_DOUBLE: case Instruction::CMPG_DOUBLE: if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegB_23x(), reg_types_.DoubleLo(), reg_types_.DoubleHi())) { break; } if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegC_23x(), reg_types_.DoubleLo(), reg_types_.DoubleHi())) { break; } work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Integer()); break; case Instruction::CMP_LONG: if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegB_23x(), reg_types_.LongLo(), reg_types_.LongHi())) { break; } if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegC_23x(), reg_types_.LongLo(), reg_types_.LongHi())) { break; } work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Integer()); break; case Instruction::THROW: { const RegType& res_type = work_line_->GetRegisterType(this, inst->VRegA_11x()); if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(res_type, this)) { if (res_type.IsUninitializedTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "thrown exception not initialized"; } else if (!res_type.IsReferenceTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "thrown value of non-reference type " << res_type; } else { Fail(res_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : VERIFY_ERROR_BAD_CLASS_SOFT) << "thrown class " << res_type << " not instanceof Throwable"; } } break; } case Instruction::GOTO: case Instruction::GOTO_16: case Instruction::GOTO_32: /* no effect on or use of registers */ break; case Instruction::PACKED_SWITCH: case Instruction::SPARSE_SWITCH: /* verify that vAA is an integer, or can be converted to one */ work_line_->VerifyRegisterType(this, inst->VRegA_31t(), reg_types_.Integer()); break; case Instruction::FILL_ARRAY_DATA: { /* Similar to the verification done for APUT */ const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegA_31t()); /* array_type can be null if the reg type is Zero */ if (!array_type.IsZeroOrNull()) { if (!array_type.IsArrayTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with array type " << array_type; } else if (array_type.IsUnresolvedTypes()) { // If it's an unresolved array type, it must be non-primitive. Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data for array of type " << array_type; } else { const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_.Get()); DCHECK(!component_type.IsConflict()); if (component_type.IsNonZeroReferenceTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type " << component_type; } else { // Now verify if the element width in the table matches the element width declared in // the array const uint16_t* array_data = insns + (insns[1] | (static_cast<int32_t>(insns[2]) << 16)); if (array_data[0] != Instruction::kArrayDataSignature) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid magic for array-data"; } else { size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType()); // Since we don't compress the data in Dex, expect to see equal width of data stored // in the table and expected from the array class. if (array_data[1] != elem_width) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1] << " vs " << elem_width << ")"; } } } } } break; } case Instruction::IF_EQ: case Instruction::IF_NE: { const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t()); const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t()); bool mismatch = false; if (reg_type1.IsZeroOrNull()) { // zero then integral or reference expected mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes(); } else if (reg_type1.IsReferenceTypes()) { // both references? mismatch = !reg_type2.IsReferenceTypes(); } else { // both integral? mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes(); } if (mismatch) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << "," << reg_type2 << ") must both be references or integral"; } break; } case Instruction::IF_LT: case Instruction::IF_GE: case Instruction::IF_GT: case Instruction::IF_LE: { const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t()); const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t()); if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << "," << reg_type2 << ") must be integral"; } break; } case Instruction::IF_EQZ: case Instruction::IF_NEZ: { const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t()); if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type << " unexpected as arg to if-eqz/if-nez"; } // Find previous instruction - its existence is a precondition to peephole optimization. uint32_t instance_of_idx = 0; if (0 != work_insn_idx_) { instance_of_idx = work_insn_idx_ - 1; while (0 != instance_of_idx && !GetInstructionFlags(instance_of_idx).IsOpcode()) { instance_of_idx--; } if (FailOrAbort(GetInstructionFlags(instance_of_idx).IsOpcode(), "Unable to get previous instruction of if-eqz/if-nez for work index ", work_insn_idx_)) { break; } } else { break; } const Instruction& instance_of_inst = code_item_accessor_.InstructionAt(instance_of_idx); /* Check for peep-hole pattern of: * ...; * instance-of vX, vY, T; * ifXXX vX, label ; * ...; * label: * ...; * and sharpen the type of vY to be type T. * Note, this pattern can't be if: * - if there are other branches to this branch, * - when vX == vY. */ if (!CurrentInsnFlags()->IsBranchTarget() && (Instruction::INSTANCE_OF == instance_of_inst.Opcode()) && (inst->VRegA_21t() == instance_of_inst.VRegA_22c()) && (instance_of_inst.VRegA_22c() != instance_of_inst.VRegB_22c())) { // Check the type of the instance-of is different than that of registers type, as if they // are the same there is no work to be done here. Check that the conversion is not to or // from an unresolved type as type information is imprecise. If the instance-of is to an // interface then ignore the type information as interfaces can only be treated as Objects // and we don't want to disallow field and other operations on the object. If the value // being instance-of checked against is known null (zero) then allow the optimization as // we didn't have type information. If the merge of the instance-of type with the original // type is assignable to the original then allow optimization. This check is performed to // ensure that subsequent merges don't lose type information - such as becoming an // interface from a class that would lose information relevant to field checks. const RegType& orig_type = work_line_->GetRegisterType(this, instance_of_inst.VRegB_22c()); const RegType& cast_type = ResolveClass<CheckAccess::kYes>( dex::TypeIndex(instance_of_inst.VRegC_22c())); if (!orig_type.Equals(cast_type) && !cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() && cast_type.HasClass() && // Could be conflict type, make sure it has a class. !cast_type.GetClass()->IsInterface() && (orig_type.IsZeroOrNull() || orig_type.IsStrictlyAssignableFrom( cast_type.Merge(orig_type, &reg_types_, this), this))) { RegisterLine* update_line = RegisterLine::Create(code_item_accessor_.RegistersSize(), allocator_, GetRegTypeCache()); if (inst->Opcode() == Instruction::IF_EQZ) { fallthrough_line.reset(update_line); } else { branch_line.reset(update_line); } update_line->CopyFromLine(work_line_.get()); update_line->SetRegisterType<LockOp::kKeep>(this, instance_of_inst.VRegB_22c(), cast_type); if (!GetInstructionFlags(instance_of_idx).IsBranchTarget() && 0 != instance_of_idx) { // See if instance-of was preceded by a move-object operation, common due to the small // register encoding space of instance-of, and propagate type information to the source // of the move-object. // Note: this is only valid if the move source was not clobbered. uint32_t move_idx = instance_of_idx - 1; while (0 != move_idx && !GetInstructionFlags(move_idx).IsOpcode()) { move_idx--; } if (FailOrAbort(GetInstructionFlags(move_idx).IsOpcode(), "Unable to get previous instruction of if-eqz/if-nez for work index ", work_insn_idx_)) { break; } auto maybe_update_fn = [&instance_of_inst, update_line, this, &cast_type]( uint16_t move_src, uint16_t move_trg) REQUIRES_SHARED(Locks::mutator_lock_) { if (move_trg == instance_of_inst.VRegB_22c() && move_src != instance_of_inst.VRegA_22c()) { update_line->SetRegisterType<LockOp::kKeep>(this, move_src, cast_type); } }; const Instruction& move_inst = code_item_accessor_.InstructionAt(move_idx); switch (move_inst.Opcode()) { case Instruction::MOVE_OBJECT: maybe_update_fn(move_inst.VRegB_12x(), move_inst.VRegA_12x()); break; case Instruction::MOVE_OBJECT_FROM16: maybe_update_fn(move_inst.VRegB_22x(), move_inst.VRegA_22x()); break; case Instruction::MOVE_OBJECT_16: maybe_update_fn(move_inst.VRegB_32x(), move_inst.VRegA_32x()); break; default: break; } } } } break; } case Instruction::IF_LTZ: case Instruction::IF_GEZ: case Instruction::IF_GTZ: case Instruction::IF_LEZ: { const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t()); if (!reg_type.IsIntegralTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez"; } break; } case Instruction::AGET_BOOLEAN: VerifyAGet(inst, reg_types_.Boolean(), true); break; case Instruction::AGET_BYTE: VerifyAGet(inst, reg_types_.Byte(), true); break; case Instruction::AGET_CHAR: VerifyAGet(inst, reg_types_.Char(), true); break; case Instruction::AGET_SHORT: VerifyAGet(inst, reg_types_.Short(), true); break; case Instruction::AGET: VerifyAGet(inst, reg_types_.Integer(), true); break; case Instruction::AGET_WIDE: VerifyAGet(inst, reg_types_.LongLo(), true); break; case Instruction::AGET_OBJECT: VerifyAGet(inst, reg_types_.JavaLangObject(false), false); break; case Instruction::APUT_BOOLEAN: VerifyAPut(inst, reg_types_.Boolean(), true); break; case Instruction::APUT_BYTE: VerifyAPut(inst, reg_types_.Byte(), true); break; case Instruction::APUT_CHAR: VerifyAPut(inst, reg_types_.Char(), true); break; case Instruction::APUT_SHORT: VerifyAPut(inst, reg_types_.Short(), true); break; case Instruction::APUT: VerifyAPut(inst, reg_types_.Integer(), true); break; case Instruction::APUT_WIDE: VerifyAPut(inst, reg_types_.LongLo(), true); break; case Instruction::APUT_OBJECT: VerifyAPut(inst, reg_types_.JavaLangObject(false), false); break; case Instruction::IGET_BOOLEAN: case Instruction::IGET_BOOLEAN_QUICK: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Boolean(), true, false); break; case Instruction::IGET_BYTE: case Instruction::IGET_BYTE_QUICK: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Byte(), true, false); break; case Instruction::IGET_CHAR: case Instruction::IGET_CHAR_QUICK: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Char(), true, false); break; case Instruction::IGET_SHORT: case Instruction::IGET_SHORT_QUICK: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Short(), true, false); break; case Instruction::IGET: case Instruction::IGET_QUICK: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Integer(), true, false); break; case Instruction::IGET_WIDE: case Instruction::IGET_WIDE_QUICK: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.LongLo(), true, false); break; case Instruction::IGET_OBJECT: case Instruction::IGET_OBJECT_QUICK: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.JavaLangObject(false), false, false); break; case Instruction::IPUT_BOOLEAN: case Instruction::IPUT_BOOLEAN_QUICK: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Boolean(), true, false); break; case Instruction::IPUT_BYTE: case Instruction::IPUT_BYTE_QUICK: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Byte(), true, false); break; case Instruction::IPUT_CHAR: case Instruction::IPUT_CHAR_QUICK: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Char(), true, false); break; case Instruction::IPUT_SHORT: case Instruction::IPUT_SHORT_QUICK: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Short(), true, false); break; case Instruction::IPUT: case Instruction::IPUT_QUICK: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Integer(), true, false); break; case Instruction::IPUT_WIDE: case Instruction::IPUT_WIDE_QUICK: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.LongLo(), true, false); break; case Instruction::IPUT_OBJECT: case Instruction::IPUT_OBJECT_QUICK: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.JavaLangObject(false), false, false); break; case Instruction::SGET_BOOLEAN: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Boolean(), true, true); break; case Instruction::SGET_BYTE: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Byte(), true, true); break; case Instruction::SGET_CHAR: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Char(), true, true); break; case Instruction::SGET_SHORT: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Short(), true, true); break; case Instruction::SGET: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Integer(), true, true); break; case Instruction::SGET_WIDE: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.LongLo(), true, true); break; case Instruction::SGET_OBJECT: VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.JavaLangObject(false), false, true); break; case Instruction::SPUT_BOOLEAN: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Boolean(), true, true); break; case Instruction::SPUT_BYTE: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Byte(), true, true); break; case Instruction::SPUT_CHAR: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Char(), true, true); break; case Instruction::SPUT_SHORT: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Short(), true, true); break; case Instruction::SPUT: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Integer(), true, true); break; case Instruction::SPUT_WIDE: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.LongLo(), true, true); break; case Instruction::SPUT_OBJECT: VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.JavaLangObject(false), false, true); break; case Instruction::INVOKE_VIRTUAL: case Instruction::INVOKE_VIRTUAL_RANGE: case Instruction::INVOKE_SUPER: case Instruction::INVOKE_SUPER_RANGE: case Instruction::INVOKE_VIRTUAL_QUICK: case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: { bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE || inst->Opcode() == Instruction::INVOKE_SUPER_RANGE || inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER || inst->Opcode() == Instruction::INVOKE_SUPER_RANGE); MethodType type = is_super ? METHOD_SUPER : METHOD_VIRTUAL; ArtMethod* called_method = VerifyInvocationArgs(inst, type, is_range); const RegType* return_type = nullptr; if (called_method != nullptr) { ObjPtr<mirror::Class> return_type_class = can_load_classes_ ? called_method->ResolveReturnType() : called_method->LookupResolvedReturnType(); if (return_type_class != nullptr) { return_type = &FromClass(called_method->GetReturnTypeDescriptor(), return_type_class, return_type_class->CannotBeAssignedFromOtherTypes()); } else { DCHECK(!can_load_classes_ || self_->IsExceptionPending()); self_->ClearException(); } } if (return_type == nullptr) { uint32_t method_idx = GetMethodIdxOfInvoke(inst); const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx); dex::TypeIndex return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; const char* descriptor = dex_file_->StringByTypeIdx(return_type_idx); return_type = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false); } if (!return_type->IsLowHalf()) { work_line_->SetResultRegisterType(this, *return_type); } else { work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(&reg_types_)); } just_set_result = true; break; } case Instruction::INVOKE_DIRECT: case Instruction::INVOKE_DIRECT_RANGE: { bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE); ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT, is_range); const char* return_type_descriptor; bool is_constructor; const RegType* return_type = nullptr; if (called_method == nullptr) { uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx); is_constructor = strcmp("<init>", dex_file_->StringDataByIdx(method_id.name_idx_)) == 0; dex::TypeIndex return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; return_type_descriptor = dex_file_->StringByTypeIdx(return_type_idx); } else { is_constructor = called_method->IsConstructor(); return_type_descriptor = called_method->GetReturnTypeDescriptor(); ObjPtr<mirror::Class> return_type_class = can_load_classes_ ? called_method->ResolveReturnType() : called_method->LookupResolvedReturnType(); if (return_type_class != nullptr) { return_type = &FromClass(return_type_descriptor, return_type_class, return_type_class->CannotBeAssignedFromOtherTypes()); } else { DCHECK(!can_load_classes_ || self_->IsExceptionPending()); self_->ClearException(); } } if (is_constructor) { /* * Some additional checks when calling a constructor. We know from the invocation arg check * that the "this" argument is an instance of called_method->klass. Now we further restrict * that to require that called_method->klass is the same as this->klass or this->super, * allowing the latter only if the "this" argument is the same as the "this" argument to * this method (which implies that we're in a constructor ourselves). */ const RegType& this_type = work_line_->GetInvocationThis(this, inst); if (this_type.IsConflict()) // failure. break; /* no null refs allowed (?) */ if (this_type.IsZeroOrNull()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref"; break; } /* must be in same class or in superclass */ // const RegType& this_super_klass = this_type.GetSuperClass(&reg_types_); // TODO: re-enable constructor type verification // if (this_super_klass.IsConflict()) { // Unknown super class, fail so we re-check at runtime. // Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "super class unknown for '" << this_type << "'"; // break; // } /* arg must be an uninitialized reference */ if (!this_type.IsUninitializedTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Expected initialization on uninitialized reference " << this_type; break; } /* * Replace the uninitialized reference with an initialized one. We need to do this for all * registers that have the same object instance in them, not just the "this" register. */ work_line_->MarkRefsAsInitialized(this, this_type); } if (return_type == nullptr) { return_type = &reg_types_.FromDescriptor(class_loader_.Get(), return_type_descriptor, false); } if (!return_type->IsLowHalf()) { work_line_->SetResultRegisterType(this, *return_type); } else { work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(&reg_types_)); } just_set_result = true; break; } case Instruction::INVOKE_STATIC: case Instruction::INVOKE_STATIC_RANGE: { bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE); ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_STATIC, is_range); const char* descriptor; if (called_method == nullptr) { uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx); dex::TypeIndex return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; descriptor = dex_file_->StringByTypeIdx(return_type_idx); } else { descriptor = called_method->GetReturnTypeDescriptor(); } const RegType& return_type = reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false); if (!return_type.IsLowHalf()) { work_line_->SetResultRegisterType(this, return_type); } else { work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_)); } just_set_result = true; } break; case Instruction::INVOKE_INTERFACE: case Instruction::INVOKE_INTERFACE_RANGE: { bool is_range = (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE); ArtMethod* abs_method = VerifyInvocationArgs(inst, METHOD_INTERFACE, is_range); if (abs_method != nullptr) { ObjPtr<mirror::Class> called_interface = abs_method->GetDeclaringClass(); if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) { Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '" << abs_method->PrettyMethod() << "'"; break; } } /* Get the type of the "this" arg, which should either be a sub-interface of called * interface or Object (see comments in RegType::JoinClass). */ const RegType& this_type = work_line_->GetInvocationThis(this, inst); if (this_type.IsZeroOrNull()) { /* null pointer always passes (and always fails at runtime) */ } else { if (this_type.IsUninitializedTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface call on uninitialized object " << this_type; break; } // In the past we have tried to assert that "called_interface" is assignable // from "this_type.GetClass()", however, as we do an imprecise Join // (RegType::JoinClass) we don't have full information on what interfaces are // implemented by "this_type". For example, two classes may implement the same // interfaces and have a common parent that doesn't implement the interface. The // join will set "this_type" to the parent class and a test that this implements // the interface will incorrectly fail. } /* * We don't have an object instance, so we can't find the concrete method. However, all of * the type information is in the abstract method, so we're good. */ const char* descriptor; if (abs_method == nullptr) { uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx); dex::TypeIndex return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; descriptor = dex_file_->StringByTypeIdx(return_type_idx); } else { descriptor = abs_method->GetReturnTypeDescriptor(); } const RegType& return_type = reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false); if (!return_type.IsLowHalf()) { work_line_->SetResultRegisterType(this, return_type); } else { work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_)); } just_set_result = true; break; } case Instruction::INVOKE_POLYMORPHIC: case Instruction::INVOKE_POLYMORPHIC_RANGE: { bool is_range = (inst->Opcode() == Instruction::INVOKE_POLYMORPHIC_RANGE); ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_POLYMORPHIC, is_range); if (called_method == nullptr) { // Convert potential soft failures in VerifyInvocationArgs() to hard errors. if (failure_messages_.size() > 0) { std::string message = failure_messages_.back()->str(); Fail(VERIFY_ERROR_BAD_CLASS_HARD) << message; } else { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-polymorphic verification failure."; } break; } if (!CheckSignaturePolymorphicMethod(called_method) || !CheckSignaturePolymorphicReceiver(inst)) { DCHECK(HasFailures()); break; } const uint16_t vRegH = (is_range) ? inst->VRegH_4rcc() : inst->VRegH_45cc(); const dex::ProtoIndex proto_idx(vRegH); const char* return_descriptor = dex_file_->GetReturnTypeDescriptor(dex_file_->GetProtoId(proto_idx)); const RegType& return_type = reg_types_.FromDescriptor(class_loader_.Get(), return_descriptor, false); if (!return_type.IsLowHalf()) { work_line_->SetResultRegisterType(this, return_type); } else { work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_)); } just_set_result = true; break; } case Instruction::INVOKE_CUSTOM: case Instruction::INVOKE_CUSTOM_RANGE: { // Verify registers based on method_type in the call site. bool is_range = (inst->Opcode() == Instruction::INVOKE_CUSTOM_RANGE); // Step 1. Check the call site that produces the method handle for invocation const uint32_t call_site_idx = is_range ? inst->VRegB_3rc() : inst->VRegB_35c(); if (!CheckCallSite(call_site_idx)) { DCHECK(HasFailures()); break; } // Step 2. Check the register arguments correspond to the expected arguments for the // method handle produced by step 1. The dex file verifier has checked ranges for // the first three arguments and CheckCallSite has checked the method handle type. const dex::ProtoIndex proto_idx = dex_file_->GetProtoIndexForCallSite(call_site_idx); const dex::ProtoId& proto_id = dex_file_->GetProtoId(proto_idx); DexFileParameterIterator param_it(*dex_file_, proto_id); // Treat method as static as it has yet to be determined. VerifyInvocationArgsFromIterator(&param_it, inst, METHOD_STATIC, is_range, nullptr); const char* return_descriptor = dex_file_->GetReturnTypeDescriptor(proto_id); // Step 3. Propagate return type information const RegType& return_type = reg_types_.FromDescriptor(class_loader_.Get(), return_descriptor, false); if (!return_type.IsLowHalf()) { work_line_->SetResultRegisterType(this, return_type); } else { work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_)); } just_set_result = true; break; } case Instruction::NEG_INT: case Instruction::NOT_INT: work_line_->CheckUnaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer()); break; case Instruction::NEG_LONG: case Instruction::NOT_LONG: work_line_->CheckUnaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.LongLo(), reg_types_.LongHi()); break; case Instruction::NEG_FLOAT: work_line_->CheckUnaryOp(this, inst, reg_types_.Float(), reg_types_.Float()); break; case Instruction::NEG_DOUBLE: work_line_->CheckUnaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), reg_types_.DoubleLo(), reg_types_.DoubleHi()); break; case Instruction::INT_TO_LONG: work_line_->CheckUnaryOpToWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.Integer()); break; case Instruction::INT_TO_FLOAT: work_line_->CheckUnaryOp(this, inst, reg_types_.Float(), reg_types_.Integer()); break; case Instruction::INT_TO_DOUBLE: work_line_->CheckUnaryOpToWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), reg_types_.Integer()); break; case Instruction::LONG_TO_INT: work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Integer(), reg_types_.LongLo(), reg_types_.LongHi()); break; case Instruction::LONG_TO_FLOAT: work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Float(), reg_types_.LongLo(), reg_types_.LongHi()); break; case Instruction::LONG_TO_DOUBLE: work_line_->CheckUnaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), reg_types_.LongLo(), reg_types_.LongHi()); break; case Instruction::FLOAT_TO_INT: work_line_->CheckUnaryOp(this, inst, reg_types_.Integer(), reg_types_.Float()); break; case Instruction::FLOAT_TO_LONG: work_line_->CheckUnaryOpToWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.Float()); break; case Instruction::FLOAT_TO_DOUBLE: work_line_->CheckUnaryOpToWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), reg_types_.Float()); break; case Instruction::DOUBLE_TO_INT: work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Integer(), reg_types_.DoubleLo(), reg_types_.DoubleHi()); break; case Instruction::DOUBLE_TO_LONG: work_line_->CheckUnaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.DoubleLo(), reg_types_.DoubleHi()); break; case Instruction::DOUBLE_TO_FLOAT: work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Float(), reg_types_.DoubleLo(), reg_types_.DoubleHi()); break; case Instruction::INT_TO_BYTE: work_line_->CheckUnaryOp(this, inst, reg_types_.Byte(), reg_types_.Integer()); break; case Instruction::INT_TO_CHAR: work_line_->CheckUnaryOp(this, inst, reg_types_.Char(), reg_types_.Integer()); break; case Instruction::INT_TO_SHORT: work_line_->CheckUnaryOp(this, inst, reg_types_.Short(), reg_types_.Integer()); break; case Instruction::ADD_INT: case Instruction::SUB_INT: case Instruction::MUL_INT: case Instruction::REM_INT: case Instruction::DIV_INT: case Instruction::SHL_INT: case Instruction::SHR_INT: case Instruction::USHR_INT: work_line_->CheckBinaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), false); break; case Instruction::AND_INT: case Instruction::OR_INT: case Instruction::XOR_INT: work_line_->CheckBinaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), true); break; case Instruction::ADD_LONG: case Instruction::SUB_LONG: case Instruction::MUL_LONG: case Instruction::DIV_LONG: case Instruction::REM_LONG: case Instruction::AND_LONG: case Instruction::OR_LONG: case Instruction::XOR_LONG: work_line_->CheckBinaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.LongLo(), reg_types_.LongHi()); break; case Instruction::SHL_LONG: case Instruction::SHR_LONG: case Instruction::USHR_LONG: /* shift distance is Int, making these different from other binary operations */ work_line_->CheckBinaryOpWideShift(this, inst, reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.Integer()); break; case Instruction::ADD_FLOAT: case Instruction::SUB_FLOAT: case Instruction::MUL_FLOAT: case Instruction::DIV_FLOAT: case Instruction::REM_FLOAT: work_line_->CheckBinaryOp(this, inst, reg_types_.Float(), reg_types_.Float(), reg_types_.Float(), false); break; case Instruction::ADD_DOUBLE: case Instruction::SUB_DOUBLE: case Instruction::MUL_DOUBLE: case Instruction::DIV_DOUBLE: case Instruction::REM_DOUBLE: work_line_->CheckBinaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), reg_types_.DoubleLo(), reg_types_.DoubleHi(), reg_types_.DoubleLo(), reg_types_.DoubleHi()); break; case Instruction::ADD_INT_2ADDR: case Instruction::SUB_INT_2ADDR: case Instruction::MUL_INT_2ADDR: case Instruction::REM_INT_2ADDR: case Instruction::SHL_INT_2ADDR: case Instruction::SHR_INT_2ADDR: case Instruction::USHR_INT_2ADDR: work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), false); break; case Instruction::AND_INT_2ADDR: case Instruction::OR_INT_2ADDR: case Instruction::XOR_INT_2ADDR: work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), true); break; case Instruction::DIV_INT_2ADDR: work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), false); break; case Instruction::ADD_LONG_2ADDR: case Instruction::SUB_LONG_2ADDR: case Instruction::MUL_LONG_2ADDR: case Instruction::DIV_LONG_2ADDR: case Instruction::REM_LONG_2ADDR: case Instruction::AND_LONG_2ADDR: case Instruction::OR_LONG_2ADDR: case Instruction::XOR_LONG_2ADDR: work_line_->CheckBinaryOp2addrWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.LongLo(), reg_types_.LongHi()); break; case Instruction::SHL_LONG_2ADDR: case Instruction::SHR_LONG_2ADDR: case Instruction::USHR_LONG_2ADDR: work_line_->CheckBinaryOp2addrWideShift(this, inst, reg_types_.LongLo(), reg_types_.LongHi(), reg_types_.Integer()); break; case Instruction::ADD_FLOAT_2ADDR: case Instruction::SUB_FLOAT_2ADDR: case Instruction::MUL_FLOAT_2ADDR: case Instruction::DIV_FLOAT_2ADDR: case Instruction::REM_FLOAT_2ADDR: work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Float(), reg_types_.Float(), reg_types_.Float(), false); break; case Instruction::ADD_DOUBLE_2ADDR: case Instruction::SUB_DOUBLE_2ADDR: case Instruction::MUL_DOUBLE_2ADDR: case Instruction::DIV_DOUBLE_2ADDR: case Instruction::REM_DOUBLE_2ADDR: work_line_->CheckBinaryOp2addrWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), reg_types_.DoubleLo(), reg_types_.DoubleHi(), reg_types_.DoubleLo(), reg_types_.DoubleHi()); break; case Instruction::ADD_INT_LIT16: case Instruction::RSUB_INT_LIT16: case Instruction::MUL_INT_LIT16: case Instruction::DIV_INT_LIT16: case Instruction::REM_INT_LIT16: work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), false, true); break; case Instruction::AND_INT_LIT16: case Instruction::OR_INT_LIT16: case Instruction::XOR_INT_LIT16: work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), true, true); break; case Instruction::ADD_INT_LIT8: case Instruction::RSUB_INT_LIT8: case Instruction::MUL_INT_LIT8: case Instruction::DIV_INT_LIT8: case Instruction::REM_INT_LIT8: case Instruction::SHL_INT_LIT8: case Instruction::SHR_INT_LIT8: case Instruction::USHR_INT_LIT8: work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), false, false); break; case Instruction::AND_INT_LIT8: case Instruction::OR_INT_LIT8: case Instruction::XOR_INT_LIT8: work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), true, false); break; // Special instructions. case Instruction::RETURN_VOID_NO_BARRIER: if (IsConstructor() && !IsStatic()) { const RegType& declaring_class = GetDeclaringClass(); if (declaring_class.IsUnresolvedReference()) { // We must iterate over the fields, even if we cannot use mirror classes to do so. Do it // manually over the underlying dex file. uint32_t first_index = GetFirstFinalInstanceFieldIndex(*dex_file_, dex_file_->GetMethodId(dex_method_idx_).class_idx_); if (first_index != dex::kDexNoIndex) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-no-barrier not expected for field " << first_index; } break; } ObjPtr<mirror::Class> klass = declaring_class.GetClass(); for (uint32_t i = 0, num_fields = klass->NumInstanceFields(); i < num_fields; ++i) { if (klass->GetInstanceField(i)->IsFinal()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-no-barrier not expected for " << klass->GetInstanceField(i)->PrettyField(); break; } } } // Handle this like a RETURN_VOID now. Code is duplicated to separate standard from // quickened opcodes (otherwise this could be a fall-through). if (!IsConstructor()) { if (!GetMethodReturnType().IsConflict()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void not expected"; } } break; /* These should never appear during verification. */ case Instruction::UNUSED_3E ... Instruction::UNUSED_43: case Instruction::UNUSED_F3 ... Instruction::UNUSED_F9: case Instruction::UNUSED_79: case Instruction::UNUSED_7A: Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_); break; /* * DO NOT add a "default" clause here. Without it the compiler will * complain if an instruction is missing (which is desirable). */ } // end - switch (dec_insn.opcode) if (have_pending_hard_failure_) { if (Runtime::Current()->IsAotCompiler()) { /* When AOT compiling, check that the last failure is a hard failure */ if (failures_[failures_.size() - 1] != VERIFY_ERROR_BAD_CLASS_HARD) { LOG(ERROR) << "Pending failures:"; for (auto& error : failures_) { LOG(ERROR) << error; } for (auto& error_msg : failure_messages_) { LOG(ERROR) << error_msg->str(); } LOG(FATAL) << "Pending hard failure, but last failure not hard."; } } /* immediate failure, reject class */ info_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_); return false; } else if (have_pending_runtime_throw_failure_) { /* checking interpreter will throw, mark following code as unreachable */ opcode_flags = Instruction::kThrow; // Note: the flag must be reset as it is only global to decouple Fail and is semantically per // instruction. However, RETURN checking may throw LOCKING errors, so we clear at the // very end. } /* * If we didn't just set the result register, clear it out. This ensures that you can only use * "move-result" immediately after the result is set. (We could check this statically, but it's * not expensive and it makes our debugging output cleaner.) */ if (!just_set_result) { work_line_->SetResultTypeToUnknown(GetRegTypeCache()); } /* * Handle "branch". Tag the branch target. * * NOTE: instructions like Instruction::EQZ provide information about the * state of the register when the branch is taken or not taken. For example, * somebody could get a reference field, check it for zero, and if the * branch is taken immediately store that register in a boolean field * since the value is known to be zero. We do not currently account for * that, and will reject the code. * * TODO: avoid re-fetching the branch target */ if ((opcode_flags & Instruction::kBranch) != 0) { bool isConditional, selfOkay; if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) { /* should never happen after static verification */ Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch"; return false; } DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0); if (!CheckNotMoveExceptionOrMoveResult(code_item_accessor_.Insns(), work_insn_idx_ + branch_target)) { return false; } /* update branch target, set "changed" if appropriate */ if (nullptr != branch_line) { if (!UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get(), false)) { return false; } } else { if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get(), false)) { return false; } } } /* * Handle "switch". Tag all possible branch targets. * * We've already verified that the table is structurally sound, so we * just need to walk through and tag the targets. */ if ((opcode_flags & Instruction::kSwitch) != 0) { int offset_to_switch = insns[1] | (static_cast<int32_t>(insns[2]) << 16); const uint16_t* switch_insns = insns + offset_to_switch; int switch_count = switch_insns[1]; int offset_to_targets, targ; if ((*insns & 0xff) == Instruction::PACKED_SWITCH) { /* 0 = sig, 1 = count, 2/3 = first key */ offset_to_targets = 4; } else { /* 0 = sig, 1 = count, 2..count * 2 = keys */ DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH); offset_to_targets = 2 + 2 * switch_count; } /* verify each switch target */ for (targ = 0; targ < switch_count; targ++) { int offset; uint32_t abs_offset; /* offsets are 32-bit, and only partly endian-swapped */ offset = switch_insns[offset_to_targets + targ * 2] | (static_cast<int32_t>(switch_insns[offset_to_targets + targ * 2 + 1]) << 16); abs_offset = work_insn_idx_ + offset; DCHECK_LT(abs_offset, code_item_accessor_.InsnsSizeInCodeUnits()); if (!CheckNotMoveExceptionOrMoveResult(code_item_accessor_.Insns(), abs_offset)) { return false; } if (!UpdateRegisters(abs_offset, work_line_.get(), false)) { return false; } } } /* * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a * "try" block when they throw, control transfers out of the method.) */ if ((opcode_flags & Instruction::kThrow) != 0 && GetInstructionFlags(work_insn_idx_).IsInTry()) { bool has_catch_all_handler = false; const dex::TryItem* try_item = code_item_accessor_.FindTryItem(work_insn_idx_); CHECK(try_item != nullptr); CatchHandlerIterator iterator(code_item_accessor_, *try_item); // Need the linker to try and resolve the handled class to check if it's Throwable. ClassLinker* linker = Runtime::Current()->GetClassLinker(); for (; iterator.HasNext(); iterator.Next()) { dex::TypeIndex handler_type_idx = iterator.GetHandlerTypeIndex(); if (!handler_type_idx.IsValid()) { has_catch_all_handler = true; } else { // It is also a catch-all if it is java.lang.Throwable. ObjPtr<mirror::Class> klass = linker->ResolveType(handler_type_idx, dex_cache_, class_loader_); if (klass != nullptr) { if (klass == GetClassRoot<mirror::Throwable>()) { has_catch_all_handler = true; } } else { // Clear exception. DCHECK(self_->IsExceptionPending()); self_->ClearException(); } } /* * Merge registers into the "catch" block. We want to use the "savedRegs" rather than * "work_regs", because at runtime the exception will be thrown before the instruction * modifies any registers. */ if (kVerifierDebug) { LogVerifyInfo() << "Updating exception handler 0x" << std::hex << iterator.GetHandlerAddress(); } if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get(), false)) { return false; } } /* * If the monitor stack depth is nonzero, there must be a "catch all" handler for this * instruction. This does apply to monitor-exit because of async exception handling. */ if (work_line_->MonitorStackDepth() > 0 && !has_catch_all_handler) { /* * The state in work_line reflects the post-execution state. If the current instruction is a * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws, * it will do so before grabbing the lock). */ if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected to be within a catch-all for an instruction where a monitor is held"; return false; } } } /* Handle "continue". Tag the next consecutive instruction. * Note: Keep the code handling "continue" case below the "branch" and "switch" cases, * because it changes work_line_ when performing peephole optimization * and this change should not be used in those cases. */ if ((opcode_flags & Instruction::kContinue) != 0) { DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst); uint32_t next_insn_idx = work_insn_idx_ + inst->SizeInCodeUnits(); if (next_insn_idx >= code_item_accessor_.InsnsSizeInCodeUnits()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Execution can walk off end of code area"; return false; } // The only way to get to a move-exception instruction is to get thrown there. Make sure the // next instruction isn't one. if (!CheckNotMoveException(code_item_accessor_.Insns(), next_insn_idx)) { return false; } if (nullptr != fallthrough_line) { // Make workline consistent with fallthrough computed from peephole optimization. work_line_->CopyFromLine(fallthrough_line.get()); } if (GetInstructionFlags(next_insn_idx).IsReturn()) { // For returns we only care about the operand to the return, all other registers are dead. const Instruction* ret_inst = &code_item_accessor_.InstructionAt(next_insn_idx); AdjustReturnLine(this, ret_inst, work_line_.get()); } RegisterLine* next_line = reg_table_.GetLine(next_insn_idx); if (next_line != nullptr) { // Merge registers into what we have for the next instruction, and set the "changed" flag if // needed. If the merge changes the state of the registers then the work line will be // updated. if (!UpdateRegisters(next_insn_idx, work_line_.get(), true)) { return false; } } else { /* * We're not recording register data for the next instruction, so we don't know what the * prior state was. We have to assume that something has changed and re-evaluate it. */ GetModifiableInstructionFlags(next_insn_idx).SetChanged(); } } /* If we're returning from the method, make sure monitor stack is empty. */ if ((opcode_flags & Instruction::kReturn) != 0) { work_line_->VerifyMonitorStackEmpty(this); } /* * Update start_guess. Advance to the next instruction of that's * possible, otherwise use the branch target if one was found. If * neither of those exists we're in a return or throw; leave start_guess * alone and let the caller sort it out. */ if ((opcode_flags & Instruction::kContinue) != 0) { DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst); *start_guess = work_insn_idx_ + inst->SizeInCodeUnits(); } else if ((opcode_flags & Instruction::kBranch) != 0) { /* we're still okay if branch_target is zero */ *start_guess = work_insn_idx_ + branch_target; } DCHECK_LT(*start_guess, code_item_accessor_.InsnsSizeInCodeUnits()); DCHECK(GetInstructionFlags(*start_guess).IsOpcode()); if (have_pending_runtime_throw_failure_) { have_any_pending_runtime_throw_failure_ = true; // Reset the pending_runtime_throw flag now. have_pending_runtime_throw_failure_ = false; } return true; } // NOLINT(readability/fn_size) template <bool kVerifierDebug> template <CheckAccess C> const RegType& MethodVerifier<kVerifierDebug>::ResolveClass(dex::TypeIndex class_idx) { ClassLinker* linker = Runtime::Current()->GetClassLinker(); ObjPtr<mirror::Class> klass = can_load_classes_ ? linker->ResolveType(class_idx, dex_cache_, class_loader_) : linker->LookupResolvedType(class_idx, dex_cache_.Get(), class_loader_.Get()); if (can_load_classes_ && klass == nullptr) { DCHECK(self_->IsExceptionPending()); self_->ClearException(); } const RegType* result = nullptr; if (klass != nullptr) { bool precise = klass->CannotBeAssignedFromOtherTypes(); if (precise && !IsInstantiableOrPrimitive(klass)) { const char* descriptor = dex_file_->StringByTypeIdx(class_idx); UninstantiableError(descriptor); precise = false; } result = reg_types_.FindClass(klass, precise); if (result == nullptr) { const char* descriptor = dex_file_->StringByTypeIdx(class_idx); result = reg_types_.InsertClass(descriptor, klass, precise); } } else { const char* descriptor = dex_file_->StringByTypeIdx(class_idx); result = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false); } DCHECK(result != nullptr); if (result->IsConflict()) { const char* descriptor = dex_file_->StringByTypeIdx(class_idx); Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "accessing broken descriptor '" << descriptor << "' in " << GetDeclaringClass(); return *result; } // Record result of class resolution attempt. VerifierDeps::MaybeRecordClassResolution(*dex_file_, class_idx, klass); // If requested, check if access is allowed. Unresolved types are included in this check, as the // interpreter only tests whether access is allowed when a class is not pre-verified and runs in // the access-checks interpreter. If result is primitive, skip the access check. // // Note: we do this for unresolved classes to trigger re-verification at runtime. if (C == CheckAccess::kYes && result->IsNonZeroReferenceTypes() && (IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP) || !result->IsUnresolvedTypes())) { const RegType& referrer = GetDeclaringClass(); if ((IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP) || !referrer.IsUnresolvedTypes()) && !referrer.CanAccess(*result)) { Fail(VERIFY_ERROR_ACCESS_CLASS) << "(possibly) illegal class access: '" << referrer << "' -> '" << *result << "'"; } } return *result; } template <bool kVerifierDebug> const RegType& MethodVerifier<kVerifierDebug>::GetCaughtExceptionType() { const RegType* common_super = nullptr; if (code_item_accessor_.TriesSize() != 0) { const uint8_t* handlers_ptr = code_item_accessor_.GetCatchHandlerData(); uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); for (uint32_t i = 0; i < handlers_size; i++) { CatchHandlerIterator iterator(handlers_ptr); for (; iterator.HasNext(); iterator.Next()) { if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) { if (!iterator.GetHandlerTypeIndex().IsValid()) { common_super = &reg_types_.JavaLangThrowable(false); } else { const RegType& exception = ResolveClass<CheckAccess::kYes>(iterator.GetHandlerTypeIndex()); if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(exception, this)) { DCHECK(!exception.IsUninitializedTypes()); // Comes from dex, shouldn't be uninit. if (exception.IsUnresolvedTypes()) { // We don't know enough about the type. Fail here and let runtime handle it. Fail(VERIFY_ERROR_NO_CLASS) << "unresolved exception class " << exception; return exception; } else { Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unexpected non-exception class " << exception; return reg_types_.Conflict(); } } else if (common_super == nullptr) { common_super = &exception; } else if (common_super->Equals(exception)) { // odd case, but nothing to do } else { common_super = &common_super->Merge(exception, &reg_types_, this); if (FailOrAbort(reg_types_.JavaLangThrowable(false).IsAssignableFrom( *common_super, this), "java.lang.Throwable is not assignable-from common_super at ", work_insn_idx_)) { break; } } } } } handlers_ptr = iterator.EndDataPointer(); } } if (common_super == nullptr) { /* no catch blocks, or no catches with classes we can find */ Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unable to find exception handler"; return reg_types_.Conflict(); } return *common_super; } template <bool kVerifierDebug> ArtMethod* MethodVerifier<kVerifierDebug>::ResolveMethodAndCheckAccess( uint32_t dex_method_idx, MethodType method_type) { const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx); const RegType& klass_type = ResolveClass<CheckAccess::kYes>(method_id.class_idx_); if (klass_type.IsConflict()) { std::string append(" in attempt to access method "); append += dex_file_->GetMethodName(method_id); AppendToLastFailMessage(append); return nullptr; } if (klass_type.IsUnresolvedTypes()) { return nullptr; // Can't resolve Class so no more to do here } ObjPtr<mirror::Class> klass = klass_type.GetClass(); const RegType& referrer = GetDeclaringClass(); ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); PointerSize pointer_size = class_linker->GetImagePointerSize(); ArtMethod* res_method = dex_cache_->GetResolvedMethod(dex_method_idx, pointer_size); if (res_method == nullptr) { res_method = class_linker->FindResolvedMethod( klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx); } // Record result of method resolution attempt. The klass resolution has recorded whether // the class is an interface or not and therefore the type of the lookup performed above. // TODO: Maybe we should not record dependency if the invoke type does not match the lookup type. VerifierDeps::MaybeRecordMethodResolution(*dex_file_, dex_method_idx, res_method); bool must_fail = false; // This is traditional and helps with screwy bytecode. It will tell you that, yes, a method // exists, but that it's called incorrectly. This significantly helps debugging, as locally it's // hard to see the differences. // If we don't have res_method here we must fail. Just use this bool to make sure of that with a // DCHECK. if (res_method == nullptr) { must_fail = true; // Try to find the method also with the other type for better error reporting below // but do not store such bogus lookup result in the DexCache or VerifierDeps. res_method = class_linker->FindIncompatibleMethod( klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx); } if (res_method == nullptr) { Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method " << klass->PrettyDescriptor() << "." << dex_file_->GetMethodName(method_id) << " " << dex_file_->GetMethodSignature(method_id); return nullptr; } // Make sure calls to constructors are "direct". There are additional restrictions but we don't // enforce them here. if (res_method->IsConstructor() && method_type != METHOD_DIRECT) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor " << res_method->PrettyMethod(); return nullptr; } // Disallow any calls to class initializers. if (res_method->IsClassInitializer()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer " << res_method->PrettyMethod(); return nullptr; } // Check that interface methods are static or match interface classes. // We only allow statics if we don't have default methods enabled. // // Note: this check must be after the initializer check, as those are required to fail a class, // while this check implies an IncompatibleClassChangeError. if (klass->IsInterface()) { // methods called on interfaces should be invoke-interface, invoke-super, invoke-direct (if // default methods are supported for the dex file), or invoke-static. if (method_type != METHOD_INTERFACE && method_type != METHOD_STATIC && (!dex_file_->SupportsDefaultMethods() || method_type != METHOD_DIRECT) && method_type != METHOD_SUPER) { Fail(VERIFY_ERROR_CLASS_CHANGE) << "non-interface method " << dex_file_->PrettyMethod(dex_method_idx) << " is in an interface class " << klass->PrettyClass(); return nullptr; } } else { if (method_type == METHOD_INTERFACE) { Fail(VERIFY_ERROR_CLASS_CHANGE) << "interface method " << dex_file_->PrettyMethod(dex_method_idx) << " is in a non-interface class " << klass->PrettyClass(); return nullptr; } } // Check specifically for non-public object methods being provided for interface dispatch. This // can occur if we failed to find a method with FindInterfaceMethod but later find one with // FindClassMethod for error message use. if (method_type == METHOD_INTERFACE && res_method->GetDeclaringClass()->IsObjectClass() && !res_method->IsPublic()) { Fail(VERIFY_ERROR_NO_METHOD) << "invoke-interface " << klass->PrettyDescriptor() << "." << dex_file_->GetMethodName(method_id) << " " << dex_file_->GetMethodSignature(method_id) << " resolved to " << "non-public object method " << res_method->PrettyMethod() << " " << "but non-public Object methods are excluded from interface " << "method resolution."; return nullptr; } // Check if access is allowed. if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) { Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call " << res_method->PrettyMethod() << " from " << referrer << ")"; return res_method; } // Check that invoke-virtual and invoke-super are not used on private methods of the same class. if (res_method->IsPrivate() && (method_type == METHOD_VIRTUAL || method_type == METHOD_SUPER)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method " << res_method->PrettyMethod(); return nullptr; } // See if the method type implied by the invoke instruction matches the access flags for the // target method. The flags for METHOD_POLYMORPHIC are based on there being precisely two // signature polymorphic methods supported by the run-time which are native methods with variable // arguments. if ((method_type == METHOD_DIRECT && (!res_method->IsDirect() || res_method->IsStatic())) || (method_type == METHOD_STATIC && !res_method->IsStatic()) || ((method_type == METHOD_SUPER || method_type == METHOD_VIRTUAL || method_type == METHOD_INTERFACE) && res_method->IsDirect()) || ((method_type == METHOD_POLYMORPHIC) && (!res_method->IsNative() || !res_method->IsVarargs()))) { Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method " "type of " << res_method->PrettyMethod(); return nullptr; } // Make sure we weren't expecting to fail. DCHECK(!must_fail) << "invoke type (" << method_type << ")" << klass->PrettyDescriptor() << "." << dex_file_->GetMethodName(method_id) << " " << dex_file_->GetMethodSignature(method_id) << " unexpectedly resolved to " << res_method->PrettyMethod() << " without error. Initially this method was " << "not found so we were expecting to fail for some reason."; return res_method; } template <bool kVerifierDebug> template <class T> ArtMethod* MethodVerifier<kVerifierDebug>::VerifyInvocationArgsFromIterator( T* it, const Instruction* inst, MethodType method_type, bool is_range, ArtMethod* res_method) { DCHECK_EQ(!is_range, inst->HasVarArgs()); // We use vAA as our expected arg count, rather than res_method->insSize, because we need to // match the call to the signature. Also, we might be calling through an abstract method // definition (which doesn't have register count values). const size_t expected_args = inst->VRegA(); /* caught by static verifier */ DCHECK(is_range || expected_args <= 5); if (expected_args > code_item_accessor_.OutsSize()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args << ") exceeds outsSize (" << code_item_accessor_.OutsSize() << ")"; return nullptr; } /* * Check the "this" argument, which must be an instance of the class that declared the method. * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a * rigorous check here (which is okay since we have to do it at runtime). */ if (method_type != METHOD_STATIC) { const RegType& actual_arg_type = work_line_->GetInvocationThis(this, inst); if (actual_arg_type.IsConflict()) { // GetInvocationThis failed. CHECK(have_pending_hard_failure_); return nullptr; } bool is_init = false; if (actual_arg_type.IsUninitializedTypes()) { if (res_method) { if (!res_method->IsConstructor()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; return nullptr; } } else { // Check whether the name of the called method is "<init>" const uint32_t method_idx = GetMethodIdxOfInvoke(inst); if (strcmp(dex_file_->GetMethodName(dex_file_->GetMethodId(method_idx)), "<init>") != 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; return nullptr; } } is_init = true; } const RegType& adjusted_type = is_init ? GetRegTypeCache()->FromUninitialized(actual_arg_type) : actual_arg_type; if (method_type != METHOD_INTERFACE && !adjusted_type.IsZeroOrNull()) { const RegType* res_method_class; // Miranda methods have the declaring interface as their declaring class, not the abstract // class. It would be wrong to use this for the type check (interface type checks are // postponed to runtime). if (res_method != nullptr && !res_method->IsMiranda()) { ObjPtr<mirror::Class> klass = res_method->GetDeclaringClass(); std::string temp; res_method_class = &FromClass(klass->GetDescriptor(&temp), klass, klass->CannotBeAssignedFromOtherTypes()); } else { const uint32_t method_idx = GetMethodIdxOfInvoke(inst); const dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_; res_method_class = &reg_types_.FromDescriptor( class_loader_.Get(), dex_file_->StringByTypeIdx(class_idx), false); } if (!res_method_class->IsAssignableFrom(adjusted_type, this)) { Fail(adjusted_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type << "' not instance of '" << *res_method_class << "'"; // Continue on soft failures. We need to find possible hard failures to avoid problems in // the compiler. if (have_pending_hard_failure_) { return nullptr; } } } } uint32_t arg[5]; if (!is_range) { inst->GetVarArgs(arg); } uint32_t sig_registers = (method_type == METHOD_STATIC) ? 0 : 1; for ( ; it->HasNext(); it->Next()) { if (sig_registers >= expected_args) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << inst->VRegA() << " argument registers, method signature has " << sig_registers + 1 << " or more"; return nullptr; } const char* param_descriptor = it->GetDescriptor(); if (param_descriptor == nullptr) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation because of missing signature " "component"; return nullptr; } const RegType& reg_type = reg_types_.FromDescriptor(class_loader_.Get(), param_descriptor, false); uint32_t get_reg = is_range ? inst->VRegC() + static_cast<uint32_t>(sig_registers) : arg[sig_registers]; if (reg_type.IsIntegralTypes()) { const RegType& src_type = work_line_->GetRegisterType(this, get_reg); if (!src_type.IsIntegralTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type << " but expected " << reg_type; return nullptr; } } else { if (!work_line_->VerifyRegisterType(this, get_reg, reg_type)) { // Continue on soft failures. We need to find possible hard failures to avoid problems in // the compiler. if (have_pending_hard_failure_) { return nullptr; } } else if (reg_type.IsLongOrDoubleTypes()) { // Check that registers are consecutive (for non-range invokes). Invokes are the only // instructions not specifying register pairs by the first component, but require them // nonetheless. Only check when there's an actual register in the parameters. If there's // none, this will fail below. if (!is_range && sig_registers + 1 < expected_args) { uint32_t second_reg = arg[sig_registers + 1]; if (second_reg != get_reg + 1) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, long or double parameter " "at index " << sig_registers << " is not a pair: " << get_reg << " + " << second_reg << "."; return nullptr; } } } } sig_registers += reg_type.IsLongOrDoubleTypes() ? 2 : 1; } if (expected_args != sig_registers) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << expected_args << " argument registers, method signature has " << sig_registers; return nullptr; } return res_method; } template <bool kVerifierDebug> void MethodVerifier<kVerifierDebug>::VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, MethodType method_type, bool is_range) { // As the method may not have been resolved, make this static check against what we expect. // The main reason for this code block is to fail hard when we find an illegal use, e.g., // wrong number of arguments or wrong primitive types, even if the method could not be resolved. const uint32_t method_idx = GetMethodIdxOfInvoke(inst); DexFileParameterIterator it(*dex_file_, dex_file_->GetProtoId(dex_file_->GetMethodId(method_idx).proto_idx_)); VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, nullptr); } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CheckCallSite(uint32_t call_site_idx) { if (call_site_idx >= dex_file_->NumCallSiteIds()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Bad call site id #" << call_site_idx << " >= " << dex_file_->NumCallSiteIds(); return false; } CallSiteArrayValueIterator it(*dex_file_, dex_file_->GetCallSiteId(call_site_idx)); // Check essential arguments are provided. The dex file verifier has verified indicies of the // main values (method handle, name, method_type). static const size_t kRequiredArguments = 3; if (it.Size() < kRequiredArguments) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx << " has too few arguments: " << it.Size() << " < " << kRequiredArguments; return false; } std::pair<const EncodedArrayValueIterator::ValueType, size_t> type_and_max[kRequiredArguments] = { { EncodedArrayValueIterator::ValueType::kMethodHandle, dex_file_->NumMethodHandles() }, { EncodedArrayValueIterator::ValueType::kString, dex_file_->NumStringIds() }, { EncodedArrayValueIterator::ValueType::kMethodType, dex_file_->NumProtoIds() } }; uint32_t index[kRequiredArguments]; // Check arguments have expected types and are within permitted ranges. for (size_t i = 0; i < kRequiredArguments; ++i) { if (it.GetValueType() != type_and_max[i].first) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx << " argument " << i << " has wrong type " << it.GetValueType() << "!=" << type_and_max[i].first; return false; } index[i] = static_cast<uint32_t>(it.GetJavaValue().i); if (index[i] >= type_and_max[i].second) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx << " argument " << i << " bad index " << index[i] << " >= " << type_and_max[i].second; return false; } it.Next(); } // Check method handle kind is valid. const dex::MethodHandleItem& mh = dex_file_->GetMethodHandle(index[0]); if (mh.method_handle_type_ != static_cast<uint16_t>(DexFile::MethodHandleType::kInvokeStatic)) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx << " argument 0 method handle type is not InvokeStatic: " << mh.method_handle_type_; return false; } return true; } class MethodParamListDescriptorIterator { public: explicit MethodParamListDescriptorIterator(ArtMethod* res_method) : res_method_(res_method), pos_(0), params_(res_method->GetParameterTypeList()), params_size_(params_ == nullptr ? 0 : params_->Size()) { } bool HasNext() { return pos_ < params_size_; } void Next() { ++pos_; } const char* GetDescriptor() REQUIRES_SHARED(Locks::mutator_lock_) { return res_method_->GetTypeDescriptorFromTypeIdx(params_->GetTypeItem(pos_).type_idx_); } private: ArtMethod* res_method_; size_t pos_; const dex::TypeList* params_; const size_t params_size_; }; template <bool kVerifierDebug> ArtMethod* MethodVerifier<kVerifierDebug>::VerifyInvocationArgs( const Instruction* inst, MethodType method_type, bool is_range) { // Resolve the method. This could be an abstract or concrete method depending on what sort of call // we're making. const uint32_t method_idx = GetMethodIdxOfInvoke(inst); ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type); if (res_method == nullptr) { // error or class is unresolved // Check what we can statically. if (!have_pending_hard_failure_) { VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range); } return nullptr; } // If we're using invoke-super(method), make sure that the executing method's class' superclass // has a vtable entry for the target method. Or the target is on a interface. if (method_type == METHOD_SUPER) { dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_; const RegType& reference_type = reg_types_.FromDescriptor( class_loader_.Get(), dex_file_->StringByTypeIdx(class_idx), false); if (reference_type.IsUnresolvedTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "Unable to find referenced class from invoke-super"; return nullptr; } if (reference_type.GetClass()->IsInterface()) { // TODO Can we verify anything else. if (class_idx == class_def_.class_idx_) { Fail(VERIFY_ERROR_CLASS_CHANGE) << "Cannot invoke-super on self as interface"; return nullptr; } // TODO Revisit whether we want to allow invoke-super on direct interfaces only like the JLS // does. if (!GetDeclaringClass().HasClass()) { Fail(VERIFY_ERROR_NO_CLASS) << "Unable to resolve the full class of 'this' used in an" << "interface invoke-super"; return nullptr; } else if (!reference_type.IsStrictlyAssignableFrom(GetDeclaringClass(), this)) { Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke-super in " << mirror::Class::PrettyClass(GetDeclaringClass().GetClass()) << " in method " << dex_file_->PrettyMethod(dex_method_idx_) << " to method " << dex_file_->PrettyMethod(method_idx) << " references " << "non-super-interface type " << mirror::Class::PrettyClass(reference_type.GetClass()); return nullptr; } } else { const RegType& super = GetDeclaringClass().GetSuperClass(&reg_types_); if (super.IsUnresolvedTypes()) { Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from " << dex_file_->PrettyMethod(dex_method_idx_) << " to super " << res_method->PrettyMethod(); return nullptr; } if (!reference_type.IsStrictlyAssignableFrom(GetDeclaringClass(), this) || (res_method->GetMethodIndex() >= super.GetClass()->GetVTableLength())) { Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from " << dex_file_->PrettyMethod(dex_method_idx_) << " to super " << super << "." << res_method->GetName() << res_method->GetSignature(); return nullptr; } } } if (UNLIKELY(method_type == METHOD_POLYMORPHIC)) { // Process the signature of the calling site that is invoking the method handle. dex::ProtoIndex proto_idx(inst->VRegH()); DexFileParameterIterator it(*dex_file_, dex_file_->GetProtoId(proto_idx)); return VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, res_method); } else { // Process the target method's signature. MethodParamListDescriptorIterator it(res_method); return VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, res_method); } } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CheckSignaturePolymorphicMethod(ArtMethod* method) { ObjPtr<mirror::Class> klass = method->GetDeclaringClass(); const char* method_name = method->GetName(); const char* expected_return_descriptor; ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = Runtime::Current()->GetClassLinker()->GetClassRoots(); if (klass == GetClassRoot<mirror::MethodHandle>(class_roots)) { expected_return_descriptor = mirror::MethodHandle::GetReturnTypeDescriptor(method_name); } else if (klass == GetClassRoot<mirror::VarHandle>(class_roots)) { expected_return_descriptor = mirror::VarHandle::GetReturnTypeDescriptor(method_name); } else { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Signature polymorphic method in unsuppported class: " << klass->PrettyDescriptor(); return false; } if (expected_return_descriptor == nullptr) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Signature polymorphic method name invalid: " << method_name; return false; } const dex::TypeList* types = method->GetParameterTypeList(); if (types->Size() != 1) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Signature polymorphic method has too many arguments " << types->Size() << " != 1"; return false; } const dex::TypeIndex argument_type_index = types->GetTypeItem(0).type_idx_; const char* argument_descriptor = method->GetTypeDescriptorFromTypeIdx(argument_type_index); if (strcmp(argument_descriptor, "[Ljava/lang/Object;") != 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Signature polymorphic method has unexpected argument type: " << argument_descriptor; return false; } const char* return_descriptor = method->GetReturnTypeDescriptor(); if (strcmp(return_descriptor, expected_return_descriptor) != 0) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Signature polymorphic method has unexpected return type: " << return_descriptor << " != " << expected_return_descriptor; return false; } return true; } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::CheckSignaturePolymorphicReceiver(const Instruction* inst) { const RegType& this_type = work_line_->GetInvocationThis(this, inst); if (this_type.IsZeroOrNull()) { /* null pointer always passes (and always fails at run time) */ return true; } else if (!this_type.IsNonZeroReferenceTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-polymorphic receiver is not a reference: " << this_type; return false; } else if (this_type.IsUninitializedReference()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-polymorphic receiver is uninitialized: " << this_type; return false; } else if (!this_type.HasClass()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-polymorphic receiver has no class: " << this_type; return false; } else { ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = Runtime::Current()->GetClassLinker()->GetClassRoots(); if (!this_type.GetClass()->IsSubClass(GetClassRoot<mirror::MethodHandle>(class_roots)) && !this_type.GetClass()->IsSubClass(GetClassRoot<mirror::VarHandle>(class_roots))) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-polymorphic receiver is not a subclass of MethodHandle or VarHandle: " << this_type; return false; } } return true; } template <bool kVerifierDebug> uint16_t MethodVerifier<kVerifierDebug>::GetMethodIdxOfInvoke(const Instruction* inst) { switch (inst->Opcode()) { case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: case Instruction::INVOKE_VIRTUAL_QUICK: { DCHECK(Runtime::Current()->IsStarted() || verify_to_dump_) << dex_file_->PrettyMethod(dex_method_idx_, true) << "@" << work_insn_idx_; DCHECK(method_being_verified_ != nullptr); uint16_t method_idx = method_being_verified_->GetIndexFromQuickening(work_insn_idx_); CHECK_NE(method_idx, DexFile::kDexNoIndex16); return method_idx; } default: { return inst->VRegB(); } } } template <bool kVerifierDebug> uint16_t MethodVerifier<kVerifierDebug>::GetFieldIdxOfFieldAccess(const Instruction* inst, bool is_static) { if (is_static) { return inst->VRegB_21c(); } else if (inst->IsQuickened()) { DCHECK(Runtime::Current()->IsStarted() || verify_to_dump_); DCHECK(method_being_verified_ != nullptr); uint16_t field_idx = method_being_verified_->GetIndexFromQuickening(work_insn_idx_); CHECK_NE(field_idx, DexFile::kDexNoIndex16); return field_idx; } else { return inst->VRegC_22c(); } } template <bool kVerifierDebug> void MethodVerifier<kVerifierDebug>::VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range) { dex::TypeIndex type_idx; if (!is_filled) { DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY); type_idx = dex::TypeIndex(inst->VRegC_22c()); } else if (!is_range) { DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY); type_idx = dex::TypeIndex(inst->VRegB_35c()); } else { DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE); type_idx = dex::TypeIndex(inst->VRegB_3rc()); } const RegType& res_type = ResolveClass<CheckAccess::kYes>(type_idx); if (res_type.IsConflict()) { // bad class DCHECK_NE(failures_.size(), 0U); } else { // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved if (!res_type.IsArrayTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type; } else if (!is_filled) { /* make sure "size" register is valid type */ work_line_->VerifyRegisterType(this, inst->VRegB_22c(), reg_types_.Integer()); /* set register type to array class */ const RegType& precise_type = reg_types_.FromUninitialized(res_type); work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_22c(), precise_type); } else { DCHECK(!res_type.IsUnresolvedMergedReference()); // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of // the list and fail. It's legal, if silly, for arg_count to be zero. const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_.Get()); uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); uint32_t arg[5]; if (!is_range) { inst->GetVarArgs(arg); } for (size_t ui = 0; ui < arg_count; ui++) { uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui]; if (!work_line_->VerifyRegisterType(this, get_reg, expected_type)) { work_line_->SetResultRegisterType(this, reg_types_.Conflict()); return; } } // filled-array result goes into "result" register const RegType& precise_type = reg_types_.FromUninitialized(res_type); work_line_->SetResultRegisterType(this, precise_type); } } } template <bool kVerifierDebug> void MethodVerifier<kVerifierDebug>::VerifyAGet(const Instruction* inst, const RegType& insn_type, bool is_primitive) { const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x()); if (!index_type.IsArrayIndexTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; } else { const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x()); if (array_type.IsZeroOrNull()) { // Null array class; this code path will fail at runtime. Infer a merge-able type from the // instruction type. if (!is_primitive) { work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Null()); } else if (insn_type.IsInteger()) { // Pick a non-zero constant (to distinguish with null) that can fit in any primitive. // We cannot use 'insn_type' as it could be a float array or an int array. work_line_->SetRegisterType<LockOp::kClear>( this, inst->VRegA_23x(), DetermineCat1Constant(1, need_precise_constants_)); } else if (insn_type.IsCategory1Types()) { // Category 1 // The 'insn_type' is exactly the type we need. work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), insn_type); } else { // Category 2 work_line_->SetRegisterTypeWide(this, inst->VRegA_23x(), reg_types_.FromCat2ConstLo(0, false), reg_types_.FromCat2ConstHi(0, false)); } } else if (!array_type.IsArrayTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget"; } else if (array_type.IsUnresolvedMergedReference()) { // Unresolved array types must be reference array types. if (is_primitive) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type << " source for category 1 aget"; } else { Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aget for " << array_type << " because of missing class"; // Approximate with java.lang.Object[]. work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.JavaLangObject(false)); } } else { /* verify the class */ const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_.Get()); if (!component_type.IsReferenceTypes() && !is_primitive) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type << " source for aget-object"; } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type << " source for category 1 aget"; } else if (is_primitive && !insn_type.Equals(component_type) && !((insn_type.IsInteger() && component_type.IsFloat()) || (insn_type.IsLong() && component_type.IsDouble()))) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type << " incompatible with aget of type " << insn_type; } else { // Use knowledge of the field type which is stronger than the type inferred from the // instruction, which can't differentiate object types and ints from floats, longs from // doubles. if (!component_type.IsLowHalf()) { work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), component_type); } else { work_line_->SetRegisterTypeWide(this, inst->VRegA_23x(), component_type, component_type.HighHalf(&reg_types_)); } } } } } template <bool kVerifierDebug> void MethodVerifier<kVerifierDebug>::VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type, const uint32_t vregA) { // Primitive assignability rules are weaker than regular assignability rules. bool instruction_compatible; bool value_compatible; const RegType& value_type = work_line_->GetRegisterType(this, vregA); if (target_type.IsIntegralTypes()) { instruction_compatible = target_type.Equals(insn_type); value_compatible = value_type.IsIntegralTypes(); } else if (target_type.IsFloat()) { instruction_compatible = insn_type.IsInteger(); // no put-float, so expect put-int value_compatible = value_type.IsFloatTypes(); } else if (target_type.IsLong()) { instruction_compatible = insn_type.IsLong(); // Additional register check: this is not checked statically (as part of VerifyInstructions), // as target_type depends on the resolved type of the field. if (instruction_compatible && work_line_->NumRegs() > vregA + 1) { const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1); value_compatible = value_type.IsLongTypes() && value_type.CheckWidePair(value_type_hi); } else { value_compatible = false; } } else if (target_type.IsDouble()) { instruction_compatible = insn_type.IsLong(); // no put-double, so expect put-long // Additional register check: this is not checked statically (as part of VerifyInstructions), // as target_type depends on the resolved type of the field. if (instruction_compatible && work_line_->NumRegs() > vregA + 1) { const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1); value_compatible = value_type.IsDoubleTypes() && value_type.CheckWidePair(value_type_hi); } else { value_compatible = false; } } else { instruction_compatible = false; // reference with primitive store value_compatible = false; // unused } if (!instruction_compatible) { // This is a global failure rather than a class change failure as the instructions and // the descriptors for the type should have been consistent within the same file at // compile time. Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type << "' but expected type '" << target_type << "'"; return; } if (!value_compatible) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA << " of type " << value_type << " but expected " << target_type << " for put"; return; } } template <bool kVerifierDebug> void MethodVerifier<kVerifierDebug>::VerifyAPut(const Instruction* inst, const RegType& insn_type, bool is_primitive) { const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x()); if (!index_type.IsArrayIndexTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; } else { const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x()); if (array_type.IsZeroOrNull()) { // Null array type; this code path will fail at runtime. // Still check that the given value matches the instruction's type. // Note: this is, as usual, complicated by the fact the the instruction isn't fully typed // and fits multiple register types. const RegType* modified_reg_type = &insn_type; if ((modified_reg_type == &reg_types_.Integer()) || (modified_reg_type == &reg_types_.LongLo())) { // May be integer or float | long or double. Overwrite insn_type accordingly. const RegType& value_type = work_line_->GetRegisterType(this, inst->VRegA_23x()); if (modified_reg_type == &reg_types_.Integer()) { if (&value_type == &reg_types_.Float()) { modified_reg_type = &value_type; } } else { if (&value_type == &reg_types_.DoubleLo()) { modified_reg_type = &value_type; } } } work_line_->VerifyRegisterType(this, inst->VRegA_23x(), *modified_reg_type); } else if (!array_type.IsArrayTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput"; } else if (array_type.IsUnresolvedMergedReference()) { // Unresolved array types must be reference array types. if (is_primitive) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type << "' but unresolved type '" << array_type << "'"; } else { Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aput for " << array_type << " because of missing class"; } } else { const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_.Get()); const uint32_t vregA = inst->VRegA_23x(); if (is_primitive) { VerifyPrimitivePut(component_type, insn_type, vregA); } else { if (!component_type.IsReferenceTypes()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type << " source for aput-object"; } else { // The instruction agrees with the type of array, confirm the value to be stored does too // Note: we use the instruction type (rather than the component type) for aput-object as // incompatible classes will be caught at runtime as an array store exception work_line_->VerifyRegisterType(this, vregA, insn_type); } } } } } template <bool kVerifierDebug> ArtField* MethodVerifier<kVerifierDebug>::GetStaticField(int field_idx) { const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx); // Check access to class const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_); if (klass_type.IsConflict()) { // bad class AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s", field_idx, dex_file_->GetFieldName(field_id), dex_file_->GetFieldDeclaringClassDescriptor(field_id))); return nullptr; } if (klass_type.IsUnresolvedTypes()) { // Accessibility checks depend on resolved fields. DCHECK(klass_type.Equals(GetDeclaringClass()) || !failures_.empty() || IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP)); return nullptr; // Can't resolve Class so no more to do here, will do checking at runtime. } ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); ArtField* field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_); // Record result of the field resolution attempt. VerifierDeps::MaybeRecordFieldResolution(*dex_file_, field_idx, field); if (field == nullptr) { VLOG(verifier) << "Unable to resolve static field " << field_idx << " (" << dex_file_->GetFieldName(field_id) << ") in " << dex_file_->GetFieldDeclaringClassDescriptor(field_id); DCHECK(self_->IsExceptionPending()); self_->ClearException(); return nullptr; } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), field->GetAccessFlags())) { Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << field->PrettyField() << " from " << GetDeclaringClass(); return nullptr; } else if (!field->IsStatic()) { Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField() << " to be static"; return nullptr; } return field; } template <bool kVerifierDebug> ArtField* MethodVerifier<kVerifierDebug>::GetInstanceField(const RegType& obj_type, int field_idx) { const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx); // Check access to class. const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_); if (klass_type.IsConflict()) { AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s", field_idx, dex_file_->GetFieldName(field_id), dex_file_->GetFieldDeclaringClassDescriptor(field_id))); return nullptr; } if (klass_type.IsUnresolvedTypes()) { // Accessibility checks depend on resolved fields. DCHECK(klass_type.Equals(GetDeclaringClass()) || !failures_.empty() || IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP)); return nullptr; // Can't resolve Class so no more to do here } ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); ArtField* field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_); // Record result of the field resolution attempt. VerifierDeps::MaybeRecordFieldResolution(*dex_file_, field_idx, field); if (field == nullptr) { VLOG(verifier) << "Unable to resolve instance field " << field_idx << " (" << dex_file_->GetFieldName(field_id) << ") in " << dex_file_->GetFieldDeclaringClassDescriptor(field_id); DCHECK(self_->IsExceptionPending()); self_->ClearException(); return nullptr; } else if (obj_type.IsZeroOrNull()) { // Cannot infer and check type, however, access will cause null pointer exception. // Fall through into a few last soft failure checks below. } else if (!obj_type.IsReferenceTypes()) { // Trying to read a field from something that isn't a reference. Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance field access on object that has " << "non-reference type " << obj_type; return nullptr; } else { std::string temp; ObjPtr<mirror::Class> klass = field->GetDeclaringClass(); const RegType& field_klass = FromClass(klass->GetDescriptor(&temp), klass, klass->CannotBeAssignedFromOtherTypes()); if (obj_type.IsUninitializedTypes()) { // Field accesses through uninitialized references are only allowable for constructors where // the field is declared in this class. // Note: this IsConstructor check is technically redundant, as UninitializedThis should only // appear in constructors. if (!obj_type.IsUninitializedThisReference() || !IsConstructor() || !field_klass.Equals(GetDeclaringClass())) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << field->PrettyField() << " of a not fully initialized object within the context" << " of " << dex_file_->PrettyMethod(dex_method_idx_); return nullptr; } } else if (!field_klass.IsAssignableFrom(obj_type, this)) { // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class // of C1. For resolution to occur the declared class of the field must be compatible with // obj_type, we've discovered this wasn't so, so report the field didn't exist. VerifyError type; bool is_aot = Runtime::Current()->IsAotCompiler(); if (is_aot && (field_klass.IsUnresolvedTypes() || obj_type.IsUnresolvedTypes())) { // Compiler & unresolved types involved, retry at runtime. type = VerifyError::VERIFY_ERROR_NO_CLASS; } else { // Classes known (resolved; and thus assignability check is precise), or we are at runtime // and still missing classes. This is a hard failure. type = VerifyError::VERIFY_ERROR_BAD_CLASS_HARD; } Fail(type) << "cannot access instance field " << field->PrettyField() << " from object of type " << obj_type; return nullptr; } } // Few last soft failure checks. if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), field->GetAccessFlags())) { Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << field->PrettyField() << " from " << GetDeclaringClass(); return nullptr; } else if (field->IsStatic()) { Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField() << " to not be static"; return nullptr; } return field; } template <bool kVerifierDebug> template <FieldAccessType kAccType> void MethodVerifier<kVerifierDebug>::VerifyISFieldAccess(const Instruction* inst, const RegType& insn_type, bool is_primitive, bool is_static) { uint32_t field_idx = GetFieldIdxOfFieldAccess(inst, is_static); ArtField* field; if (is_static) { field = GetStaticField(field_idx); } else { const RegType& object_type = work_line_->GetRegisterType(this, inst->VRegB_22c()); // One is not allowed to access fields on uninitialized references, except to write to // fields in the constructor (before calling another constructor). // GetInstanceField does an assignability check which will fail for uninitialized types. // We thus modify the type if the uninitialized reference is a "this" reference (this also // checks at the same time that we're verifying a constructor). bool should_adjust = (kAccType == FieldAccessType::kAccPut) && object_type.IsUninitializedThisReference(); const RegType& adjusted_type = should_adjust ? GetRegTypeCache()->FromUninitialized(object_type) : object_type; field = GetInstanceField(adjusted_type, field_idx); if (UNLIKELY(have_pending_hard_failure_)) { return; } if (should_adjust) { if (field == nullptr) { Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "Might be accessing a superclass instance field prior " << "to the superclass being initialized in " << dex_file_->PrettyMethod(dex_method_idx_); } else if (field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access superclass instance field " << field->PrettyField() << " of a not fully initialized " << "object within the context of " << dex_file_->PrettyMethod(dex_method_idx_); return; } } } const RegType* field_type = nullptr; if (field != nullptr) { if (kAccType == FieldAccessType::kAccPut) { if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << field->PrettyField() << " from other class " << GetDeclaringClass(); // Keep hunting for possible hard fails. } } ObjPtr<mirror::Class> field_type_class = can_load_classes_ ? field->ResolveType() : field->LookupResolvedType(); if (field_type_class != nullptr) { field_type = &FromClass(field->GetTypeDescriptor(), field_type_class, field_type_class->CannotBeAssignedFromOtherTypes()); } else { DCHECK(!can_load_classes_ || self_->IsExceptionPending()); self_->ClearException(); } } else if (IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP)) { // If we don't have the field (it seems we failed resolution) and this is a PUT, we need to // redo verification at runtime as the field may be final, unless the field id shows it's in // the same class. // // For simplicity, it is OK to not distinguish compile-time vs runtime, and post this an // ACCESS_FIELD failure at runtime. This has the same effect as NO_FIELD - punting the class // to the access-checks interpreter. // // Note: see b/34966607. This and above may be changed in the future. if (kAccType == FieldAccessType::kAccPut) { const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx); const char* field_class_descriptor = dex_file_->GetFieldDeclaringClassDescriptor(field_id); const RegType* field_class_type = &reg_types_.FromDescriptor(class_loader_.Get(), field_class_descriptor, false); if (!field_class_type->Equals(GetDeclaringClass())) { Fail(VERIFY_ERROR_ACCESS_FIELD) << "could not check field put for final field modify of " << field_class_descriptor << "." << dex_file_->GetFieldName(field_id) << " from other class " << GetDeclaringClass(); } } } if (field_type == nullptr) { const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx); const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id); field_type = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false); } DCHECK(field_type != nullptr); const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c(); static_assert(kAccType == FieldAccessType::kAccPut || kAccType == FieldAccessType::kAccGet, "Unexpected third access type"); if (kAccType == FieldAccessType::kAccPut) { // sput or iput. if (is_primitive) { VerifyPrimitivePut(*field_type, insn_type, vregA); } else { if (!insn_type.IsAssignableFrom(*field_type, this)) { // If the field type is not a reference, this is a global failure rather than // a class change failure as the instructions and the descriptors for the type // should have been consistent within the same file at compile time. VerifyError error = field_type->IsReferenceTypes() ? VERIFY_ERROR_BAD_CLASS_SOFT : VERIFY_ERROR_BAD_CLASS_HARD; Fail(error) << "expected field " << ArtField::PrettyField(field) << " to be compatible with type '" << insn_type << "' but found type '" << *field_type << "' in put-object"; return; } work_line_->VerifyRegisterType(this, vregA, *field_type); } } else if (kAccType == FieldAccessType::kAccGet) { // sget or iget. if (is_primitive) { if (field_type->Equals(insn_type) || (field_type->IsFloat() && insn_type.IsInteger()) || (field_type->IsDouble() && insn_type.IsLong())) { // expected that read is of the correct primitive type or that int reads are reading // floats or long reads are reading doubles } else { // This is a global failure rather than a class change failure as the instructions and // the descriptors for the type should have been consistent within the same file at // compile time Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << ArtField::PrettyField(field) << " to be of type '" << insn_type << "' but found type '" << *field_type << "' in get"; return; } } else { if (!insn_type.IsAssignableFrom(*field_type, this)) { // If the field type is not a reference, this is a global failure rather than // a class change failure as the instructions and the descriptors for the type // should have been consistent within the same file at compile time. VerifyError error = field_type->IsReferenceTypes() ? VERIFY_ERROR_BAD_CLASS_SOFT : VERIFY_ERROR_BAD_CLASS_HARD; Fail(error) << "expected field " << ArtField::PrettyField(field) << " to be compatible with type '" << insn_type << "' but found type '" << *field_type << "' in get-object"; if (error != VERIFY_ERROR_BAD_CLASS_HARD) { work_line_->SetRegisterType<LockOp::kClear>(this, vregA, reg_types_.Conflict()); } return; } } if (!field_type->IsLowHalf()) { work_line_->SetRegisterType<LockOp::kClear>(this, vregA, *field_type); } else { work_line_->SetRegisterTypeWide(this, vregA, *field_type, field_type->HighHalf(&reg_types_)); } } else { LOG(FATAL) << "Unexpected case."; } } template <bool kVerifierDebug> bool MethodVerifier<kVerifierDebug>::UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line, bool update_merge_line) { bool changed = true; RegisterLine* target_line = reg_table_.GetLine(next_insn); if (!GetInstructionFlags(next_insn).IsVisitedOrChanged()) { /* * We haven't processed this instruction before, and we haven't touched the registers here, so * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the * only way a register can transition out of "unknown", so this is not just an optimization.) */ target_line->CopyFromLine(merge_line); if (GetInstructionFlags(next_insn).IsReturn()) { // Verify that the monitor stack is empty on return. merge_line->VerifyMonitorStackEmpty(this); // For returns we only care about the operand to the return, all other registers are dead. // Initialize them as conflicts so they don't add to GC and deoptimization information. const Instruction* ret_inst = &code_item_accessor_.InstructionAt(next_insn); AdjustReturnLine(this, ret_inst, target_line); // Directly bail if a hard failure was found. if (have_pending_hard_failure_) { return false; } } } else { RegisterLineArenaUniquePtr copy; if (kVerifierDebug) { copy.reset(RegisterLine::Create(target_line->NumRegs(), allocator_, GetRegTypeCache())); copy->CopyFromLine(target_line); } changed = target_line->MergeRegisters(this, merge_line); if (have_pending_hard_failure_) { return false; } if (kVerifierDebug && changed) { LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]" << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n" << copy->Dump(this) << " MERGE\n" << merge_line->Dump(this) << " ==\n" << target_line->Dump(this); } if (update_merge_line && changed) { merge_line->CopyFromLine(target_line); } } if (changed) { GetModifiableInstructionFlags(next_insn).SetChanged(); } return true; } template <bool kVerifierDebug> const RegType& MethodVerifier<kVerifierDebug>::GetMethodReturnType() { if (return_type_ == nullptr) { if (method_being_verified_ != nullptr) { ObjPtr<mirror::Class> return_type_class = can_load_classes_ ? method_being_verified_->ResolveReturnType() : method_being_verified_->LookupResolvedReturnType(); if (return_type_class != nullptr) { return_type_ = &FromClass(method_being_verified_->GetReturnTypeDescriptor(), return_type_class, return_type_class->CannotBeAssignedFromOtherTypes()); } else { DCHECK(!can_load_classes_ || self_->IsExceptionPending()); self_->ClearException(); } } if (return_type_ == nullptr) { const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); const dex::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id); dex::TypeIndex return_type_idx = proto_id.return_type_idx_; const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx)); return_type_ = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false); } } return *return_type_; } template <bool kVerifierDebug> const RegType& MethodVerifier<kVerifierDebug>::GetDeclaringClass() { if (declaring_class_ == nullptr) { const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(method_id.class_idx_)); if (method_being_verified_ != nullptr) { ObjPtr<mirror::Class> klass = method_being_verified_->GetDeclaringClass(); declaring_class_ = &FromClass(descriptor, klass, klass->CannotBeAssignedFromOtherTypes()); } else { declaring_class_ = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false); } } return *declaring_class_; } template <bool kVerifierDebug> const RegType& MethodVerifier<kVerifierDebug>::DetermineCat1Constant(int32_t value, bool precise) { if (precise) { // Precise constant type. return reg_types_.FromCat1Const(value, true); } else { // Imprecise constant type. if (value < -32768) { return reg_types_.IntConstant(); } else if (value < -128) { return reg_types_.ShortConstant(); } else if (value < 0) { return reg_types_.ByteConstant(); } else if (value == 0) { return reg_types_.Zero(); } else if (value == 1) { return reg_types_.One(); } else if (value < 128) { return reg_types_.PosByteConstant(); } else if (value < 32768) { return reg_types_.PosShortConstant(); } else if (value < 65536) { return reg_types_.CharConstant(); } else { return reg_types_.IntConstant(); } } } template <bool kVerifierDebug> const RegType& MethodVerifier<kVerifierDebug>::FromClass(const char* descriptor, ObjPtr<mirror::Class> klass, bool precise) { DCHECK(klass != nullptr); if (precise && !klass->IsInstantiable() && !klass->IsPrimitive()) { Fail(VerifyError::VERIFY_ERROR_NO_CLASS) << "Could not create precise reference for " << "non-instantiable klass " << descriptor; precise = false; } return reg_types_.FromClass(descriptor, klass, precise); } } // namespace } // namespace impl MethodVerifier::MethodVerifier(Thread* self, const DexFile* dex_file, const dex::CodeItem* code_item, uint32_t dex_method_idx, bool can_load_classes, bool allow_thread_suspension, bool allow_soft_failures) : self_(self), arena_stack_(Runtime::Current()->GetArenaPool()), allocator_(&arena_stack_), reg_types_(can_load_classes, allocator_, allow_thread_suspension), reg_table_(allocator_), work_insn_idx_(dex::kDexNoIndex), dex_method_idx_(dex_method_idx), dex_file_(dex_file), code_item_accessor_(*dex_file, code_item), have_pending_hard_failure_(false), have_pending_runtime_throw_failure_(false), have_pending_experimental_failure_(false), have_any_pending_runtime_throw_failure_(false), encountered_failure_types_(0), can_load_classes_(can_load_classes), allow_soft_failures_(allow_soft_failures), has_check_casts_(false), link_(nullptr) { self->PushVerifier(this); } MethodVerifier::~MethodVerifier() { Thread::Current()->PopVerifier(this); STLDeleteElements(&failure_messages_); } MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self, uint32_t method_idx, const DexFile* dex_file, Handle<mirror::DexCache> dex_cache, Handle<mirror::ClassLoader> class_loader, const dex::ClassDef& class_def, const dex::CodeItem* code_item, ArtMethod* method, uint32_t method_access_flags, CompilerCallbacks* callbacks, bool allow_soft_failures, HardFailLogMode log_level, bool need_precise_constants, uint32_t api_level, std::string* hard_failure_msg) { if (VLOG_IS_ON(verifier_debug)) { return VerifyMethod<true>(self, method_idx, dex_file, dex_cache, class_loader, class_def, code_item, method, method_access_flags, callbacks, allow_soft_failures, log_level, need_precise_constants, api_level, hard_failure_msg); } else { return VerifyMethod<false>(self, method_idx, dex_file, dex_cache, class_loader, class_def, code_item, method, method_access_flags, callbacks, allow_soft_failures, log_level, need_precise_constants, api_level, hard_failure_msg); } } template <bool kVerifierDebug> MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self, uint32_t method_idx, const DexFile* dex_file, Handle<mirror::DexCache> dex_cache, Handle<mirror::ClassLoader> class_loader, const dex::ClassDef& class_def, const dex::CodeItem* code_item, ArtMethod* method, uint32_t method_access_flags, CompilerCallbacks* callbacks, bool allow_soft_failures, HardFailLogMode log_level, bool need_precise_constants, uint32_t api_level, std::string* hard_failure_msg) { MethodVerifier::FailureData result; uint64_t start_ns = kTimeVerifyMethod ? NanoTime() : 0; impl::MethodVerifier<kVerifierDebug> verifier(self, dex_file, dex_cache, class_loader, class_def, code_item, method_idx, method, method_access_flags, /* can_load_classes= */ true, allow_soft_failures, need_precise_constants, /* verify to dump */ false, /* allow_thread_suspension= */ true, api_level); if (verifier.Verify()) { // Verification completed, however failures may be pending that didn't cause the verification // to hard fail. CHECK(!verifier.have_pending_hard_failure_); if (code_item != nullptr && callbacks != nullptr) { // Let the interested party know that the method was verified. callbacks->MethodVerified(&verifier); } if (verifier.failures_.size() != 0) { if (VLOG_IS_ON(verifier)) { verifier.DumpFailures(VLOG_STREAM(verifier) << "Soft verification failures in " << dex_file->PrettyMethod(method_idx) << "\n"); } if (kVerifierDebug) { LOG(INFO) << verifier.info_messages_.str(); verifier.Dump(LOG_STREAM(INFO)); } result.kind = FailureKind::kSoftFailure; if (method != nullptr && !CanCompilerHandleVerificationFailure(verifier.encountered_failure_types_)) { method->SetDontCompile(); } } if (method != nullptr) { if (verifier.HasInstructionThatWillThrow()) { method->SetDontCompile(); if (Runtime::Current()->IsAotCompiler() && (callbacks != nullptr) && !callbacks->IsBootImage()) { // When compiling apps, make HasInstructionThatWillThrow a soft error to trigger // re-verification at runtime. // The dead code after the throw is not verified and might be invalid. This may cause // the JIT compiler to crash since it assumes that all the code is valid. // // There's a strong assumption that the entire boot image is verified and all its dex // code is valid (even the dead and unverified one). As such this is done only for apps. // (CompilerDriver DCHECKs in VerifyClassVisitor that methods from boot image are // fully verified). result.kind = FailureKind::kSoftFailure; } } if ((verifier.encountered_failure_types_ & VerifyError::VERIFY_ERROR_LOCKING) != 0) { method->SetMustCountLocks(); } } } else { // Bad method data. CHECK_NE(verifier.failures_.size(), 0U); if (UNLIKELY(verifier.have_pending_experimental_failure_)) { // Failed due to being forced into interpreter. This is ok because // we just want to skip verification. result.kind = FailureKind::kSoftFailure; } else { CHECK(verifier.have_pending_hard_failure_); if (VLOG_IS_ON(verifier)) { log_level = std::max(HardFailLogMode::kLogVerbose, log_level); } if (log_level >= HardFailLogMode::kLogVerbose) { LogSeverity severity; switch (log_level) { case HardFailLogMode::kLogVerbose: severity = LogSeverity::VERBOSE; break; case HardFailLogMode::kLogWarning: severity = LogSeverity::WARNING; break; case HardFailLogMode::kLogInternalFatal: severity = LogSeverity::FATAL_WITHOUT_ABORT; break; default: LOG(FATAL) << "Unsupported log-level " << static_cast<uint32_t>(log_level); UNREACHABLE(); } verifier.DumpFailures(LOG_STREAM(severity) << "Verification error in " << dex_file->PrettyMethod(method_idx) << "\n"); } if (hard_failure_msg != nullptr) { CHECK(!verifier.failure_messages_.empty()); *hard_failure_msg = verifier.failure_messages_[verifier.failure_messages_.size() - 1]->str(); } result.kind = FailureKind::kHardFailure; if (callbacks != nullptr) { // Let the interested party know that we failed the class. ClassReference ref(dex_file, dex_file->GetIndexForClassDef(class_def)); callbacks->ClassRejected(ref); } } if (kVerifierDebug || VLOG_IS_ON(verifier)) { LOG(ERROR) << verifier.info_messages_.str(); verifier.Dump(LOG_STREAM(ERROR)); } // Under verifier-debug, dump the complete log into the error message. if (kVerifierDebug && hard_failure_msg != nullptr) { hard_failure_msg->append("\n"); hard_failure_msg->append(verifier.info_messages_.str()); hard_failure_msg->append("\n"); std::ostringstream oss; verifier.Dump(oss); hard_failure_msg->append(oss.str()); } } if (kTimeVerifyMethod) { uint64_t duration_ns = NanoTime() - start_ns; if (duration_ns > MsToNs(Runtime::Current()->GetVerifierLoggingThresholdMs())) { LOG(WARNING) << "Verification of " << dex_file->PrettyMethod(method_idx) << " took " << PrettyDuration(duration_ns) << (impl::IsLargeMethod(verifier.CodeItem()) ? " (large method)" : ""); } } result.types = verifier.encountered_failure_types_; return result; } MethodVerifier* MethodVerifier::VerifyMethodAndDump(Thread* self, VariableIndentationOutputStream* vios, uint32_t dex_method_idx, const DexFile* dex_file, Handle<mirror::DexCache> dex_cache, Handle<mirror::ClassLoader> class_loader, const dex::ClassDef& class_def, const dex::CodeItem* code_item, ArtMethod* method, uint32_t method_access_flags, uint32_t api_level) { impl::MethodVerifier<false>* verifier = new impl::MethodVerifier<false>( self, dex_file, dex_cache, class_loader, class_def, code_item, dex_method_idx, method, method_access_flags, /* can_load_classes= */ true, /* allow_soft_failures= */ true, /* need_precise_constants= */ true, /* verify_to_dump= */ true, /* allow_thread_suspension= */ true, api_level); verifier->Verify(); verifier->DumpFailures(vios->Stream()); vios->Stream() << verifier->info_messages_.str(); // Only dump and return if no hard failures. Otherwise the verifier may be not fully initialized // and querying any info is dangerous/can abort. if (verifier->have_pending_hard_failure_) { delete verifier; return nullptr; } else { verifier->Dump(vios); return verifier; } } void MethodVerifier::FindLocksAtDexPc( ArtMethod* m, uint32_t dex_pc, std::vector<MethodVerifier::DexLockInfo>* monitor_enter_dex_pcs, uint32_t api_level) { StackHandleScope<2> hs(Thread::Current()); Handle<mirror::DexCache> dex_cache(hs.NewHandle(m->GetDexCache())); Handle<mirror::ClassLoader> class_loader(hs.NewHandle(m->GetClassLoader())); impl::MethodVerifier<false> verifier(hs.Self(), m->GetDexFile(), dex_cache, class_loader, m->GetClassDef(), m->GetCodeItem(), m->GetDexMethodIndex(), m, m->GetAccessFlags(), /* can_load_classes= */ false, /* allow_soft_failures= */ true, /* need_precise_constants= */ false, /* verify_to_dump= */ false, /* allow_thread_suspension= */ false, api_level); verifier.interesting_dex_pc_ = dex_pc; verifier.monitor_enter_dex_pcs_ = monitor_enter_dex_pcs; verifier.FindLocksAtDexPc(); } MethodVerifier* MethodVerifier::CreateVerifier(Thread* self, const DexFile* dex_file, Handle<mirror::DexCache> dex_cache, Handle<mirror::ClassLoader> class_loader, const dex::ClassDef& class_def, const dex::CodeItem* code_item, uint32_t method_idx, ArtMethod* method, uint32_t access_flags, bool can_load_classes, bool allow_soft_failures, bool need_precise_constants, bool verify_to_dump, bool allow_thread_suspension, uint32_t api_level) { return new impl::MethodVerifier<false>(self, dex_file, dex_cache, class_loader, class_def, code_item, method_idx, method, access_flags, can_load_classes, allow_soft_failures, need_precise_constants, verify_to_dump, allow_thread_suspension, api_level); } void MethodVerifier::Init() { art::verifier::RegTypeCache::Init(); } void MethodVerifier::Shutdown() { verifier::RegTypeCache::ShutDown(); } void MethodVerifier::VisitStaticRoots(RootVisitor* visitor) { RegTypeCache::VisitStaticRoots(visitor); } void MethodVerifier::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) { reg_types_.VisitRoots(visitor, root_info); } std::ostream& MethodVerifier::Fail(VerifyError error) { // Mark the error type as encountered. encountered_failure_types_ |= static_cast<uint32_t>(error); switch (error) { case VERIFY_ERROR_NO_CLASS: case VERIFY_ERROR_NO_FIELD: case VERIFY_ERROR_NO_METHOD: case VERIFY_ERROR_ACCESS_CLASS: case VERIFY_ERROR_ACCESS_FIELD: case VERIFY_ERROR_ACCESS_METHOD: case VERIFY_ERROR_INSTANTIATION: case VERIFY_ERROR_CLASS_CHANGE: case VERIFY_ERROR_FORCE_INTERPRETER: case VERIFY_ERROR_LOCKING: if (Runtime::Current()->IsAotCompiler() || !can_load_classes_) { // If we're optimistically running verification at compile time, turn NO_xxx, ACCESS_xxx, // class change and instantiation errors into soft verification errors so that we re-verify // at runtime. We may fail to find or to agree on access because of not yet available class // loaders, or class loaders that will differ at runtime. In these cases, we don't want to // affect the soundness of the code being compiled. Instead, the generated code runs "slow // paths" that dynamically perform the verification and cause the behavior to be that akin // to an interpreter. error = VERIFY_ERROR_BAD_CLASS_SOFT; } else { // If we fail again at runtime, mark that this instruction would throw and force this // method to be executed using the interpreter with checks. have_pending_runtime_throw_failure_ = true; // We need to save the work_line if the instruction wasn't throwing before. Otherwise we'll // try to merge garbage. // Note: this assumes that Fail is called before we do any work_line modifications. // Note: this can fail before we touch any instruction, for the signature of a method. So // add a check. if (work_insn_idx_ < dex::kDexNoIndex) { const Instruction& inst = code_item_accessor_.InstructionAt(work_insn_idx_); int opcode_flags = Instruction::FlagsOf(inst.Opcode()); if ((opcode_flags & Instruction::kThrow) == 0 && GetInstructionFlags(work_insn_idx_).IsInTry()) { saved_line_->CopyFromLine(work_line_.get()); } } } break; // Indication that verification should be retried at runtime. case VERIFY_ERROR_BAD_CLASS_SOFT: if (!allow_soft_failures_) { have_pending_hard_failure_ = true; } break; // Hard verification failures at compile time will still fail at runtime, so the class is // marked as rejected to prevent it from being compiled. case VERIFY_ERROR_BAD_CLASS_HARD: { have_pending_hard_failure_ = true; break; } } failures_.push_back(error); std::string location(StringPrintf("%s: [0x%X] ", dex_file_->PrettyMethod(dex_method_idx_).c_str(), work_insn_idx_)); std::ostringstream* failure_message = new std::ostringstream(location, std::ostringstream::ate); failure_messages_.push_back(failure_message); return *failure_message; } ScopedNewLine MethodVerifier::LogVerifyInfo() { ScopedNewLine ret{info_messages_}; ret << "VFY: " << dex_file_->PrettyMethod(dex_method_idx_) << '[' << reinterpret_cast<void*>(work_insn_idx_) << "] : "; return ret; } static FailureKind FailureKindMax(FailureKind fk1, FailureKind fk2) { static_assert(FailureKind::kNoFailure < FailureKind::kSoftFailure && FailureKind::kSoftFailure < FailureKind::kHardFailure, "Unexpected FailureKind order"); return std::max(fk1, fk2); } void MethodVerifier::FailureData::Merge(const MethodVerifier::FailureData& fd) { kind = FailureKindMax(kind, fd.kind); types |= fd.types; } } // namespace verifier } // namespace art
44.983174
104
0.632856
Paschalis
32cd67bff30596424078cb678afc661879634df1
61
hpp
C++
src/boost_metaparse_error_unexpected_end_of_input.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_metaparse_error_unexpected_end_of_input.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_metaparse_error_unexpected_end_of_input.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/metaparse/error/unexpected_end_of_input.hpp>
30.5
60
0.852459
miathedev
32cdd136909d5c3cc58f8a2df095b70277a36735
478
cc
C++
Code/0152-maximum-product-subarray.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
2
2019-12-06T14:08:57.000Z
2020-01-15T15:25:32.000Z
Code/0152-maximum-product-subarray.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
1
2020-01-15T16:29:16.000Z
2020-01-26T12:40:13.000Z
Code/0152-maximum-product-subarray.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
null
null
null
class Solution { public: int maxProduct(vector<int>& nums) { if (nums.size() == 0) { return 0; } int result = nums[0], pos = nums[0], neg = nums[0]; for (int i = 1; i < nums.size(); i++) { int tmp = pos; pos = max(nums[i], max(nums[i] * pos, nums[i] * neg)); neg = min(nums[i], min(nums[i] * tmp, nums[i] * neg)); result = max(result, pos); } return result; } };
29.875
66
0.439331
SMartQi
32ce8149e468185aaa18447e4a322920f41b8889
941
cpp
C++
126B.cpp
basuki57/Codeforces
5227c3deecf13d90e5ea45dab0dfc16b44bd028c
[ "MIT" ]
null
null
null
126B.cpp
basuki57/Codeforces
5227c3deecf13d90e5ea45dab0dfc16b44bd028c
[ "MIT" ]
null
null
null
126B.cpp
basuki57/Codeforces
5227c3deecf13d90e5ea45dab0dfc16b44bd028c
[ "MIT" ]
2
2020-10-03T04:52:14.000Z
2020-10-03T05:19:12.000Z
//https://codeforces.com/contest/126/problem/B #include<bits/stdc++.h> using namespace std; typedef long long int ll; vector<ll> zfun(string s){ ll n = s.length(); vector<ll> z(n); for(ll i = 1; i < n; ++i){ ll j = z[i-1]; while(j > 0 && s[i] != s[j]) j = z[j-1]; if(s[i]== s[j])++j; z[i] = j; } return z; } void solve(){ string s, t, st; cin >> s; t = s; reverse(t.begin(), t.end()); vector<ll> z = zfun(s), rz = zfun(t); ll indx = -1, n = s.length(), ma = 0; for(ll i = 0; i < n; i++){ if(z[i] == rz[n-1-(i-(z[i]-1))] && z[i] > ma){ indx = i; ma = z[i]; } } if(indx == -1){ cout << "Just a legend" << endl; return; } for(ll i = 0; i < z[indx]; i++) st+=s[i]; cout << st << endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); //int t;cin>>t;while(t--) solve(); return 0; }
21.386364
54
0.446334
basuki57
32d06204c27b116774669b99f6e78685736e1171
1,578
cpp
C++
SYCL/USM/source_kernel_indirect_access.cpp
asidoren-intel/llvm-test-suite
93d8391573adfc19b759f971e1269a245be4b87a
[ "Apache-2.0" ]
null
null
null
SYCL/USM/source_kernel_indirect_access.cpp
asidoren-intel/llvm-test-suite
93d8391573adfc19b759f971e1269a245be4b87a
[ "Apache-2.0" ]
null
null
null
SYCL/USM/source_kernel_indirect_access.cpp
asidoren-intel/llvm-test-suite
93d8391573adfc19b759f971e1269a245be4b87a
[ "Apache-2.0" ]
null
null
null
// RUN: %clangxx -fsycl -fsycl-targets=%sycl_triple %opencl_lib %s -o %t1.out // RUN: %CPU_RUN_PLACEHOLDER %t1.out // RUN: %GPU_RUN_PLACEHOLDER %t1.out // RUN: %ACC_RUN_PLACEHOLDER %t1.out // REQUIRES: opencl,opencl_icd #include <CL/cl.h> #include <CL/sycl.hpp> using namespace sycl; static const char *Src = R"( kernel void test(global ulong *PSrc, global ulong *PDst) { global int *Src = (global int *) *PSrc; global int *Dst = (global int *) *PDst; int Old = *Src, New = Old + 1; printf("Read %d from %p; write %d to %p\n", Old, Src, New, Dst); *Dst = New; } )"; int main() { queue Q{}; cl_context Ctx = Q.get_context().get(); cl_program Prog = clCreateProgramWithSource(Ctx, 1, &Src, NULL, NULL); clBuildProgram(Prog, 0, NULL, NULL, NULL, NULL); cl_kernel OclKernel = clCreateKernel(Prog, "test", NULL); cl::sycl::kernel SyclKernel(OclKernel, Q.get_context()); auto POuter = malloc_shared<int *>(1, Q); auto PInner = malloc_shared<int>(1, Q); auto QOuter = malloc_shared<int *>(1, Q); auto QInner = malloc_shared<int>(1, Q); *PInner = 4; *POuter = PInner; *QInner = 0; *QOuter = QInner; Q.submit([&](handler &CGH) { CGH.set_arg(0, POuter); CGH.set_arg(1, QOuter); CGH.parallel_for(cl::sycl::range<1>(1), SyclKernel); }).wait(); assert(*PInner == 4 && "Read value is corrupted"); assert(*QInner == 5 && "Value value is incorrect"); std::cout << "Increment: " << *PInner << " -> " << *QInner << std::endl; clReleaseKernel(OclKernel); clReleaseProgram(Prog); clReleaseContext(Ctx); }
27.206897
77
0.636248
asidoren-intel
32d2a8c84b423fb5fe0febe95ee200a0dd62bb4a
1,064
ipp
C++
coast/mtfoundation/ThreadPools.ipp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/mtfoundation/ThreadPools.ipp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/mtfoundation/ThreadPools.ipp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2007, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #ifndef _ThreadPools_IPP #define _ThreadPools_IPP //--- c-modules used ----------------------------------------------------------- template< class WorkerParamType > bool WorkerPoolManager::Enter( WorkerParamType workload, long lFindWorkerHint ) { // guard the entry to request handling // we're doing flow control on the main thread // causing it to wait for a request thread to // be available LockUnlockEntry me(fMutex); StartTrace1(WorkerPoolManager.Enter, "hint: " << lFindWorkerHint); bool bEnterSuccess( false ); // find a worker object that can run this request WorkerThread *hr( FindNextRunnable( lFindWorkerHint ) ); if ( hr != NULL ) { bEnterSuccess = hr->SetWorking(workload); } return bEnterSuccess; } #endif
32.242424
102
0.709586
zer0infinity
32d4bc55702032746bfcd58d055e479b509c06c9
6,713
cpp
C++
src/misaxx/ome/caches/misa_ome_tiff_cache.cpp
applied-systems-biology/misaxx-ome
8cffeb3a7bbf569ede1e2777417116e082d1a660
[ "BSD-2-Clause" ]
null
null
null
src/misaxx/ome/caches/misa_ome_tiff_cache.cpp
applied-systems-biology/misaxx-ome
8cffeb3a7bbf569ede1e2777417116e082d1a660
[ "BSD-2-Clause" ]
null
null
null
src/misaxx/ome/caches/misa_ome_tiff_cache.cpp
applied-systems-biology/misaxx-ome
8cffeb3a7bbf569ede1e2777417116e082d1a660
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright by Ruman Gerst * Research Group Applied Systems Biology - Head: Prof. Dr. Marc Thilo Figge * https://www.leibniz-hki.de/en/applied-systems-biology.html * HKI-Center for Systems Biology of Infection * Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Insitute (HKI) * Adolf-Reichwein-Straße 23, 07745 Jena, Germany * * This code is licensed under BSD 2-Clause * See the LICENSE file provided with this code for the full license. */ #include <misaxx/ome/caches/misa_ome_tiff_cache.h> #include <misaxx/ome/attachments/misa_ome_planes_location.h> #include <misaxx/core/runtime/misa_parameter_registry.h> #include <src/misaxx/ome/utils/ome_tiff_io.h> #include <misaxx/core/misa_parameter.h> #include <ome/common/log.h> #include <misaxx/core/utils/filesystem.h> misaxx::ome::misa_ome_tiff_cache::misa_ome_tiff_cache() { m_remove_write_buffer_parameter = misaxx::misa_parameter<bool> { {"runtime", "misaxx-ome", "remove-write-buffer"} }; m_remove_write_buffer_parameter.schema->document_title("Remove OME TIFF write buffer") .document_description("If true, the OME TIFF write buffer is removed during postprocessing") .declare_optional(true); m_disable_ome_tiff_writing_parameter = misaxx::misa_parameter<bool> { {"runtime", "misaxx-ome", "disable-write-buffer-to-ome-tiff"} }; m_disable_ome_tiff_writing_parameter.schema->document_title("Disable OME TIFF writing") .document_description("If true, the write buffer will not be postprocessed into a proper OME TIFF") .declare_optional(false); m_enable_compression_parameter = misaxx::misa_parameter<bool> { {"runtime", "misaxx-ome", "enable-compression"} }; m_enable_compression_parameter.schema->document_title("Enable compression of output images") .document_description("If true, output data is compressed with LZW") .declare_optional(true); } void misaxx::ome::misa_ome_tiff_cache::do_link(const misaxx::ome::misa_ome_tiff_description &t_description) { // Set the OME log level (needed for Windows) ::ome::common::setLogLevel(::ome::logging::trivial::warning); if (t_description.filename.empty()) throw std::runtime_error("Cannot link to file description with empty file name!"); // We do cache initialization during linkage this->set_unique_location(this->get_location() / t_description.filename); // OME TIFF is very sensitive about file paths // Convert to preferred representation this->set_unique_location(misaxx::utils::make_preferred(this->get_unique_location())); if (boost::filesystem::exists(this->get_unique_location())) { std::cout << "[Cache] Opening OME TIFF " << this->get_unique_location() << "\n"; m_tiff = std::make_shared<ome_tiff_io>(this->get_unique_location()); // Put the loaded metadata into the description this->describe()->template get<misa_ome_tiff_description>().metadata = m_tiff->get_metadata(); } else { std::cout << "[Cache] Creating OME TIFF " << this->get_unique_location() << "\n"; // Create the TIFF and generate the image caches m_tiff = std::make_shared<ome_tiff_io>(this->get_unique_location(), t_description.metadata); } // Enable compression if needed m_tiff->set_compression(m_enable_compression_parameter.query()); // Create the plane caches for (size_t series = 0; series < m_tiff->get_num_series(); ++series) { const auto size_Z = m_tiff->get_size_z(series); const auto size_C = m_tiff->get_size_c(series); const auto size_T = m_tiff->get_size_t(series); for (size_t z = 0; z < size_Z; ++z) { for (size_t c = 0; c < size_C; ++c) { for (size_t t = 0; t < size_T; ++t) { misa_ome_plane cache; cache.data = std::make_shared<misa_ome_plane_cache>(); cache.data->set_tiff_io(m_tiff); cache.force_link(this->get_internal_location(), this->get_location(), misaxx::misa_description_storage::with( misa_ome_plane_description(series, z, c, t))); this->get().emplace_back(std::move(cache)); } } } } } bool misaxx::ome::misa_ome_tiff_cache::has() const { return static_cast<bool>(m_tiff); } std::shared_ptr<misaxx::ome::ome_tiff_io> misaxx::ome::misa_ome_tiff_cache::get_tiff_io() const { return m_tiff; } misaxx::ome::misa_ome_plane misaxx::ome::misa_ome_tiff_cache::get_plane(const misaxx::ome::misa_ome_plane_description &t_location) const { // const auto num_series = m_tiff->get_num_series(); // const auto size_Z = m_tiff->get_size_z(t_location.series); const auto size_C = m_tiff->get_size_c(t_location.series); const auto size_T = m_tiff->get_size_t(t_location.series); // Calculate the plane index size_t start_index = 0; for (size_t series = 0; series < t_location.series; ++series) { start_index += m_tiff->get_num_planes(series); } size_t index = start_index + t_location.t + t_location.c * size_T + t_location.z * size_T * size_C; return this->get().at(index); } void misaxx::ome::misa_ome_tiff_cache::postprocess() { misaxx::misa_default_cache<misaxx::utils::memory_cache<std::vector<misa_ome_plane>>, misa_ome_tiff_pattern, misa_ome_tiff_description>::postprocess(); if (m_disable_ome_tiff_writing_parameter.query()) { std::cout << "[WARNING] No OME TIFF is written, because it is disabled by a parameter!" << "\n"; return; } // Close the TIFF m_tiff->close(m_remove_write_buffer_parameter.query()); } misaxx::ome::misa_ome_tiff_description misaxx::ome::misa_ome_tiff_cache::produce_description(const boost::filesystem::path &t_location, const misaxx::ome::misa_ome_tiff_pattern &t_pattern) { misa_ome_tiff_description result; t_pattern.apply(result, t_location); return result; } std::shared_ptr<misaxx::misa_location> misaxx::ome::misa_ome_tiff_cache::create_location_interface() const { auto result = std::make_shared<misaxx::ome::misa_ome_planes_location>(); result->internal_location = get_internal_location(); result->filesystem_location = get_location(); result->filesystem_unique_location = get_unique_location(); for (const auto &plane : this->get()) { result->planes.push_back(plane.get_plane_location()); } return result; } void misaxx::ome::misa_ome_tiff_cache::simulate_link() { misa_default_cache::simulate_link(); }
43.590909
138
0.688515
applied-systems-biology
32d6400d5b4faed0e74ecd60a5837859c0850664
3,731
cpp
C++
libiop/tests/algebra/test_gf256.cpp
pwang00/libiop
640a627f0e844caf88ac66cc2ab16f1ef3ea3283
[ "MIT" ]
null
null
null
libiop/tests/algebra/test_gf256.cpp
pwang00/libiop
640a627f0e844caf88ac66cc2ab16f1ef3ea3283
[ "MIT" ]
null
null
null
libiop/tests/algebra/test_gf256.cpp
pwang00/libiop
640a627f0e844caf88ac66cc2ab16f1ef3ea3283
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "libiop/algebra/fields/gf256.hpp" namespace libiop { gf256 gf256_mul(const uint64_t &a_val_high, const uint64_t &a_val_midh, const uint64_t &a_val_midl, const uint64_t &a_val_low, const uint64_t &b_val_high, const uint64_t &b_val_midh, const uint64_t &b_val_midl, const uint64_t &b_val_low) { return gf256(a_val_high, a_val_midh, a_val_midl, a_val_low) * gf256(b_val_high, b_val_midh, b_val_midl, b_val_low); } /* test cases generated by sage/gf256.sage script */ TEST(MultiplicationTest, SageTests) { EXPECT_EQ(gf256_mul(0xf764a67447957a65LL, 0x897bb93561e04d72LL, 0x0fe9a9f10ea6b3beLL, 0x614becf0f6981970LL, 0xf507be43450e596cLL, 0x7625671a07a1b127LL, 0xb6f0e7fe834a305fLL, 0x5d1bce4867374275LL), gf256(0x7830000656b147bbLL, 0x84aedc89d9eef7d5LL, 0x206521a58a74c76dLL, 0x15b45070f9272694LL)); EXPECT_EQ(gf256_mul(0xb4dab96b1454919dLL, 0x23fad70584b9ff24LL, 0x00a7fced16ffa59bLL, 0x7009d6ea6cbc3723LL, 0x633c9cefc089eb74LL, 0x0fd73239d93bd077LL, 0x5756b56a1d208f91LL, 0xac2c97ebcf121998LL), gf256(0xec433aa096b7c5a3LL, 0xb988c6486912b0ffLL, 0xf4974416b3ec0351LL, 0xa0abd7439b4a90b4LL)); EXPECT_EQ(gf256_mul(0xfae308c406eb08feLL, 0x49bfcd0bd4d96b01LL, 0xf55ab02f9dae69b8LL, 0xc1c42adfa999b078LL, 0x1cf009d26ee1f80fLL, 0xf2e6b1294f40ac62LL, 0x512288f4b06917d3LL, 0xd2c36d17d828d9b4LL), gf256(0xd4c9b1f1b6032f4aLL, 0x5a443906b0fd92f4LL, 0x069ef58da6005ef0LL, 0x81149bf7a2a4e9efLL)); EXPECT_EQ(gf256_mul(0x579c25544b3ba640LL, 0x7766723a1141eddcLL, 0x206901073d267fa5LL, 0x9a2789bfb11c03c4LL, 0x1d5e8949c38296e0LL, 0x224aa1e6e025b316LL, 0x84eb9e2187501666LL, 0xc78b2478a98afb85LL), gf256(0xc92ed4a7f831b22eLL, 0x42d345a89b213da0LL, 0x6ca9b1401b327636LL, 0x81a1d4e28ecb3203LL)); EXPECT_EQ(gf256_mul(0x034858f4f1f7b14bLL, 0x75bee645ed32bf73LL, 0xfaaf7393e729adf5LL, 0xe4e8ae96b691f6d2LL, 0xae8f8592118650dfLL, 0x4105e1bce7fda1a5LL, 0x94659c82eed44ed6LL, 0x0d6f1491ffab6313LL), gf256(0x3c58c4917b50380aLL, 0x155a26d3e04dc3f9LL, 0x0ece08a653d5d785LL, 0xa0491208d489ad20LL)); EXPECT_EQ(gf256_mul(0x22677e786437ded8LL, 0xeab6bb9efffe16f2LL, 0xae333a6c2e525a7eLL, 0x9ded3331f7e20e08LL, 0x724efc0872e555d7LL, 0x13ee2aa2bc56bb9fLL, 0x4b28b4a78b34aed6LL, 0xc9a973387db34f3cLL), gf256(0x31c713050f9fe79fLL, 0x91f3134564072e28LL, 0xbd3b97df5ceaa321LL, 0x85ae031df2087301LL)); EXPECT_EQ(gf256_mul(0xe103fdd38559f718LL, 0xbde830a033005e9dLL, 0x5980393a96b7e262LL, 0xbee979d0d3e73491LL, 0x24d79165090b54bbLL, 0x6be4979855b9f4a1LL, 0x3c84f51267ae0f3eLL, 0x49762387dc75fbcfLL), gf256(0xaf3c148f5a6d62b6LL, 0xcb2caa9c1491eb09LL, 0x9d964ce7c25f9cc4LL, 0xf0774bdc5efd321bLL)); EXPECT_EQ(gf256_mul(0xc8d362a82d40e33dLL, 0x7ebb79ea0539aab6LL, 0xd4cb229a76bbfdf8LL, 0xe1ed007e6b4d18c4LL, 0xc5ff42586ffe84beLL, 0x2fa0d6324909d6bcLL, 0xd059de8a3f216806LL, 0x11ce6283a327c2aeLL), gf256(0x6d8f5131a50a1174LL, 0x3716b1b7b85aa29fLL, 0x786f09fc7add372aLL, 0xd9be899417749c66LL)); EXPECT_EQ(gf256_mul(0xa34a5c6dc2269e92LL, 0xd4926e0f5173ba59LL, 0xad04af41cefd288cLL, 0xd6910fac0958e021LL, 0xb8efe59559134148LL, 0xe2df550b05c8346bLL, 0x471c649050d8df10LL, 0x3c4ddb6e1d7bdf2bLL), gf256(0x31bc02040d35ef67LL, 0xf4df56b7f489a233LL, 0x94a98345cd1c505eLL, 0x9b8880399d5b6f17LL)); EXPECT_EQ(gf256_mul(0x0dd2d419a879877eLL, 0xbbd7c0e1cb89df45LL, 0xb920792cb175a788LL, 0xfe328eb0319d0dd7LL, 0xfdd10984711604a6LL, 0x449e2950c151d1f4LL, 0x06b95b1542038a8aLL, 0xbbc51592da56e2feLL), gf256(0x5eac8a0dfe585d7dLL, 0x8bb81c1be4902348LL, 0xb441d39d98693d34LL, 0x480e988c351ac9f3LL)); } TEST(InverseTest, SimpleTest) { const gf256 a = gf256::random_element(); const gf256 a_inv = a.inverse(); EXPECT_EQ(a*a_inv, gf256(1)); } }
95.666667
296
0.845886
pwang00
32d832956b93505661a7cfc46df77b05ea14772c
6,193
cpp
C++
PopcornTime_Desktop-src/Import/QtAV/examples/player/playlist/PlayList.cpp
officialrafsan/POPCORNtime
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
[ "MIT" ]
null
null
null
PopcornTime_Desktop-src/Import/QtAV/examples/player/playlist/PlayList.cpp
officialrafsan/POPCORNtime
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
[ "MIT" ]
null
null
null
PopcornTime_Desktop-src/Import/QtAV/examples/player/playlist/PlayList.cpp
officialrafsan/POPCORNtime
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
[ "MIT" ]
null
null
null
/****************************************************************************** QtAV Player Demo: this file is part of QtAV examples Copyright (C) 2012-2015 Wang Bin <wbsecg1@gmail.com> * This file is part of QtAV This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #include "PlayList.h" #include "PlayListModel.h" #include "PlayListDelegate.h" #include "common/common.h" #include <QFileDialog> #include <QListView> #include <QLayout> #include <QToolButton> #include <QtCore/QFile> #include <QtCore/QDataStream> PlayList::PlayList(QWidget *parent) : QWidget(parent) { mFirstShow = true; mMaxRows = -1; mpModel = new PlayListModel(this); mpDelegate = new PlayListDelegate(this); mpListView = new QListView; //mpListView->setResizeMode(QListView::Adjust); mpListView->setModel(mpModel); mpListView->setItemDelegate(mpDelegate); mpListView->setSelectionMode(QAbstractItemView::ExtendedSelection); //ctrl,shift mpListView->setEditTriggers(QAbstractItemView::NoEditTriggers); mpListView->setToolTip(QString::fromLatin1("Ctrl/Shift + ") + tr("Click to select multiple")); QVBoxLayout *vbl = new QVBoxLayout; setLayout(vbl); vbl->addWidget(mpListView); QHBoxLayout *hbl = new QHBoxLayout; mpClear = new QToolButton(0); mpClear->setText(tr("Clear")); mpRemove = new QToolButton(0); mpRemove->setText(QString::fromLatin1("-")); mpRemove->setToolTip(tr("Remove selected items")); mpAdd = new QToolButton(0); mpAdd->setText(QString::fromLatin1("+")); hbl->addWidget(mpClear); hbl->addSpacing(width()); hbl->addWidget(mpRemove); hbl->addWidget(mpAdd); vbl->addLayout(hbl); connect(mpClear, SIGNAL(clicked()), SLOT(clearItems())); connect(mpRemove, SIGNAL(clicked()), SLOT(removeSelectedItems())); connect(mpAdd, SIGNAL(clicked()), SLOT(addItems())); connect(mpListView, SIGNAL(doubleClicked(QModelIndex)), SLOT(onAboutToPlay(QModelIndex))); // enter to highight //connect(mpListView, SIGNAL(entered(QModelIndex)), SLOT(highlight(QModelIndex))); } PlayList::~PlayList() { qDebug("+++++++++++++~PlayList()"); save(); } void PlayList::setSaveFile(const QString &file) { mFile = file; } QString PlayList::saveFile() const { return mFile; } void PlayList::load() { QFile f(mFile); if (!f.exists()) return; if (!f.open(QIODevice::ReadOnly)) return; QDataStream ds(&f); QList<PlayListItem> list; ds >> list; for (int i = 0; i < list.size(); ++i) { insertItemAt(list.at(i), i); } } void PlayList::save() { QFile f(mFile); if (!f.open(QIODevice::WriteOnly)) { qWarning("File open error: %s", qPrintable(f.errorString())); return; } QDataStream ds(&f); ds << mpModel->items(); } PlayListItem PlayList::itemAt(int row) { if (mpModel->rowCount() < 0) { qWarning("Invalid rowCount"); return PlayListItem(); } return mpModel->data(mpModel->index(row), Qt::DisplayRole).value<PlayListItem>(); } void PlayList::insertItemAt(const PlayListItem &item, int row) { if (mMaxRows > 0 && mpModel->rowCount() >= mMaxRows) { // +1 because new row is to be inserted mpModel->removeRows(mMaxRows, mpModel->rowCount() - mMaxRows + 1); } int i = mpModel->items().indexOf(item, row+1); if (i > 0) { mpModel->removeRow(i); } if (!mpModel->insertRow(row)) return; if (row > 0) { i = mpModel->items().lastIndexOf(item, row - 1); if (i >= 0) mpModel->removeRow(i); } setItemAt(item, row); } void PlayList::setItemAt(const PlayListItem &item, int row) { mpModel->setData(mpModel->index(row), QVariant::fromValue(item), Qt::DisplayRole); } void PlayList::insert(const QString &url, int row) { PlayListItem item; item.setUrl(url); item.setDuration(0); item.setLastTime(0); QString title = url; if (!url.contains(QLatin1String("://")) || url.startsWith(QLatin1String("file://"))) { title = QFileInfo(url).fileName(); } item.setTitle(title); insertItemAt(item, row); } void PlayList::remove(const QString &url) { for (int i = mpModel->rowCount() - 1; i >= 0; --i) { PlayListItem item = mpModel->data(mpModel->index(i), Qt::DisplayRole).value<PlayListItem>(); if (item.url() == url) { mpModel->removeRow(i); } } } void PlayList::setMaxRows(int r) { mMaxRows = r; } int PlayList::maxRows() const { return mMaxRows; } void PlayList::removeSelectedItems() { QItemSelectionModel *selection = mpListView->selectionModel(); if (!selection->hasSelection()) return; QModelIndexList s = selection->selectedIndexes(); for (int i = s.size()-1; i >= 0; --i) { mpModel->removeRow(s.at(i).row()); } } void PlayList::clearItems() { mpModel->removeRows(0, mpModel->rowCount()); } void PlayList::addItems() { // TODO: add url; QStringList files = QFileDialog::getOpenFileNames(0, tr("Select files")); if (files.isEmpty()) return; // TODO: check playlist file: m3u, pls... In another thread for (int i = 0; i < files.size(); ++i) { QString file = files.at(i); if (!QFileInfo(file).isFile()) continue; insert(file, i); } } void PlayList::onAboutToPlay(const QModelIndex &index) { emit aboutToPlay(index.data(Qt::DisplayRole).value<PlayListItem>().url()); save(); }
28.15
100
0.627967
officialrafsan
32dcdf57ff8a79e18f9c97c82c1e0f33056c689a
3,011
hpp
C++
include/codegen/include/OVR/OpenVR/IVRSystem__GetStringTrackedDeviceProperty.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/OVR/OpenVR/IVRSystem__GetStringTrackedDeviceProperty.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/OVR/OpenVR/IVRSystem__GetStringTrackedDeviceProperty.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:00 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: OVR.OpenVR.IVRSystem #include "OVR/OpenVR/IVRSystem.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: OVR::OpenVR namespace OVR::OpenVR { // Forward declaring type: ETrackedDeviceProperty struct ETrackedDeviceProperty; // Forward declaring type: ETrackedPropertyError struct ETrackedPropertyError; } // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: StringBuilder class StringBuilder; } // Completed forward declares // Type namespace: OVR.OpenVR namespace OVR::OpenVR { // Autogenerated type: OVR.OpenVR.IVRSystem/_GetStringTrackedDeviceProperty class IVRSystem::_GetStringTrackedDeviceProperty : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x16A6D0C static IVRSystem::_GetStringTrackedDeviceProperty* New_ctor(::Il2CppObject* object, System::IntPtr method); // public System.UInt32 Invoke(System.UInt32 unDeviceIndex, OVR.OpenVR.ETrackedDeviceProperty prop, System.Text.StringBuilder pchValue, System.UInt32 unBufferSize, OVR.OpenVR.ETrackedPropertyError pError) // Offset: 0x16A6D20 uint Invoke(uint unDeviceIndex, OVR::OpenVR::ETrackedDeviceProperty prop, System::Text::StringBuilder* pchValue, uint unBufferSize, OVR::OpenVR::ETrackedPropertyError& pError); // public System.IAsyncResult BeginInvoke(System.UInt32 unDeviceIndex, OVR.OpenVR.ETrackedDeviceProperty prop, System.Text.StringBuilder pchValue, System.UInt32 unBufferSize, OVR.OpenVR.ETrackedPropertyError pError, System.AsyncCallback callback, System.Object object) // Offset: 0x16A7004 System::IAsyncResult* BeginInvoke(uint unDeviceIndex, OVR::OpenVR::ETrackedDeviceProperty prop, System::Text::StringBuilder* pchValue, uint unBufferSize, OVR::OpenVR::ETrackedPropertyError& pError, System::AsyncCallback* callback, ::Il2CppObject* object); // public System.UInt32 EndInvoke(OVR.OpenVR.ETrackedPropertyError pError, System.IAsyncResult result) // Offset: 0x16A70F0 uint EndInvoke(OVR::OpenVR::ETrackedPropertyError& pError, System::IAsyncResult* result); }; // OVR.OpenVR.IVRSystem/_GetStringTrackedDeviceProperty } DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::IVRSystem::_GetStringTrackedDeviceProperty*, "OVR.OpenVR", "IVRSystem/_GetStringTrackedDeviceProperty"); #pragma pack(pop)
52.824561
272
0.771504
Futuremappermydud
32dcfa27d365d926a6a189e23f69bdf5da32d1a9
5,016
cpp
C++
Engine/tr/gameobject/SpriteComponent.cpp
manimax3/Tronus
f4ddd78d3332a1fbe0956e7c1a407811be3d2bc7
[ "MIT" ]
null
null
null
Engine/tr/gameobject/SpriteComponent.cpp
manimax3/Tronus
f4ddd78d3332a1fbe0956e7c1a407811be3d2bc7
[ "MIT" ]
null
null
null
Engine/tr/gameobject/SpriteComponent.cpp
manimax3/Tronus
f4ddd78d3332a1fbe0956e7c1a407811be3d2bc7
[ "MIT" ]
null
null
null
#include "SpriteComponent.h" #include "../core/Engine.h" #include "../filesystem/ResourceManager.h" #include "../graphics/GraphicsHandler.h" #include "../graphics/Texture.h" #include "World.h" #define GLM_ENABLE_EXPERIMENTAL #include "glm/gtx/matrix_transform_2d.hpp" void tr::SpriteComponent::OnWorldEnter(World &world) { auto &renderer = world.GetEngine().sGraphicsHandler->GetRenderer2D(); mRenderer = &renderer; SetupRenderState(); // We have the rendere now we can setup a state. } void tr::SpriteComponent::ChangeVisibleTo(bool visible) { if (visible != mVisible) { mVisible = visible; UpdateRenderState(); } } void tr::SpriteComponent::SetUVs(Rect rect) { mUVs = rect; UpdateRenderState(); } void tr::SpriteComponent::SetUVs(Vec2 pos, Vec2 size) { SetUVs(Rect(pos, size)); } void tr::SpriteComponent::SetSize(Vec2 size) { mSize = size; UpdateRenderState(); } void tr::SpriteComponent::SetColor(Vec4 color) { mColor = color; UpdateRenderState(); } void tr::SpriteComponent::SetTexture(std::string_view name) { auto *const rm = tr::Engine::Get().sResourceManager; const auto res = rm->GetResource(name); if (!res) return; auto res_t = ResCast<Texture>(res); if (!res_t) return; mTexture = std::move(res_t); UpdateRenderState(); } void tr::SpriteComponent::SetTexture(ResourcePtr<Texture> res) { mTexture = std::move(res); // Just set it and update if its null who cares. UpdateRenderState(); } void tr::SpriteComponent::ResetTexture() { if (!mTexture) return; mTexture = ResourcePtr<Texture>(); UpdateRenderState(); } void tr::SpriteComponent::ForceRenderStateUpdate() { UpdateRenderState(); } void tr::SpriteComponent::SetupRenderState() { if (!mRenderer) return; // Without the renderer we cant do much if (mRenderState != 0) { // Look like we already have some state going on. This really shouldnt // ever be the case. But we will handle it anyway. mRenderer->DeleteRenderable(mRenderState); mRenderState = 0; } // Just create a default renderable and submit it to the renderer. Renderer2D::Renderable renderable; mRenderState = mRenderer->SubmitRenderable(renderable); } void tr::SpriteComponent::UpdateRenderState() { if (!mRenderer || mRenderState == 0) { // Not that much we can do without compromising performance. // Someone should have called SetupRenderState() return; } auto *const r_ptr = mRenderer->ModifyRenderable(mRenderState); if (!r_ptr) return; auto &renderable = *r_ptr; renderable.visible = mVisible; renderable.color = mColor; renderable.texture = mTexture ? mTexture.get() : nullptr; renderable.layer = GetLayer(); if (renderable.texture) { const auto r = GetUV(); const auto ts = renderable.texture->GetSize(); const Vec4 rel_uv{ r.pos.x / ts.x, r.pos.y / ts.y, (r.pos.x + r.size.x) / ts.x, (r.pos.y + r.size.y) / ts.y }; renderable.uv = rel_uv; } // Create the transform matrix math::mat3 transform(1.f); transform = math::translate(transform, GetAbsolutePosition2D()); transform = math::scale(transform, GetAbsoluteScale2D()); transform = math::rotate(transform, GetAbsoluteRotation2D().get()); const auto size = GetSize(); renderable.top_left = transform * Vec3{ 0.f, 0.f, 1.f }; renderable.top_right = transform * Vec3{ size.x, 0.f, 1.f }; renderable.bottom_left = transform * Vec3{ 0.f, size.y, 1.f }; renderable.bottom_right = transform * Vec3{ size.x, size.y, 1.f }; } void tr::SpriteComponent::OnRelativeChange() { UpdateRenderState(); } void tr::FlipbookComponent::OnWorldEnter(World &world) { SpriteComponent::OnWorldEnter(world); TickingComponent = true; } void tr::FlipbookComponent::OnComponentUpdate() { if (!AutoAnimate) return; mMsUntilNext -= Engine::UPDATE_MS_DELTA; if (mMsUntilNext < 0) { NextFrame(); } } void tr::FlipbookComponent::NextFrame() { mCurrentFrame += 1; mCurrentFrame = mCurrentFrame % mFrames.size(); auto it = mFrames.begin(); std::advance(it, mCurrentFrame); SetUVs(std::get<1>(*it)); mMsUntilNext = std::get<0>(*it); } int tr::FlipbookComponent::AddFrame(Rect rect, int duration, int position_hint) { if (position_hint < 0 || static_cast<uint>(position_hint) >= mFrames.size()) { mFrames.emplace_back(std::tuple{ duration, rect }); return mFrames.size(); } else { auto it = std::begin(mFrames); std::advance(it, position_hint); mFrames.emplace(it, std::tuple{ duration, rect }); return position_hint; } } void tr::FlipbookComponent::RemoveFrame(int position) { auto it = std::begin(mFrames); std::advance(it, position); mFrames.erase(it); }
25.333333
79
0.647129
manimax3
32dd370c0f9c38cd961a39812a5bbedf9285e81b
676
cc
C++
Code/1659-get-the-maximum-score.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
2
2019-12-06T14:08:57.000Z
2020-01-15T15:25:32.000Z
Code/1659-get-the-maximum-score.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
1
2020-01-15T16:29:16.000Z
2020-01-26T12:40:13.000Z
Code/1659-get-the-maximum-score.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
null
null
null
class Solution { public: int maxSum(vector<int>& nums1, vector<int>& nums2) { long long n1 = 0, n2 = 0; int p = nums1.size() - 1, q = nums2.size() - 1; while (p >= 0 && q >= 0) { if (nums1[p] > nums2[q]) { n1 += nums1[p--]; } else if (nums1[p] < nums2[q]) { n2 += nums2[q--]; } else { n2 = n1 = nums1[p] + max(n1, n2); p--; q--; } } while (p >= 0) { n1 += nums1[p--]; } while (q >= 0) { n2 += nums2[q--]; } return max(n1, n2) % 1000000007; } };
27.04
56
0.337278
SMartQi
77fe6c5d2daaf516cecb61e5772274380ff47193
1,278
cpp
C++
bindings/python/src/LibraryPhysicsPy/Environment/Magnetic/Dipole.cpp
cowlicks/library-physics
dd314011132430fcf074a9a1633b24471745cf92
[ "Apache-2.0" ]
null
null
null
bindings/python/src/LibraryPhysicsPy/Environment/Magnetic/Dipole.cpp
cowlicks/library-physics
dd314011132430fcf074a9a1633b24471745cf92
[ "Apache-2.0" ]
null
null
null
bindings/python/src/LibraryPhysicsPy/Environment/Magnetic/Dipole.cpp
cowlicks/library-physics
dd314011132430fcf074a9a1633b24471745cf92
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Library ▸ Physics /// @file LibraryPhysicsPy/Environment/Magnetic/Dipole.cpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <Library/Physics/Environment/Magnetic/Dipole.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline void LibraryPhysicsPy_Environment_Magnetic_Dipole ( ) { using namespace boost::python ; using library::math::obj::Vector3d ; using library::physics::environment::magnetic::Dipole ; scope in_Dipole = class_<Dipole>("Dipole", init<const Vector3d&>()) .def("getFieldValueAt", &Dipole::getFieldValueAt) ; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
39.9375
160
0.324726
cowlicks
ae045c9a460af1c7b67fd9565e570a701c9257d3
171
cpp
C++
config_tools/check_cpu.tool.cpp
SamuraiCrow/AmosKittens
e89477b94a28916e4320fa946c18c0d769c710b2
[ "MIT" ]
7
2018-04-24T22:11:58.000Z
2021-09-10T22:12:35.000Z
config_tools/check_cpu.tool.cpp
SamuraiCrow/AmosKittens
e89477b94a28916e4320fa946c18c0d769c710b2
[ "MIT" ]
36
2018-02-24T18:34:18.000Z
2021-08-08T10:33:29.000Z
config_tools/check_cpu.tool.cpp
SamuraiCrow/AmosKittens
e89477b94a28916e4320fa946c18c0d769c710b2
[ "MIT" ]
2
2018-10-22T18:47:30.000Z
2020-09-16T06:10:52.000Z
#include <stdio.h> #include <stdlib.h> int main(int args,char **arg) { int value = 1; if ( *((char *) &value) == 1 ) { printf("#define __LITTLE_ENDIAN__\n"); } }
12.214286
40
0.578947
SamuraiCrow
ae09efe5f7bc628a40fca75a74fd9b271f95c7d0
810
cpp
C++
Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryMessageDialogWithToggle.h" #include "ui_berryMessageDialogWithToggle.h" MessageDialogWithToggle::MessageDialogWithToggle(QWidget *parent) : QDialog(parent), ui(new Ui::MessageDialogWithToggle) { ui->setupUi(this); } MessageDialogWithToggle::~MessageDialogWithToggle() { delete ui; }
26.129032
70
0.633333
liu3xing3long
ae0a3f06fce60ff1b318cb37a140de678f9abca3
1,156
cpp
C++
Codeforces/1462C.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
Codeforces/1462C.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
Codeforces/1462C.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define y1 yy #define f first #define s second #define ll long long #define vi vector<int> #define pii pair<int, int> #define debug if(printDebug) #define noDebug if(!printDebug) using namespace std; template<class T> using v=vector<T>; bool printDebug=false; int ans[51]; bool used[10]; void test(int pos){ if(pos>9){ int sum=0; string str; for(int i=0; i<10; i++){ if(used[i]){ sum+=i; str+=i+'0'; } } if(str.size()==0) return; int num=stoi(str); if(sum<=50 && ans[sum]!=-1 && num<ans[sum]) ans[sum]=num; if(sum<=50 && ans[sum]==-1) ans[sum]=num; return; } used[pos]=false; test(pos+1); used[pos]=true; test(pos+1); } int main(){ memset(ans, -1, sizeof(ans)); //printDebug=true; /*freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout);//*/ noDebug ios_base::sync_with_stdio(0); noDebug cin.tie(0); test(1); int cases; cin >> cases; while(cases--){ int n; cin >> n; cout << ans[n] << "\n"; } return 0; }
21.407407
65
0.521626
DT3264
ae0ad4adaed1a74b592b4dca91d9e1528077222c
2,376
cpp
C++
test/istream.cpp
danra/scnlib
815782badc1b548c21bb151372497e1516bee806
[ "Apache-2.0" ]
556
2018-11-17T01:49:32.000Z
2022-03-25T09:35:10.000Z
test/istream.cpp
danra/scnlib
815782badc1b548c21bb151372497e1516bee806
[ "Apache-2.0" ]
51
2019-05-09T14:36:53.000Z
2022-03-19T12:47:12.000Z
test/istream.cpp
danra/scnlib
815782badc1b548c21bb151372497e1516bee806
[ "Apache-2.0" ]
21
2019-02-11T19:56:30.000Z
2022-03-28T02:52:27.000Z
// Copyright 2017 Elias Kosunen // // 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 // // https://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. // // This file is a part of scnlib: // https://github.com/eliaskosunen/scnlib #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <scn/istream.h> #include <istream> #include <sstream> #include "test.h" struct my_type { int value{}; friend std::istream& operator>>(std::istream& is, my_type& val) { is >> val.value; return is; } }; TEST_CASE("istream value") { my_type val{}; auto ret = scn::scan("123", "{}", val); CHECK(ret); CHECK(val.value == 123); } TEST_CASE("istream fail") { my_type val{}; auto ret = scn::scan("foo", "{}", val); CHECK(!ret); CHECK(ret.error().code() == scn::error::invalid_scanned_value); CHECK(val.value == 0); } TEST_CASE("istream eof") { my_type val{}; auto ret = scn::scan("", "{}", val); CHECK(!ret); CHECK(ret.error().code() == scn::error::end_of_range); CHECK(val.value == 0); } TEST_CASE("istream composite") { auto source = std::string{"foo 123 456"}; std::string s; auto ret = scn::scan_default(source, s); CHECK(ret); CHECK(s == "foo"); my_type val{}; ret = scn::scan_default(ret.range(), val); CHECK(ret); CHECK(val.value == 123); int i; ret = scn::scan_default(ret.range(), i); CHECK(ret); CHECK(i == 456); CHECK(ret.empty()); } TEST_CASE("istream composite error") { auto source = std::string{"123 foo 456"}; int i; auto ret = scn::scan_default(source, i); CHECK(ret); CHECK(i == 123); my_type val{}; ret = scn::scan_default(ret.range(), val); CHECK(!ret); CHECK(ret.error() == scn::error::invalid_scanned_value); CHECK(val.value == 0); std::string s; ret = scn::scan_default(ret.range(), s); CHECK(ret); CHECK(s == "foo"); }
23.294118
75
0.621212
danra
ae0cf9861d85e17a183690be0bd6bf178259c176
44,069
cpp
C++
src/ModelSet.cpp
marcussvensson92/inner_conservative_occluder_rasterization
cbf05803d1e7658e95277d093dbae9570a874c59
[ "MIT" ]
null
null
null
src/ModelSet.cpp
marcussvensson92/inner_conservative_occluder_rasterization
cbf05803d1e7658e95277d093dbae9570a874c59
[ "MIT" ]
1
2017-09-10T11:58:30.000Z
2017-09-10T11:58:30.000Z
src/ModelSet.cpp
marcussvensson92/inner_conservative_occluder_rasterization
cbf05803d1e7658e95277d093dbae9570a874c59
[ "MIT" ]
null
null
null
#include "ModelSet.h" #include "OcclusionAlgorithm.h" #include <DDSTextureLoader.h> #include <fstream> #include <locale> #include <codecvt> CModelSet::CModelSet() : m_InstanceCount( 0 ), m_MaterialBuffer( nullptr ), m_MaterialBufferUpload( nullptr ), m_WorldMatrixBufferSize( 0 ), m_WorldMatrixBuffer( nullptr ), m_WorldMatrixBufferUpload( nullptr ), m_ModelInstanceCountBufferSize( 0 ), m_InstanceIndexMappingsBufferSize( 0 ), m_InstanceModelMappingsBuffer( nullptr ), m_InstanceModelMappingsBufferUpload( nullptr ), m_ModelInstanceOffsetBuffer( nullptr ), m_ModelInstanceOffsetBufferUpload( nullptr ), m_ModelInstanceCountBuffer( nullptr ), m_ModelInstanceCountBufferReset( nullptr ), m_InstanceIndexMappingsBuffer( nullptr ), m_OutputCommandBufferCounterOffset( 0 ), m_InputCommandBuffer( nullptr ), m_InputCommandBufferUpload( nullptr ), m_OutputCommandBuffer( nullptr ), m_OutputCommandBufferCounterReset( nullptr ) { } void CModelSet::Load( const std::string& directory, const std::string& filename ) { m_Directory = directory; m_Filename = filename; LoadModels(); } void CModelSet::Save() { SaveModels(); } void CModelSet::Create( ID3D12Device* device, ID3D12GraphicsCommandList* command_list, NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] ) { m_InstanceCount = 0; for ( SModel* model : m_Models ) { m_InstanceCount += static_cast< UINT >( model->m_Instances.size() ); } CreateMeshes( device, command_list ); CreateTexturesAndMaterials( device, command_list, descriptor_heaps ); CreateWorldMatrixBuffer( device, command_list, descriptor_heaps ); CreateInstanceMappingsBuffers( device, command_list, descriptor_heaps ); CreateCommandBuffers( device, command_list, descriptor_heaps ); CalculateOccludees(); CalculateOccluders(); } void CModelSet::Destroy() { m_InstanceCount = 0; for ( SModel* model : m_Models ) { model->m_Mesh.Destroy(); delete model; } m_Models.clear(); SAFE_RELEASE( m_MaterialBufferUpload ); SAFE_RELEASE( m_MaterialBuffer ); for ( STexture texture_array : m_Textures ) { texture_array.m_Resource->Release(); texture_array.m_ResourceUpload->Release(); } m_Textures.clear(); m_WorldMatrixBufferSize = 0; SAFE_RELEASE( m_WorldMatrixBuffer ); SAFE_RELEASE_UNMAP( m_WorldMatrixBufferUpload ); m_ModelInstanceCountBufferSize = 0; m_InstanceIndexMappingsBufferSize = 0; SAFE_RELEASE( m_InstanceModelMappingsBuffer ); SAFE_RELEASE( m_InstanceModelMappingsBufferUpload ); SAFE_RELEASE( m_ModelInstanceOffsetBuffer ); SAFE_RELEASE( m_ModelInstanceOffsetBufferUpload ); SAFE_RELEASE( m_ModelInstanceCountBuffer ); SAFE_RELEASE( m_ModelInstanceCountBufferReset ); SAFE_RELEASE( m_InstanceIndexMappingsBuffer ); SAFE_RELEASE( m_InstanceIndexMappingsBufferUpload ); m_OutputCommandBufferCounterOffset = 0; SAFE_RELEASE( m_InputCommandBuffer ); SAFE_RELEASE( m_InputCommandBufferUpload ); SAFE_RELEASE( m_OutputCommandBuffer ); SAFE_RELEASE( m_OutputCommandBufferCounterReset ); } void CModelSet::UpdateWorldMatrixBuffer( ID3D12GraphicsCommandList* command_list ) { for ( SModel* model : m_Models ) { model->m_VisibleInstanceCount = static_cast< UINT >( model->m_Instances.size() ); DirectX::XMFLOAT4X4* mapped_world_matrix_buffer = model->m_MappedWorldMatrixBuffer; for ( SInstance instance : model->m_Instances ) { DirectX::XMStoreFloat4x4( mapped_world_matrix_buffer, DirectX::XMMatrixTranspose( DirectX::XMLoadFloat4x4( &instance.m_World ) ) ); ++mapped_world_matrix_buffer; } } command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition( m_WorldMatrixBuffer, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST ) ); command_list->CopyBufferRegion( m_WorldMatrixBuffer, 0, m_WorldMatrixBufferUpload, 0, m_WorldMatrixBufferSize ); command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition( m_WorldMatrixBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ) ); } void CModelSet::UpdateInstanceMappings( ID3D12GraphicsCommandList* command_list, COcclusionAlgorithm* occlusion_algorithm, UINT occludee_offset ) { UINT* mapped_instance_index_mappings_upload = nullptr; HR( m_InstanceIndexMappingsBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_instance_index_mappings_upload ) ) ); UINT instance_index = 0; for ( SModel* model : m_Models ) { model->m_VisibleInstanceCount = 0; for ( SInstance instance : model->m_Instances ) { if ( occlusion_algorithm->IsOccludeeVisible( occludee_offset + instance_index ) ) { mapped_instance_index_mappings_upload[ model->m_VisibleInstanceCount++ ] = instance_index; } ++instance_index; } mapped_instance_index_mappings_upload += model->m_Instances.size(); } m_InstanceIndexMappingsBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) ); command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition( m_InstanceIndexMappingsBuffer, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST ) ); command_list->CopyBufferRegion( m_InstanceIndexMappingsBuffer, 0, m_InstanceIndexMappingsBufferUpload, 0, m_InstanceIndexMappingsBufferSize ); command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition( m_InstanceIndexMappingsBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ) ); } void CModelSet::CalculateOccluders() { size_t total_occluder_obb_count = 0; size_t total_occluder_cylinder_count = 0; for ( SModel* model : m_Models ) { total_occluder_obb_count += model->m_OccluderObbs.size() * model->m_Instances.size(); total_occluder_cylinder_count += model->m_OccluderCylinders.size() * model->m_Instances.size(); } m_OccluderObbs.resize( total_occluder_obb_count ); m_OccluderCylinders.resize( total_occluder_cylinder_count ); size_t occluder_obb_index = 0; size_t occluder_cylinder_index = 0; for ( SModel* model : m_Models ) { for ( size_t i = 0; i < model->m_Instances.size(); ++i ) { DirectX::XMMATRIX instance_world = DirectX::XMLoadFloat4x4( &model->m_Instances[ i ].m_World ); DirectX::XMVECTOR scale, rotation, translation; DirectX::XMMatrixDecompose( &scale, &rotation, &translation, instance_world ); instance_world = DirectX::XMMatrixRotationQuaternion( rotation ) * DirectX::XMMatrixTranslationFromVector( translation ); for ( size_t j = 0; j < model->m_OccluderObbs.size(); ++j ) { DirectX::XMMATRIX obb_center = DirectX::XMMatrixScaling( model->m_OccluderObbs[ j ].m_Extent.x, model->m_OccluderObbs[ j ].m_Extent.y, model->m_OccluderObbs[ j ].m_Extent.z ) * DirectX::XMMatrixRotationX( DirectX::XMConvertToRadians( model->m_OccluderObbs[ j ].m_Rotation.x ) ) * DirectX::XMMatrixRotationY( DirectX::XMConvertToRadians( model->m_OccluderObbs[ j ].m_Rotation.y ) ) * DirectX::XMMatrixRotationZ( DirectX::XMConvertToRadians( model->m_OccluderObbs[ j ].m_Rotation.z ) ) * DirectX::XMMatrixTranslation( model->m_OccluderObbs[ j ].m_Center.x, model->m_OccluderObbs[ j ].m_Center.y, model->m_OccluderObbs[ j ].m_Center.z ); DirectX::XMStoreFloat4x4( &m_OccluderObbs[ occluder_obb_index++ ], DirectX::XMMatrixTranspose( DirectX::XMMatrixMultiply( obb_center, instance_world ) ) ); } for ( size_t j = 0; j < model->m_OccluderCylinders.size(); ++j ) { DirectX::XMMATRIX cylinder_center = DirectX::XMMatrixScaling( model->m_OccluderCylinders[ j ].m_Radius, model->m_OccluderCylinders[ j ].m_Height, model->m_OccluderCylinders[ j ].m_Radius ) * DirectX::XMMatrixRotationX( DirectX::XMConvertToRadians( model->m_OccluderCylinders[ j ].m_Rotation.x ) ) * DirectX::XMMatrixRotationY( DirectX::XMConvertToRadians( model->m_OccluderCylinders[ j ].m_Rotation.y ) ) * DirectX::XMMatrixRotationZ( DirectX::XMConvertToRadians( model->m_OccluderCylinders[ j ].m_Rotation.z ) ) * DirectX::XMMatrixTranslation( model->m_OccluderCylinders[ j ].m_Center.x, model->m_OccluderCylinders[ j ].m_Center.y, model->m_OccluderCylinders[ j ].m_Center.z ); DirectX::XMStoreFloat4x4( &m_OccluderCylinders[ occluder_cylinder_index++ ], DirectX::XMMatrixTranspose( DirectX::XMMatrixMultiply( cylinder_center, instance_world ) ) ); } } } } void CModelSet::CalculateOccludees() { m_OccludeeAabbs.resize( m_InstanceCount ); UINT occludee_aabb_index = 0; for ( SModel* model : m_Models ) { DirectX::XMVECTOR center = XMLoadFloat3( &model->m_OccludeeBoundingBoxCenter ); DirectX::XMVECTOR extent = XMLoadFloat3( &model->m_OccludeeBoundingBoxExtent ); DirectX::XMVECTOR positions[ 8 ] = { DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( 1.0f, 1.0f, 1.0f, 0.0f ), extent ) ), DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( 1.0f, 1.0f, -1.0f, 0.0f ), extent ) ), DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( 1.0f, -1.0f, 1.0f, 0.0f ), extent ) ), DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( 1.0f, -1.0f, -1.0f, 0.0f ), extent ) ), DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( -1.0f, 1.0f, 1.0f, 0.0f ), extent ) ), DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( -1.0f, 1.0f, -1.0f, 0.0f ), extent ) ), DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( -1.0f, -1.0f, 1.0f, 0.0f ), extent ) ), DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( -1.0f, -1.0f, -1.0f, 0.0f ), extent ) ) }; for ( SInstance& instance : model->m_Instances ) { DirectX::XMMATRIX instance_world = DirectX::XMLoadFloat4x4( &instance.m_World ); DirectX::XMVECTOR aabb_min = DirectX::XMVectorSet( FLT_MAX, FLT_MAX, FLT_MAX, 1.0f ); DirectX::XMVECTOR aabb_max = DirectX::XMVectorSet( -FLT_MAX, -FLT_MAX, -FLT_MAX, 1.0f ); for ( UINT i = 0; i < 8; ++i ) { DirectX::XMVECTOR position = DirectX::XMVector3TransformCoord( positions[ i ], instance_world ); aabb_min = DirectX::XMVectorMin( aabb_min, position ); aabb_max = DirectX::XMVectorMax( aabb_max, position ); } DirectX::XMStoreFloat3( &instance.m_OccludeeAabbMin, aabb_min ); DirectX::XMStoreFloat3( &instance.m_OccludeeAabbMax, aabb_max ); DirectX::XMStoreFloat3( &m_OccludeeAabbs[ occludee_aabb_index ].m_Center, ( aabb_max + aabb_min ) * 0.5f ); DirectX::XMStoreFloat3( &m_OccludeeAabbs[ occludee_aabb_index ].m_Extent, ( aabb_max - aabb_min ) * 0.5f ); ++occludee_aabb_index; } } } const UINT CModelSet::GetModelCount() const { return static_cast< UINT >( m_Models.size() ); } const UINT CModelSet::GetInstanceCount() const { return m_InstanceCount; } const UINT CModelSet::GetTextureCount() const { return static_cast< UINT >( m_Textures.size() ); } std::vector< CModelSet::SModel* >* CModelSet::GetModels() { return &m_Models; } std::vector< DirectX::XMFLOAT4X4 >* CModelSet::GetOccluderObbs() { return &m_OccluderObbs; } std::vector< DirectX::XMFLOAT4X4 >* CModelSet::GetOccluderCylinders() { return &m_OccluderCylinders; } std::vector< COccludeeCollection::SAabb >* CModelSet::GetOccludeeAabbs() { return &m_OccludeeAabbs; } NGraphics::SDescriptorHandle CModelSet::GetMaterialBufferSrv() const { return m_MaterialBufferSrv; } NGraphics::SDescriptorHandle CModelSet::GetWorldMatrixBufferSrv() const { return m_WorldMatrixBufferSrv; } NGraphics::SDescriptorHandle CModelSet::GetTexturesSrv() const { return m_Textures[ 0 ].m_Handle; } NGraphics::SDescriptorHandle CModelSet::GetInstanceModelMappingsBufferSrv() const { return m_InstanceModelMappingsBufferSrv; } NGraphics::SDescriptorHandle CModelSet::GetModelInstanceOffsetBufferSrv() const { return m_ModelInstanceOffsetBufferSrv; } NGraphics::SDescriptorHandle CModelSet::GetModelInstanceCountBufferUav() const { return m_ModelInstanceCountBufferUav; } NGraphics::SDescriptorHandle CModelSet::GetModelInstanceCountBufferSrv() const { return m_ModelInstanceCountBufferSrv; } NGraphics::SDescriptorHandle CModelSet::GetInstanceIndexMappingsBufferUav() const { return m_InstanceIndexMappingsBufferUav; } NGraphics::SDescriptorHandle CModelSet::GetInstanceIndexMappingsBufferSrv() const { return m_InstanceIndexMappingsBufferSrv; } NGraphics::SDescriptorHandle CModelSet::GetInputCommandBufferSrv() const { return m_InputCommandBufferSrv; } NGraphics::SDescriptorHandle CModelSet::GetOutputCommandBufferUav() const { return m_OutputCommandBufferUav; } ID3D12Resource* CModelSet::GetModelInstanceCountBuffer() const { return m_ModelInstanceCountBuffer; } ID3D12Resource* CModelSet::GetModelInstanceCountBufferReset() const { return m_ModelInstanceCountBufferReset; } ID3D12Resource* CModelSet::GetInstanceIndexMappingsBuffer() const { return m_InstanceIndexMappingsBuffer; } ID3D12Resource* CModelSet::GetOutputCommandBuffer() const { return m_OutputCommandBuffer; } ID3D12Resource* CModelSet::GetOutputCommandBufferCounterReset() const { return m_OutputCommandBufferCounterReset; } const UINT CModelSet::GetModelInstanceCountBufferSize() const { return m_ModelInstanceCountBufferSize; } const UINT CModelSet::GetOutputCommandBufferCounterOffset() const { return m_OutputCommandBufferCounterOffset; } void CModelSet::LoadModels() { std::fstream file( m_Directory + "/" + m_Filename, std::ios::in | std::ios::binary ); assert( file.is_open() && file.good() ); size_t size; file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); m_Models.resize( size ); for ( size_t i = 0; i < m_Models.size(); ++i ) { SModel* model = new SModel; file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); model->m_Name.resize( size ); file.read( reinterpret_cast< char* >( &model->m_Name[ 0 ] ), size * sizeof( char ) ); file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); model->m_Vertices.resize( size ); file.read( reinterpret_cast< char* >( &model->m_Vertices[ 0 ] ), size * sizeof( SVertex ) ); file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); model->m_Indices.resize( size ); file.read( reinterpret_cast< char* >( &model->m_Indices[ 0 ] ), size * sizeof( UINT ) ); size_t texture_filepath_count; file.read( reinterpret_cast< char* >( &texture_filepath_count ), sizeof( size_t ) ); for ( size_t j = 0; j < texture_filepath_count; ++j ) { std::string texture_filepath_key; std::string texture_filepath_value; file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); texture_filepath_key.resize( size ); file.read( reinterpret_cast< char* >( &texture_filepath_key[ 0 ] ), size * sizeof( char ) ); file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); texture_filepath_value.resize( size ); file.read( reinterpret_cast< char* >( &texture_filepath_value[ 0 ] ), size * sizeof( char ) ); model->m_TextureFilepathMap[ texture_filepath_key ] = texture_filepath_value; } file.read( reinterpret_cast< char* >( &model->m_OccludeeBoundingBoxCenter ), sizeof( DirectX::XMFLOAT3 ) ); file.read( reinterpret_cast< char* >( &model->m_OccludeeBoundingBoxExtent ), sizeof( DirectX::XMFLOAT3 ) ); file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); model->m_OccluderObbs.resize( size ); if ( size > 0 ) { file.read( reinterpret_cast< char* >( &model->m_OccluderObbs[ 0 ] ), sizeof( SOccluderObb ) * size ); } file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); model->m_OccluderCylinders.resize( size ); if ( size > 0 ) { file.read( reinterpret_cast< char* >( &model->m_OccluderCylinders[ 0 ] ), sizeof( SOccluderCylinder ) * size ); } file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); model->m_Instances.resize( size ); for ( size_t j = 0; j < model->m_Instances.size(); ++j ) { file.read( reinterpret_cast< char* >( &model->m_Instances[ j ].m_World ), sizeof( DirectX::XMFLOAT4X4 ) ); } m_Models[ i ] = model; } file.close(); } void CModelSet::SaveModels() { std::fstream file( m_Directory + "/" + m_Filename, std::ios::out | std::ios::binary ); size_t size = m_Models.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); for ( size_t i = 0; i < m_Models.size(); ++i ) { SModel* model = m_Models[ i ]; size = model->m_Name.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); file.write( reinterpret_cast< char* >( &model->m_Name[ 0 ] ), model->m_Name.size() * sizeof( char ) ); size = model->m_Vertices.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); file.write( reinterpret_cast< char* >( &model->m_Vertices[ 0 ] ), model->m_Vertices.size() * sizeof( SVertex ) ); size = model->m_Indices.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); file.write( reinterpret_cast< char* >( &model->m_Indices[ 0 ] ), model->m_Indices.size() * sizeof( UINT ) ); size = model->m_TextureFilepathMap.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); for ( std::pair<std::string, std::string> texture_filepath_entry : model->m_TextureFilepathMap ) { size = texture_filepath_entry.first.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); file.write( reinterpret_cast< char* >( &texture_filepath_entry.first[ 0 ] ), texture_filepath_entry.first.size() * sizeof( char ) ); size = texture_filepath_entry.second.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); file.write( reinterpret_cast< char* >( &texture_filepath_entry.second[ 0 ] ), texture_filepath_entry.second.size() * sizeof( char ) ); } file.write( reinterpret_cast< char* >( &model->m_OccludeeBoundingBoxCenter ), sizeof( DirectX::XMFLOAT3 ) ); file.write( reinterpret_cast< char* >( &model->m_OccludeeBoundingBoxExtent ), sizeof( DirectX::XMFLOAT3 ) ); size = model->m_OccluderObbs.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); if ( size > 0 ) { file.write( reinterpret_cast< char* >( &model->m_OccluderObbs[ 0 ] ), sizeof( SOccluderObb ) * size ); } size = model->m_OccluderCylinders.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); if ( size > 0 ) { file.write( reinterpret_cast< char* >( &model->m_OccluderCylinders[ 0 ] ), sizeof( SOccluderCylinder ) * size ); } size = model->m_Instances.size(); file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) ); for ( size_t j = 0; j < model->m_Instances.size(); ++j ) { file.write( reinterpret_cast< char* >( &model->m_Instances[ j ].m_World ), sizeof( DirectX::XMFLOAT4X4 ) ); } } file.close(); } void CModelSet::CreateMeshes( ID3D12Device* device, ID3D12GraphicsCommandList* command_list ) { for ( SModel* model : m_Models ) { model->m_Mesh.Create( device, command_list, &model->m_Vertices, &model->m_Indices ); } } void CModelSet::CreateTexturesAndMaterials( ID3D12Device* device, ID3D12GraphicsCommandList* command_list, NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] ) { assert( !m_Models.empty() ); size_t material_texture_count = m_Models[ 0 ]->m_TextureFilepathMap.size(); std::vector< std::wstring > texture_filepaths; std::vector< UINT > materials; std::vector< UINT > material_textures( material_texture_count ); for ( SModel* model : m_Models ) { size_t material_texture_index = 0; for ( std::pair<std::string, std::string> texture_filepath_entry : model->m_TextureFilepathMap ) { std::wstring_convert< std::codecvt_utf8_utf16< wchar_t > > converter; std::wstring texture_filepath = converter.from_bytes( m_Directory + "/" + texture_filepath_entry.second ); bool is_texture_found = false; for ( size_t i = 0; i < texture_filepaths.size(); ++i ) { if ( texture_filepaths[ i ] == texture_filepath ) { material_textures[ material_texture_index++ ] = static_cast< UINT >( i ); is_texture_found = true; break; } } if ( !is_texture_found ) { STexture texture; texture.m_Resource = nullptr; texture.m_ResourceUpload = nullptr; texture.m_Handle = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); CreateDDSTextureFromFile( device, command_list, texture_filepath.c_str(), 0, false, &texture.m_Resource, &texture.m_ResourceUpload, texture.m_Handle.m_Cpu, nullptr ); m_Textures.push_back( texture ); texture_filepaths.push_back( texture_filepath ); material_textures[ material_texture_index++ ] = static_cast< UINT >( texture_filepaths.size() - 1 ); } } bool is_material_found = false; UINT material_index = 0; for ( size_t i = 0; i < materials.size(); i += material_texture_count ) { is_material_found = true; for ( size_t j = 0; j < material_texture_count; ++j ) { if ( materials[ i + j ] != material_textures[ j ] ) { is_material_found = false; break; } } if ( is_material_found ) { break; } ++material_index; } if ( !is_material_found ) { materials.insert( materials.end(), material_textures.begin(), material_textures.end() ); } model->m_MaterialIndex = material_index; } UINT material_buffer_size = static_cast< UINT >( sizeof( UINT ) * materials.size() ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( material_buffer_size ), D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS( &m_MaterialBuffer ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( material_buffer_size ), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &m_MaterialBufferUpload ) ) ); BYTE* mapped_material_buffer_upload = nullptr; HR( m_MaterialBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_material_buffer_upload ) ) ); memcpy( mapped_material_buffer_upload, materials.data(), material_buffer_size ); m_MaterialBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) ); command_list->CopyBufferRegion( m_MaterialBuffer, 0, m_MaterialBufferUpload, 0, material_buffer_size ); command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition( m_MaterialBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE ) ); m_MaterialBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc; ZeroMemory( &srv_desc, sizeof( srv_desc ) ); srv_desc.Format = DXGI_FORMAT_UNKNOWN; srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srv_desc.Buffer.NumElements = static_cast< UINT >( materials.size() / material_texture_count ); srv_desc.Buffer.StructureByteStride = static_cast< UINT >( material_texture_count * sizeof( UINT ) ); srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; device->CreateShaderResourceView( m_MaterialBuffer, &srv_desc, m_MaterialBufferSrv.m_Cpu ); } void CModelSet::CreateWorldMatrixBuffer( ID3D12Device* device, ID3D12GraphicsCommandList* command_list, NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] ) { m_WorldMatrixBufferSize = sizeof( DirectX::XMFLOAT4X4 ) * m_InstanceCount; HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( m_WorldMatrixBufferSize ), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, nullptr, IID_PPV_ARGS( &m_WorldMatrixBuffer ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( m_WorldMatrixBufferSize ), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &m_WorldMatrixBufferUpload ) ) ); DirectX::XMFLOAT4X4* mapped_world_matrix_buffer_upload = nullptr; HR( m_WorldMatrixBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_world_matrix_buffer_upload ) ) ); UINT world_matrix_buffer_offset = 0; for ( SModel* model : m_Models ) { model->m_MappedWorldMatrixBuffer = mapped_world_matrix_buffer_upload; mapped_world_matrix_buffer_upload += static_cast< UINT >( model->m_Instances.size() ); world_matrix_buffer_offset += static_cast< UINT >( model->m_Instances.size() ); } m_WorldMatrixBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc; ZeroMemory( &srv_desc, sizeof( srv_desc ) ); srv_desc.Format = DXGI_FORMAT_UNKNOWN; srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srv_desc.Buffer.NumElements = m_InstanceCount; srv_desc.Buffer.StructureByteStride = sizeof( DirectX::XMFLOAT4X4 ); srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; device->CreateShaderResourceView( m_WorldMatrixBuffer, &srv_desc, m_WorldMatrixBufferSrv.m_Cpu ); UpdateWorldMatrixBuffer( command_list ); } void CModelSet::CreateInstanceMappingsBuffers( ID3D12Device* device, ID3D12GraphicsCommandList* command_list, NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] ) { UINT instance_model_mappings_buffer_size = m_InstanceCount * sizeof( UINT ); UINT model_instance_offset_buffer_size = static_cast< UINT >( m_Models.size() ) * sizeof( UINT ); m_ModelInstanceCountBufferSize = static_cast< UINT >( m_Models.size() ) * sizeof( UINT ); m_InstanceIndexMappingsBufferSize = m_InstanceCount * sizeof( UINT ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( instance_model_mappings_buffer_size ), D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS( &m_InstanceModelMappingsBuffer ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( instance_model_mappings_buffer_size ), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &m_InstanceModelMappingsBufferUpload ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( model_instance_offset_buffer_size ), D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS( &m_ModelInstanceOffsetBuffer ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( model_instance_offset_buffer_size ), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &m_ModelInstanceOffsetBufferUpload ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( m_ModelInstanceCountBufferSize, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, nullptr, IID_PPV_ARGS( &m_ModelInstanceCountBuffer ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( m_ModelInstanceCountBufferSize ), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &m_ModelInstanceCountBufferReset ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( m_InstanceIndexMappingsBufferSize, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ), D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS( &m_InstanceIndexMappingsBuffer ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( m_InstanceIndexMappingsBufferSize ), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &m_InstanceIndexMappingsBufferUpload ) ) ); UINT* mapped_instance_model_mappings_buffer_upload = nullptr; UINT* mapped_model_instance_offset_buffer_upload = nullptr; UINT* mapped_model_instance_count_buffer_reset = nullptr; UINT* mapped_instance_index_mappings_upload = nullptr; HR( m_InstanceModelMappingsBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_instance_model_mappings_buffer_upload ) ) ); HR( m_ModelInstanceOffsetBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_model_instance_offset_buffer_upload ) ) ); HR( m_ModelInstanceCountBufferReset->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_model_instance_count_buffer_reset ) ) ); HR( m_InstanceIndexMappingsBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_instance_index_mappings_upload ) ) ); UINT model_instance_offset = 0; for ( UINT i = 0; i < static_cast< UINT >( m_Models.size() ); ++i ) { for ( UINT j = 0; j < static_cast< UINT >( m_Models[ i ]->m_Instances.size() ); ++j ) { *mapped_instance_model_mappings_buffer_upload = i; ++mapped_instance_model_mappings_buffer_upload; mapped_instance_index_mappings_upload[ model_instance_offset + j ] = model_instance_offset + j; } *mapped_model_instance_offset_buffer_upload = model_instance_offset; ++mapped_model_instance_offset_buffer_upload; model_instance_offset += static_cast< UINT >( m_Models[ i ]->m_Instances.size() ); } ZeroMemory( mapped_model_instance_count_buffer_reset, m_ModelInstanceCountBufferSize ); m_InstanceModelMappingsBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) ); m_ModelInstanceOffsetBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) ); m_ModelInstanceCountBufferReset->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) ); m_InstanceIndexMappingsBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) ); command_list->CopyBufferRegion( m_InstanceModelMappingsBuffer, 0, m_InstanceModelMappingsBufferUpload, 0, instance_model_mappings_buffer_size ); command_list->CopyBufferRegion( m_ModelInstanceOffsetBuffer, 0, m_ModelInstanceOffsetBufferUpload, 0, model_instance_offset_buffer_size ); command_list->CopyBufferRegion( m_InstanceIndexMappingsBuffer, 0, m_InstanceIndexMappingsBufferUpload, 0, m_InstanceIndexMappingsBufferSize ); const D3D12_RESOURCE_BARRIER post_copy_barriers[] = { CD3DX12_RESOURCE_BARRIER::Transition( m_InstanceModelMappingsBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ), CD3DX12_RESOURCE_BARRIER::Transition( m_ModelInstanceOffsetBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ), CD3DX12_RESOURCE_BARRIER::Transition( m_InstanceIndexMappingsBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ), }; command_list->ResourceBarrier( _countof( post_copy_barriers ), post_copy_barriers ); m_InstanceModelMappingsBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); m_ModelInstanceOffsetBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); m_ModelInstanceCountBufferUav = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); m_InstanceIndexMappingsBufferUav = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); m_ModelInstanceCountBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); m_InstanceIndexMappingsBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc; D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc; ZeroMemory( &srv_desc, sizeof( srv_desc ) ); srv_desc.Format = DXGI_FORMAT_UNKNOWN; srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srv_desc.Buffer.NumElements = m_InstanceCount; srv_desc.Buffer.StructureByteStride = sizeof( UINT ); srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; device->CreateShaderResourceView( m_InstanceModelMappingsBuffer, &srv_desc, m_InstanceModelMappingsBufferSrv.m_Cpu ); ZeroMemory( &srv_desc, sizeof( srv_desc ) ); srv_desc.Format = DXGI_FORMAT_UNKNOWN; srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srv_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() ); srv_desc.Buffer.StructureByteStride = sizeof( UINT ); srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; device->CreateShaderResourceView( m_ModelInstanceOffsetBuffer, &srv_desc, m_ModelInstanceOffsetBufferSrv.m_Cpu ); ZeroMemory( &uav_desc, sizeof( uav_desc ) ); uav_desc.Format = DXGI_FORMAT_UNKNOWN; uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uav_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() ); uav_desc.Buffer.StructureByteStride = sizeof( UINT ); uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; device->CreateUnorderedAccessView( m_ModelInstanceCountBuffer, nullptr, &uav_desc, m_ModelInstanceCountBufferUav.m_Cpu ); ZeroMemory( &uav_desc, sizeof( uav_desc ) ); uav_desc.Format = DXGI_FORMAT_UNKNOWN; uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uav_desc.Buffer.NumElements = m_InstanceCount; uav_desc.Buffer.StructureByteStride = sizeof( UINT ); uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; device->CreateUnorderedAccessView( m_InstanceIndexMappingsBuffer, nullptr, &uav_desc, m_InstanceIndexMappingsBufferUav.m_Cpu ); ZeroMemory( &srv_desc, sizeof( srv_desc ) ); srv_desc.Format = DXGI_FORMAT_UNKNOWN; srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srv_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() ); srv_desc.Buffer.StructureByteStride = sizeof( UINT ); srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; device->CreateShaderResourceView( m_ModelInstanceCountBuffer, &srv_desc, m_ModelInstanceCountBufferSrv.m_Cpu ); ZeroMemory( &srv_desc, sizeof( srv_desc ) ); srv_desc.Format = DXGI_FORMAT_UNKNOWN; srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srv_desc.Buffer.NumElements = m_InstanceCount; srv_desc.Buffer.StructureByteStride = sizeof( UINT ); srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; device->CreateShaderResourceView( m_InstanceIndexMappingsBuffer, &srv_desc, m_InstanceIndexMappingsBufferSrv.m_Cpu ); } void CModelSet::CreateCommandBuffers( ID3D12Device* device, ID3D12GraphicsCommandList* command_list, NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] ) { UINT input_command_buffer_size = static_cast< UINT >( sizeof( SIndirectCommand ) * m_Models.size() ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( input_command_buffer_size ), D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS( &m_InputCommandBuffer ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( input_command_buffer_size ), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &m_InputCommandBufferUpload ) ) ); UINT output_command_buffer_misalignment = input_command_buffer_size % D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT; m_OutputCommandBufferCounterOffset = input_command_buffer_size + ( output_command_buffer_misalignment > 0 ? D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT - output_command_buffer_misalignment : 0 ); UINT output_command_buffer_size = m_OutputCommandBufferCounterOffset + sizeof( UINT ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( output_command_buffer_size, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, nullptr, IID_PPV_ARGS( &m_OutputCommandBuffer ) ) ); HR( device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer( sizeof( UINT ) ), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &m_OutputCommandBufferCounterReset ) ) ); SIndirectCommand* mapped_input_command_buffer_upload = nullptr; UINT* mapped_output_command_buffer_counter_reset = nullptr; HR( m_InputCommandBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_input_command_buffer_upload ) ) ); HR( m_OutputCommandBufferCounterReset->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_output_command_buffer_counter_reset ) ) ); UINT instance_offset = 0; for ( size_t i = 0; i < m_Models.size(); ++i ) { mapped_input_command_buffer_upload[ i ].m_InstanceOffset = instance_offset; mapped_input_command_buffer_upload[ i ].m_MaterialIndex = m_Models[ i ]->m_MaterialIndex; mapped_input_command_buffer_upload[ i ].m_VertexBufferView = m_Models[ i ]->m_Mesh.GetVertexBufferView(); mapped_input_command_buffer_upload[ i ].m_IndexBufferView = m_Models[ i ]->m_Mesh.GetIndexBufferView(); mapped_input_command_buffer_upload[ i ].m_DrawArguments.IndexCountPerInstance = static_cast< UINT >( m_Models[ i ]->m_Indices.size() ); mapped_input_command_buffer_upload[ i ].m_DrawArguments.InstanceCount = static_cast< UINT >( m_Models[ i ]->m_Instances.size() ); mapped_input_command_buffer_upload[ i ].m_DrawArguments.StartIndexLocation = 0; mapped_input_command_buffer_upload[ i ].m_DrawArguments.BaseVertexLocation = 0; mapped_input_command_buffer_upload[ i ].m_DrawArguments.StartInstanceLocation = 0; instance_offset += static_cast< UINT >( m_Models[ i ]->m_Instances.size() ); } *mapped_output_command_buffer_counter_reset = 0; m_InputCommandBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) ); m_OutputCommandBufferCounterReset->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) ); command_list->CopyBufferRegion( m_InputCommandBuffer, 0, m_InputCommandBufferUpload, 0, input_command_buffer_size ); command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition( m_InputCommandBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ) ); m_InputCommandBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); m_OutputCommandBufferUav = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle(); D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc; D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc; ZeroMemory( &srv_desc, sizeof( srv_desc ) ); srv_desc.Format = DXGI_FORMAT_UNKNOWN; srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srv_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() ); srv_desc.Buffer.StructureByteStride = sizeof( SIndirectCommand ); srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; device->CreateShaderResourceView( m_InputCommandBuffer, &srv_desc, m_InputCommandBufferSrv.m_Cpu ); ZeroMemory( &uav_desc, sizeof( uav_desc ) ); uav_desc.Format = DXGI_FORMAT_UNKNOWN; uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uav_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() ); uav_desc.Buffer.StructureByteStride = sizeof( SIndirectCommand ); uav_desc.Buffer.CounterOffsetInBytes = m_OutputCommandBufferCounterOffset; uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; device->CreateUnorderedAccessView( m_OutputCommandBuffer, m_OutputCommandBuffer, &uav_desc, m_OutputCommandBufferUav.m_Cpu ); }
45.85744
193
0.700992
marcussvensson92
ae0fc2433cb8618561f8767d7d610762b4fcf790
2,675
cc
C++
legacy/src/game/event.cc
hengruo/RuneSim
f975374c7ce52baf8f226e8485e2e6e155d52cb2
[ "Apache-2.0" ]
9
2020-04-28T13:47:07.000Z
2020-10-03T16:05:53.000Z
legacy/src/game/event.cc
hengruo/RuneSim
f975374c7ce52baf8f226e8485e2e6e155d52cb2
[ "Apache-2.0" ]
null
null
null
legacy/src/game/event.cc
hengruo/RuneSim
f975374c7ce52baf8f226e8485e2e6e155d52cb2
[ "Apache-2.0" ]
4
2020-04-27T08:13:09.000Z
2020-06-02T02:48:07.000Z
#include "event.h" CastEvent::CastEvent(RSID PlayerId, RSID SpellId) : playerId(PlayerId), spellId(SpellId) {} DeclAttackEvent::DeclAttackEvent(RSID PlayerId, RSID AttackerId, i8 Position) : playerId(PlayerId), attackerId(AttackerId), position(Position) {} DeclBlockEvent::DeclBlockEvent(RSID PlayerId, RSID AttackerId, i8 Position) : playerId(PlayerId), attackerId(AttackerId), position(Position) {} DieEvent::DieEvent(RSID PlayerId, RSID DeadId) : playerId(PlayerId), deadId(DeadId) {} DrawCardEvent::DrawCardEvent(RSID PlayerId, RSID IndeckCardId) : playerId(PlayerId), indeckCardId(IndeckCardId) {} GetCardEvent::GetCardEvent(RSID PlayerId, RSID CardEntityId) : playerId(PlayerId), cardEntityId(CardEntityId) {} LevelUpEvent::LevelUpEvent(RSID PlayerId, RSID ChampionId) : playerId(PlayerId), championId(ChampionId) {} NexusStrikeEvent::NexusStrikeEvent(RSID AttackingPlayerId, RSID AttackedNexusId, i64 Damage) : attackingPlayerId( AttackingPlayerId), attackedNexusId(AttackedNexusId), damage(Damage) {} PlayEvent::PlayEvent(RSID PlayerId, RSID InhandCardId) : playerId(PlayerId), inhandCardId(InhandCardId) {} PutSpell::PutSpell(RSID PlayerId, RSID SpellId) : playerId(PlayerId), spellId(SpellId) {} StartRoundEvent::StartRoundEvent(i32 Round) : round(Round) {} StrikeEvent::StrikeEvent(RSID PlayerId, RSID StrikerId) : playerId(PlayerId), strikerId(StrikerId) {} SummonEvent::SummonEvent(RSID PlayerId, RSID SummoneeId) : playerId(PlayerId), summoneeId(SummoneeId) {} TargetEvent::TargetEvent(RSID PlayerId, RSID TargetedId) : playerId(PlayerId), targetedId(TargetedId) {} Event::Event(const LevelUpEvent &LevelUp) : levelUp(LevelUp) {} Event::Event(const AnyEvent &Any) : any(Any) {} Event::Event(const CastEvent &Cast) : cast(Cast) {} Event::Event(const DeclAttackEvent &DeclAttack) : declAttack(DeclAttack) {} Event::Event(const DeclBlockEvent &DeclBlock) : declBlock(DeclBlock) {} Event::Event(const DieEvent &Die) : die(Die) {} Event::Event(const DrawCardEvent &DrawCard) : drawCard(DrawCard) {} Event::Event(const EndRoundEvent &EndRound) : endRound(EndRound) {} Event::Event(const EnlightenEvent &Enlighten) : enlighten(Enlighten) {} Event::Event(const GetCardEvent &GetCard) : getCard(GetCard) {} Event::Event(const NexusStrikeEvent &NexusStrike) : nexusStrike(NexusStrike) {} Event::Event(const PlayEvent &Play) : play(Play) {} Event::Event(const PutSpell &PutSpell) : putSpell(PutSpell) {} Event::Event(const StartRoundEvent &StartRound) : startRound(StartRound) {} Event::Event(const StrikeEvent &Strike) : strike(Strike) {} Event::Event(const SummonEvent &Summon) : summon(Summon) {} Event::Event(const TargetEvent &Target) : target(Target) {}
74.305556
114
0.776075
hengruo
ae11b66c536b7876bda8e855c60424e8136d3641
10,081
cpp
C++
test/type/logic/And.main.cpp
AnantaYudica/basic
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
[ "MIT" ]
null
null
null
test/type/logic/And.main.cpp
AnantaYudica/basic
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
[ "MIT" ]
178
2018-08-08T04:04:27.000Z
2019-12-15T01:47:58.000Z
test/type/logic/And.main.cpp
AnantaYudica/basic
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
[ "MIT" ]
null
null
null
#include "type/logic/And.h" #define USING_BASIC_TEST_MEMORY #include "Test.h" BASIC_TEST_CONSTRUCT; #include "test/Base.h" #include "test/Case.h" #include "test/Message.h" #include "test/Variable.h" #include "test/var/At.h" #include <typeinfo> #include <type_traits> struct CaseVTa {}; // case value and target struct CaseV {}; // case value template<typename TAnd, bool TValue> using VariableTestAnd = basic::test::Variable< TAnd, basic::test::type::Value<bool, TValue>, basic::test::val::Function<const char*(bool&&)>>; constexpr std::size_t IAnd = 0; constexpr std::size_t ITypeValValue = 1; constexpr std::size_t IValFuncBoolToCString = 2; template<std::size_t I> using ArgTypeName = basic::test::msg::arg::type::Name<I>; template<std::size_t I> using ArgTypeValue = basic::test::msg::arg::type::Value<I>; template<std::size_t I> using ArgTypeParamName = basic::test::msg::arg::type::param::Name<I>; template<std::size_t I, typename... TArgArgs> using ArgValFunction = basic::test::msg::arg::val::Function<I, TArgArgs...>; typedef basic::test::msg::Argument<CaseVTa, ArgTypeName<IAnd>, ArgValFunction<IValFuncBoolToCString, ArgTypeValue<ITypeValValue>>> ArgCaseVTa; typedef basic::test::msg::Base<CaseVTa, char, ArgCaseVTa, ArgCaseVTa, ArgCaseVTa> MsgBaseCaseVTa; typedef basic::test::msg::Argument<CaseV, ArgTypeName<IAnd>, ArgTypeName<IAnd>> ArgCaseV; typedef basic::test::msg::Base<CaseV, char, ArgCaseV, ArgCaseV, ArgCaseV> MsgBaseCaseV; template<typename TCases, typename... TVars> class TestAnd : public MsgBaseCaseVTa, public MsgBaseCaseV, public basic::test::Message<BASIC_TEST, TestAnd<TCases, TVars...>>, public basic::test::Case<TestAnd<TCases, TVars...>, TCases>, public basic::test::Base<TestAnd<TCases, TVars...>, TVars...> { public: typedef basic::test::Base<TestAnd<TCases, TVars...>, TVars...> BaseType; typedef basic::test::Message<BASIC_TEST, TestAnd<TCases, TVars...>> BaseMessageType; typedef basic::test::Case<TestAnd<TCases, TVars...>, TCases> BaseCaseType; protected: using MsgBaseCaseVTa::SetFormat; using MsgBaseCaseV::SetFormat; public: using MsgBaseCaseVTa::Format; using MsgBaseCaseV::Format; using MsgBaseCaseVTa::Argument; using MsgBaseCaseV::Argument; public: using BaseType::Run; using BaseCaseType::Run; public: TestAnd(TVars&... vars) : BaseType(*this, vars...), BaseMessageType(*this), BaseCaseType(*this) { basic::test::msg::base::Info info; basic::test::msg::base::Debug debug; basic::test::msg::base::Error err; CaseVTa case_value_and_target; SetFormat(info, case_value_and_target, "test compare between %s::value and %s\n"); SetFormat(debug, case_value_and_target, "test compare between %s::value and %s\n"); SetFormat(err, case_value_and_target, "error %s::value is not same with %s\n"); CaseV case_value; SetFormat(info, case_value, "test compare between %s::value and %s::Value\n"); SetFormat(debug, case_value, "test compare between %s::value and %s::Value\n"); SetFormat(err, case_value, "error %s::value is not same with %s::Value\n"); } template<typename TAnd, bool TValue> bool Result(const CaseVTa&, VariableTestAnd<TAnd, TValue>& var) { return TAnd::value == TValue; } template<typename TAnd, bool TValue> bool Result(const CaseV&, VariableTestAnd<TAnd, TValue>& var) { return TAnd::value == TAnd::Value; } }; using Cases = basic::test::type::Parameter<CaseVTa, CaseV>; BASIC_TEST_TYPE_NAME("std::true_type", std::true_type); BASIC_TEST_TYPE_NAME("std::false_type", std::false_type); BASIC_TEST_TYPE_NAME("void", void); #ifdef _WIN32 template<typename TTrue, typename TArg, typename... TArgs> struct basic::test::type::Name<basic::type::logic::And<TTrue, TArg, TArgs...>> #else template<typename... TArgs> struct basic::test::type::Name<basic::type::logic::And<TArgs...>> #endif { static basic::test::CString<char> CStr() { static char _format_cstr[] = "basic::type::logic::And<%s>"; #ifdef _WIN32 const auto& param_cstr = basic::test::type::param::Name< basic::test::type::Parameter<TTrue, TArg, TArgs...>>::CStr(); #else const auto& param_cstr = basic::test::type::param::Name< basic::test::type::Parameter<TArgs...>>::CStr(); #endif return basic::test::cstr::Format(sizeof(_format_cstr) + param_cstr.Size(), _format_cstr, *param_cstr);\ } }; const char* true_cstr = "true"; const char* false_cstr = "false"; const char* BoolToString(bool&& b) { return b ? true_cstr : false_cstr; } using TDefaultAnd1_1 = basic::type::logic::And<std::true_type, std::false_type>; using TDefaultAnd1_2 = basic::type::logic::And<std::true_type, std::true_type>; typedef VariableTestAnd<TDefaultAnd1_1, false> T1Var1; typedef VariableTestAnd<TDefaultAnd1_2, true> T1Var2; T1Var1 t1_var1(&BoolToString); T1Var2 t1_var2(&BoolToString); REGISTER_TEST(t1, new TestAnd<Cases, T1Var1, T1Var2>(t1_var1, t1_var2)); using TDefaultAnd2_1 = basic::type::logic::And<std::true_type, std::false_type, std::false_type>; using TDefaultAnd2_2 = basic::type::logic::And<std::true_type, std::false_type, std::true_type>; using TDefaultAnd2_3 = basic::type::logic::And<std::true_type, std::true_type, std::false_type>; using TDefaultAnd2_4 = basic::type::logic::And<std::true_type, std::true_type, std::true_type>; typedef VariableTestAnd<TDefaultAnd2_1, false> T2Var1; typedef VariableTestAnd<TDefaultAnd2_2, false> T2Var2; typedef VariableTestAnd<TDefaultAnd2_3, false> T2Var3; typedef VariableTestAnd<TDefaultAnd2_4, true> T2Var4; T2Var1 t2_var1(&BoolToString); T2Var2 t2_var2(&BoolToString); T2Var3 t2_var3(&BoolToString); T2Var4 t2_var4(&BoolToString); REGISTER_TEST(t2, new TestAnd<Cases, T2Var1, T2Var2, T2Var3, T2Var4>(t2_var1, t2_var2, t2_var3, t2_var4)); using TDefaultAnd4_1 = basic::type::logic::And<std::true_type, std::false_type, std::false_type, std::false_type, std::false_type>; using TDefaultAnd4_2 = basic::type::logic::And<std::true_type, std::false_type, std::false_type, std::false_type, std::true_type>; using TDefaultAnd4_3 = basic::type::logic::And<std::true_type, std::false_type, std::false_type, std::true_type, std::false_type>; using TDefaultAnd4_4 = basic::type::logic::And<std::true_type, std::false_type, std::false_type, std::true_type, std::true_type>; using TDefaultAnd4_5 = basic::type::logic::And<std::true_type, std::false_type, std::true_type, std::false_type, std::false_type>; using TDefaultAnd4_6 = basic::type::logic::And<std::true_type, std::false_type, std::true_type, std::false_type, std::true_type>; using TDefaultAnd4_7 = basic::type::logic::And<std::true_type, std::false_type, std::true_type, std::true_type, std::false_type>; using TDefaultAnd4_8 = basic::type::logic::And<std::true_type, std::false_type, std::true_type, std::true_type, std::true_type>; using TDefaultAnd4_9 = basic::type::logic::And<std::true_type, std::true_type, std::false_type, std::false_type, std::false_type>; using TDefaultAnd4_10 = basic::type::logic::And<std::true_type, std::true_type, std::false_type, std::false_type, std::true_type>; using TDefaultAnd4_11 = basic::type::logic::And<std::true_type, std::true_type, std::false_type, std::true_type, std::false_type>; using TDefaultAnd4_12 = basic::type::logic::And<std::true_type, std::true_type, std::false_type, std::true_type, std::true_type>; using TDefaultAnd4_13 = basic::type::logic::And<std::true_type, std::true_type, std::true_type, std::false_type, std::false_type>; using TDefaultAnd4_14 = basic::type::logic::And<std::true_type, std::true_type, std::true_type, std::false_type, std::true_type>; using TDefaultAnd4_15 = basic::type::logic::And<std::true_type, std::true_type, std::true_type, std::true_type, std::false_type>; using TDefaultAnd4_16 = basic::type::logic::And<std::true_type, std::true_type, std::true_type, std::true_type, std::true_type>; typedef VariableTestAnd<TDefaultAnd4_1, false> T3Var1; typedef VariableTestAnd<TDefaultAnd4_2, false> T3Var2; typedef VariableTestAnd<TDefaultAnd4_3, false> T3Var3; typedef VariableTestAnd<TDefaultAnd4_4, false> T3Var4; typedef VariableTestAnd<TDefaultAnd4_5, false> T3Var5; typedef VariableTestAnd<TDefaultAnd4_6, false> T3Var6; typedef VariableTestAnd<TDefaultAnd4_7, false> T3Var7; typedef VariableTestAnd<TDefaultAnd4_8, false> T3Var8; typedef VariableTestAnd<TDefaultAnd4_9, false> T3Var9; typedef VariableTestAnd<TDefaultAnd4_10, false> T3Var10; typedef VariableTestAnd<TDefaultAnd4_11, false> T3Var11; typedef VariableTestAnd<TDefaultAnd4_12, false> T3Var12; typedef VariableTestAnd<TDefaultAnd4_13, false> T3Var13; typedef VariableTestAnd<TDefaultAnd4_14, false> T3Var14; typedef VariableTestAnd<TDefaultAnd4_15, false> T3Var15; typedef VariableTestAnd<TDefaultAnd4_16, true> T3Var16; T3Var1 t3_var1(&BoolToString); T3Var2 t3_var2(&BoolToString); T3Var3 t3_var3(&BoolToString); T3Var4 t3_var4(&BoolToString); T3Var5 t3_var5(&BoolToString); T3Var6 t3_var6(&BoolToString); T3Var7 t3_var7(&BoolToString); T3Var8 t3_var8(&BoolToString); T3Var9 t3_var9(&BoolToString); T3Var10 t3_var10(&BoolToString); T3Var11 t3_var11(&BoolToString); T3Var12 t3_var12(&BoolToString); T3Var13 t3_var13(&BoolToString); T3Var14 t3_var14(&BoolToString); T3Var15 t3_var15(&BoolToString); T3Var16 t3_var16(&BoolToString); REGISTER_TEST(t3, new TestAnd<Cases, T3Var1, T3Var2, T3Var3, T3Var4, T3Var5, T3Var6, T3Var7, T3Var8, T3Var9, T3Var10, T3Var11, T3Var12, T3Var13, T3Var14, T3Var15, T3Var16>(t3_var1, t3_var2, t3_var3, t3_var4, t3_var5, t3_var6, t3_var7, t3_var8, t3_var9, t3_var10, t3_var11, t3_var12, t3_var13, t3_var14, t3_var15, t3_var16)); int main() { return RUN_TEST(); }
37.337037
80
0.716397
AnantaYudica
ae13b2316bf455bd9154221d528693bb9c139d71
778
cpp
C++
solved/10338 Mischievous Children.cpp
goutomroy/uva.onlinejudge
5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2
[ "MIT" ]
null
null
null
solved/10338 Mischievous Children.cpp
goutomroy/uva.onlinejudge
5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2
[ "MIT" ]
null
null
null
solved/10338 Mischievous Children.cpp
goutomroy/uva.onlinejudge
5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2
[ "MIT" ]
null
null
null
// WRONG ANSWERE #include<stdio.h> #include<string.h> char word[22],nline; int time[22],len; void main() { int tcase,i,j, k; double N, fact; scanf("%d%c",&tcase,&nline); for(i=0;i<tcase;i++) { scanf("%s",word); scanf("%c",&nline); len = strlen(word); if(len==1) { printf("Data set %d: 1\n",i+1); continue; } for(j=0;j<20;j++) time[j] = 1; for(j=0;j<len;j++) { for( k=j+1; k<len; k++ ) { if( word[j]==NULL) break; else if( word[j] == word[k] ) { time[j]++; word[k] = NULL; } } } N=1; for(k=len;k>1;k--) N = N*k; for(j=0;j<len;j++) { for(fact = 1;time[j]>1;time[j]--) fact = fact*time[j]; N = N/fact; } printf("Data set %d: %.0lf\n",i+1,N); } }
11.61194
39
0.458869
goutomroy
ae161ce585be03f44f9691664d2e5dfe6507241a
6,759
cpp
C++
examples/main.cpp
DarkCaster/Micro-AES-Arduino
ebb1cbf89c2c8d971e9ea111eef2299789c56762
[ "MIT" ]
null
null
null
examples/main.cpp
DarkCaster/Micro-AES-Arduino
ebb1cbf89c2c8d971e9ea111eef2299789c56762
[ "MIT" ]
null
null
null
examples/main.cpp
DarkCaster/Micro-AES-Arduino
ebb1cbf89c2c8d971e9ea111eef2299789c56762
[ "MIT" ]
null
null
null
#include <Arduino.h> //dummy arduino.h for compiling arduino code on desktop systems #include <aes.h> #include <cstdio> #define BLKSZ 16 void verify(const uint8_t * const input, const uint8_t * const output, const uint8_t * const test) { //verify bool verifyOk=true; for(int i=0;i<BLKSZ;++i) if(*(test+i)!=*(output+i)) { verifyOk=false; break; } printf("Input data : "); for(int i=0;i<BLKSZ;++i) printf("0x%02x ",*(input+i)); printf("<<END\n"); printf("Output data: "); for(int i=0;i<BLKSZ;++i) printf("0x%02x ",*(output+i)); printf("<<END\n"); printf("Test data : "); for(int i=0;i<BLKSZ;++i) printf("0x%02x ",*(test+i)); printf("<<END\n"); printf(verifyOk?"Verify OK.\n\n":"Verify failed!\n\n"); } void encrypt128(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output) { //copy input block uint8_t test[BLKSZ]; for(int i=0;i<BLKSZ;++i) *(test+i)=*(input+i); //encrypt aes_128_context_t context; aes_128_init(&context, key); aes_128_encrypt(&context, test); printf("Encrypt AES128 test\n"); verify(input,output,test); } void decrypt128(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output) { //copy input block uint8_t test[BLKSZ]; for(int i=0;i<BLKSZ;++i) *(test+i)=*(input+i); //encrypt aes_128_context_t context; aes_128_init(&context, key); aes_128_decrypt(&context, test); printf("Decrypt AES128 test\n"); verify(input,output,test); } void encrypt192(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output) { //copy input block uint8_t test[BLKSZ]; for(int i=0;i<BLKSZ;++i) *(test+i)=*(input+i); //encrypt aes_192_context_t context; aes_192_init(&context, key); aes_192_encrypt(&context, test); printf("Encrypt AES192 test\n"); verify(input,output,test); } void decrypt192(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output) { //copy input block uint8_t test[BLKSZ]; for(int i=0;i<BLKSZ;++i) *(test+i)=*(input+i); //encrypt aes_192_context_t context; aes_192_init(&context, key); aes_192_decrypt(&context, test); printf("Decrypt AES192 test\n"); verify(input,output,test); } void encrypt256(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output) { //copy input block uint8_t test[BLKSZ]; for(int i=0;i<BLKSZ;++i) *(test+i)=*(input+i); //encrypt aes_256_context_t context; aes_256_init(&context, key); aes_256_encrypt(&context, test); printf("Encrypt AES256 test\n"); verify(input,output,test); } void decrypt256(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output) { //copy input block uint8_t test[BLKSZ]; for(int i=0;i<BLKSZ;++i) *(test+i)=*(input+i); //encrypt aes_256_context_t context; aes_256_init(&context, key); aes_256_decrypt(&context, test); printf("Decrypt AES256 test\n"); verify(input,output,test); } int main() { // using test vectors from this document: http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf //F.1.1 //ECB-AES128.Encrypt const uint8_t key_128[]={0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c}; const uint8_t plaintext1[]={0x6b,0xc1,0xbe,0xe2,0x2e,0x40,0x9f,0x96,0xe9,0x3d,0x7e,0x11,0x73,0x93,0x17,0x2a}; const uint8_t plaintext2[]={0xae,0x2d,0x8a,0x57,0x1e,0x03,0xac,0x9c,0x9e,0xb7,0x6f,0xac,0x45,0xaf,0x8e,0x51}; const uint8_t plaintext3[]={0x30,0xc8,0x1c,0x46,0xa3,0x5c,0xe4,0x11,0xe5,0xfb,0xc1,0x19,0x1a,0x0a,0x52,0xef}; const uint8_t plaintext4[]={0xf6,0x9f,0x24,0x45,0xdf,0x4f,0x9b,0x17,0xad,0x2b,0x41,0x7b,0xe6,0x6c,0x37,0x10}; const uint8_t ciphertext1_128[]={0x3a,0xd7,0x7b,0xb4,0x0d,0x7a,0x36,0x60,0xa8,0x9e,0xca,0xf3,0x24,0x66,0xef,0x97}; const uint8_t ciphertext2_128[]={0xf5,0xd3,0xd5,0x85,0x03,0xb9,0x69,0x9d,0xe7,0x85,0x89,0x5a,0x96,0xfd,0xba,0xaf}; const uint8_t ciphertext3_128[]={0x43,0xb1,0xcd,0x7f,0x59,0x8e,0xce,0x23,0x88,0x1b,0x00,0xe3,0xed,0x03,0x06,0x88}; const uint8_t ciphertext4_128[]={0x7b,0x0c,0x78,0x5e,0x27,0xe8,0xad,0x3f,0x82,0x23,0x20,0x71,0x04,0x72,0x5d,0xd4}; encrypt128(key_128,plaintext1,ciphertext1_128); encrypt128(key_128,plaintext2,ciphertext2_128); encrypt128(key_128,plaintext3,ciphertext3_128); encrypt128(key_128,plaintext4,ciphertext4_128); decrypt128(key_128,ciphertext1_128,plaintext1); decrypt128(key_128,ciphertext2_128,plaintext2); decrypt128(key_128,ciphertext3_128,plaintext3); decrypt128(key_128,ciphertext4_128,plaintext4); //F.1.3 //ECB-AES192.Encrypt const uint8_t key_192[]={0x8e,0x73,0xb0,0xf7,0xda,0x0e,0x64,0x52,0xc8,0x10,0xf3,0x2b,0x80,0x90,0x79,0xe5,0x62,0xf8,0xea,0xd2,0x52,0x2c,0x6b,0x7b}; const uint8_t ciphertext1_192[]={0xbd,0x33,0x4f,0x1d,0x6e,0x45,0xf2,0x5f,0xf7,0x12,0xa2,0x14,0x57,0x1f,0xa5,0xcc}; const uint8_t ciphertext2_192[]={0x97,0x41,0x04,0x84,0x6d,0x0a,0xd3,0xad,0x77,0x34,0xec,0xb3,0xec,0xee,0x4e,0xef}; const uint8_t ciphertext3_192[]={0xef,0x7a,0xfd,0x22,0x70,0xe2,0xe6,0x0a,0xdc,0xe0,0xba,0x2f,0xac,0xe6,0x44,0x4e}; const uint8_t ciphertext4_192[]={0x9a,0x4b,0x41,0xba,0x73,0x8d,0x6c,0x72,0xfb,0x16,0x69,0x16,0x03,0xc1,0x8e,0x0e}; encrypt192(key_192,plaintext1,ciphertext1_192); encrypt192(key_192,plaintext2,ciphertext2_192); encrypt192(key_192,plaintext3,ciphertext3_192); encrypt192(key_192,plaintext4,ciphertext4_192); decrypt192(key_192,ciphertext1_192,plaintext1); decrypt192(key_192,ciphertext2_192,plaintext2); decrypt192(key_192,ciphertext3_192,plaintext3); decrypt192(key_192,ciphertext4_192,plaintext4); //F.1.5 //ECB-AES256.Encrypt const uint8_t key_256[]={0x60,0x3d,0xeb,0x10,0x15,0xca,0x71,0xbe,0x2b,0x73,0xae,0xf0,0x85,0x7d,0x77,0x81,0x1f,0x35,0x2c,0x07,0x3b,0x61,0x08,0xd7,0x2d,0x98,0x10,0xa3,0x09,0x14,0xdf,0xf4}; const uint8_t ciphertext1_256[]={0xf3,0xee,0xd1,0xbd,0xb5,0xd2,0xa0,0x3c,0x06,0x4b,0x5a,0x7e,0x3d,0xb1,0x81,0xf8}; const uint8_t ciphertext2_256[]={0x59,0x1c,0xcb,0x10,0xd4,0x10,0xed,0x26,0xdc,0x5b,0xa7,0x4a,0x31,0x36,0x28,0x70}; const uint8_t ciphertext3_256[]={0xb6,0xed,0x21,0xb9,0x9c,0xa6,0xf4,0xf9,0xf1,0x53,0xe7,0xb1,0xbe,0xaf,0xed,0x1d}; const uint8_t ciphertext4_256[]={0x23,0x30,0x4b,0x7a,0x39,0xf9,0xf3,0xff,0x06,0x7d,0x8d,0x8f,0x9e,0x24,0xec,0xc7}; encrypt256(key_256,plaintext1,ciphertext1_256); encrypt256(key_256,plaintext2,ciphertext2_256); encrypt256(key_256,plaintext3,ciphertext3_256); encrypt256(key_256,plaintext4,ciphertext4_256); decrypt256(key_256,ciphertext1_256,plaintext1); decrypt256(key_256,ciphertext2_256,plaintext2); decrypt256(key_256,ciphertext3_256,plaintext3); decrypt256(key_256,ciphertext4_256,plaintext4); return 0; }
37.759777
188
0.733245
DarkCaster
ae16385cc7eca56e94f53701d593e2310f2f8d21
970
cpp
C++
graph-source-code/230-E/4442480.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/230-E/4442480.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/230-E/4442480.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <iostream> #include <fstream> #include <sstream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cctype> #include <cmath> #include <ctime> #include <algorithm> #include <vector> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include <complex> #include <bitset> #include <iomanip> #include <utility> #define xx first #define yy second #define ll long long #define ull unsigned long long #define pb push_back #define pp pop_back #define pii pair<int ,int> #define vi vector<int> using namespace std; const int maxn=1000000+10; int deg[maxn]; ll n,m; ll ans; int main() { ios::sync_with_stdio(false); cin>>n>>m; for(int i=1;i<=m;i++){ int u,v; cin>>u>>v; deg[u]++;deg[v]++; } ans=n*(n-1)*(n-2)/6; ans-=m*(n-2); for(int i=1;i<=n;i++)ans+=deg[i]*(deg[i]-1)/2; cout<<ans; //cin>>n; }
18.653846
51
0.598969
AmrARaouf
ae194a06ae06c7f94a886e778f5295ea8d9b2247
24,020
hpp
C++
engine/generic_list.hpp
iyupeng/kvdk
35e882bf6adc5e931d57fb07c648d0478b9ea146
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
engine/generic_list.hpp
iyupeng/kvdk
35e882bf6adc5e931d57fb07c648d0478b9ea146
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
engine/generic_list.hpp
iyupeng/kvdk
35e882bf6adc5e931d57fb07c648d0478b9ea146
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2021 Intel Corporation */ #pragma once #include <immintrin.h> #include <libpmem.h> #include <x86intrin.h> #include <array> #include <atomic> #include <deque> #include <iomanip> #include <iostream> #include <libpmemobj++/string_view.hpp> #include <mutex> #include <random> #include <stdexcept> #include <unordered_map> #include "alias.hpp" #include "collection.hpp" #include "data_record.hpp" #include "macros.hpp" #include "pmem_allocator/pmem_allocator.hpp" #include "utils/utils.hpp" namespace KVDK_NAMESPACE { constexpr PMemOffsetType NullPMemOffset = kNullPMemOffset; template <RecordType ListType, RecordType DataType> class GenericList final : public Collection { private: // For offset-address translation PMEMAllocator* alloc{nullptr}; // Persisted ListType on PMem, contains List name(key) and id(value). DLRecord* list_record{nullptr}; // First Element in List, nullptr indicates empty List DLRecord* first{nullptr}; // Last Element in List, nullptr indicates empty List DLRecord* last{nullptr}; // Size of list size_t sz{0U}; // Recursive mutex to lock the List using LockType = std::recursive_mutex; LockType mu; public: class Iterator { private: // owner must be initialized with a List GenericList const* owner; // curr == nullptr indicates Head() and Tail() DLRecord* curr{nullptr}; public: // Always start at Head()/Tail() // Head() and Tail() is the same state, // just for convention this state has two names // Tail() for iterating forward // Head() for iterating backward explicit Iterator(GenericList const* o) : owner{o} { kvdk_assert(owner != nullptr, "Invalid iterator!"); } Iterator() = delete; Iterator(Iterator const&) = default; Iterator(Iterator&&) = default; Iterator& operator=(Iterator const&) = default; Iterator& operator=(Iterator&&) = default; ~Iterator() = default; /// Increment and Decrement operators Iterator& operator++() { if (curr == nullptr) { // Head(), goto Front() // Front() == Tail() if List is empty. curr = owner->first; } else if (curr->next != NullPMemOffset) { // Not Back(), goto next curr = owner->addressOf(curr->next); } else { // Back(), goto Tail() curr = nullptr; } return *this; } Iterator const operator++(int) { Iterator old{*this}; this->operator++(); return old; } Iterator& operator--() { if (curr == nullptr) { // Tail(), goto Back() // Back() == Head() if List is empty. curr = owner->last; } else if (curr->prev != NullPMemOffset) { // Not Front(), goto prev curr = owner->addressOf(curr->prev); } else { // Front(), goto Head() curr = nullptr; } return *this; } Iterator const operator--(int) { Iterator old{*this}; this->operator--(); return old; } DLRecord& operator*() { return *curr; } DLRecord* operator->() { return curr; } PMemOffsetType Offset() const { return owner->offsetOf(Address()); } DLRecord* Address() const { kvdk_assert(curr != nullptr, "Trying to address dummy Iterator Head()!"); return curr; } private: friend bool operator==(Iterator const& lhs, Iterator const& rhs) { return (lhs.owner == rhs.owner) && (lhs.curr == rhs.curr); } friend bool operator!=(Iterator const& lhs, Iterator const& rhs) { return !(lhs == rhs); } }; public: // Default to an empty list with no name and 0 as id // Must Init() or Restore() before further use. GenericList() : Collection{"", CollectionIDType{}} {} GenericList(GenericList const&) = delete; GenericList(GenericList&&) = delete; GenericList& operator=(GenericList const&) = delete; GenericList& operator=(GenericList&&) = delete; ~GenericList() = default; // Initialize a List with pmem base address p_base, pre-space space, // Creation time, List name and id. void Init(PMEMAllocator* a, SpaceEntry space, TimeStampType timestamp, StringView const key, CollectionIDType id) { collection_name_.assign(key.data(), key.size()); collection_id_ = id; alloc = a; list_record = DLRecord::PersistDLRecord( addressOf(space.offset), space.size, timestamp, RecordType::ListRecord, NullPMemOffset, NullPMemOffset, NullPMemOffset, key, ID2String(id)); } template <typename ListDeleter> void Destroy(ListDeleter list_deleter) { kvdk_assert(sz == 0 && list_record != nullptr && first == nullptr && last == nullptr, "Only initialized empty List can be destroyed!"); list_deleter(list_record); list_record = nullptr; alloc = nullptr; } bool Valid() const { return (list_record != nullptr); } // Restore a List with its ListRecord, first and last element and size // This function is used by GenericListBuilder to restore the List void Restore(PMEMAllocator* a, DLRecord* list_rec, DLRecord* fi, DLRecord* la, size_t n) { auto key = list_rec->Key(); collection_name_.assign(key.data(), key.size()); kvdk_assert(list_rec->Value().size() == sizeof(CollectionIDType), ""); collection_id_ = ExtractID(list_rec->Value()); alloc = a; list_record = list_rec; first = fi; last = la; sz = n; } LockType* Mutex() { return &mu; } std::unique_lock<LockType> AcquireLock() { return std::unique_lock<LockType>(mu); } ExpiredTimeType GetExpireTime() const final { return list_record->GetExpireTime(); } bool HasExpired() const final { return TimeUtils::CheckIsExpired(GetExpireTime()); } Status SetExpireTime(ExpiredTimeType time) final { list_record->PersistExpireTimeNT(time); return Status::Ok; } size_t Size() const { return sz; } Iterator Front() { return ++Head(); } Iterator Back() { return --Tail(); } Iterator Head() const { return Iterator{this}; } Iterator Tail() const { return Iterator{this}; } Iterator Seek(std::int64_t index) { if (index >= 0) { auto iter = Front(); while (index != 0 && iter != Tail()) { ++iter; --index; } return iter; } else { auto iter = Back(); while (index != -1 && iter != Head()) { --iter; ++index; } return iter; } } template <typename ElemDeleter> Iterator Erase(Iterator pos, ElemDeleter elem_deleter) { kvdk_assert(pos != Head(), "Cannot erase Head()"); kvdk_assert(sz >= 1, "Cannot erase from empty List!"); kvdk_assert(ExtractID(pos->Key()) == ID(), "Erase from wrong List!"); Iterator prev{pos}; --prev; Iterator next{pos}; ++next; if (sz == 1) { kvdk_assert(prev == Head() && next == Tail(), "Impossible!"); first = nullptr; last = nullptr; } else if (prev == Head()) { // Erase Front() kvdk_assert(next != Tail(), ""); first = next.Address(); next->PersistPrevNT(NullPMemOffset); } else if (next == Tail()) { // Erase Back() kvdk_assert(prev != Head(), ""); last = prev.Address(); prev->PersistNextNT(NullPMemOffset); } else { kvdk_assert(prev != Head() && next != Tail(), ""); // Reverse procedure of emplace_between() between two elements next->PersistPrevNT(prev.Offset()); prev->PersistNextNT(next.Offset()); } elem_deleter(pos.Address()); --sz; return next; } template <typename ElemDeleter> void PopFront(ElemDeleter elem_deleter) { Erase(Front(), elem_deleter); } template <typename ElemDeleter> void PopBack(ElemDeleter elem_deleter) { Erase(Back(), elem_deleter); } void EmplaceBefore(SpaceEntry space, Iterator pos, TimeStampType timestamp, StringView const key, StringView const value) { Iterator prev{pos}; --prev; Iterator next{pos}; emplace_between(space, prev, next, timestamp, key, value); ++sz; } void EmplaceAfter(SpaceEntry space, Iterator pos, TimeStampType timestamp, StringView const key, StringView const value) { Iterator prev{pos}; Iterator next{pos}; ++next; emplace_between(space, prev, next, timestamp, key, value); ++sz; } void PushFront(SpaceEntry space, TimeStampType timestamp, StringView const key, StringView const value) { emplace_between(space, Head(), Front(), timestamp, key, value); ++sz; } void PushBack(SpaceEntry space, TimeStampType timestamp, StringView const key, StringView const value) { emplace_between(space, Back(), Tail(), timestamp, key, value); ++sz; } template <typename ElemDeleter> void Replace(SpaceEntry space, Iterator pos, TimeStampType timestamp, StringView const key, StringView const value, ElemDeleter elem_deleter) { kvdk_assert(ExtractID(pos->Key()) == ID(), "Wrong List!"); Iterator prev{pos}; --prev; Iterator next{pos}; ++next; emplace_between(space, prev, next, timestamp, key, value); elem_deleter(pos.Address()); } private: inline DLRecord* addressOf(PMemOffsetType offset) const { return static_cast<DLRecord*>(alloc->offset2addr_checked(offset)); } inline PMemOffsetType offsetOf(DLRecord* rec) const { return alloc->addr2offset_checked(rec); } Iterator emplace_between(SpaceEntry space, Iterator prev, Iterator next, TimeStampType timestamp, StringView const key, StringView const value) { kvdk_assert(++Iterator{prev} == next || ++++Iterator{prev} == next, "Should only insert or replace"); PMemOffsetType prev_off = (prev == Head()) ? NullPMemOffset : prev.Offset(); PMemOffsetType next_off = (next == Tail()) ? NullPMemOffset : next.Offset(); DLRecord* record = DLRecord::PersistDLRecord( addressOf(space.offset), space.size, timestamp, DataType, NullPMemOffset, prev_off, next_off, InternalKey(key), value); if (sz == 0) { kvdk_assert(prev == Head() && next == Tail(), "Impossible!"); first = record; last = record; } else if (prev == Head()) { // PushFront() kvdk_assert(next != Tail(), ""); next->PersistPrevNT(space.offset); first = record; } else if (next == Tail()) { // PushBack() kvdk_assert(prev != Head(), ""); prev->PersistNextNT(space.offset); last = record; } else { // Emplace between two elements on PMem kvdk_assert(prev != Head() && next != Tail(), ""); prev->PersistNextNT(space.offset); next->PersistPrevNT(space.offset); } return (next == Tail()) ? --next : ++prev; } friend std::ostream& operator<<(std::ostream& out, GenericList const& list) { auto printRecord = [&](DLRecord* record) { out << "Type:\t" << to_hex(record->entry.meta.type) << "\t" << "Prev:\t" << to_hex(record->prev) << "\t" << "Offset:\t" << to_hex(reinterpret_cast<char*>(record) - list.pmem_base) << "\t" << "Next:\t" << to_hex(record->next) << "\t" << "ID:\t" << to_hex(Collection::ExtractID(record->Key())) << "\t" << "Key: " << Collection::ExtractUserKey(record->Key()) << "\t" << "Value: " << record->Value() << "\n"; }; out << "Contents of List:\n"; Iterator iter = list.Head(); for (Iterator iter = list.Head(); iter != list.Tail(); iter++) { printRecord(iter.record); } printRecord(iter.record); return out; } }; template <RecordType ListType, RecordType DataType> class GenericListBuilder final { static constexpr size_t NMiddlePoints = 1024; using List = GenericList<ListType, DataType>; PMEMAllocator* alloc; size_t n_worker{0}; std::mutex mu; std::vector<std::unique_ptr<List>>* rebuilded_lists{nullptr}; // Resevoir for middle points // Middle points can be used for multi-thread interating through Lists std::atomic_uint64_t mpoint_cnt{0U}; std::array<DLRecord*, NMiddlePoints> mpoints{}; struct ListPrimer { DLRecord* list_record{nullptr}; DLRecord* unique{nullptr}; DLRecord* first{nullptr}; DLRecord* last{nullptr}; std::atomic_uint64_t size{0U}; ListPrimer() = default; ListPrimer(ListPrimer const& other) : list_record{other.list_record}, unique{other.unique}, first{other.first}, last{other.last}, size{other.size.load()} {} ListPrimer(ListPrimer&& other) = delete; ListPrimer& operator=(ListPrimer const&) = delete; ListPrimer& operator=(ListPrimer&&) = delete; ~ListPrimer() = default; }; std::vector<ListPrimer> primers{}; RWLock primers_lock; std::vector<DLRecord*> brokens{}; std::mutex brokens_lock{}; // There are 4 types of DLRecord // 0. Unique: prev == Null && next == Null // 1. First: prev == Null && next != Null // 2. Last: prev != Null && next == Null // 3. Middle: prev != Null && next != Null enum class ListRecordType { Unique, First, Last, Middle }; // There are several types of failure during GenericList operations // 1. PushFront/PushBack/PopFront/PopBack Failure // Interruption in Pop() after unlink before purge, same as // Interruption in Push() after persist before link // For uniformity with 1-elem Pop crash, which cannot be detected // Discard the node not linked to/unlinked from List // 2. ReplaceFront/ReplaceBack Failure // Discard the unlinked node // 3. Replace Failure // a. Node not linked from its prev and next purged directly // b. Node not linked from prev but linked from next is linked from prev // This node is older // c. Node linked from prev but not linked from next is saved to broken // This node is newer // After all nodes repaired, this node is unlinked from prev and next // and can be purged // 4. Insertion/Erase Failure // a. Node not linked from its prev and next purged directly // b. Node not linked from prev but linked from next is linked from prev // c. Node linked from prev but not linked from next is saved to broken // After all nodes repaired, this node is unlinked from prev and next // and can be purged // In conclusion, // All unsuccessful Emplace/Push/Replace(before fully linked) will rollback // All unsuccessful Erase/Pop will be finished // This way, we avoid generating duplicate First/Last elements, which will // complicate the recovery procedure public: explicit GenericListBuilder(PMEMAllocator* a, std::vector<std::unique_ptr<List>>* lists, size_t num_worker) : alloc{a}, rebuilded_lists{lists}, n_worker{num_worker} { kvdk_assert(lists != nullptr && lists->empty(), ""); kvdk_assert(num_worker != 0, ""); kvdk_assert(rebuilded_lists != nullptr, "Empty input!"); } void AddListRecord(DLRecord* lrec) { kvdk_assert(lrec->Value().size() == sizeof(CollectionIDType), ""); CollectionIDType id = Collection::ExtractID(lrec->Value()); maybeResizePrimers(id); primers_lock.lock_shared(); kvdk_assert(primers.at(id).list_record == nullptr, ""); primers.at(id).list_record = lrec; primers_lock.unlock_shared(); } void AddListElem(DLRecord* elem) { kvdk_assert(elem->entry.meta.type == DataType, ""); switch (typeOf(elem)) { case ListRecordType::Unique: { addUniqueElem(elem); break; } case ListRecordType::First: { addFirstElem(elem); break; } case ListRecordType::Last: { addLastElem(elem); break; } case ListRecordType::Middle: { addMiddleElem(elem); break; } } return; } template <typename Func> void ProcessCachedElems(Func f, void* args) { f(mpoints, args); return; } void RebuildLists() { for (auto const& primer : primers) { if (primer.list_record == nullptr) { kvdk_assert(primer.first == nullptr, ""); kvdk_assert(primer.last == nullptr, ""); kvdk_assert(primer.unique == nullptr, ""); kvdk_assert(primer.size.load() == 0U, ""); continue; } rebuilded_lists->emplace_back(new List{}); switch (primer.size.load()) { case 0: { // Empty List kvdk_assert(primer.first == nullptr, ""); kvdk_assert(primer.last == nullptr, ""); kvdk_assert(primer.unique == nullptr, ""); kvdk_assert(primer.size.load() == 0, ""); rebuilded_lists->back()->Restore(alloc, primer.list_record, nullptr, nullptr, 0); break; } case 1: { // 1-elem List kvdk_assert(primer.first == nullptr, ""); kvdk_assert(primer.last == nullptr, ""); kvdk_assert(primer.unique != nullptr, ""); kvdk_assert(primer.size.load() == 1, ""); rebuilded_lists->back()->Restore(alloc, primer.list_record, primer.unique, primer.unique, 1); break; } default: { // k-elem List kvdk_assert(primer.first != nullptr, ""); kvdk_assert(primer.last != nullptr, ""); kvdk_assert(primer.unique == nullptr, ""); rebuilded_lists->back()->Restore(alloc, primer.list_record, primer.first, primer.last, primer.size.load()); break; } } } } template <typename ElemDeleter> void CleanBrokens(ElemDeleter elem_deleter) { for (DLRecord* elem : brokens) { switch (typeOf(elem)) { case ListRecordType::Unique: { kvdk_assert(false, "Impossible!"); break; } case ListRecordType::First: { kvdk_assert(!isValidFirst(elem), ""); break; } case ListRecordType::Last: { kvdk_assert(!isValidLast(elem), ""); break; } case ListRecordType::Middle: { kvdk_assert(isDiscardedMiddle(elem), ""); break; } } elem_deleter(elem); } } private: inline DLRecord* addressOf(PMemOffsetType offset) const { return static_cast<DLRecord*>(alloc->offset2addr_checked(offset)); } inline PMemOffsetType offsetOf(DLRecord* rec) const { return alloc->addr2offset_checked(rec); } ListRecordType typeOf(DLRecord* elem) { if (elem->prev == NullPMemOffset) { if (elem->next == NullPMemOffset) { return ListRecordType::Unique; } else { return ListRecordType::First; } } else { if (elem->next == NullPMemOffset) { return ListRecordType::Last; } else { return ListRecordType::Middle; } } } void addUniqueElem(DLRecord* elem) { kvdk_assert(elem->prev == NullPMemOffset && elem->next == NullPMemOffset, "Not UniqueElem!"); CollectionIDType id = Collection::ExtractID(elem->Key()); maybeResizePrimers(id); primers_lock.lock_shared(); kvdk_assert(primers.at(id).unique == nullptr, ""); kvdk_assert(primers.at(id).first == nullptr, ""); kvdk_assert(primers.at(id).last == nullptr, ""); primers.at(id).unique = elem; primers.at(id).size.fetch_add(1U); primers_lock.unlock_shared(); } void addFirstElem(DLRecord* elem) { kvdk_assert(elem->prev == NullPMemOffset && elem->next != NullPMemOffset, "Not FirstElem!"); if (!isValidFirst(elem)) { std::lock_guard<std::mutex> guard{brokens_lock}; brokens.push_back(elem); return; } CollectionIDType id = Collection::ExtractID(elem->Key()); maybeResizePrimers(id); primers_lock.lock_shared(); kvdk_assert(primers.at(id).first == nullptr, ""); kvdk_assert(primers.at(id).unique == nullptr, ""); primers.at(id).first = elem; primers.at(id).size.fetch_add(1U); primers_lock.unlock_shared(); } void addLastElem(DLRecord* elem) { kvdk_assert(elem->next == NullPMemOffset && elem->prev != NullPMemOffset, "Not LastElem!"); if (!isValidLast(elem)) { std::lock_guard<std::mutex> guard{brokens_lock}; brokens.push_back(elem); return; } CollectionIDType id = Collection::ExtractID(elem->Key()); maybeResizePrimers(id); primers_lock.lock_shared(); kvdk_assert(primers.at(id).last == nullptr, ""); kvdk_assert(primers.at(id).unique == nullptr, ""); primers.at(id).last = elem; primers.at(id).size.fetch_add(1U); primers_lock.unlock_shared(); } // Reservoir algorithm void addMiddleElem(DLRecord* elem) { kvdk_assert(elem->prev != NullPMemOffset && elem->next != NullPMemOffset, "Not MiddleElem!"); if (!maybeTryFixMiddle(elem)) { std::lock_guard<std::mutex> guard{brokens_lock}; brokens.push_back(elem); return; } CollectionIDType id = Collection::ExtractID(elem->Key()); maybeResizePrimers(id); primers_lock.lock_shared(); primers.at(id).size.fetch_add(1U); primers_lock.unlock_shared(); thread_local std::default_random_engine rengine{get_seed()}; auto cnt = mpoint_cnt.fetch_add(1U); auto pos = cnt % NMiddlePoints; auto k = cnt / NMiddlePoints; // k-th point has posibility 1/(k+1) to replace previous point in reservoir if (std::bernoulli_distribution{1.0 / static_cast<double>(k + 1)}(rengine)) { mpoints.at(pos) = elem; } return; } bool isValidFirst(DLRecord* elem) { if (addressOf(elem->next)->prev == NullPMemOffset) { // Interrupted PushFront()/PopFront() return false; } else if (addressOf(elem->next)->prev == offsetOf(elem)) { return true; } else { // Interrupted ReplaceFront() kvdk_assert(addressOf(addressOf(elem->next)->prev)->next == elem->next, ""); return false; } } bool isValidLast(DLRecord* elem) { if (addressOf(elem->prev)->next == NullPMemOffset) { // Interrupted PushBack()/PopBack() return false; } else if (addressOf(elem->prev)->next == offsetOf(elem)) { return true; } else { // Interrupted ReplaceBack() kvdk_assert(addressOf(addressOf(elem->prev)->next)->prev == elem->prev, ""); return false; } } // Check for discarded Middle bool isDiscardedMiddle(DLRecord* elem) { kvdk_assert(typeOf(elem) == ListRecordType::Middle, "Not a middle"); return (offsetOf(elem) != addressOf(elem->prev)->next) && (offsetOf(elem) != addressOf(elem->next)->prev); } // When false is returned, the node is put in temporary pool // and processed after all restoration is done bool maybeTryFixMiddle(DLRecord* elem) { if (offsetOf(elem) == addressOf(elem->prev)->next) { if (offsetOf(elem) == addressOf(elem->next)->prev) { // Normal Middle return true; } else { // Interrupted Replace/Emplace(newer), discard return false; } } else { if (offsetOf(elem) == addressOf(elem->next)->prev) { // Interrupted Replace/Emplace(older), repair into List addressOf(elem->prev)->PersistNextNT(offsetOf(elem)); return true; } else { // Un-purged, discard return false; } } } void maybeResizePrimers(CollectionIDType id) { if (id >= primers.size()) { std::lock_guard<decltype(primers_lock)> guard{primers_lock}; for (size_t i = primers.size(); i < (id + 1) * 3 / 2; i++) { primers.emplace_back(); } } } }; } // namespace KVDK_NAMESPACE
31.154345
80
0.613197
iyupeng
ae236083dd3d4f9d4d431e5a1fd8148244353fc5
1,417
cpp
C++
Ejercicio03/compset_iteration_01/lib/RequestHandler/test/test.cpp
SmartNetAR/edi3
68e28b58e04b728bc48700378b2afe8f16872974
[ "MIT" ]
null
null
null
Ejercicio03/compset_iteration_01/lib/RequestHandler/test/test.cpp
SmartNetAR/edi3
68e28b58e04b728bc48700378b2afe8f16872974
[ "MIT" ]
null
null
null
Ejercicio03/compset_iteration_01/lib/RequestHandler/test/test.cpp
SmartNetAR/edi3
68e28b58e04b728bc48700378b2afe8f16872974
[ "MIT" ]
null
null
null
/** * Copyright (c) 2016 Gabriel Ferreira <gabrielinuz@gmail.com>. All rights reserved. * This file is part of COMPSET. * Released under the GPL3 license * https://opensource.org/licenses/GPL-3.0 **/ #include <iostream> #include <vector> #include <unordered_map> #include <string> #include <compset/ComponentInterface.h> #include <compset/ComponentFactory.h> #include <compset/RequestHandlerInterface.h> typedef std::vector< std::unordered_map<std::string, std::string> > DataType; typedef std::unordered_map<std::string, std::string> DatumType; int main() { DataType data; DatumType datum; ComponentFactory* componentFactoryObject = new ComponentFactory(); componentFactoryObject->setInterfaceName("RequestHandlerInterface"); ComponentInterface* requestHandlerComponent = componentFactoryObject->createFrom("../RequestHandler"); RequestHandlerInterface* requestHandlerObject = ( (RequestHandlerInterface*) requestHandlerComponent->getInstance() ); DatumType requestParameters = requestHandlerObject->getRequestParameters(); data.push_back(requestParameters); requestHandlerComponent->release(); delete componentFactoryObject; std::cout << requestParameters["action"] << std::endl; std::cout << "RESULT:" << std::endl; std::cout << "\t\tTEST OK!!!!!" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; return 0; }
32.204545
122
0.721948
SmartNetAR
ae23abb8b6a210768d8f1f3438cd33e73abbf59c
61
hpp
C++
addons/modules/modules/curator/prep.hpp
Krzyciu/A3CS
b7144fc9089b5ded6e37cc1fad79b1c2879521be
[ "MIT" ]
1
2020-06-07T00:45:49.000Z
2020-06-07T00:45:49.000Z
addons/modules/modules/curator/prep.hpp
Krzyciu/A3CS
b7144fc9089b5ded6e37cc1fad79b1c2879521be
[ "MIT" ]
27
2020-05-24T11:09:56.000Z
2020-05-25T12:28:10.000Z
addons/modules/modules/curator/prep.hpp
Krzyciu/A3CS
b7144fc9089b5ded6e37cc1fad79b1c2879521be
[ "MIT" ]
2
2020-05-31T08:52:45.000Z
2021-04-16T23:16:37.000Z
PREP_MODULE(curator,module); PREP_MODULE(curator,validate);
15.25
30
0.819672
Krzyciu
ae253bbbba2b1326e6621f9d165fd1fd8ec7ae36
264
cpp
C++
src/triangle-rasterizer-demo/src/trdDirectionalLight.cpp
frmr/triangle-rasterizer-demo
963f32435ebae5b7fbe6fa212709bdc3ea66ac36
[ "MIT" ]
null
null
null
src/triangle-rasterizer-demo/src/trdDirectionalLight.cpp
frmr/triangle-rasterizer-demo
963f32435ebae5b7fbe6fa212709bdc3ea66ac36
[ "MIT" ]
null
null
null
src/triangle-rasterizer-demo/src/trdDirectionalLight.cpp
frmr/triangle-rasterizer-demo
963f32435ebae5b7fbe6fa212709bdc3ea66ac36
[ "MIT" ]
null
null
null
#include "trdDirectionalLight.hpp" trd::DirectionalLight::DirectionalLight(const Vector3& color, Vector3 direction) : Light(color), m_direction(direction.normalize()) { } const tr::QuadVec3& trd::DirectionalLight::getDirection() const { return m_direction; }
20.307692
82
0.772727
frmr
ae29405ad0a2b3f5557e18d58f596bd9ecdd8ee0
1,249
cpp
C++
android/android_42/base/services/jni/com_android_server_SystemServer.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
1
2021-03-05T06:48:29.000Z
2021-03-05T06:48:29.000Z
frameworks/base/services/jni/com_android_server_SystemServer.cpp
CPU-Code/android_bottom
76db08af7719d88d8ee3e51ed310ffe14f14e522
[ "Apache-2.0" ]
null
null
null
frameworks/base/services/jni/com_android_server_SystemServer.cpp
CPU-Code/android_bottom
76db08af7719d88d8ee3e51ed310ffe14f14e522
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2007 The Android Open Source Project * * 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 <utils/Log.h> #include <utils/misc.h> #include "jni.h" #include "JNIHelp.h" namespace android { extern "C" int system_init(); static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz) { system_init(); } /* * JNI registration. */ static JNINativeMethod gMethods[] = { /* name, signature, funcPtr */ { "init1", "([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 }, }; int register_android_server_SystemServer(JNIEnv* env) { return jniRegisterNativeMethods(env, "com/android/server/SystemServer", gMethods, NELEM(gMethods)); } }; // namespace android
26.020833
85
0.717374
yakuizhao
ae2c48b1aa5739963134ca4224fbc585db1d1a24
981
hpp
C++
aboveGroundSpace.hpp
KrisBierma/textBasedStrategyGame
231b0e9a33d8892edfb3fd85fb64679c8b237540
[ "MIT" ]
null
null
null
aboveGroundSpace.hpp
KrisBierma/textBasedStrategyGame
231b0e9a33d8892edfb3fd85fb64679c8b237540
[ "MIT" ]
null
null
null
aboveGroundSpace.hpp
KrisBierma/textBasedStrategyGame
231b0e9a33d8892edfb3fd85fb64679c8b237540
[ "MIT" ]
null
null
null
/******************************************************************** ** Program name:The Secret Treasure, A Text-Based Game (Project 5) ** Author: Kris Bierma ** Date: 12/6/19 ** Description: AboveGroundSpace class is derived from Space class. ** It overrides the getSpaceType functions, has its own ** setPointers function and inherits everything else ** the base Space class. ********************************************************************/ #include "space.hpp" #ifndef KBIERMA_ABOVEGROUNDSPACE_HPP #define KBIERMA_ABOVEGROUNDSPACE_HPP class AboveGroundSpace : public Space { private: Space *down; public: AboveGroundSpace(string spaceNameIn, string printSpaceNameIn, string spaceDescrptionIn, string spaceDescriptionAfterDependencyIn); ~AboveGroundSpace() {}; void setPointers(Space *northIn, Space *eastIn, Space *southIn, Space *westIn, Space *downIn); virtual string getSpaceType(); }; #endif
39.24
134
0.618756
KrisBierma
ae2d6f76a540fbc65b45fd727817188f11835f8d
1,236
cpp
C++
src/run_async_simple.cpp
drix00/MonteCarlo-BSE
f8131f25794e1afe393f54812caae37a06effb8e
[ "Apache-2.0" ]
null
null
null
src/run_async_simple.cpp
drix00/MonteCarlo-BSE
f8131f25794e1afe393f54812caae37a06effb8e
[ "Apache-2.0" ]
13
2021-07-26T16:41:30.000Z
2021-07-26T17:15:24.000Z
src/run_async_simple.cpp
drix00/MonteCarlo-BSE
f8131f25794e1afe393f54812caae37a06effb8e
[ "Apache-2.0" ]
null
null
null
// // Created by Hendrix Demers on 2020-05-10. // #include <string> #include "inputs.h" #include "simulate.h" void simulate_number_trajectories_repetitions(std::string suffix) { run_simulations_async_simple("simulate_async_simple_number_trajectories_repetitions", suffix, get_inputs_number_trajectories_repetitions()); } void simulate_elements_energies(std::string suffix) { run_simulations_async_simple("simulate_async_simple_elements_energies", suffix, get_inputs_elements_energies()); } void simulate_atomic_numbers(std::string suffix) { run_simulations_async_simple("simulate_async_simple_atomic_numbers", suffix, get_inputs_atomic_numbers()); } void simulate_densities(std::string suffix) { run_simulations_async_simple("simulate_async_simple_densities", suffix, get_inputs_densities()); } void simulate_thickness(std::string suffix) { run_simulations_async_simple("simulate_async_simple_thickness", suffix, get_inputs_thickness()); } int main(int , const char **) { std::string suffix = get_suffix(); simulate_number_trajectories_repetitions(suffix); simulate_elements_energies(suffix); simulate_atomic_numbers(suffix); simulate_densities(suffix); simulate_thickness(suffix); }
28.090909
144
0.800162
drix00
ae2f9969a23231b099261429bcf4614bbb48e80c
769
cpp
C++
Luogu/P7947.cpp
Nickel-Angel/Coding-Practice
6fb70e9c9542323f82a9a8714727cc668ff58567
[ "MIT" ]
null
null
null
Luogu/P7947.cpp
Nickel-Angel/Coding-Practice
6fb70e9c9542323f82a9a8714727cc668ff58567
[ "MIT" ]
1
2021-11-18T15:10:29.000Z
2021-11-20T07:13:31.000Z
Luogu/P7947.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
/* * @author Nickel_Angel (1239004072@qq.com) * @copyright Copyright (c) 2021 */ #include <algorithm> #include <cstdio> #include <cstring> #include <numeric> #include <vector> int n, k; std::vector<int> ans; int main() { scanf("%d%d", &n, &k); for (int i = 2, bound = n; i * i <= bound; ++i) { while (n % i == 0) { n /= i; ans.push_back(i); } if (n == 1) break; } if (n != 1) ans.push_back(n); int sum = std::accumulate(ans.begin(), ans.end(), 0); if (sum > k) { puts("-1"); return 0; } printf("%d\n", ans.size() + k - sum); for (int i : ans) printf("%d ", i); for (int i = 0; i < k - sum; ++i) printf("1 "); }
18.756098
57
0.446034
Nickel-Angel
ae30af79ea1f3c2125eb94c5fd7f2b5e5aab7fa2
1,009
hpp
C++
Questless/Questless/src/animation/scene_node.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
2
2020-07-14T12:50:06.000Z
2020-11-04T02:25:09.000Z
Questless/Questless/src/animation/scene_node.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
null
null
null
Questless/Questless/src/animation/scene_node.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
null
null
null
//! @file //! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>. #pragma once #include "animation.hpp" #include "utility/reference.hpp" #include <deque> namespace ql { //! An animation with attached child animations. A scene node's transform is composed with its children's transforms. struct scene_node : animation { //! The animation to draw at this node. uptr<animation> node_animation; //! Children drawn behind this node. Drawn back-to-front, so back_children.back() is the back-most node. std::deque<uptr<animation>> back_children{}; //! Children drawn in front of this node. Drawn back-to-front, so front_children.front() is the front-most node. std::deque<uptr<animation>> front_children{}; //! @param node_animation The animation to draw at this node. scene_node(uptr<animation> node_animation); private: auto animation_subupdate(sec elapsed_time) -> void final; auto animation_subdraw(sf::RenderTarget& target, sf::RenderStates states) const -> void final; }; }
30.575758
118
0.733399
jonathansharman
ae31b3c508e6deebb4beac171151e2d81164be59
119,953
cpp
C++
src/parser/ds_lexer.cpp
profelis/daScript
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
[ "BSD-3-Clause" ]
421
2019-08-15T15:40:04.000Z
2022-03-29T06:59:06.000Z
src/parser/ds_lexer.cpp
profelis/daScript
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
[ "BSD-3-Clause" ]
55
2019-08-17T13:50:53.000Z
2022-03-25T17:58:38.000Z
src/parser/ds_lexer.cpp
profelis/daScript
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
[ "BSD-3-Clause" ]
58
2019-08-22T17:04:13.000Z
2022-03-25T17:43:28.000Z
#line 1 "ds_lexer.cpp" #line 3 "ds_lexer.cpp" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 4 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif #ifdef yy_create_buffer #define das_yy_create_buffer_ALREADY_DEFINED #else #define yy_create_buffer das_yy_create_buffer #endif #ifdef yy_delete_buffer #define das_yy_delete_buffer_ALREADY_DEFINED #else #define yy_delete_buffer das_yy_delete_buffer #endif #ifdef yy_scan_buffer #define das_yy_scan_buffer_ALREADY_DEFINED #else #define yy_scan_buffer das_yy_scan_buffer #endif #ifdef yy_scan_string #define das_yy_scan_string_ALREADY_DEFINED #else #define yy_scan_string das_yy_scan_string #endif #ifdef yy_scan_bytes #define das_yy_scan_bytes_ALREADY_DEFINED #else #define yy_scan_bytes das_yy_scan_bytes #endif #ifdef yy_init_buffer #define das_yy_init_buffer_ALREADY_DEFINED #else #define yy_init_buffer das_yy_init_buffer #endif #ifdef yy_flush_buffer #define das_yy_flush_buffer_ALREADY_DEFINED #else #define yy_flush_buffer das_yy_flush_buffer #endif #ifdef yy_load_buffer_state #define das_yy_load_buffer_state_ALREADY_DEFINED #else #define yy_load_buffer_state das_yy_load_buffer_state #endif #ifdef yy_switch_to_buffer #define das_yy_switch_to_buffer_ALREADY_DEFINED #else #define yy_switch_to_buffer das_yy_switch_to_buffer #endif #ifdef yypush_buffer_state #define das_yypush_buffer_state_ALREADY_DEFINED #else #define yypush_buffer_state das_yypush_buffer_state #endif #ifdef yypop_buffer_state #define das_yypop_buffer_state_ALREADY_DEFINED #else #define yypop_buffer_state das_yypop_buffer_state #endif #ifdef yyensure_buffer_stack #define das_yyensure_buffer_stack_ALREADY_DEFINED #else #define yyensure_buffer_stack das_yyensure_buffer_stack #endif #ifdef yylex #define das_yylex_ALREADY_DEFINED #else #define yylex das_yylex #endif #ifdef yyrestart #define das_yyrestart_ALREADY_DEFINED #else #define yyrestart das_yyrestart #endif #ifdef yylex_init #define das_yylex_init_ALREADY_DEFINED #else #define yylex_init das_yylex_init #endif #ifdef yylex_init_extra #define das_yylex_init_extra_ALREADY_DEFINED #else #define yylex_init_extra das_yylex_init_extra #endif #ifdef yylex_destroy #define das_yylex_destroy_ALREADY_DEFINED #else #define yylex_destroy das_yylex_destroy #endif #ifdef yyget_debug #define das_yyget_debug_ALREADY_DEFINED #else #define yyget_debug das_yyget_debug #endif #ifdef yyset_debug #define das_yyset_debug_ALREADY_DEFINED #else #define yyset_debug das_yyset_debug #endif #ifdef yyget_extra #define das_yyget_extra_ALREADY_DEFINED #else #define yyget_extra das_yyget_extra #endif #ifdef yyset_extra #define das_yyset_extra_ALREADY_DEFINED #else #define yyset_extra das_yyset_extra #endif #ifdef yyget_in #define das_yyget_in_ALREADY_DEFINED #else #define yyget_in das_yyget_in #endif #ifdef yyset_in #define das_yyset_in_ALREADY_DEFINED #else #define yyset_in das_yyset_in #endif #ifdef yyget_out #define das_yyget_out_ALREADY_DEFINED #else #define yyget_out das_yyget_out #endif #ifdef yyset_out #define das_yyset_out_ALREADY_DEFINED #else #define yyset_out das_yyset_out #endif #ifdef yyget_leng #define das_yyget_leng_ALREADY_DEFINED #else #define yyget_leng das_yyget_leng #endif #ifdef yyget_text #define das_yyget_text_ALREADY_DEFINED #else #define yyget_text das_yyget_text #endif #ifdef yyget_lineno #define das_yyget_lineno_ALREADY_DEFINED #else #define yyget_lineno das_yyget_lineno #endif #ifdef yyset_lineno #define das_yyset_lineno_ALREADY_DEFINED #else #define yyset_lineno das_yyset_lineno #endif #ifdef yyget_column #define das_yyget_column_ALREADY_DEFINED #else #define yyget_column das_yyget_column #endif #ifdef yyset_column #define das_yyset_column_ALREADY_DEFINED #else #define yyset_column das_yyset_column #endif #ifdef yywrap #define das_yywrap_ALREADY_DEFINED #else #define yywrap das_yywrap #endif #ifdef yyget_lval #define das_yyget_lval_ALREADY_DEFINED #else #define yyget_lval das_yyget_lval #endif #ifdef yyset_lval #define das_yyset_lval_ALREADY_DEFINED #else #define yyset_lval das_yyset_lval #endif #ifdef yyalloc #define das_yyalloc_ALREADY_DEFINED #else #define yyalloc das_yyalloc #endif #ifdef yyrealloc #define das_yyrealloc_ALREADY_DEFINED #else #define yyrealloc das_yyrealloc #endif #ifdef yyfree #define das_yyfree_ALREADY_DEFINED #else #define yyfree das_yyfree #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #ifndef SIZE_MAX #define SIZE_MAX (~(size_t)0) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ /* begin standard C++ headers. */ /* TODO: this is always defined, so inline it */ #define yyconst const #if defined(__GNUC__) && __GNUC__ >= 3 #define yynoreturn __attribute__((__noreturn__)) #else #define yynoreturn #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an * integer in range [0..255] for use as an array index. */ #define YY_SC_TO_UI(c) ((YY_CHAR) (c)) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart( yyin , yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ int yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void yyrestart ( FILE *input_file , yyscan_t yyscanner ); void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner ); YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner ); void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner ); void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner ); void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner ); void yypop_buffer_state ( yyscan_t yyscanner ); static void yyensure_buffer_stack ( yyscan_t yyscanner ); static void yy_load_buffer_state ( yyscan_t yyscanner ); static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file , yyscan_t yyscanner ); #define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER , yyscanner) YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner ); YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner ); YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner ); void *yyalloc ( yy_size_t , yyscan_t yyscanner ); void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner ); void yyfree ( void * , yyscan_t yyscanner ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define das_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef flex_uint8_t YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state ( yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans ( yy_state_type current_state , yyscan_t yyscanner); static int yy_get_next_buffer ( yyscan_t yyscanner ); static void yynoreturn yy_fatal_error ( const char* msg , yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (int) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 212 #define YY_END_OF_BUFFER 213 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static const flex_int16_t yy_accept[600] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 29, 0, 0, 0, 0, 213, 212, 28, 26, 24, 28, 25, 28, 28, 28, 23, 22, 21, 20, 16, 23, 17, 12, 13, 12, 12, 12, 8, 9, 31, 30, 29, 211, 209, 210, 208, 211, 131, 211, 211, 211, 211, 156, 155, 211, 211, 211, 211, 211, 142, 142, 211, 211, 211, 211, 211, 211, 130, 158, 157, 211, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 160, 211, 159, 15, 14, 0, 24, 0, 2, 3, 6, 19, 18, 11, 10, 31, 29, 195, 180, 184, 187, 0, 0, 4, 179, 190, 176, 191, 177, 174, 147, 5, 7, 178, 148, 142, 0, 149, 140, 141, 0, 140, 161, 173, 175, 199, 192, 169, 194, 204, 193, 197, 172, 170, 171, 0, 0, 0, 130, 205, 206, 189, 186, 130, 130, 130, 130, 90, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 35, 130, 82, 91, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 207, 188, 162, 185, 0, 0, 27, 0, 181, 138, 0, 0, 0, 0, 0, 0, 0, 147, 0, 0, 210, 0, 147, 0, 148, 0, 0, 150, 139, 146, 153, 198, 201, 0, 164, 0, 0, 200, 196, 168, 0, 0, 183, 130, 130, 43, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 41, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 33, 130, 130, 130, 130, 130, 110, 130, 130, 130, 46, 130, 100, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 52, 130, 130, 130, 130, 130, 130, 48, 130, 130, 130, 130, 130, 182, 0, 0, 137, 132, 135, 134, 136, 133, 0, 147, 151, 0, 0, 147, 0, 0, 148, 152, 150, 0, 144, 145, 203, 165, 166, 0, 202, 167, 130, 93, 130, 130, 104, 130, 130, 105, 130, 71, 130, 130, 130, 130, 130, 130, 37, 39, 51, 130, 130, 130, 130, 130, 130, 130, 56, 130, 130, 130, 114, 115, 116, 130, 111, 130, 130, 130, 0, 0, 130, 94, 130, 130, 130, 73, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 102, 130, 99, 117, 130, 130, 130, 0, 0, 130, 106, 130, 130, 42, 130, 0, 0, 147, 151, 154, 143, 0, 163, 130, 80, 130, 130, 62, 97, 50, 68, 130, 130, 92, 130, 130, 130, 103, 130, 126, 130, 130, 130, 130, 112, 113, 130, 55, 130, 0, 130, 130, 130, 130, 130, 130, 108, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 79, 66, 130, 130, 130, 122, 123, 124, 130, 119, 130, 130, 130, 0, 130, 70, 34, 96, 0, 130, 44, 130, 130, 101, 125, 78, 130, 130, 127, 128, 129, 130, 130, 130, 130, 130, 64, 0, 45, 57, 130, 130, 130, 130, 58, 130, 130, 130, 95, 76, 85, 130, 130, 107, 49, 130, 130, 120, 121, 89, 72, 109, 0, 47, 130, 0, 130, 130, 130, 130, 40, 130, 130, 130, 32, 130, 130, 59, 130, 86, 53, 130, 61, 130, 130, 54, 130, 0, 88, 67, 0, 77, 118, 69, 84, 63, 130, 83, 81, 60, 75, 130, 130, 130, 130, 98, 1, 65, 130, 87, 130, 36, 130, 130, 74, 38, 0 } ; static const YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 26, 28, 26, 29, 1, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 38, 38, 38, 38, 39, 38, 38, 38, 38, 38, 38, 38, 38, 40, 38, 38, 41, 38, 38, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 38, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 38, 72, 73, 74, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static const YY_CHAR yy_meta[75] = { 0, 1, 2, 3, 2, 2, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 1, 1, 6, 5, 5, 7, 7, 7, 7, 1, 1, 1, 1, 7, 7, 6, 6, 6, 6, 5, 5, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1 } ; static const flex_int16_t yy_base[619] = { 0, 0, 0, 0, 8, 15, 22, 27, 29, 985, 984, 32, 36, 94, 0, 983, 982, 984, 989, 989, 48, 989, 52, 57, 45, 963, 28, 989, 989, 989, 989, 989, 2, 989, 989, 989, 989, 962, 966, 989, 989, 0, 989, 975, 989, 989, 989, 989, 948, 989, 56, 947, 158, 934, 989, 989, 44, 154, 155, 153, 168, 181, 22, 57, 164, 58, 140, 177, 196, 0, 142, 989, 166, 178, 167, 188, 163, 180, 196, 180, 200, 164, 915, 195, 23, 207, 216, 217, 213, 225, 225, 135, 919, 902, 247, 989, 989, 989, 288, 989, 277, 989, 989, 255, 989, 989, 989, 989, 0, 968, 989, 989, 941, 989, 959, 270, 989, 989, 989, 989, 989, 989, 989, 259, 989, 294, 989, 273, 265, 321, 989, 989, 249, 0, 917, 989, 989, 989, 162, 989, 348, 989, 989, 989, 284, 989, 989, 989, 327, 896, 336, 0, 989, 989, 989, 937, 902, 915, 917, 900, 898, 896, 895, 899, 898, 906, 892, 908, 895, 269, 887, 298, 886, 890, 893, 890, 888, 884, 887, 886, 879, 0, 882, 258, 0, 891, 269, 876, 890, 871, 881, 204, 886, 872, 880, 886, 874, 306, 885, 884, 883, 307, 881, 293, 867, 866, 867, 861, 875, 876, 859, 866, 309, 855, 868, 989, 989, 989, 888, 352, 364, 989, 367, 989, 989, 906, 905, 904, 903, 902, 901, 367, 989, 859, 378, 989, 379, 360, 398, 989, 858, 379, 406, 989, 396, 989, 879, 989, 435, 989, 445, 889, 989, 877, 989, 440, 834, 989, 840, 841, 0, 856, 836, 841, 848, 850, 841, 850, 831, 831, 293, 0, 843, 842, 844, 839, 839, 831, 357, 824, 840, 839, 0, 836, 833, 823, 825, 824, 449, 817, 828, 830, 476, 811, 0, 819, 812, 819, 810, 808, 804, 813, 816, 808, 808, 800, 799, 807, 800, 799, 796, 385, 803, 808, 0, 801, 806, 791, 808, 807, 794, 480, 802, 788, 793, 795, 791, 989, 466, 448, 989, 989, 989, 989, 989, 989, 480, 488, 989, 455, 505, 989, 795, 526, 534, 989, 989, 794, 989, 282, 989, 989, 989, 843, 989, 989, 781, 0, 773, 784, 0, 786, 784, 0, 783, 0, 774, 772, 781, 770, 782, 776, 0, 0, 0, 783, 776, 779, 772, 763, 762, 763, 0, 770, 758, 797, 0, 0, 0, 798, 0, 774, 763, 769, 515, 799, 760, 0, 769, 755, 751, 0, 766, 757, 760, 743, 744, 753, 744, 755, 754, 739, 748, 743, 752, 749, 0, 748, 405, 515, 746, 733, 743, 561, 776, 747, 0, 742, 741, 0, 741, 784, 551, 572, 989, 989, 989, 787, 989, 741, 0, 736, 735, 0, 0, 0, 0, 726, 733, 0, 732, 717, 732, 0, 723, 474, 724, 731, 728, 726, 0, 0, 710, 0, 727, 771, 721, 706, 711, 714, 703, 718, 0, 715, 714, 701, 700, 678, 677, 671, 666, 643, 623, 0, 0, 636, 569, 601, 0, 0, 0, 602, 0, 574, 558, 571, 619, 561, 0, 0, 0, 0, 570, 0, 561, 551, 0, 0, 0, 561, 545, 0, 0, 0, 554, 548, 557, 559, 549, 0, 605, 989, 0, 546, 541, 554, 550, 0, 526, 525, 536, 0, 0, 0, 524, 539, 0, 0, 531, 517, 0, 0, 578, 0, 0, 566, 989, 502, 560, 498, 494, 492, 468, 0, 464, 461, 452, 0, 431, 422, 0, 427, 0, 0, 405, 0, 400, 401, 0, 401, 599, 989, 0, 452, 0, 0, 0, 0, 0, 382, 0, 0, 0, 0, 353, 347, 352, 355, 0, 989, 0, 334, 0, 211, 0, 147, 40, 0, 0, 989, 630, 638, 646, 654, 662, 670, 678, 686, 694, 698, 706, 710, 718, 722, 726, 732, 740, 748, 756 } ; static const flex_int16_t yy_def[619] = { 0, 600, 600, 601, 601, 602, 602, 603, 603, 604, 604, 605, 605, 599, 13, 606, 606, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 607, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 608, 599, 599, 599, 599, 599, 599, 599, 599, 61, 599, 599, 599, 599, 599, 599, 609, 599, 599, 599, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 610, 599, 599, 599, 599, 607, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 611, 599, 612, 599, 613, 61, 599, 599, 599, 599, 614, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 609, 599, 599, 599, 599, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 599, 599, 599, 599, 599, 610, 599, 610, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 612, 599, 612, 613, 599, 599, 599, 599, 599, 599, 614, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 599, 599, 610, 599, 599, 599, 599, 599, 599, 599, 599, 599, 612, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 615, 599, 599, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 599, 599, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 599, 599, 609, 609, 609, 609, 609, 609, 599, 599, 599, 599, 599, 599, 615, 599, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 616, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 617, 609, 609, 609, 609, 618, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 616, 599, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 617, 599, 609, 618, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 599, 599, 609, 599, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 609, 599, 609, 609, 609, 609, 609, 609, 609, 609, 609, 0, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599 } ; static const flex_int16_t yy_nxt[1064] = { 0, 599, 20, 21, 22, 23, 599, 599, 24, 104, 20, 21, 22, 23, 599, 25, 24, 28, 29, 30, 26, 599, 31, 25, 28, 29, 30, 599, 26, 31, 35, 36, 35, 36, 42, 18, 18, 43, 42, 18, 18, 43, 37, 102, 37, 105, 599, 38, 103, 38, 98, 99, 98, 98, 98, 99, 98, 98, 32, 98, 99, 98, 98, 599, 116, 32, 100, 100, 100, 100, 100, 100, 100, 100, 104, 117, 104, 100, 100, 100, 100, 100, 100, 100, 100, 191, 135, 33, 136, 141, 142, 192, 599, 598, 33, 44, 45, 46, 47, 47, 48, 49, 50, 44, 51, 52, 53, 54, 55, 56, 57, 44, 58, 59, 60, 61, 62, 62, 62, 62, 62, 62, 62, 63, 64, 65, 66, 67, 68, 69, 69, 69, 69, 69, 69, 69, 70, 44, 71, 72, 69, 44, 73, 74, 75, 76, 77, 78, 79, 69, 80, 69, 81, 82, 83, 84, 85, 69, 86, 87, 88, 89, 90, 91, 69, 92, 93, 94, 95, 112, 118, 143, 144, 120, 123, 123, 123, 123, 123, 123, 123, 123, 137, 124, 152, 119, 121, 122, 125, 113, 212, 213, 246, 247, 138, 139, 145, 154, 148, 126, 127, 148, 128, 128, 128, 128, 128, 128, 128, 128, 146, 155, 186, 597, 153, 169, 187, 129, 130, 147, 131, 132, 133, 162, 170, 163, 149, 156, 164, 157, 150, 165, 179, 129, 130, 158, 166, 140, 171, 134, 172, 180, 159, 160, 174, 161, 167, 189, 132, 168, 173, 133, 175, 181, 176, 193, 296, 177, 221, 182, 183, 202, 190, 178, 196, 184, 185, 596, 197, 198, 297, 194, 199, 210, 195, 222, 200, 203, 216, 217, 204, 206, 224, 201, 205, 207, 211, 208, 243, 209, 98, 99, 98, 98, 219, 231, 232, 235, 100, 100, 100, 100, 100, 100, 100, 100, 599, 243, 287, 238, 239, 231, 232, 225, 236, 252, 253, 233, 290, 226, 218, 436, 271, 227, 288, 238, 239, 272, 291, 148, 228, 240, 148, 273, 229, 599, 230, 241, 255, 241, 436, 255, 242, 242, 242, 242, 242, 242, 242, 242, 248, 249, 250, 248, 275, 310, 303, 149, 367, 368, 313, 323, 304, 276, 314, 324, 256, 221, 251, 305, 221, 311, 306, 328, 328, 328, 328, 328, 328, 328, 328, 235, 235, 336, 222, 336, 595, 329, 337, 337, 337, 337, 337, 337, 337, 337, 340, 341, 236, 339, 242, 242, 242, 242, 242, 242, 242, 242, 594, 375, 593, 592, 340, 341, 343, 376, 343, 591, 342, 344, 344, 344, 344, 344, 344, 344, 344, 242, 242, 242, 242, 242, 242, 242, 242, 348, 349, 250, 249, 250, 250, 413, 255, 346, 351, 255, 590, 250, 249, 250, 250, 221, 414, 586, 348, 251, 485, 587, 235, 346, 589, 486, 588, 349, 347, 251, 585, 584, 329, 352, 256, 385, 386, 387, 388, 339, 389, 390, 394, 583, 394, 394, 423, 431, 423, 423, 582, 328, 328, 328, 328, 328, 328, 328, 328, 581, 395, 511, 512, 513, 424, 337, 337, 337, 337, 337, 337, 337, 337, 337, 337, 337, 337, 337, 337, 337, 337, 394, 580, 394, 394, 432, 579, 432, 578, 232, 433, 433, 433, 433, 433, 433, 433, 433, 577, 395, 425, 487, 488, 489, 490, 232, 491, 492, 576, 575, 233, 344, 344, 344, 344, 344, 344, 344, 344, 344, 344, 344, 344, 344, 344, 344, 344, 423, 574, 423, 423, 573, 572, 546, 569, 239, 433, 433, 433, 433, 433, 433, 433, 433, 570, 424, 570, 570, 568, 567, 566, 239, 565, 564, 563, 571, 240, 433, 433, 433, 433, 433, 433, 433, 433, 570, 562, 570, 570, 561, 560, 559, 521, 341, 558, 557, 571, 556, 555, 554, 553, 552, 551, 550, 549, 547, 546, 544, 543, 341, 542, 541, 540, 539, 342, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 27, 27, 27, 27, 27, 27, 27, 27, 34, 34, 34, 34, 34, 34, 34, 34, 39, 39, 39, 39, 39, 39, 39, 39, 41, 41, 41, 41, 41, 41, 41, 41, 96, 96, 96, 96, 96, 96, 96, 96, 108, 538, 537, 108, 108, 108, 108, 108, 114, 114, 536, 114, 114, 114, 114, 114, 151, 151, 151, 151, 220, 220, 220, 220, 220, 220, 220, 220, 123, 535, 534, 123, 234, 234, 234, 234, 234, 234, 234, 234, 237, 533, 532, 237, 244, 244, 437, 437, 437, 437, 437, 437, 437, 437, 520, 520, 520, 520, 520, 520, 520, 520, 545, 545, 545, 545, 545, 545, 545, 545, 548, 548, 548, 531, 548, 548, 548, 548, 530, 529, 528, 527, 526, 525, 524, 523, 522, 521, 519, 518, 517, 516, 515, 514, 510, 509, 508, 507, 506, 505, 504, 503, 502, 438, 501, 500, 499, 498, 497, 496, 495, 494, 493, 484, 483, 482, 481, 480, 479, 478, 477, 476, 475, 474, 473, 472, 471, 470, 469, 468, 467, 466, 465, 464, 463, 462, 461, 460, 459, 458, 457, 456, 455, 454, 453, 452, 451, 450, 449, 448, 447, 446, 445, 444, 443, 442, 441, 440, 439, 438, 435, 434, 430, 429, 428, 427, 426, 422, 421, 420, 419, 418, 417, 416, 415, 412, 411, 410, 409, 408, 407, 406, 405, 404, 403, 402, 401, 400, 399, 398, 397, 396, 393, 392, 391, 384, 383, 382, 381, 380, 379, 378, 377, 374, 373, 372, 371, 370, 369, 366, 365, 364, 363, 362, 361, 360, 359, 358, 357, 356, 355, 354, 353, 350, 345, 338, 335, 334, 333, 332, 331, 330, 327, 326, 325, 322, 321, 320, 319, 318, 317, 316, 315, 312, 309, 308, 307, 302, 301, 300, 299, 298, 295, 294, 293, 292, 289, 286, 285, 284, 283, 282, 281, 280, 279, 278, 277, 274, 270, 269, 268, 267, 266, 265, 264, 263, 262, 261, 260, 259, 258, 257, 254, 245, 224, 223, 109, 215, 214, 188, 115, 111, 110, 109, 107, 106, 101, 599, 97, 97, 40, 40, 17, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599 } ; static const flex_int16_t yy_chk[1064] = { 0, 0, 3, 3, 3, 3, 0, 0, 3, 32, 4, 4, 4, 4, 0, 3, 4, 5, 5, 5, 3, 0, 5, 4, 6, 6, 6, 0, 4, 6, 7, 7, 8, 8, 11, 11, 11, 11, 12, 12, 12, 12, 7, 26, 8, 32, 0, 7, 26, 8, 20, 20, 20, 20, 22, 22, 22, 22, 5, 23, 23, 23, 23, 62, 56, 6, 24, 24, 24, 24, 24, 24, 24, 24, 32, 56, 32, 50, 50, 50, 50, 50, 50, 50, 50, 84, 63, 5, 63, 65, 65, 84, 62, 596, 6, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 52, 57, 66, 66, 58, 59, 59, 59, 59, 59, 59, 59, 59, 64, 60, 70, 57, 58, 58, 60, 52, 91, 91, 138, 138, 64, 64, 67, 72, 68, 60, 61, 68, 61, 61, 61, 61, 61, 61, 61, 61, 67, 72, 81, 595, 70, 76, 81, 61, 61, 67, 61, 61, 61, 74, 76, 74, 68, 73, 74, 73, 68, 74, 79, 61, 61, 73, 75, 64, 77, 61, 77, 79, 73, 73, 78, 73, 75, 83, 61, 75, 77, 61, 78, 80, 78, 85, 191, 78, 103, 80, 80, 88, 83, 78, 86, 80, 80, 593, 86, 87, 191, 85, 87, 90, 85, 103, 87, 88, 94, 94, 88, 89, 115, 87, 88, 89, 90, 89, 132, 89, 98, 98, 98, 98, 100, 123, 123, 125, 100, 100, 100, 100, 100, 100, 100, 100, 128, 132, 183, 127, 127, 123, 123, 115, 125, 144, 144, 123, 186, 115, 94, 349, 169, 115, 183, 127, 127, 169, 186, 148, 115, 127, 148, 169, 115, 128, 115, 129, 150, 129, 349, 150, 129, 129, 129, 129, 129, 129, 129, 129, 140, 140, 140, 140, 171, 201, 197, 148, 270, 270, 203, 212, 197, 171, 203, 212, 150, 220, 140, 197, 222, 201, 197, 219, 219, 219, 219, 219, 219, 219, 219, 234, 236, 231, 220, 231, 591, 222, 231, 231, 231, 231, 231, 231, 231, 231, 237, 237, 234, 236, 241, 241, 241, 241, 241, 241, 241, 241, 587, 278, 586, 585, 237, 237, 238, 278, 238, 584, 237, 238, 238, 238, 238, 238, 238, 238, 238, 242, 242, 242, 242, 242, 242, 242, 242, 244, 244, 248, 248, 248, 248, 311, 255, 242, 248, 255, 579, 250, 250, 250, 250, 329, 311, 567, 244, 248, 418, 567, 339, 242, 573, 418, 569, 244, 242, 250, 566, 564, 329, 248, 255, 288, 288, 288, 288, 339, 288, 288, 292, 561, 292, 292, 321, 328, 321, 321, 559, 328, 328, 328, 328, 328, 328, 328, 328, 558, 292, 455, 455, 455, 321, 336, 336, 336, 336, 336, 336, 336, 336, 337, 337, 337, 337, 337, 337, 337, 337, 394, 556, 394, 394, 340, 555, 340, 554, 337, 340, 340, 340, 340, 340, 340, 340, 340, 552, 394, 321, 419, 419, 419, 419, 337, 419, 419, 551, 550, 337, 343, 343, 343, 343, 343, 343, 343, 343, 344, 344, 344, 344, 344, 344, 344, 344, 423, 549, 423, 423, 548, 547, 545, 539, 344, 432, 432, 432, 432, 432, 432, 432, 432, 542, 423, 542, 542, 538, 535, 534, 344, 530, 529, 528, 542, 344, 433, 433, 433, 433, 433, 433, 433, 433, 570, 526, 570, 570, 525, 524, 523, 520, 433, 518, 517, 570, 516, 515, 514, 510, 509, 505, 504, 502, 497, 496, 495, 494, 433, 493, 491, 487, 486, 433, 600, 600, 600, 600, 600, 600, 600, 600, 601, 601, 601, 601, 601, 601, 601, 601, 602, 602, 602, 602, 602, 602, 602, 602, 603, 603, 603, 603, 603, 603, 603, 603, 604, 604, 604, 604, 604, 604, 604, 604, 605, 605, 605, 605, 605, 605, 605, 605, 606, 606, 606, 606, 606, 606, 606, 606, 607, 485, 482, 607, 607, 607, 607, 607, 608, 608, 481, 608, 608, 608, 608, 608, 609, 609, 609, 609, 610, 610, 610, 610, 610, 610, 610, 610, 611, 480, 479, 611, 612, 612, 612, 612, 612, 612, 612, 612, 613, 478, 477, 613, 614, 614, 615, 615, 615, 615, 615, 615, 615, 615, 616, 616, 616, 616, 616, 616, 616, 616, 617, 617, 617, 617, 617, 617, 617, 617, 618, 618, 618, 476, 618, 618, 618, 618, 475, 474, 473, 471, 470, 469, 468, 467, 466, 465, 464, 462, 459, 458, 457, 456, 454, 452, 451, 450, 448, 447, 442, 441, 439, 437, 431, 430, 428, 427, 425, 424, 422, 421, 420, 417, 415, 414, 413, 412, 411, 410, 409, 408, 407, 406, 405, 404, 403, 402, 400, 399, 398, 396, 395, 393, 392, 391, 389, 385, 384, 383, 381, 380, 379, 378, 377, 376, 375, 371, 370, 369, 368, 367, 366, 364, 362, 361, 359, 358, 356, 353, 347, 342, 326, 325, 324, 323, 322, 320, 319, 318, 317, 316, 315, 313, 312, 310, 309, 308, 307, 306, 305, 304, 303, 302, 301, 300, 299, 298, 297, 296, 295, 293, 291, 290, 289, 287, 286, 285, 284, 283, 281, 280, 279, 277, 276, 275, 274, 273, 272, 269, 268, 267, 266, 265, 264, 263, 262, 261, 259, 258, 256, 253, 251, 246, 240, 233, 230, 229, 228, 227, 226, 225, 218, 214, 213, 211, 210, 209, 208, 207, 206, 205, 204, 202, 200, 199, 198, 196, 195, 194, 193, 192, 190, 189, 188, 187, 185, 182, 180, 179, 178, 177, 176, 175, 174, 173, 172, 170, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 149, 134, 114, 112, 109, 93, 92, 82, 53, 51, 48, 43, 38, 37, 25, 17, 16, 15, 10, 9, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599 } ; /* Table of booleans, true if rule could match eol. */ static const flex_int32_t yy_rule_can_match_eol[213] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "ds_lexer.lpp" #line 2 "ds_lexer.lpp" #include "daScript/misc/platform.h" #include <inttypes.h> #include "daScript/ast/ast.h" #include "parser_state.h" #include "ds_parser.hpp" #ifndef SCNi64 #define SCNi64 "lli" #endif #ifndef SCNu64 #define SCNu64 "llu" #endif #ifndef SCNx64 #define SCNx64 "llx" #endif using namespace das; union DAS_YYSTYPE; typedef DAS_YYSTYPE YYSTYPE; #define YY_NO_INPUT void das_yyfatalerror(DAS_YYLTYPE * lloc, yyscan_t scanner, const string & error, CompilationError cerr = CompilationError::syntax_error); #define YY_USER_ACTION \ yylloc_param->first_line = yylloc_param->last_line = yylineno; \ yylloc_param->first_column = yyextra->das_yycolumn; \ yylloc_param->last_column = yyextra->das_yycolumn + yyleng - 1; \ YYCOLUMN (yyextra->das_yycolumn += yyleng, "YY_USER_ACTION"); #ifdef FLEX_DEBUG void YYCOLUMN ( int, const char * comment ) { printf("%i:%i %s\n", yyextra->das_yycolumn, yylineno, comment ? comment : ""); } #else #define YYCOLUMN(expr,comment) ((expr)) #endif void YYTAB() { // YYCOLUMN(yyextra->das_yycolumn = (yyextra->das_yycolumn - 1 + yyextra->das_tab_size) & ~(yyextra->das_tab_size-1), "TAB"); } void YYNEWLINE(yyscan_t yyscanner); #define YY_DECL int yylex(DAS_YYSTYPE *yylval_param, DAS_YYLTYPE *yylloc_param, yyscan_t yyscanner) #define YY_EXTRA_TYPE das::DasParserState * #line 1167 "ds_lexer.cpp" #define YY_NO_UNISTD_H 1 /* %option debug */ #line 1171 "ds_lexer.cpp" #define INITIAL 0 #define indent 1 #define strb 2 #define c_comment 3 #define cpp_comment 4 #define include 5 #define normal 6 #define reader 7 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; int yy_n_chars; int yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals ( yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int yylex_init (yyscan_t* scanner); int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy ( yyscan_t yyscanner ); int yyget_debug ( yyscan_t yyscanner ); void yyset_debug ( int debug_flag , yyscan_t yyscanner ); YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner ); void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner ); FILE *yyget_in ( yyscan_t yyscanner ); void yyset_in ( FILE * _in_str , yyscan_t yyscanner ); FILE *yyget_out ( yyscan_t yyscanner ); void yyset_out ( FILE * _out_str , yyscan_t yyscanner ); int yyget_leng ( yyscan_t yyscanner ); char *yyget_text ( yyscan_t yyscanner ); int yyget_lineno ( yyscan_t yyscanner ); void yyset_lineno ( int _line_number , yyscan_t yyscanner ); int yyget_column ( yyscan_t yyscanner ); void yyset_column ( int _column_no , yyscan_t yyscanner ); YYSTYPE * yyget_lval ( yyscan_t yyscanner ); void yyset_lval ( YYSTYPE * yylval_param , yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap ( yyscan_t yyscanner ); #else extern int yywrap ( yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT static void yyunput ( int c, char *buf_ptr , yyscan_t yyscanner); #endif #ifndef yytext_ptr static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen ( const char * , yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput ( yyscan_t yyscanner ); #else static int input ( yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ int n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner); #define YY_DECL int yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); } yy_load_buffer_state( yyscanner ); } { #line 74 "ds_lexer.lpp" #line 1455 "ds_lexer.cpp" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 600 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; ++yy_cp; } while ( yy_current_state != 599 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { int yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: /* rule 1 can match eol */ YY_RULE_SETUP #line 76 "ds_lexer.lpp" { string txt = yytext; int lRow, lCol; char lFile[256]; if ( sscanf ( yytext, "#%i,%i,\"%255s\"#", &lRow, &lCol, lFile )==3 ) { lFile[strlen(lFile)-2] = 0; auto cfi = yyextra->g_FileAccessStack.back(); string incFileName = yyextra->g_Access->getIncludeFileName(cfi->name,lFile); auto info = yyextra->g_Access->getFileInfo(incFileName); if ( !info ) { das_yyfatalerror(yylloc_param,yyscanner,"can't open "+incFileName); } else { yyextra->g_FileAccessStack.pop_back(); yyextra->g_FileAccessStack.push_back(info); yylineno = lRow; YYCOLUMN ( yyextra->das_yycolumn = lCol, "LINE DIRECTIVE"); } } else { das_yyfatalerror(yylloc_param,yyscanner,"can't process line directive " + string(yytext), CompilationError::invalid_line_directive); return LEXER_ERROR; } } YY_BREAK case 2: YY_RULE_SETUP #line 98 "ds_lexer.lpp" das_yyfatalerror(yylloc_param,yyscanner,"Unexpected */", CompilationError::unexpected_close_comment); return LEXER_ERROR; YY_BREAK case 3: YY_RULE_SETUP #line 99 "ds_lexer.lpp" BEGIN(c_comment); yyextra->das_c_style_depth = 1; yyextra->das_in_normal = false; YY_BREAK case 4: YY_RULE_SETUP #line 100 "ds_lexer.lpp" das_yyfatalerror(yylloc_param,yyscanner,"Unexpected */", CompilationError::unexpected_close_comment); return LEXER_ERROR; YY_BREAK case 5: YY_RULE_SETUP #line 101 "ds_lexer.lpp" BEGIN(c_comment); yyextra->das_c_style_depth = 1; yyextra->das_in_normal = true; YY_BREAK case 6: YY_RULE_SETUP #line 102 "ds_lexer.lpp" BEGIN(cpp_comment); YY_BREAK case 7: YY_RULE_SETUP #line 103 "ds_lexer.lpp" BEGIN(cpp_comment); YY_BREAK case 8: YY_RULE_SETUP #line 104 "ds_lexer.lpp" YY_BREAK case 9: /* rule 9 can match eol */ YY_RULE_SETUP #line 105 "ds_lexer.lpp" BEGIN(normal); unput('\n'); YY_BREAK case YY_STATE_EOF(cpp_comment): #line 106 "ds_lexer.lpp" BEGIN(normal); YY_BREAK case 10: YY_RULE_SETUP #line 107 "ds_lexer.lpp" yyextra->das_c_style_depth ++; YY_BREAK case 11: YY_RULE_SETUP #line 108 "ds_lexer.lpp" { yyextra->das_c_style_depth --; if ( yyextra->das_c_style_depth==0 ) { if ( yyextra->das_in_normal ) { BEGIN(normal); } else { BEGIN(indent); } } } YY_BREAK case 12: YY_RULE_SETUP #line 118 "ds_lexer.lpp" /* skipping comment body */ YY_BREAK case 13: /* rule 13 can match eol */ YY_RULE_SETUP #line 119 "ds_lexer.lpp" /* skipping comment eol */ YY_BREAK case YY_STATE_EOF(c_comment): #line 120 "ds_lexer.lpp" { das_yyfatalerror(yylloc_param,yyscanner,"end of file encountered inside c-style comment", CompilationError::comment_contains_eof); BEGIN(normal); } YY_BREAK case YY_STATE_EOF(reader): #line 124 "ds_lexer.lpp" { das_yyfatalerror(yylloc_param,yyscanner,"reader constant exceeds file", CompilationError::string_constant_exceeds_file); BEGIN(normal); return END_OF_READ; } YY_BREAK case 14: /* rule 14 can match eol */ YY_RULE_SETUP #line 129 "ds_lexer.lpp" { YYNEWLINE(yyscanner); yylval_param->ch = yytext[0]; return STRING_CHARACTER; } YY_BREAK case 15: YY_RULE_SETUP #line 134 "ds_lexer.lpp" { yylval_param->ch = yytext[0]; return STRING_CHARACTER; } YY_BREAK case 16: YY_RULE_SETUP #line 138 "ds_lexer.lpp" { // assert(nested_sb==0); BEGIN(normal); return END_STRING; } YY_BREAK case 17: YY_RULE_SETUP #line 143 "ds_lexer.lpp" { DAS_ASSERT(yyextra->das_nested_sb==0); yyextra->das_nested_sb ++; BEGIN(normal); return BEGIN_STRING_EXPR; } YY_BREAK case YY_STATE_EOF(strb): #line 149 "ds_lexer.lpp" { das_yyfatalerror(yylloc_param,yyscanner,"string constant exceeds file", CompilationError::string_constant_exceeds_file); BEGIN(normal); return END_STRING; } YY_BREAK case 18: YY_RULE_SETUP #line 154 "ds_lexer.lpp" { return STRING_CHARACTER_ESC; } YY_BREAK case 19: YY_RULE_SETUP #line 157 "ds_lexer.lpp" { yylval_param->ch = yytext[1]; return STRING_CHARACTER; } YY_BREAK case 20: YY_RULE_SETUP #line 161 "ds_lexer.lpp" /* do exactly nothing */ YY_BREAK case 21: /* rule 21 can match eol */ YY_RULE_SETUP #line 162 "ds_lexer.lpp" { yylval_param->ch = *yytext; YYNEWLINE(yyscanner); return STRING_CHARACTER; } YY_BREAK case 22: YY_RULE_SETUP #line 167 "ds_lexer.lpp" { YYTAB(); yylval_param->ch = *yytext; return STRING_CHARACTER; } YY_BREAK case 23: YY_RULE_SETUP #line 172 "ds_lexer.lpp" { yylval_param->ch = *yytext; return STRING_CHARACTER; } YY_BREAK case 24: /* rule 24 can match eol */ YY_RULE_SETUP #line 176 "ds_lexer.lpp" /* skip empty line */ { yyextra->das_current_line_indent = 0; YYNEWLINE(yyscanner); } YY_BREAK case 25: YY_RULE_SETUP #line 180 "ds_lexer.lpp" { yyextra->das_current_line_indent++; #ifdef FLEX_DEBUG printf("[ ], indent=%i\n", yyextra->das_current_line_indent); #endif } YY_BREAK case 26: YY_RULE_SETUP #line 186 "ds_lexer.lpp" { yyextra->das_current_line_indent = (yyextra->das_current_line_indent + yyextra->das_tab_size) & ~(yyextra->das_tab_size-1); #ifdef FLEX_DEBUG printf("\\t, cli=%i\n", yyextra->das_current_line_indent); #endif YYTAB(); } YY_BREAK case 27: /* rule 27 can match eol */ YY_RULE_SETUP #line 193 "ds_lexer.lpp" { yyextra->das_current_line_indent = 0; yyextra->das_need_oxford_comma = true; YYNEWLINE(yyscanner); #ifdef FLEX_DEBUG printf("new line\n"); #endif } YY_BREAK case 28: YY_RULE_SETUP #line 201 "ds_lexer.lpp" { unput(*yytext); YYCOLUMN(yyextra->das_yycolumn--, "UNPUT"); if (yyextra->das_current_line_indent > yyextra->das_indent_level*yyextra->das_tab_size ) { if ( yyextra->das_current_line_indent % yyextra->das_tab_size ) { #ifdef FLEX_DEBUG printf("INVALID INDENT at %i, emit {\n", yyextra->das_current_line_indent); #endif das_yyfatalerror(yylloc_param,yyscanner,"invalid indentation"); // pretend tab was pressed yyextra->das_current_line_indent = (yyextra->das_current_line_indent + yyextra->das_tab_size) & ~(yyextra->das_tab_size-1); } yyextra->das_indent_level++; #ifdef FLEX_DEBUG printf("emit {, cli=%i, indent =%i\n", yyextra->das_current_line_indent, yyextra->das_indent_level); #endif return '{'; } else if (yyextra->das_current_line_indent < yyextra->das_indent_level*yyextra->das_tab_size ) { yyextra->das_indent_level--; #ifdef FLEX_DEBUG printf("emit }, cli=%i, indent =%i\n", yyextra->das_current_line_indent, yyextra->das_indent_level); #endif return '}'; } else { BEGIN(normal); } } YY_BREAK case YY_STATE_EOF(indent): #line 227 "ds_lexer.lpp" { if ( yyextra->g_FileAccessStack.size()==1 ) { if ( yyextra->das_indent_level ) { yyextra->das_indent_level--; unput('\r'); #ifdef FLEX_DEBUG printf("emit }\n"); #endif return '}'; } else { return 0; } } else { yypop_buffer_state(yyscanner); yyextra->g_FileAccessStack.pop_back(); yylineno = yyextra->das_line_no.back(); yyextra->das_line_no.pop_back(); } } YY_BREAK case 29: YY_RULE_SETUP #line 247 "ds_lexer.lpp" /* eat the whitespace */ YY_BREAK case 30: YY_RULE_SETUP #line 248 "ds_lexer.lpp" { YYTAB(); } YY_BREAK case 31: YY_RULE_SETUP #line 251 "ds_lexer.lpp" { /* got the include file name */ auto cfi = yyextra->g_FileAccessStack.back(); string incFileName = yyextra->g_Access->getIncludeFileName(cfi->name,yytext); auto info = yyextra->g_Access->getFileInfo(incFileName); if ( !info ) { das_yyfatalerror(yylloc_param,yyscanner,"can't open "+incFileName); } else { if ( yyextra->das_already_include.find(incFileName) == yyextra->das_already_include.end() ) { yyextra->das_already_include.insert(incFileName); yyextra->g_FileAccessStack.push_back(info); yyextra->das_line_no.push_back(yylineno); yylineno = 1; yypush_buffer_state(YY_CURRENT_BUFFER, yyscanner); const char * src = nullptr; uint32_t len = 0; info->getSourceAndLength(src, len); yy_scan_bytes(src, len, yyscanner); } } BEGIN(normal); } YY_BREAK case 32: YY_RULE_SETUP #line 273 "ds_lexer.lpp" BEGIN(include); YY_BREAK case 33: YY_RULE_SETUP #line 274 "ds_lexer.lpp" /* yyextra->das_need_oxford_comma = false; */ return DAS_FOR; YY_BREAK case 34: YY_RULE_SETUP #line 275 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_WHILE; YY_BREAK case 35: YY_RULE_SETUP #line 276 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_IF; YY_BREAK case 36: YY_RULE_SETUP #line 277 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_STATIC_IF; YY_BREAK case 37: YY_RULE_SETUP #line 278 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_ELIF; YY_BREAK case 38: YY_RULE_SETUP #line 279 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_STATIC_ELIF; YY_BREAK case 39: YY_RULE_SETUP #line 280 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_ELSE; YY_BREAK case 40: YY_RULE_SETUP #line 281 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_FINALLY; YY_BREAK case 41: YY_RULE_SETUP #line 282 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_DEF; YY_BREAK case 42: YY_RULE_SETUP #line 283 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_WITH; YY_BREAK case 43: YY_RULE_SETUP #line 284 "ds_lexer.lpp" return DAS_AKA; YY_BREAK case 44: YY_RULE_SETUP #line 285 "ds_lexer.lpp" return DAS_ASSUME; YY_BREAK case 45: /* rule 45 can match eol */ YY_RULE_SETUP #line 286 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; unput('\n'); return DAS_LET; YY_BREAK case 46: YY_RULE_SETUP #line 287 "ds_lexer.lpp" return DAS_LET; YY_BREAK case 47: /* rule 47 can match eol */ YY_RULE_SETUP #line 288 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; unput('\n'); return DAS_VAR; YY_BREAK case 48: YY_RULE_SETUP #line 289 "ds_lexer.lpp" return DAS_VAR; YY_BREAK case 49: YY_RULE_SETUP #line 290 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_STRUCT; YY_BREAK case 50: YY_RULE_SETUP #line 291 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_CLASS; YY_BREAK case 51: YY_RULE_SETUP #line 292 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_ENUM; YY_BREAK case 52: YY_RULE_SETUP #line 293 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_TRY; YY_BREAK case 53: YY_RULE_SETUP #line 294 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_CATCH; YY_BREAK case 54: YY_RULE_SETUP #line 295 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_TYPEDEF; YY_BREAK case 55: YY_RULE_SETUP #line 296 "ds_lexer.lpp" return DAS_LABEL; YY_BREAK case 56: YY_RULE_SETUP #line 297 "ds_lexer.lpp" return DAS_GOTO; YY_BREAK case 57: YY_RULE_SETUP #line 298 "ds_lexer.lpp" return DAS_MODULE; YY_BREAK case 58: YY_RULE_SETUP #line 299 "ds_lexer.lpp" return DAS_PUBLIC; YY_BREAK case 59: YY_RULE_SETUP #line 300 "ds_lexer.lpp" return DAS_OPTIONS; YY_BREAK case 60: YY_RULE_SETUP #line 301 "ds_lexer.lpp" return DAS_OPERATOR; YY_BREAK case 61: YY_RULE_SETUP #line 302 "ds_lexer.lpp" return DAS_REQUIRE; YY_BREAK case 62: YY_RULE_SETUP #line 303 "ds_lexer.lpp" return DAS_TBLOCK; YY_BREAK case 63: YY_RULE_SETUP #line 304 "ds_lexer.lpp" return DAS_TFUNCTION; YY_BREAK case 64: YY_RULE_SETUP #line 305 "ds_lexer.lpp" return DAS_TLAMBDA; YY_BREAK case 65: YY_RULE_SETUP #line 306 "ds_lexer.lpp" return DAS_GENERATOR; YY_BREAK case 66: YY_RULE_SETUP #line 307 "ds_lexer.lpp" return DAS_TTUPLE; YY_BREAK case 67: YY_RULE_SETUP #line 308 "ds_lexer.lpp" return DAS_TVARIANT; YY_BREAK case 68: YY_RULE_SETUP #line 309 "ds_lexer.lpp" return DAS_CONST; YY_BREAK case 69: YY_RULE_SETUP #line 310 "ds_lexer.lpp" return DAS_CONTINUE; YY_BREAK case 70: YY_RULE_SETUP #line 311 "ds_lexer.lpp" return DAS_WHERE; YY_BREAK case 71: YY_RULE_SETUP #line 312 "ds_lexer.lpp" return DAS_CAST; YY_BREAK case 72: YY_RULE_SETUP #line 313 "ds_lexer.lpp" return DAS_UPCAST; YY_BREAK case 73: YY_RULE_SETUP #line 314 "ds_lexer.lpp" return DAS_PASS; YY_BREAK case 74: YY_RULE_SETUP #line 315 "ds_lexer.lpp" return DAS_REINTERPRET; YY_BREAK case 75: YY_RULE_SETUP #line 316 "ds_lexer.lpp" return DAS_OVERRIDE; YY_BREAK case 76: YY_RULE_SETUP #line 317 "ds_lexer.lpp" return DAS_SEALED; YY_BREAK case 77: YY_RULE_SETUP #line 318 "ds_lexer.lpp" return DAS_ABSTRACT; YY_BREAK case 78: YY_RULE_SETUP #line 319 "ds_lexer.lpp" return DAS_EXPECT; YY_BREAK case 79: YY_RULE_SETUP #line 320 "ds_lexer.lpp" return DAS_TABLE; YY_BREAK case 80: YY_RULE_SETUP #line 321 "ds_lexer.lpp" return DAS_ARRAY; YY_BREAK case 81: YY_RULE_SETUP #line 322 "ds_lexer.lpp" return DAS_ITERATOR; YY_BREAK case 82: YY_RULE_SETUP #line 323 "ds_lexer.lpp" return DAS_IN; YY_BREAK case 83: YY_RULE_SETUP #line 324 "ds_lexer.lpp" return DAS_IMPLICIT; YY_BREAK case 84: YY_RULE_SETUP #line 325 "ds_lexer.lpp" return DAS_EXPLICIT; YY_BREAK case 85: YY_RULE_SETUP #line 326 "ds_lexer.lpp" return DAS_SHARED; YY_BREAK case 86: YY_RULE_SETUP #line 327 "ds_lexer.lpp" return DAS_PRIVATE; YY_BREAK case 87: YY_RULE_SETUP #line 328 "ds_lexer.lpp" return DAS_SMART_PTR; YY_BREAK case 88: YY_RULE_SETUP #line 329 "ds_lexer.lpp" { unput('('); YYCOLUMN(yyextra->das_yycolumn--, "UNPUT ("); return DAS_UNSAFE; } YY_BREAK case 89: YY_RULE_SETUP #line 334 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; return DAS_UNSAFE; YY_BREAK case 90: YY_RULE_SETUP #line 335 "ds_lexer.lpp" return DAS_AS; YY_BREAK case 91: YY_RULE_SETUP #line 336 "ds_lexer.lpp" return DAS_IS; YY_BREAK case 92: YY_RULE_SETUP #line 337 "ds_lexer.lpp" return DAS_DEREF; YY_BREAK case 93: YY_RULE_SETUP #line 338 "ds_lexer.lpp" return DAS_ADDR; YY_BREAK case 94: YY_RULE_SETUP #line 339 "ds_lexer.lpp" return DAS_NULL; YY_BREAK case 95: YY_RULE_SETUP #line 340 "ds_lexer.lpp" return DAS_RETURN; YY_BREAK case 96: YY_RULE_SETUP #line 341 "ds_lexer.lpp" return DAS_YIELD; YY_BREAK case 97: YY_RULE_SETUP #line 342 "ds_lexer.lpp" return DAS_BREAK; YY_BREAK case 98: YY_RULE_SETUP #line 343 "ds_lexer.lpp" return DAS_TYPEINFO; YY_BREAK case 99: YY_RULE_SETUP #line 344 "ds_lexer.lpp" return DAS_TYPE; YY_BREAK case 100: YY_RULE_SETUP #line 345 "ds_lexer.lpp" return DAS_NEWT; YY_BREAK case 101: YY_RULE_SETUP #line 346 "ds_lexer.lpp" return DAS_DELETE; YY_BREAK case 102: YY_RULE_SETUP #line 347 "ds_lexer.lpp" return DAS_TRUE; YY_BREAK case 103: YY_RULE_SETUP #line 348 "ds_lexer.lpp" return DAS_FALSE; YY_BREAK case 104: YY_RULE_SETUP #line 349 "ds_lexer.lpp" return DAS_TAUTO; YY_BREAK case 105: YY_RULE_SETUP #line 350 "ds_lexer.lpp" return DAS_TBOOL; YY_BREAK case 106: YY_RULE_SETUP #line 351 "ds_lexer.lpp" return DAS_TVOID; YY_BREAK case 107: YY_RULE_SETUP #line 352 "ds_lexer.lpp" return DAS_TSTRING; YY_BREAK case 108: YY_RULE_SETUP #line 353 "ds_lexer.lpp" return DAS_TRANGE; YY_BREAK case 109: YY_RULE_SETUP #line 354 "ds_lexer.lpp" return DAS_TURANGE; YY_BREAK case 110: YY_RULE_SETUP #line 355 "ds_lexer.lpp" return DAS_TINT; YY_BREAK case 111: YY_RULE_SETUP #line 356 "ds_lexer.lpp" return DAS_TINT8; YY_BREAK case 112: YY_RULE_SETUP #line 357 "ds_lexer.lpp" return DAS_TINT16; YY_BREAK case 113: YY_RULE_SETUP #line 358 "ds_lexer.lpp" return DAS_TINT64; YY_BREAK case 114: YY_RULE_SETUP #line 359 "ds_lexer.lpp" return DAS_TINT2; YY_BREAK case 115: YY_RULE_SETUP #line 360 "ds_lexer.lpp" return DAS_TINT3; YY_BREAK case 116: YY_RULE_SETUP #line 361 "ds_lexer.lpp" return DAS_TINT4; YY_BREAK case 117: YY_RULE_SETUP #line 362 "ds_lexer.lpp" return DAS_TUINT; YY_BREAK case 118: YY_RULE_SETUP #line 363 "ds_lexer.lpp" return DAS_TBITFIELD; YY_BREAK case 119: YY_RULE_SETUP #line 364 "ds_lexer.lpp" return DAS_TUINT8; YY_BREAK case 120: YY_RULE_SETUP #line 365 "ds_lexer.lpp" return DAS_TUINT16; YY_BREAK case 121: YY_RULE_SETUP #line 366 "ds_lexer.lpp" return DAS_TUINT64; YY_BREAK case 122: YY_RULE_SETUP #line 367 "ds_lexer.lpp" return DAS_TUINT2; YY_BREAK case 123: YY_RULE_SETUP #line 368 "ds_lexer.lpp" return DAS_TUINT3; YY_BREAK case 124: YY_RULE_SETUP #line 369 "ds_lexer.lpp" return DAS_TUINT4; YY_BREAK case 125: YY_RULE_SETUP #line 370 "ds_lexer.lpp" return DAS_TDOUBLE; YY_BREAK case 126: YY_RULE_SETUP #line 371 "ds_lexer.lpp" return DAS_TFLOAT; YY_BREAK case 127: YY_RULE_SETUP #line 372 "ds_lexer.lpp" return DAS_TFLOAT2; YY_BREAK case 128: YY_RULE_SETUP #line 373 "ds_lexer.lpp" return DAS_TFLOAT3; YY_BREAK case 129: YY_RULE_SETUP #line 374 "ds_lexer.lpp" return DAS_TFLOAT4; YY_BREAK case 130: YY_RULE_SETUP #line 375 "ds_lexer.lpp" yylval_param->s = new string(yytext); return NAME; // TODO: track allocations YY_BREAK case 131: YY_RULE_SETUP #line 376 "ds_lexer.lpp" { BEGIN(strb); return BEGIN_STRING; } YY_BREAK case 132: YY_RULE_SETUP #line 380 "ds_lexer.lpp" yylval_param->i = 8; return INTEGER; YY_BREAK case 133: YY_RULE_SETUP #line 381 "ds_lexer.lpp" yylval_param->i = 9; return INTEGER; YY_BREAK case 134: YY_RULE_SETUP #line 382 "ds_lexer.lpp" yylval_param->i = 10; return INTEGER; YY_BREAK case 135: YY_RULE_SETUP #line 383 "ds_lexer.lpp" yylval_param->i = 12; return INTEGER; YY_BREAK case 136: YY_RULE_SETUP #line 384 "ds_lexer.lpp" yylval_param->i = 13; return INTEGER; YY_BREAK case 137: YY_RULE_SETUP #line 385 "ds_lexer.lpp" yylval_param->i = '\\'; return INTEGER; YY_BREAK case 138: YY_RULE_SETUP #line 386 "ds_lexer.lpp" yylval_param->i = int32_t(yytext[1]); return INTEGER; YY_BREAK case 139: YY_RULE_SETUP #line 387 "ds_lexer.lpp" { char * endtext = nullptr; yylval_param->ui64 = strtoull(yytext,&endtext,10); return ( endtext!=(yytext+strlen(yytext)-2) ) ? LEXER_ERROR : UNSIGNED_LONG_INTEGER; } YY_BREAK case 140: YY_RULE_SETUP #line 392 "ds_lexer.lpp" { char * endtext = nullptr; yylval_param->i64 = strtoll(yytext,&endtext,10); return ( endtext!=(yytext+strlen(yytext)-1) ) ? LEXER_ERROR : LONG_INTEGER; } YY_BREAK case 141: YY_RULE_SETUP #line 397 "ds_lexer.lpp" { char * endtext = nullptr; uint64_t uint_const = strtoull(yytext,&endtext,10); if ( endtext!=(yytext+strlen(yytext)-1) ) { return LEXER_ERROR; } else { if ( uint_const>UINT32_MAX ) { das_yyfatalerror(yylloc_param,yyscanner,"integer constant out of range", CompilationError::integer_constant_out_of_range); } yylval_param->ui = uint32_t(uint_const); return UNSIGNED_INTEGER; } } YY_BREAK case 142: YY_RULE_SETUP #line 410 "ds_lexer.lpp" { char * endtext = nullptr; int64_t int_const = strtoll(yytext,&endtext,10); if ( endtext!=(yytext+strlen(yytext)) ) { return LEXER_ERROR; } else { if ( int_const<INT32_MIN || int_const>INT32_MAX ) { das_yyfatalerror(yylloc_param,yyscanner,"integer constant out of range", CompilationError::integer_constant_out_of_range); } yylval_param->i = int32_t(int_const); return INTEGER; } } YY_BREAK case 143: YY_RULE_SETUP #line 424 "ds_lexer.lpp" return sscanf(yytext, "%" SCNx64, &yylval_param->ui64)!=1 ? LEXER_ERROR : UNSIGNED_LONG_INTEGER; YY_BREAK case 144: YY_RULE_SETUP #line 425 "ds_lexer.lpp" return sscanf(yytext, "%" SCNx64, &yylval_param->ui64)!=1 ? LEXER_ERROR : UNSIGNED_LONG_INTEGER; YY_BREAK case 145: YY_RULE_SETUP #line 427 "ds_lexer.lpp" { uint64_t int_const; if ( sscanf(yytext, "%" SCNx64, &int_const)!=1 ) { return LEXER_ERROR; } else { if ( int_const>UINT32_MAX ) { das_yyfatalerror(yylloc_param,yyscanner,"integer constant out of range", CompilationError::integer_constant_out_of_range); } yylval_param->ui = uint32_t(int_const); return UNSIGNED_INTEGER; } } YY_BREAK case 146: YY_RULE_SETUP #line 440 "ds_lexer.lpp" { uint64_t int_const; if ( sscanf(yytext, "%" SCNx64, &int_const)!=1 ) { return LEXER_ERROR; } else { if ( int_const>UINT32_MAX ) { das_yyfatalerror(yylloc_param,yyscanner,"integer constant out of range", CompilationError::integer_constant_out_of_range); } yylval_param->ui = uint32_t(int_const); return UNSIGNED_INTEGER; } } YY_BREAK case 147: YY_RULE_SETUP #line 453 "ds_lexer.lpp" return sscanf(yytext, "%lf", &yylval_param->fd)!=1 ? LEXER_ERROR : FLOAT; YY_BREAK case 148: YY_RULE_SETUP #line 454 "ds_lexer.lpp" return sscanf(yytext, "%lf", &yylval_param->fd)!=1 ? LEXER_ERROR : FLOAT; YY_BREAK case 149: YY_RULE_SETUP #line 455 "ds_lexer.lpp" return sscanf(yytext, "%lf", &yylval_param->fd)!=1 ? LEXER_ERROR : FLOAT; YY_BREAK case 150: YY_RULE_SETUP #line 456 "ds_lexer.lpp" return sscanf(yytext, "%lf", &yylval_param->fd)!=1 ? LEXER_ERROR : FLOAT; YY_BREAK case 151: YY_RULE_SETUP #line 458 "ds_lexer.lpp" return sscanf(yytext, "%lf", &yylval_param->d)!=1 ? LEXER_ERROR : DOUBLE; YY_BREAK case 152: YY_RULE_SETUP #line 459 "ds_lexer.lpp" return sscanf(yytext, "%lf", &yylval_param->d)!=1 ? LEXER_ERROR : DOUBLE; YY_BREAK case 153: YY_RULE_SETUP #line 460 "ds_lexer.lpp" return sscanf(yytext, "%lf", &yylval_param->d)!=1 ? LEXER_ERROR : DOUBLE; YY_BREAK case 154: YY_RULE_SETUP #line 461 "ds_lexer.lpp" return sscanf(yytext, "%lf", &yylval_param->d)!=1 ? LEXER_ERROR : DOUBLE; YY_BREAK case 155: YY_RULE_SETUP #line 462 "ds_lexer.lpp" { if ( !yyextra->das_nested_parentheses ) { das_yyfatalerror(yylloc_param,yyscanner,"mismatching parentheses", CompilationError::mismatching_parentheses); return LEXER_ERROR; } yyextra->das_nested_parentheses --; return ')'; } YY_BREAK case 156: YY_RULE_SETUP #line 470 "ds_lexer.lpp" { yyextra->das_nested_parentheses ++; return '('; } YY_BREAK case 157: YY_RULE_SETUP #line 474 "ds_lexer.lpp" { if ( !yyextra->das_nested_square_braces ) { das_yyfatalerror(yylloc_param,yyscanner,"mismatching square braces", CompilationError::mismatching_parentheses); return LEXER_ERROR; } yyextra->das_nested_square_braces --; return ']'; } YY_BREAK case 158: YY_RULE_SETUP #line 482 "ds_lexer.lpp" { yyextra->das_nested_square_braces ++; return '['; } YY_BREAK case 159: YY_RULE_SETUP #line 486 "ds_lexer.lpp" { if ( yyextra->das_nested_sb ) { yyextra->das_nested_sb --; if ( !yyextra->das_nested_sb ) { BEGIN(strb); return END_STRING_EXPR; } else { return '}'; } } else { if ( !yyextra->das_nested_curly_braces ) { das_yyfatalerror(yylloc_param,yyscanner,"mismatching curly braces", CompilationError::mismatching_curly_bracers); return LEXER_ERROR; } yyextra->das_nested_curly_braces --; return '}'; } } YY_BREAK case 160: YY_RULE_SETUP #line 504 "ds_lexer.lpp" { if ( yyextra->das_nested_sb ) { yyextra->das_nested_sb ++; } else { yyextra->das_nested_curly_braces ++; } return '{'; } YY_BREAK case 161: YY_RULE_SETUP #line 512 "ds_lexer.lpp" return COLCOL; YY_BREAK case 162: YY_RULE_SETUP #line 513 "ds_lexer.lpp" return RPIPE; YY_BREAK case 163: /* rule 163 can match eol */ YY_RULE_SETUP #line 514 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; unput('\n'); return LBPIPE; YY_BREAK case 164: /* rule 164 can match eol */ YY_RULE_SETUP #line 515 "ds_lexer.lpp" yyextra->das_need_oxford_comma = false; unput('\n'); return LBPIPE; YY_BREAK case 165: YY_RULE_SETUP #line 516 "ds_lexer.lpp" { unput('$'); YYCOLUMN(yyextra->das_yycolumn--, "UNPUT $"); if ( yyextra->das_nested_parentheses ) { return LPIPE; } else { yyextra->das_need_oxford_comma = false; return LBPIPE; } } YY_BREAK case 166: YY_RULE_SETUP #line 526 "ds_lexer.lpp" { unput('@'); YYCOLUMN(yyextra->das_yycolumn--, "UNPUT @"); if ( yyextra->das_nested_parentheses ) { return LPIPE; } else { yyextra->das_need_oxford_comma = false; return LBPIPE; } } YY_BREAK case 167: YY_RULE_SETUP #line 536 "ds_lexer.lpp" { unput('@'); unput('@'); YYCOLUMN(yyextra->das_yycolumn-=2, "UNPUT @@"); if ( yyextra->das_nested_parentheses ) { return LFPIPE; } else { yyextra->das_need_oxford_comma = false; return LFPIPE; } } YY_BREAK case 168: YY_RULE_SETUP #line 547 "ds_lexer.lpp" { unput('@'); YYCOLUMN(yyextra->das_yycolumn--, "UNPUT @"); if ( yyextra->das_nested_parentheses ) { return LAPIPE; } else { yyextra->das_need_oxford_comma = false; return LAPIPE; } } YY_BREAK case 169: YY_RULE_SETUP #line 557 "ds_lexer.lpp" return LPIPE; YY_BREAK case 170: YY_RULE_SETUP #line 558 "ds_lexer.lpp" return QQ; YY_BREAK case 171: YY_RULE_SETUP #line 559 "ds_lexer.lpp" { yyextra->das_nested_square_braces ++; return QBRA; } YY_BREAK case 172: YY_RULE_SETUP #line 563 "ds_lexer.lpp" return QDOT; YY_BREAK case 173: YY_RULE_SETUP #line 564 "ds_lexer.lpp" return CLONEEQU; YY_BREAK case 174: YY_RULE_SETUP #line 565 "ds_lexer.lpp" return RARROW; YY_BREAK case 175: YY_RULE_SETUP #line 566 "ds_lexer.lpp" return LARROW; YY_BREAK case 176: YY_RULE_SETUP #line 567 "ds_lexer.lpp" return ADDEQU; YY_BREAK case 177: YY_RULE_SETUP #line 568 "ds_lexer.lpp" return SUBEQU; YY_BREAK case 178: YY_RULE_SETUP #line 569 "ds_lexer.lpp" return DIVEQU; YY_BREAK case 179: YY_RULE_SETUP #line 570 "ds_lexer.lpp" return MULEQU; YY_BREAK case 180: YY_RULE_SETUP #line 571 "ds_lexer.lpp" return MODEQU; YY_BREAK case 181: YY_RULE_SETUP #line 572 "ds_lexer.lpp" return ANDANDEQU; YY_BREAK case 182: YY_RULE_SETUP #line 573 "ds_lexer.lpp" return OROREQU; YY_BREAK case 183: YY_RULE_SETUP #line 574 "ds_lexer.lpp" return XORXOREQU; YY_BREAK case 184: YY_RULE_SETUP #line 575 "ds_lexer.lpp" return ANDAND; YY_BREAK case 185: YY_RULE_SETUP #line 576 "ds_lexer.lpp" return OROR; YY_BREAK case 186: YY_RULE_SETUP #line 577 "ds_lexer.lpp" return XORXOR; YY_BREAK case 187: YY_RULE_SETUP #line 578 "ds_lexer.lpp" return ANDEQU; YY_BREAK case 188: YY_RULE_SETUP #line 579 "ds_lexer.lpp" return OREQU; YY_BREAK case 189: YY_RULE_SETUP #line 580 "ds_lexer.lpp" return XOREQU; YY_BREAK case 190: YY_RULE_SETUP #line 581 "ds_lexer.lpp" return ADDADD; YY_BREAK case 191: YY_RULE_SETUP #line 582 "ds_lexer.lpp" return SUBSUB; YY_BREAK case 192: YY_RULE_SETUP #line 583 "ds_lexer.lpp" return LEEQU; YY_BREAK case 193: YY_RULE_SETUP #line 584 "ds_lexer.lpp" return GREQU; YY_BREAK case 194: YY_RULE_SETUP #line 585 "ds_lexer.lpp" return EQUEQU; YY_BREAK case 195: YY_RULE_SETUP #line 586 "ds_lexer.lpp" return NOTEQU; YY_BREAK case 196: YY_RULE_SETUP #line 587 "ds_lexer.lpp" { if ( yyextra->das_arrow_depth ) { unput('>'); unput('>'); YYCOLUMN(yyextra->das_yycolumn-=2, "UNPUT"); return '>'; } else { return ROTR; } } YY_BREAK case 197: YY_RULE_SETUP #line 597 "ds_lexer.lpp" { if ( yyextra->das_arrow_depth ) { unput('>'); YYCOLUMN(yyextra->das_yycolumn--, "UNPUT"); return '>'; } else { return SHR; } } YY_BREAK case 198: YY_RULE_SETUP #line 606 "ds_lexer.lpp" return ROTL; YY_BREAK case 199: YY_RULE_SETUP #line 607 "ds_lexer.lpp" return SHL; YY_BREAK case 200: YY_RULE_SETUP #line 608 "ds_lexer.lpp" return SHREQU; YY_BREAK case 201: YY_RULE_SETUP #line 609 "ds_lexer.lpp" return SHLEQU; YY_BREAK case 202: YY_RULE_SETUP #line 610 "ds_lexer.lpp" return ROTREQU; YY_BREAK case 203: YY_RULE_SETUP #line 611 "ds_lexer.lpp" return ROTLEQU; YY_BREAK case 204: YY_RULE_SETUP #line 612 "ds_lexer.lpp" return MAPTO; YY_BREAK case 205: YY_RULE_SETUP #line 613 "ds_lexer.lpp" { yyextra->das_nested_square_braces ++; yyextra->das_nested_square_braces ++; return BRABRAB; } YY_BREAK case 206: YY_RULE_SETUP #line 618 "ds_lexer.lpp" { yyextra->das_nested_square_braces ++; yyextra->das_nested_curly_braces ++; return BRACBRB; } YY_BREAK case 207: YY_RULE_SETUP #line 623 "ds_lexer.lpp" { yyextra->das_nested_curly_braces ++; yyextra->das_nested_curly_braces ++; return CBRCBRB; } YY_BREAK case 208: YY_RULE_SETUP #line 628 "ds_lexer.lpp" /* skip white space */ YY_BREAK case 209: YY_RULE_SETUP #line 629 "ds_lexer.lpp" { YYTAB(); } YY_BREAK case 210: /* rule 210 can match eol */ YY_RULE_SETUP #line 632 "ds_lexer.lpp" { YYCOLUMN(yyextra->das_yycolumn = 0, "NEW LINE"); if ( !yyextra->das_nested_parentheses && !yyextra->das_nested_curly_braces && !yyextra->das_nested_square_braces ) { bool ns = ((yyextra->das_current_line_indent!=0) && yyextra->das_need_oxford_comma) || yyextra->das_force_oxford_comma; #ifdef FLEX_DEBUG if ( yyextra->das_force_oxford_comma ) printf ( "forcing oxford comma\n"); #endif yyextra->das_force_oxford_comma = false; yyextra->das_current_line_indent = 0; yyextra->das_need_oxford_comma = true; BEGIN(indent); if ( ns ) { #ifdef FLEX_DEBUG printf("emit ; at EOL\n"); #endif return ';'; } } } YY_BREAK case YY_STATE_EOF(normal): #line 651 "ds_lexer.lpp" { if ( yyextra->g_FileAccessStack.size()==1 ) { YYCOLUMN(yyextra->das_yycolumn = 0,"EOF"); if ( !yyextra->das_nested_parentheses && !yyextra->das_nested_curly_braces && !yyextra->das_nested_square_braces ) { bool ns = (yyextra->das_current_line_indent!=0) && yyextra->das_need_oxford_comma; yyextra->das_current_line_indent = 0; yyextra->das_need_oxford_comma = true; BEGIN(indent); if ( ns ) { #ifdef FLEX_DEBUG printf("emit ; at EOF\n"); #endif return ';'; } } else { return 0; } } else { yypop_buffer_state(yyscanner); yyextra->g_FileAccessStack.pop_back(); yylineno = yyextra->das_line_no.back(); yyextra->das_line_no.pop_back(); } } YY_BREAK case 211: YY_RULE_SETUP #line 675 "ds_lexer.lpp" return *yytext; YY_BREAK case 212: YY_RULE_SETUP #line 677 "ds_lexer.lpp" ECHO; YY_BREAK #line 2992 "ds_lexer.cpp" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(include): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( yywrap( yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; int number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr - 1); for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc( (void *) b->yy_ch_buf, (yy_size_t) (b->yy_buf_size + 2) , yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = NULL; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart( yyin , yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc( (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size , yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); /* "- 2" to take care of EOB's */ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 600 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 600 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; yy_is_jam = (yy_current_state == 599); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT static void yyunput (int c, char * yy_bp , yyscan_t yyscanner) { char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_cp = yyg->yy_c_buf_p; /* undo effects of setting up yytext */ *yy_cp = yyg->yy_hold_char; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ int number_to_move = yyg->yy_n_chars + 2; char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; if ( c == '\n' ){ --yylineno; } yyg->yytext_ptr = yy_bp; yyg->yy_hold_char = *yy_cp; yyg->yy_c_buf_p = yy_cp; } #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ int offset = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr); ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart( yyin , yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( yyscanner ) ) return 0; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); } yy_init_buffer( YY_CURRENT_BUFFER, input_file , yyscanner); yy_load_buffer_state( yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( yyscanner ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) , yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer( b, file , yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * @param yyscanner The scanner object. */ void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree( (void *) b->yy_ch_buf , yyscanner ); yyfree( (void *) b , yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flush_buffer( b , yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; yyensure_buffer_stack(yyscanner); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER , yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { yy_load_buffer_state( yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return NULL; b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = NULL; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer( b , yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (const char * yystr , yyscan_t yyscanner) { return yy_scan_bytes( yystr, (int) strlen(yystr) , yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = (yy_size_t) (_yybytes_len + 2); buf = (char *) yyalloc( n , yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer( buf, n , yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yynoreturn yy_fatal_error (const char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ int yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see yy_switch_to_buffer */ void yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* yylex_init_extra has the same functionality as yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to yyalloc in * the yyextra field. */ int yylex_init_extra( YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = NULL; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = NULL; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = NULL; yyout = NULL; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer( YY_CURRENT_BUFFER , yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ yyfree(yyg->yy_buffer_stack , yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ yyfree( yyg->yy_start_stack , yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, const char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (const char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return malloc(size); } void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return realloc(ptr, size); } void yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 677 "ds_lexer.lpp" void das_yybegin_reader ( yyscan_t yyscanner ) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; BEGIN(reader); } void das_yyend_reader ( yyscan_t yyscanner ) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; BEGIN(normal); } #if DAS_YYDEBUG extern int das_yydebug; #endif void das_yybegin(const char * str, uint32_t len, yyscan_t yyscanner ) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra->g_thisStructure = nullptr; yyextra->das_module_alias.clear(); yyextra->das_already_include.clear(); #if DAS_YYDEBUG das_yydebug = 0; #endif yyextra->das_tab_size = yyextra->das_def_tab_size; yyextra->das_line_no.clear(); YYCOLUMN(yyextra->das_yycolumn = 0,"YYBEGIN"); yyextra->das_current_line_indent = 0; yyextra->das_indent_level = 0; yyextra->das_nested_parentheses = 0; yyextra->das_nested_curly_braces = 0; yyextra->das_nested_square_braces = 0; yyextra->das_nested_sb = 0; yyextra->das_need_oxford_comma = true; yyextra->das_force_oxford_comma = false; yyextra->das_c_style_depth = 0; yyextra->das_arrow_depth = 0; yyextra->g_ReaderMacro = nullptr; yyextra->g_ReaderExpr = nullptr; BEGIN(normal); yy_scan_bytes(str, len, yyscanner); yylineno = 1; } void YYNEWLINE ( yyscan_t yyscanner ) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; YYCOLUMN(yyextra->das_yycolumn = 0,"NEW LINE"); }
28.304153
142
0.631289
profelis
ae321c80dfaadc0e06163c683151a761e76510f2
767
cpp
C++
union_find/test.cpp
fedom/Algorithms
94f9c80c7425d4739be8fb67292deb6b8bb78cc2
[ "MIT" ]
null
null
null
union_find/test.cpp
fedom/Algorithms
94f9c80c7425d4739be8fb67292deb6b8bb78cc2
[ "MIT" ]
null
null
null
union_find/test.cpp
fedom/Algorithms
94f9c80c7425d4739be8fb67292deb6b8bb78cc2
[ "MIT" ]
null
null
null
#include "quick_find_uf.h" #include <stdio.h> #include <time.h> #include <fstream> #include <iostream> int main(int argc, char *argv[]) { char *file = "tinyUF.txt"; if (argc >= 2) file = argv[1]; std::ifstream ifs(file); if (ifs.is_open()) { int total; ifs >> total; std::cout << "total:" << total << std::endl; QuickFindUF uf(total); time_t a = time(NULL); while (!ifs.eof()) { int a; int b; ifs >> a; ifs >> b; uf.Connect(a, b); } time_t d = time(NULL) - a; std::cout << "uf count:" << uf.Count() << std::endl; std::cout << "union time : " << d << std::endl; } ifs.close(); return 0; }
18.707317
60
0.461538
fedom
ae32608389dcce554a973f5f0a4686186be5e47b
2,286
cc
C++
src/ragnarok/ui_window_mgr/ui_window_mgr.cc
sctnightcore/Bourgeon
d2386dc9e141dc4d830337f3ab0a654826819a85
[ "MIT" ]
null
null
null
src/ragnarok/ui_window_mgr/ui_window_mgr.cc
sctnightcore/Bourgeon
d2386dc9e141dc4d830337f3ab0a654826819a85
[ "MIT" ]
null
null
null
src/ragnarok/ui_window_mgr/ui_window_mgr.cc
sctnightcore/Bourgeon
d2386dc9e141dc4d830337f3ab0a654826819a85
[ "MIT" ]
null
null
null
#include "ui_window_mgr.h" #include <iostream> #include "bourgeon.h" bool UIWindowMgr::ProcessPushButton(unsigned long vkey, int new_key, int accurate_key) { return ProcessPushButtonRef(this_, vkey, new_key, accurate_key); } size_t UIWindowMgr::SendMsg(UIMessage message, int val1, int val2, int val3, int val4) { return SendMsgRef(this_, static_cast<int>(message), val1, val2, val3, val4); } bool UIWindowMgr::ProcessPushButtonHook(unsigned long vkey, int new_key, int accurate_key) { auto registrees = Bourgeon::Instance().GetCallbackRegistrees("OnKeyDown"); for (auto registree : registrees) { try { registree(vkey, new_key, accurate_key); } catch (pybind11::error_already_set& error) { std::cerr << error.what() << std::endl; Bourgeon::Instance().UnregisterCallback("OnKeyDown", registree); } } return ProcessPushButtonRef(this, vkey, new_key, accurate_key); } size_t UIWindowMgr::SendMsgHook(UIMessage message, int val1, int val2, int val3, int val4) { if (message != UIMessage::UIM_PUSHINTOCHATHISTORY) return SendMsgRef(this, static_cast<int>(message), val1, val2, val3, val4); auto registrees = Bourgeon::Instance().GetCallbackRegistrees("OnChatMessage"); const char* chat_buffer = reinterpret_cast<const char*>(val1); for (auto registree : registrees) { try { pybind11::str py_chat = pybind11::reinterpret_steal<pybind11::str>( PyUnicode_DecodeLatin1(chat_buffer, strlen(chat_buffer), nullptr)); registree(py_chat); } catch (pybind11::error_already_set& error) { std::cerr << error.what() << std::endl; Bourgeon::Instance().UnregisterCallback("OnChatMessage", registree); } } return SendMsgRef(this, static_cast<int>(message), val1, val2, val3, val4); } // References MethodRef<UIWindowMgr, bool (UIWindowMgr::*)(unsigned long vkey, int new_key, int accurate_key)> UIWindowMgr::ProcessPushButtonRef; MethodRef<UIWindowMgr, size_t (UIWindowMgr::*)(int message, int val1, int val2, int val3, int val4)> UIWindowMgr::SendMsgRef;
37.47541
80
0.651356
sctnightcore
ae32bfab82b547009bae83a8b64a52cb93584c57
7,730
cpp
C++
src/slg/kernels/texture_noise_funcs_kernel.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
src/slg/kernels/texture_noise_funcs_kernel.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
src/slg/kernels/texture_noise_funcs_kernel.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
#include <string> namespace slg { namespace ocl { std::string KernelSource_texture_noise_funcs = "#line 2 \"texture_noise_funcs.cl\"\n" "\n" "/***************************************************************************\n" " * Copyright 1998-2015 by authors (see AUTHORS.txt) *\n" " * *\n" " * This file is part of LuxRender. *\n" " * *\n" " * Licensed under the Apache License, Version 2.0 (the \"License\"); *\n" " * you may not use this file except in compliance with the License. *\n" " * You may obtain a copy of the License at *\n" " * *\n" " * http://www.apache.org/licenses/LICENSE-2.0 *\n" " * *\n" " * Unless required by applicable law or agreed to in writing, software *\n" " * distributed under the License is distributed on an \"AS IS\" BASIS, *\n" " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*\n" " * See the License for the specific language governing permissions and *\n" " * limitations under the License. *\n" " ***************************************************************************/\n" "\n" "//------------------------------------------------------------------------------\n" "// Texture utility functions\n" "//------------------------------------------------------------------------------\n" "\n" "// Perlin Noise Data\n" "#define NOISE_PERM_SIZE 256\n" "__constant int NoisePerm[2 * NOISE_PERM_SIZE] = {\n" " 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96,\n" " 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142,\n" " // Rest of noise permutation table\n" " 8, 99, 37, 240, 21, 10, 23,\n" " 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,\n" " 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,\n" " 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244,\n" " 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196,\n" " 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123,\n" " 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42,\n" " 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n" " 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228,\n" " 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107,\n" " 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254,\n" " 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,\n" " 151, 160, 137, 91, 90, 15,\n" " 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,\n" " 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,\n" " 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,\n" " 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244,\n" " 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196,\n" " 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123,\n" " 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42,\n" " 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n" " 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228,\n" " 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107,\n" " 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254,\n" " 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180\n" "};\n" "\n" "float Grad(int x, int y, int z, float dx, float dy, float dz) {\n" " const int h = NoisePerm[NoisePerm[NoisePerm[x] + y] + z] & 15;\n" " const float u = h < 8 || h == 12 || h == 13 ? dx : dy;\n" " const float v = h < 4 || h == 12 || h == 13 ? dy : dz;\n" " return ((h & 1) ? -u : u) + ((h & 2) ? -v : v);\n" "}\n" "\n" "float NoiseWeight(float t) {\n" " const float t3 = t * t * t;\n" " const float t4 = t3 * t;\n" " return 6.f * t4 * t - 15.f * t4 + 10.f * t3;\n" "}\n" "\n" "float Noise(float x, float y, float z) {\n" " // Compute noise cell coordinates and offsets\n" " int ix = Floor2Int(x);\n" " int iy = Floor2Int(y);\n" " int iz = Floor2Int(z);\n" " const float dx = x - ix, dy = y - iy, dz = z - iz;\n" " // Compute gradient weights\n" " ix &= (NOISE_PERM_SIZE - 1);\n" " iy &= (NOISE_PERM_SIZE - 1);\n" " iz &= (NOISE_PERM_SIZE - 1);\n" " const float w000 = Grad(ix, iy, iz, dx, dy, dz);\n" " const float w100 = Grad(ix + 1, iy, iz, dx - 1, dy, dz);\n" " const float w010 = Grad(ix, iy + 1, iz, dx, dy - 1, dz);\n" " const float w110 = Grad(ix + 1, iy + 1, iz, dx - 1, dy - 1, dz);\n" " const float w001 = Grad(ix, iy, iz + 1, dx, dy, dz - 1);\n" " const float w101 = Grad(ix + 1, iy, iz + 1, dx - 1, dy, dz - 1);\n" " const float w011 = Grad(ix, iy + 1, iz + 1, dx, dy - 1, dz - 1);\n" " const float w111 = Grad(ix + 1, iy + 1, iz + 1, dx - 1, dy - 1, dz - 1);\n" " // Compute trilinear interpolation of weights\n" " const float wx = NoiseWeight(dx);\n" " const float wy = NoiseWeight(dy);\n" " const float wz = NoiseWeight(dz);\n" " const float x00 = Lerp(wx, w000, w100);\n" " const float x10 = Lerp(wx, w010, w110);\n" " const float x01 = Lerp(wx, w001, w101);\n" " const float x11 = Lerp(wx, w011, w111);\n" " const float y0 = Lerp(wy, x00, x10);\n" " const float y1 = Lerp(wy, x01, x11);\n" " return Lerp(wz, y0, y1);\n" "}\n" "\n" "float Noise3(const float3 P) {\n" " return Noise(P.x, P.y, P.z);\n" "}\n" "\n" "float FBm(const float3 P, const float omega, const int maxOctaves) {\n" " // Compute number of octaves for anti-aliased FBm\n" " const float foctaves = (float)maxOctaves;\n" " const int octaves = Floor2Int(foctaves);\n" " // Compute sum of octaves of noise for FBm\n" " float sum = 0.f, lambda = 1.f, o = 1.f;\n" " for (int i = 0; i < octaves; ++i) {\n" " sum += o * Noise3(lambda * P);\n" " lambda *= 1.99f;\n" " o *= omega;\n" " }\n" " const float partialOctave = foctaves - (float)octaves;\n" " sum += o * SmoothStep(.3f, .7f, partialOctave) *\n" " Noise3(lambda * P);\n" " return sum;\n" "}\n" "\n" "float Turbulence(const float3 P, const float omega, const int maxOctaves) {\n" " // Compute number of octaves for anti-aliased FBm\n" " const float foctaves = (float)maxOctaves;\n" " const int octaves = Floor2Int(foctaves);\n" " // Compute sum of octaves of noise for turbulence\n" " float sum = 0.f, lambda = 1.f, o = 1.f;\n" " for (int i = 0; i < octaves; ++i) {\n" " sum += o * fabs(Noise3(lambda * P));\n" " lambda *= 1.99f;\n" " o *= omega;\n" " }\n" " const float partialOctave = foctaves - (float)(octaves);\n" " sum += o * SmoothStep(.3f, .7f, partialOctave) *\n" " fabs(Noise3(lambda * P));\n" "\n" " // finally, add in value to account for average value of fabsf(Noise())\n" " // (~0.2) for the remaining octaves...\n" " sum += (maxOctaves - foctaves) * 0.2f;\n" "\n" " return sum;\n" "}\n" ; } }
52.22973
103
0.520181
DavidBluecame
ae33f2a025285a2f707a6f723ac0a96c58b54f7e
10,060
cpp
C++
LEGACY/src/librapid/array/multiarray_constructors.cpp
NervousNullPtr/librapid
2a8f4baccf479138097d5b4ee9e6e060ecab55db
[ "MIT" ]
null
null
null
LEGACY/src/librapid/array/multiarray_constructors.cpp
NervousNullPtr/librapid
2a8f4baccf479138097d5b4ee9e6e060ecab55db
[ "MIT" ]
null
null
null
LEGACY/src/librapid/array/multiarray_constructors.cpp
NervousNullPtr/librapid
2a8f4baccf479138097d5b4ee9e6e060ecab55db
[ "MIT" ]
null
null
null
#include <librapid/array/multiarray.hpp> #include <librapid/utils/array_utils.hpp> namespace librapid { RawArray validRawArray = RawArray {(int64_t *)nullptr, Datatype::VALIDNONE, Accelerator::CPU}; #ifdef LIBRAPID_HAS_CUDA # ifdef LIBRAPID_CUDA_STREAM cudaStream_t cudaStream; bool streamCreated = false; # endif // LIBRAPID_CUDA_STREAM #endif // LIBRAPID_HAS_CUDA Array::Array() { initializeCudaStream(); } Array::Array(const Extent &extent, Datatype dtype, Accelerator location) { initializeCudaStream(); if (extent.containsAutomatic()) { throw std::invalid_argument( "Cannot create an Array from an Extent" " containing automatic values. " "Extent was " + extent.str()); } constructNew(extent, Stride::fromExtent(extent), dtype, location); } Array::Array(const Array &other, Datatype dtype, Accelerator locn) { // Quick return if possible if (other.m_references == nullptr) { return; } if (dtype == Datatype::NONE) { dtype = other.m_dtype; } if (locn == Accelerator::NONE) { locn = other.m_location; } if (dtype != other.m_dtype || locn != other.m_location) { // Must cast other to the correct value Array tmp = other.clone(dtype, locn); m_location = tmp.m_location; m_dtype = tmp.m_dtype; m_dataStart = tmp.m_dataStart; m_dataOrigin = tmp.m_dataOrigin; m_references = tmp.m_references; m_extent = tmp.m_extent; m_stride = tmp.m_stride; m_isScalar = tmp.m_isScalar; m_isChild = tmp.m_isChild; increment(); return; } m_location = other.m_location; m_dtype = other.m_dtype; m_dataStart = other.m_dataStart; m_dataOrigin = other.m_dataOrigin; m_references = other.m_references; m_extent = other.m_extent; m_stride = other.m_stride; m_isScalar = other.m_isScalar; m_isChild = other.m_isChild; increment(); } Array::Array(bool val, Datatype dtype, Accelerator locn) { initializeCudaStream(); constructNew(Extent(1), Stride(1), dtype, locn); m_isScalar = true; if (locn == Accelerator::CPU) { std::visit([&](auto *data) { *data = val; }, m_dataStart); } #ifdef LIBRAPID_HAS_CUDA else { int64_t tmpVal = val; RawArray temp = RawArray {m_dataStart, dtype, locn}; rawArrayMemcpy( temp, {&tmpVal, Datatype::INT64, Accelerator::CPU}, 1); } #else else { throw std::invalid_argument( "CUDA support was not enabled, " "so a value cannot be created on the GPU"); } #endif // LIBRAPID_HAS_CUDA } Array::Array(float val, Datatype dtype, Accelerator locn) { initializeCudaStream(); constructNew(Extent(1), Stride(1), dtype, locn); m_isScalar = true; if (locn == Accelerator::CPU) { std::visit([&](auto *data) { *data = val; }, m_dataStart); } #ifdef LIBRAPID_HAS_CUDA else { RawArray temp = RawArray {m_dataStart, dtype, locn}; rawArrayMemcpy( temp, {&val, Datatype::FLOAT32, Accelerator::CPU}, 1); } #else else { throw std::invalid_argument( "CUDA support was not enabled, " "so a value cannot be created on the GPU"); } #endif // LIBRAPID_HAS_CUDA } Array::Array(double val, Datatype dtype, Accelerator locn) { initializeCudaStream(); constructNew(Extent(1), Stride(1), dtype, locn); m_isScalar = true; if (locn == Accelerator::CPU) { std::visit([&](auto *data) { *data = val; }, m_dataStart); } #ifdef LIBRAPID_HAS_CUDA else { RawArray temp = RawArray {m_dataStart, dtype, locn}; rawArrayMemcpy( temp, {&val, Datatype::FLOAT64, Accelerator::CPU}, 1); } #else else { throw std::invalid_argument( "CUDA support was not enabled, " "so a value cannot be created on the GPU"); } #endif // LIBRAPID_HAS_CUDA } Array &Array::operator=(const Array &other) { // Quick return if possible if (this == &other) return *this; if (other.m_references == nullptr) { return *this; } if (!m_isChild) { // If the array is not a child, decrement it and copy the relevant // data, then increment this decrement(); m_location = other.m_location; m_dtype = other.m_dtype; m_dataStart = other.m_dataStart; m_dataOrigin = other.m_dataOrigin; m_references = other.m_references; m_extent = other.m_extent; m_stride = other.m_stride; m_isScalar = other.m_isScalar; m_isChild = other.m_isChild; increment(); } else { // The array is a child, so the data MUST be copied by value, not by // reference // Ensure the Arrays have the same extent if (m_extent != other.m_extent) { std::string err = fmt::format("Cannot set child array with {} to {}", m_extent.str(), other.m_extent.str()); throw std::invalid_argument(err); } if (m_stride.isContiguous() && other.m_stride.isContiguous()) { // If both arrays are contiguous in memory, copy the data with // memcpy to speed things up rawArrayMemcpy(createRaw(), other.createRaw(), m_extent.size()); } else { applyUnaryOp(*this, other, ops::Copy()); } // No need to increment as the data was copied directly } return *this; // if (m_references == nullptr) { // constructNew( // other.m_extent, other.m_stride, other.m_dtype, // other.m_location); } else { // // Array already exists, so check if it must be reallocated // // // This condition might be needed? => || m_dtype != // other.m_dtype if (!m_isChild && m_extent != // other.m_extent) // { // // Extents are not equal, so memory can not be safely // copied decrement(); // constructNew(other.m_extent, other.m_stride, // other.m_dtype, other.m_location); m_isScalar // = // other.m_isScalar; } else { increment(); // } // } // // if (!m_isChild) { // m_extent = other.m_extent; // m_stride = other.m_stride; // } // // // Attempt to copy the data from other into *this // if (m_stride.isContiguous() && other.m_stride.isContiguous()) { // // auto raw = createRaw(); // rawArrayMemcpy(createRaw(), other.createRaw(), // m_extent.size()); } else { throw // std::runtime_error("Haven't gotten to this yet..."); // } // // m_isScalar = other.m_isScalar; // m_dtype = other.m_dtype; // m_location = other.m_location; // // return *this; } Array &Array::operator=(bool val) { if (m_isChild && !m_isScalar) { throw std::invalid_argument( "Cannot set an array with more than zero" " dimensions to a scalar value. Array must" " have zero dimensions (i.e. scalar)"); } if (!m_isChild) { if (m_references != nullptr) { decrement(); } constructNew( Extent(1), Stride(1), Datatype::INT64, Accelerator::CPU); } int64_t tmpVal = val; auto raw = createRaw(); rawArrayMemcpy( raw, RawArray {&tmpVal, Datatype::INT64, Accelerator::CPU}, 1); m_isScalar = true; return *this; } Array &Array::operator=(float val) { if (m_isChild && !m_isScalar) { throw std::invalid_argument( "Cannot set an array with more than zero" " dimensions to a scalar value. Array must" " have zero dimensions (i.e. scalar)"); } if (!m_isChild) { if (m_references != nullptr) { decrement(); } constructNew( Extent(1), Stride(1), Datatype::FLOAT32, Accelerator::CPU); } auto raw = createRaw(); rawArrayMemcpy( raw, RawArray {&val, Datatype::FLOAT32, Accelerator::CPU}, 1); m_isScalar = true; return *this; } Array &Array::operator=(double val) { if (m_isChild && !m_isScalar) { throw std::invalid_argument( "Cannot set an array with more than zero" " dimensions to a scalar value. Array must" " have zero dimensions (i.e. scalar)"); } if (!m_isChild) { if (m_references != nullptr) { decrement(); } constructNew( Extent(1), Stride(1), Datatype::FLOAT64, Accelerator::CPU); } auto raw = createRaw(); rawArrayMemcpy( raw, RawArray {&val, Datatype::FLOAT64, Accelerator::CPU}, 1); m_isScalar = true; return *this; } Array &Array::operator=(Complex<double> val) { if (m_isChild && !m_isScalar) { throw std::invalid_argument( "Cannot set an array with more than zero" " dimensions to a scalar value. Array must" " have zero dimensions (i.e. scalar)"); } if (!m_isChild) { if (m_references != nullptr) { decrement(); } constructNew( Extent(1), Stride(1), Datatype::CFLOAT64, Accelerator::CPU); } auto raw = createRaw(); rawArrayMemcpy( raw, RawArray {&val, Datatype::FLOAT64, Accelerator::CPU}, 1); m_isScalar = true; return *this; } Array::~Array() { decrement(); } void Array::constructNew(const Extent &e, const Stride &s, const Datatype &dtype, const Accelerator &location) { // Is scalar if extent is [0] bool isScalar = (e.ndim() == 1) && (e[0] == 0); // Construct members m_location = location; m_dtype = dtype; // If array is scalar, allocate "sizeof(dtype)" bytes -- e.size() is 0 auto raw = RawArray {m_dataStart, dtype, location}; m_dataStart = rawArrayMalloc(raw, e.size() + isScalar).data; m_dataOrigin = m_dataStart; m_references = new std::atomic<int64_t>(1); m_extent = e; m_stride = s; m_isScalar = isScalar; m_isChild = false; } void Array::constructHollow(const Extent &e, const Stride &s, const Datatype &dtype, const Accelerator &location) { m_extent = e; m_stride = s; m_dtype = dtype; m_location = location; m_stride.setContiguity(m_stride.checkContiguous(m_extent)); if (ndim() > LIBRAPID_MAX_DIMS) { throw std::domain_error("Cannot create an array with " + std::to_string(ndim()) + " dimensions. The " "maximum allowed number of dimensions is " + std::to_string(LIBRAPID_MAX_DIMS)); } } Array zerosLike(const Array &other) { Array res(other.extent(), other.dtype(), other.location()); res.fill(0); return res; } Array onesLike(const Array &other) { Array res(other.extent(), other.dtype(), other.location()); res.fill(1); return res; } } // namespace librapid
26.826667
75
0.647614
NervousNullPtr
ae36c8f83d840e914ead13a81dc0fa31d4615f64
49
cpp
C++
SpaceStationRescueSouls/SpaceStationRescueSouls/src/component/CollisionWorld.cpp
Neversee-Productions/Space-Station-Rescue-Souls
48621dd8ddf9c6282669b1547ebca0af56ef7fa9
[ "MIT" ]
1
2020-03-24T04:40:18.000Z
2020-03-24T04:40:18.000Z
SpaceStationRescueSouls/SpaceStationRescueSouls/src/component/CollisionWorld.cpp
Neversee-Productions/Space-Station-Rescue-Souls
48621dd8ddf9c6282669b1547ebca0af56ef7fa9
[ "MIT" ]
null
null
null
SpaceStationRescueSouls/SpaceStationRescueSouls/src/component/CollisionWorld.cpp
Neversee-Productions/Space-Station-Rescue-Souls
48621dd8ddf9c6282669b1547ebca0af56ef7fa9
[ "MIT" ]
1
2020-03-24T04:40:19.000Z
2020-03-24T04:40:19.000Z
#include "stdafx.h" #include "CollisionWorld.h"
16.333333
27
0.734694
Neversee-Productions
ae3ec18d2a119012ad56ed7f81928f0c4bcf9c5d
4,579
cpp
C++
frameworks/compile/mclinker/tools/lite/main.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
frameworks/compile/mclinker/tools/lite/main.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
frameworks/compile/mclinker/tools/lite/main.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
//===- ld-lite.cpp --------------------------------------------------------===// // // The MCLinker Project // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <lite/PreferenceOptions.h> #include <lite/TripleOptions.h> #include <lite/DynamicSectionOptions.h> #include <lite/OutputFormatOptions.h> #include <lite/SearchPathOptions.h> #include <lite/OptimizationOptions.h> #include <lite/SymbolOptions.h> #include <lite/TargetControlOptions.h> #include <lite/ScriptOptions.h> #include <lite/PositionalOptions.h> #include <mcld/Module.h> #include <mcld/Environment.h> #include <mcld/LinkerConfig.h> #include <mcld/LinkerScript.h> #include <mcld/Linker.h> #include <mcld/IRBuilder.h> #include <mcld/MC/InputAction.h> #include <mcld/Support/raw_ostream.h> #include <mcld/Support/MsgHandling.h> #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/Signals.h> #include <string> #include <cassert> /// configure linker static inline bool ConfigLinker(int pArgc, char* pArgv[], const char* pName, mcld::Module& pModule, mcld::LinkerScript& pScript, mcld::LinkerConfig& pConfig, mcld::IRBuilder& pBuilder, std::vector<mcld::InputAction*>& pInputActions) { mcld::PreferenceOptions preference; mcld::TripleOptions triple; mcld::DynamicSectionOptions dynamic_section; mcld::OutputFormatOptions output_format; mcld::SearchPathOptions search_path; mcld::OptimizationOptions optimization; mcld::SymbolOptions symbol; mcld::TargetControlOptions target_control; mcld::ScriptOptions script; mcld::PositionalOptions positional; llvm::cl::ParseCommandLineOptions(pArgc, pArgv, pName); if (!preference.parse(pConfig)) return false; if (!triple.parse(pArgc, pArgv, pConfig)) return false; if (!dynamic_section.parse(pConfig, pScript)) return false; if (!output_format.parse(pModule, pConfig)) return false; if (!search_path.parse(pConfig, pScript)) return false; if (!optimization.parse(pConfig)) return false; if (!symbol.parse(pConfig)) return false; if (!target_control.parse(pConfig)) return false; if (!script.parse(pScript)) return false; if (!positional.parse(pInputActions, pConfig, pScript)) return false; if (pConfig.options().soname().empty()) pConfig.options().setSOName(pModule.name()); return true; } static inline bool InitializeInputs(mcld::IRBuilder& pBuilder, std::vector<mcld::InputAction*>& pInputActions) { for (std::vector<mcld::InputAction*>::iterator action = pInputActions.begin(), actionEnd = pInputActions.end(); action != actionEnd; ++action) { assert(*action != NULL); (*action)->activate(pBuilder.getInputBuilder()); delete *action; } if (pBuilder.getInputBuilder().isInGroup()) { mcld::fatal(mcld::diag::fatal_forbid_nest_group); return false; } return true; } int main(int argc, char* argv[]) { llvm::sys::PrintStackTraceOnErrorSignal(); llvm::llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. mcld::Initialize(); mcld::LinkerScript script; mcld::LinkerConfig config; mcld::Module module(script); mcld::IRBuilder builder(module, config); std::vector<mcld::InputAction*> input_actions; if (!ConfigLinker(argc, argv, "MCLinker\n", module, script, config, builder, input_actions)) { mcld::errs() << argv[0] << ": failed to process linker options from command line!\n"; return 1; } mcld::Linker linker; if (!linker.emulate(script, config)) { mcld::errs() << argv[0] << ": failed to emulate target!\n"; return 1; } // FIXME: is it possible to have a lightweight MCLinker pass? if (!InitializeInputs(builder, input_actions)) { mcld::errs() << argv[0] << ": failed to initialize input tree!\n"; return 1; } if (!linker.link(module, builder)) { mcld::errs() << argv[0] << ": failed to link objects!\n"; return 1; } if (!linker.emit(module.name())) { mcld::errs() << argv[0] << ": failed to emit output!\n"; return 1; } mcld::Finalize(); return 0; }
28.440994
80
0.618257
touxiong88
ae447a75f3782605d88fb73540042d950f0cd565
4,680
hpp
C++
common/phonebook.hpp
canaryinthemines/ILLIXR
1e3d9b2a4c56f6bf311cbeda83171359e285b10e
[ "NCSA", "MIT" ]
null
null
null
common/phonebook.hpp
canaryinthemines/ILLIXR
1e3d9b2a4c56f6bf311cbeda83171359e285b10e
[ "NCSA", "MIT" ]
null
null
null
common/phonebook.hpp
canaryinthemines/ILLIXR
1e3d9b2a4c56f6bf311cbeda83171359e285b10e
[ "NCSA", "MIT" ]
null
null
null
#pragma once #include <typeindex> #include <stdexcept> #include <iostream> #include <cassert> #include <mutex> #include <memory> #include <unordered_map> namespace ILLIXR { /** * @brief A [service locator][1] for ILLIXR. * * This will be explained through an exmaple: Suppose one dynamically-loaded plugin, `A_plugin`, * needs a service, `B_service`, provided by another, `B_plugin`. `A_plugin` cannot statically * construct a `B_service`, because the implementation `B_plugin` is dynamically * loaded. However, `B_plugin` can register an implementation of `B_service` when it is loaded, * and `A_plugin` can lookup that implementation without knowing it. * * `B_service.hpp` in `common`: * \code{.cpp} * class B_service { * public: * virtual void frobnicate(foo data) = 0; * }; * \endcode * * `B_plugin.hpp`: * \code{.cpp} * class B_impl : public B_service { * public: * virtual void frobnicate(foo data) { * // ... * } * }; * void blah_blah(phonebook* pb) { * // Expose `this` as the "official" implementation of `B_service` for this run. * pb->register_impl<B_service>(new B_impl); * } * \endcode * * `A_plugin.cpp`: * \code{.cpp} * #include "B_service.hpp" * void blah_blah(phonebook* pb) { * B_service* b = pb->lookup_impl<B_service>(); * b->frobnicate(data); * } * \endcode * * If the implementation of `B_service` is not known to `A_plugin` (the usual case), `B_service * should be an [abstract class][2]. In either case `B_service` should be in `common`, so both * plugins can refer to it. * * One could even selectively return a different implementation of `B_service` depending on the * caller (through the parameters), but we have not encountered the need for that yet. * * [1]: https://en.wikipedia.org/wiki/Service_locator_pattern * [2]: https://en.wikibooks.org/wiki/C%2B%2B_Programming/Classes/Abstract_Classes */ class phonebook { /* Proof of thread-safety: - Since all instance members are private, acquiring a lock in each method implies the class is datarace-free. - Since there is only one lock and this does not call any code containing locks, this is deadlock-free. - Both of these methods are only used during initialization, so the locks are not contended in steady-state. However, to write a correct program, one must also check the thread-safety of the elements inserted into this class by the caller. */ public: /** * @brief A 'service' that can be registered in the phonebook. * * These must be 'destructible', have a virtual destructor that phonebook can call in its * destructor. */ class service { public: /** */ virtual ~service() { } }; /** * @brief Registers an implementation of @p baseclass for future calls to lookup. * * Safe to be called from any thread. * * The implementation will be owned by phonebook (phonebook calls `delete`). */ template <typename specific_service> void register_impl(std::shared_ptr<specific_service> impl) { const std::lock_guard<std::mutex> lock{_m_mutex}; const std::type_index type_index = std::type_index(typeid(specific_service)); #ifndef NDEBUG std::cerr << "Register " << type_index.name() << std::endl; #endif assert(_m_registry.count(type_index) == 0); _m_registry.try_emplace(type_index, impl); } /** * @brief Look up an implementation of @p specific_service, which should be registered first. * * Safe to be called from any thread. * * Do not call `delete` on the returned object; it is still managed by phonebook. * * @throws if an implementation is not already registered. */ template <typename specific_service> std::shared_ptr<specific_service> lookup_impl() const { const std::lock_guard<std::mutex> lock{_m_mutex}; const std::type_index type_index = std::type_index(typeid(specific_service)); #ifndef NDEBUG // if this assert fails, and there are no duplicate base classes, ensure the hash_code's are unique. if (_m_registry.count(type_index) != 1) { throw std::runtime_error{"Attempted to lookup an unregistered implementation " + std::string{type_index.name()}}; } #endif std::shared_ptr<service> this_service = _m_registry.at(type_index); assert(this_service); std::shared_ptr<specific_service> this_specific_service = std::dynamic_pointer_cast<specific_service>(this_service); assert(this_specific_service); return this_specific_service; } private: std::unordered_map<std::type_index, const std::shared_ptr<service>> _m_registry; mutable std::mutex _m_mutex; }; }
32.275862
119
0.693162
canaryinthemines
ae458514d58e34cb953920fcf571b4c06af3bdc4
5,176
cpp
C++
mars/uwpproj/uwpStnCallback.cpp
jonetomtom/mars
3f11714e0aee826eb12bfd52496b59675125204a
[ "BSD-2-Clause", "Apache-2.0" ]
17,104
2016-12-28T07:45:54.000Z
2022-03-31T07:02:52.000Z
mars/uwpproj/uwpStnCallback.cpp
jonetomtom/mars
3f11714e0aee826eb12bfd52496b59675125204a
[ "BSD-2-Clause", "Apache-2.0" ]
964
2016-12-28T08:13:33.000Z
2022-03-31T13:36:40.000Z
mars/uwpproj/uwpStnCallback.cpp
pengjinning/mars
227aff64a5b819555091a7d6eae6727701e9fff0
[ "Apache-2.0", "BSD-2-Clause" ]
3,568
2016-12-28T07:47:46.000Z
2022-03-31T02:13:19.000Z
#include "uwpStnCallback.h" #include "runtime2cs.h" #include "runtime_utils.h" using namespace mars; Platform::Array<uint8>^ bufferToPlatformArray(const AutoBuffer & autoBuffer) { const void * buffer = autoBuffer.Ptr(); int iLen = autoBuffer.Length(); if (buffer == nullptr) return ref new Platform::Array<uint8>(0); Platform::Array<uint8>^ arrayBuffer = ref new Platform::Array<uint8>(iLen); uint8 * ptr = (uint8*)buffer; for (int i = 0; i< iLen; i++) { arrayBuffer[i] = ptr[i]; } return arrayBuffer; } bool appendPlatfomrBufferToAutoBuffer(AutoBuffer& autoBuffer, Platform::Array<uint8>^ platformBuffer) { if (platformBuffer == nullptr || platformBuffer->Length <= 0) { return false; } if (autoBuffer.Capacity() < (size_t)platformBuffer->Length) { autoBuffer.AddCapacity(platformBuffer->Length); } autoBuffer.Write(platformBuffer->Data, platformBuffer->Length); return true; } bool uwpStnCallback::MakesureAuthed() { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return false; } return callback->MakesureAuthed(); } void uwpStnCallback::TrafficData(ssize_t _send, ssize_t _recv) { } std::vector<std::string> uwpStnCallback::OnNewDns(const std::string& host) { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); std::vector<std::string> iplist; if (nullptr == callback) { return iplist; } Platform::Array<Platform::String^>^ list = callback->OnNewDns(stdstring2String(host)); for each (Platform::String^ cstring in list) { std::string tmp = String2stdstring(cstring); if (tmp.length() > 0) { iplist.push_back(tmp); } } return iplist; } void uwpStnCallback::OnPush(int32_t cmdid, const AutoBuffer & msgpayload) { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return; } Platform::Array<uint8>^ buffer = bufferToPlatformArray(msgpayload); callback->OnPush(cmdid, buffer); } bool uwpStnCallback::Req2Buf(int32_t taskid, void * const user_context, AutoBuffer & outbuffer, int & error_code, const int channel_select) { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return false; } Req2BufRet^ retInfo = callback->Req2Buf(taskid, (int)user_context, error_code, channel_select); error_code = retInfo->nErrCode; appendPlatfomrBufferToAutoBuffer(outbuffer, retInfo->outbuffer); return retInfo->bRet; } int uwpStnCallback::Buf2Resp(int32_t taskid, void * const user_context, const AutoBuffer & inbuffer, int & error_code, const int channel_select) { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return 0; } Platform::Array<uint8>^ buffer = bufferToPlatformArray(inbuffer); Buf2RespRet^ retInfo = callback->Buf2Resp(taskid, (int)user_context, buffer, error_code, channel_select); error_code = retInfo->nErrCode; return retInfo->bRet; } int uwpStnCallback::OnTaskEnd(int32_t taskid, void * const user_context, int error_type, int error_code) { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return 0; } return callback->OnTaskEnd(taskid, (int)user_context, error_type, error_code); } void uwpStnCallback::ReportConnectStatus(int status, int longlink_status) { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return; } callback->ReportConnectStatus(status, longlink_status); } int uwpStnCallback::GetLonglinkIdentifyCheckBuffer(AutoBuffer & identify_buffer, AutoBuffer & buffer_hash, int32_t & cmdid) { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return false; } GetLonglinkIdentifyRet^ retInfo = callback->GetLonglinkIdentifyCheckBuffer(); cmdid = retInfo->cmdid; appendPlatfomrBufferToAutoBuffer(identify_buffer, retInfo->identify_buffer); appendPlatfomrBufferToAutoBuffer(buffer_hash, retInfo->buffer_hash); return (int)(retInfo->nRet); } bool uwpStnCallback::OnLonglinkIdentifyResponse(const AutoBuffer & response_buffer, const AutoBuffer & identify_buffer_hash) { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return false; } Platform::Array<uint8>^ platBufferResponse = bufferToPlatformArray(response_buffer); Platform::Array<uint8>^ platBufferHash = bufferToPlatformArray(identify_buffer_hash); return callback->OnLonglinkIdentifyResponse(platBufferResponse, platBufferHash); } void uwpStnCallback::RequestSync() { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return; } callback->RequestSync(); } bool uwpStnCallback::IsLogoned() { ICallback_Comm^ callback = Runtime2Cs_Comm::Singleton()->GetCallBack(); if (nullptr == callback) { return false; } return callback->IsLogoned(); }
24.074419
145
0.713679
jonetomtom
ae492e4348816dbcaed0271fbc78e88ccbe1e4aa
1,270
cpp
C++
MKE/src/MKE/SpriteBatch.cpp
tMario2111/MKE
a5adf18d41f08b35c31e3ddb2679e5cad62da07f
[ "MIT" ]
3
2021-11-03T07:43:07.000Z
2022-03-10T09:45:15.000Z
MKE/src/MKE/SpriteBatch.cpp
tMario2111/MKE
a5adf18d41f08b35c31e3ddb2679e5cad62da07f
[ "MIT" ]
null
null
null
MKE/src/MKE/SpriteBatch.cpp
tMario2111/MKE
a5adf18d41f08b35c31e3ddb2679e5cad62da07f
[ "MIT" ]
null
null
null
#include "SpriteBatch.h" namespace mke { SpriteBatch::SpriteBatch() : batch(sf::PrimitiveType::Quads) { } void SpriteBatch::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(batch, states); } void SpriteBatch::append(const sf::Sprite& sprite) { sf::FloatRect texture_rect = static_cast<sf::FloatRect>(sprite.getTextureRect()); sf::Vertex verts[4]; verts[0].texCoords = sf::Vector2f(texture_rect.left, texture_rect.top); verts[1].texCoords = sf::Vector2f(texture_rect.left + texture_rect.width, texture_rect.top); verts[2].texCoords = sf::Vector2f(texture_rect.left + texture_rect.width, texture_rect.top + texture_rect.height); verts[3].texCoords = sf::Vector2f(texture_rect.left, texture_rect.top + texture_rect.height); verts[0].position = sprite.getTransform().transformPoint(0, 0); verts[1].position = sprite.getTransform().transformPoint(texture_rect.width, 0); verts[2].position = sprite.getTransform().transformPoint(texture_rect.width, texture_rect.height); verts[3].position = sprite.getTransform().transformPoint(0, texture_rect.height); for (int i = 0; i < 4; i++) { verts[i].color = sprite.getColor(); batch.append(verts[i]); } } void SpriteBatch::clear() { batch.clear(); } }
31.75
116
0.722047
tMario2111
ae49617c7348852fdc63f59c7deba2236c460f1b
2,072
hpp
C++
include/upp/impl/cli/value.hpp
tlammi/upp
480615e11b8dd12b36fee0e78b984e1b5051183d
[ "MIT" ]
null
null
null
include/upp/impl/cli/value.hpp
tlammi/upp
480615e11b8dd12b36fee0e78b984e1b5051183d
[ "MIT" ]
null
null
null
include/upp/impl/cli/value.hpp
tlammi/upp
480615e11b8dd12b36fee0e78b984e1b5051183d
[ "MIT" ]
null
null
null
/* SPDX-License-Identifier: MIT */ /* Copyright @ 2020 Toni Lammi */ #pragma once #include <string> #include <string_view> #include <vector> #include "upp/impl/cli/convert.hpp" namespace upp { namespace cli { class ValueBase { public: virtual ~ValueBase() {} virtual void add_value(const char* str) = 0; virtual bool full() const = 0; virtual std::vector<std::pair<std::string_view, std::string_view>> restrictions() const { return {}; } virtual bool support_multiple() const { return false; } private: }; template <typename T> class Value : public ValueBase { public: explicit Value(T& data) : data_{data} {} void add_value(const char* str) { if (value_set_) throw ParsingError("Argument specified multiple times"); data_ = converter<T>::convert(str); value_set_ = true; } bool full() const { return value_set_; } std::vector<std::string_view> help() const { return {}; } private: T& data_; bool value_set_{false}; }; template <typename T> class Value<std::vector<T>> : public ValueBase { public: explicit Value(std::vector<T>& data) : data_{data} {} void add_value(const char* str) { data_.emplace_back(converter<T>::convert(str)); } bool full() const { return false; } bool support_multiple() const { return true; } private: std::vector<T>& data_; std::string help_{}; }; template <typename T> class Value<Enum<T>> : public ValueBase { public: explicit Value(Enum<T>& data) : data_{data} {} void add_value(const char* str) { if (value_set_) throw ParsingError("Argument specified multiple times"); data_ = converter<Enum<T>>::convert(str); value_set_ = true; } bool full() const { return value_set_; } std::vector<std::pair<std::string_view, std::string_view>> restrictions() const { std::vector<std::pair<std::string_view, std::string_view>> out; for (const auto& pair : data_) { out.push_back({pair.str, pair.help}); } return out; } private: bool value_set_{false}; Enum<T>& data_; }; } // namespace cli } // namespace upp
22.521739
68
0.665058
tlammi
ae49a7c7457f2af902956b3caed120e334f8ab11
1,268
cpp
C++
coursework2/test/map_gen_disp/map_gen_test.cpp
foundnet/UOE_PS_coursework
eb719fee024806ec03fbec528e9eb42d444f6289
[ "Apache-2.0" ]
null
null
null
coursework2/test/map_gen_disp/map_gen_test.cpp
foundnet/UOE_PS_coursework
eb719fee024806ec03fbec528e9eb42d444f6289
[ "Apache-2.0" ]
null
null
null
coursework2/test/map_gen_disp/map_gen_test.cpp
foundnet/UOE_PS_coursework
eb719fee024806ec03fbec528e9eb42d444f6289
[ "Apache-2.0" ]
null
null
null
#include "../../include/randommap.h" #include "gtest/gtest.h" #include <vector> #include <cmath> using std::vector; TEST(mapgenTestSuite, NormalSizeCheck){ vector<vector<double>> map = map_gen(30,20,1.0,10,4); EXPECT_EQ(map.size(), 200); EXPECT_EQ(map[0].size(), 300); } TEST(mapgenTestSuite, NarrowSizeCheck1){ vector<vector<double>> map = map_gen(1,10,1.0,10,4); EXPECT_EQ(map.size(), 100); EXPECT_EQ(map[0].size(), 10); } TEST(mapgenTestSuite, NarrowSizeCheck2){ vector<vector<double>> map = map_gen(10,1,1.0,10,4); EXPECT_EQ(map.size(), 10); EXPECT_EQ(map[0].size(), 100); } TEST(mapgenTestSuite, WhiteNoiseSizeCheck){ vector<vector<double>> map = map_gen(30,20,1.0,1,4); EXPECT_EQ(map.size(), 20); EXPECT_EQ(map[0].size(), 30); } TEST(mapgenTestSuite, ZeroOctaveThrowCheck){ EXPECT_ANY_THROW(map_gen(30,20,1.0,10,0)); } TEST(mapgenTestSuite, ZeroSampleThrowCheck){ EXPECT_ANY_THROW(map_gen(30,20,1.0,0,4)); } TEST(mapgenTestSuite, ZeroSizeThrowCheck1){ EXPECT_ANY_THROW(map_gen(0,20,1.0,10,4)); } TEST(mapgenTestSuite, ZeroSizeThrowCheck2){ EXPECT_ANY_THROW(map_gen(30,0,1.0,10,4)); } int main(int argc,char **argv) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
23.924528
57
0.685331
foundnet
ae4fdbe1785af7f213e21e2bdde416975c9183e6
7,878
cpp
C++
src/Keyboard.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
src/Keyboard.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
src/Keyboard.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
#include "Keyboard.h" void Keyboard::Setup(){ timer.TicksPerSecond(2); valueX = 100; valueY = 40; backButton = new Button(Int2(10,10),Int2(90,90),"Back"); delButton = new Button(Int2(410,10),Int2(470,90),"<--"); int keyWidth = 43; int keyHeight = 50; int keySpace = 3; int x = 11; int y = 100; qButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"q"); x += keySpace; wButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"w"); x += keySpace; eButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"e"); x += keySpace; rButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"r"); x += keySpace; tButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"t"); x += keySpace; yButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"y"); x += keySpace; uButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"u"); x += keySpace; iButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"i"); x += keySpace; oButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"o"); x += keySpace; pButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"p"); x += keySpace; x = 34; y += keyHeight + keySpace; aButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"a"); x += keySpace; sButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"s"); x += keySpace; dButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"d"); x += keySpace; fButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"f"); x += keySpace; gButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"g"); x += keySpace; hButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"h"); x += keySpace; jButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"j"); x += keySpace; kButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"k"); x += keySpace; lButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"l"); x += keySpace; x = 57; y += keyHeight + keySpace; zButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"z"); x += keySpace; xButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"x"); x += keySpace; cButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"c"); x += keySpace; vButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"v"); x += keySpace; bButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"b"); x += keySpace; nButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"n"); x += keySpace; mButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"m"); x += keySpace; x = 80; y += keyHeight + keySpace; spaceButton = new Button(Int2(x,y),Int2(x+=keyWidth*4,y+keyHeight),""); x += keySpace; } Keyboard::Keyboard(String *value,short maxLength) : value(value), blinker(false), maxLength(maxLength) { Setup(); } Keyboard::~Keyboard(){ delete aButton; delete bButton; delete cButton; delete dButton; delete eButton; delete fButton; delete gButton; delete hButton; delete iButton; delete jButton; delete kButton; delete lButton; delete mButton; delete nButton; delete oButton; delete pButton; delete qButton; delete rButton; delete sButton; delete tButton; delete uButton; delete vButton; delete wButton; delete xButton; delete yButton; delete zButton; delete spaceButton; delete delButton; delete backButton; } void Keyboard::Update(){ if(Button::CheckForScreenPress()){ Serial.println("keyboard press"); if(backButton->Pressing()){ Button::WaitForDepress(); Finished(true); } if(delButton->Pressing()){ DrawDel(); *value = value->substring(0,value->length()-1); } if(value->length() < maxLength){ if(aButton->Pressing()) {*value += 'a';DrawDel();DrawChars(value->length()-1);} if(bButton->Pressing()) {*value += 'b';DrawDel();DrawChars(value->length()-1);} if(cButton->Pressing()) {*value += 'c';DrawDel();DrawChars(value->length()-1);} if(dButton->Pressing()) {*value += 'd';DrawDel();DrawChars(value->length()-1);} if(eButton->Pressing()) {*value += 'e';DrawDel();DrawChars(value->length()-1);} if(fButton->Pressing()) {*value += 'f';DrawDel();DrawChars(value->length()-1);} if(gButton->Pressing()) {*value += 'g';DrawDel();DrawChars(value->length()-1);} if(hButton->Pressing()) {*value += 'h';DrawDel();DrawChars(value->length()-1);} if(iButton->Pressing()) {*value += 'i';DrawDel();DrawChars(value->length()-1);} if(jButton->Pressing()) {*value += 'j';DrawDel();DrawChars(value->length()-1);} if(kButton->Pressing()) {*value += 'k';DrawDel();DrawChars(value->length()-1);} if(lButton->Pressing()) {*value += 'l';DrawDel();DrawChars(value->length()-1);} if(mButton->Pressing()) {*value += 'm';DrawDel();DrawChars(value->length()-1);} if(nButton->Pressing()) {*value += 'n';DrawDel();DrawChars(value->length()-1);} if(oButton->Pressing()) {*value += 'o';DrawDel();DrawChars(value->length()-1);} if(pButton->Pressing()) {*value += 'p';DrawDel();DrawChars(value->length()-1);} if(qButton->Pressing()) {*value += 'q';DrawDel();DrawChars(value->length()-1);} if(rButton->Pressing()) {*value += 'r';DrawDel();DrawChars(value->length()-1);} if(sButton->Pressing()) {*value += 's';DrawDel();DrawChars(value->length()-1);} if(tButton->Pressing()) {*value += 't';DrawDel();DrawChars(value->length()-1);} if(uButton->Pressing()) {*value += 'u';DrawDel();DrawChars(value->length()-1);} if(vButton->Pressing()) {*value += 'v';DrawDel();DrawChars(value->length()-1);} if(wButton->Pressing()) {*value += 'w';DrawDel();DrawChars(value->length()-1);} if(xButton->Pressing()) {*value += 'x';DrawDel();DrawChars(value->length()-1);} if(yButton->Pressing()) {*value += 'y';DrawDel();DrawChars(value->length()-1);} if(zButton->Pressing()) {*value += 'z';DrawDel();DrawChars(value->length()-1);} if(spaceButton->Pressing()) {*value += ' ';DrawDel();DrawChars(value->length()-1);} Serial.println(*value); } } Draw(); } void Keyboard::Draw(){ if(timer.Tick()){ blinker = !blinker; tft.setCursor(valueX+value->length()*25,valueY); tft.setTextSize(4); if(blinker){ tft.setTextColor(0xFFFF); } else { tft.setTextColor(0x0000); } tft.print("_"); tft.setTextSize(2); } } void Keyboard::DrawDel(){ tft.fillRect(valueX+value->length()*25,valueY,25,35,0x0000); } void Keyboard::DrawChars(unsigned int startingIndex){ tft.setTextColor(0xFFFF); tft.setTextSize(4); while(startingIndex < value->length()){ tft.setCursor(valueX + startingIndex*25,valueY); tft.print((*value)[startingIndex]); ++startingIndex; } } void Keyboard::Redraw(){ tft.fillScreen(0x0000); backButton->Draw(); delButton->Draw(); DrawChars(0); tft.setTextSize(2); qButton->Draw(); wButton->Draw(); eButton->Draw(); rButton->Draw(); tButton->Draw(); yButton->Draw(); uButton->Draw(); iButton->Draw(); oButton->Draw(); pButton->Draw(); aButton->Draw(); sButton->Draw(); dButton->Draw(); fButton->Draw(); gButton->Draw(); hButton->Draw(); jButton->Draw(); kButton->Draw(); lButton->Draw(); zButton->Draw(); xButton->Draw(); cButton->Draw(); vButton->Draw(); bButton->Draw(); nButton->Draw(); mButton->Draw(); spaceButton->Draw(); }
39.19403
173
0.59114
00steve
ae520a80dc64b3bc801fd8c65f711a88ae94e971
1,371
cpp
C++
server_config.cpp
shizuku/server
5608cfa1e048efc8a54a68e4ad18b2d52248e1a2
[ "MIT" ]
null
null
null
server_config.cpp
shizuku/server
5608cfa1e048efc8a54a68e4ad18b2d52248e1a2
[ "MIT" ]
null
null
null
server_config.cpp
shizuku/server
5608cfa1e048efc8a54a68e4ad18b2d52248e1a2
[ "MIT" ]
null
null
null
/*********************** * @file: server_config.cpp * @author: shizuku * @date: 2020/7/15 ***********************/ #include "server_config.h" server_config::server_config(const std::string &filename) { boost::property_tree::ptree root; boost::property_tree::read_json(filename, root); port = root.get<int>("port"); auto r = root.get_child("router"); for (auto &i : r) { router.insert_or_assign(i.first, i.second.get<std::string>("")); } auto e = root.get_child("expires"); for (auto &i : e) { expires.insert_or_assign(i.first, i.second.get<std::string>("")); } auto ep = root.get_child("error_pages"); for (auto &i : ep) { error_pages.insert_or_assign(i.first, i.second.get<std::string>("")); } auto pp = root.get_child("proxy_pass"); for (auto &i : pp) { proxy_pass.insert_or_assign(i.first, std::map<std::string, std::string>{ {"host", i.second.get<std::string>("host")}, {"port", i.second.get<std::string>("port")}, {"url", i.second.get<std::string>("url")}, }); } } std::ostream &operator<<(std::ostream &o, const server_config &sc) { o << "port: " << sc.port << "\n"; o << "router:\n"; for (auto &i:sc.router) { o << "\t" << i.first << "\t\t" << i.second << "\n"; } return o; }
29.170213
80
0.536105
shizuku
ae54d1d37aa672496acb17e53e2c43c2904c6629
970
cpp
C++
day25/solution.cpp
qwoprocks/Advent-of-Code-2020-Solutions
65d96f89af013585ac994b8556d003b6455b0de1
[ "MIT" ]
null
null
null
day25/solution.cpp
qwoprocks/Advent-of-Code-2020-Solutions
65d96f89af013585ac994b8556d003b6455b0de1
[ "MIT" ]
null
null
null
day25/solution.cpp
qwoprocks/Advent-of-Code-2020-Solutions
65d96f89af013585ac994b8556d003b6455b0de1
[ "MIT" ]
null
null
null
/* Link to problem: https://adventofcode.com/2020/day/25 */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <set> using namespace std; long long part1(long long card_public_key, long long door_public_key) { long long mod = 20201227; long long subject_number = 7; long long card_loop_size = 0; long long start = 1; while (start != card_public_key) { start = (start * subject_number) % mod; ++card_loop_size; } long long encryption_key = 1; for (int i = 0; i < card_loop_size; ++i) { encryption_key = (encryption_key * door_public_key) % mod; } return encryption_key; } int main() { ifstream reader("input.txt"); string line; getline(reader, line); long long card_public_key = stoll(line); getline(reader, line); long long door_public_key = stoll(line); cout << "Part 1: " << part1(card_public_key, door_public_key) << endl; return 0; }
27.714286
74
0.652577
qwoprocks
ae5536b006c6f3bc39bcf0b5e0c2d583d75ef7f3
1,956
cpp
C++
2A. C++ Advanced (STL)/Attic/ruleof3.cpp
alemesa1991/School-Projects
ed9170fa4cadfe18c6d9850a17077686ca16d1a1
[ "MIT" ]
null
null
null
2A. C++ Advanced (STL)/Attic/ruleof3.cpp
alemesa1991/School-Projects
ed9170fa4cadfe18c6d9850a17077686ca16d1a1
[ "MIT" ]
null
null
null
2A. C++ Advanced (STL)/Attic/ruleof3.cpp
alemesa1991/School-Projects
ed9170fa4cadfe18c6d9850a17077686ca16d1a1
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> /// memcpy using namespace std; template <class T> class X { size_t size; T *data; public: X() : size(0), data(nullptr) { cout << "X constructor()\n"; } X(size_t s) : size(s), data(new T[size]) { cout << "X (" << s << ") constructor\n"; } ~X() { cout << "X destructor, size=" << size << "\n"; if(data) // if(...) not needed but good practice. 'delete [] nullptr' handled correctly in C++. delete [] data; } X& operator= (const X& rhs) { cout << "assignment operator size,rhs.size=" << size << "," << rhs.size << "\n"; if(this != &rhs) { if(data) // If(data) is needed. The copy construconstructor may have a block of memory with garbage in the 'data' field. delete [] data; data = nullptr; // we are a zombie size = 0; if(rhs.data) { size = rhs.size; data = new T[size]; memcpy( data, rhs.data, size * sizeof(T) ); // returns dest (data in our case) // data = memcpy( new T[size], rhs.data, size * sizeof(T) ); // 1 line } } else { cout << "assignment operator called on itself\n"; } return *this; } X(const X& rhs) { cout << "copy constructor rhs.size=" << rhs.size << "\n"; data = nullptr; *this = rhs; // let assignment operator do the work. } void print() { cout << "size=" << size << " (" << size*sizeof(T) << " BYTES)\n"; } }; int main(int argc, char**argv) { cout << "program " << argv[0] << "\n\n"; cout << "LINE " << __LINE__ << ": X<double> x, y(1000);\n"; X<double> x, y(1000); cout << "x:"; x.print(); cout << "y:"; y.print(); cout << "LINE " << __LINE__ << ": x = y;\n"; x = y; cout << "x:"; x.print(); cout << "y:"; y.print(); cout << "LINE " << __LINE__ << ": X<double> z(x);\n"; X<double> z(x); cout << "z:"; z.print(); cout << "x:"; x.print(); cout << "LINE " << __LINE__ << ": MAIN OVER\n\n"; }
24.759494
127
0.514826
alemesa1991
ae59ce7e42db92d0d43e3bc4b87f979c6e0dd4f6
1,058
hpp
C++
osl/Construct.hpp
elnormous/OuzelShadingLanguage
d1644bf2bb244adc44223dd8570c1acd51ff39d2
[ "BSD-2-Clause" ]
5
2018-03-28T10:37:46.000Z
2022-03-28T13:45:50.000Z
osl/Construct.hpp
elnormous/OuzelShadingLanguage
d1644bf2bb244adc44223dd8570c1acd51ff39d2
[ "BSD-2-Clause" ]
null
null
null
osl/Construct.hpp
elnormous/OuzelShadingLanguage
d1644bf2bb244adc44223dd8570c1acd51ff39d2
[ "BSD-2-Clause" ]
null
null
null
// // OSL // #ifndef CONSTRUCT_HPP #define CONSTRUCT_HPP namespace ouzel { class Construct { public: enum class Kind { Declaration, Statement, Expression, Attribute }; explicit Construct(Kind initKind) noexcept: kind{initKind} {} virtual ~Construct() = default; Construct(const Construct&) = delete; Construct& operator=(const Construct&) = delete; Construct(Construct&&) = delete; Construct& operator=(Construct&&) = delete; const Kind kind; }; inline std::string toString(Construct::Kind kind) { switch (kind) { case Construct::Kind::Declaration: return "Declaration"; case Construct::Kind::Statement: return "Statement"; case Construct::Kind::Expression: return "Expression"; case Construct::Kind::Attribute: return "Attribute"; } throw std::runtime_error("Unknown construct kind"); } } #endif // CONSTRUCT_HPP
23
69
0.579395
elnormous
ae5a56571b8152aafbb749f31b862d784eabae29
302
hpp
C++
src/include/Bus/Memory/Memory.hpp
Garoze/Console
d99a08fb88fab4da5ca7c2c2c6d81fb9e5d6cb56
[ "MIT" ]
null
null
null
src/include/Bus/Memory/Memory.hpp
Garoze/Console
d99a08fb88fab4da5ca7c2c2c6d81fb9e5d6cb56
[ "MIT" ]
null
null
null
src/include/Bus/Memory/Memory.hpp
Garoze/Console
d99a08fb88fab4da5ca7c2c2c6d81fb9e5d6cb56
[ "MIT" ]
null
null
null
#pragma once #include <array> #include <cstdint> #define MEMORY_SIZE 64 * 1024 class Memory { public: Memory(); void viewAt(std::uint16_t); public: std::uint8_t& operator[](std::uint16_t i) { return data[i]; } private: std::array<std::uint8_t, MEMORY_SIZE> data; };
13.727273
47
0.629139
Garoze
ae5a6edd3b942d1a548dcc1be78fb51ac455f527
1,335
cpp
C++
seeded_lda/libc/t/test.cpp
qinliuliuqin/Arbitrage-Strategy-Analysis
d735481a2480174366e3f90025a1f935d5ad1f8b
[ "MIT" ]
null
null
null
seeded_lda/libc/t/test.cpp
qinliuliuqin/Arbitrage-Strategy-Analysis
d735481a2480174366e3f90025a1f935d5ad1f8b
[ "MIT" ]
null
null
null
seeded_lda/libc/t/test.cpp
qinliuliuqin/Arbitrage-Strategy-Analysis
d735481a2480174366e3f90025a1f935d5ad1f8b
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> #include <stdlib.h> #include "utils/utils.cpp" #include "utils/Pair.cpp" using namespace std; void Temp(vector<int> &vList){ for(int i=0;i<vList.size();i++) vList[i] /= 2; } int main(int argc,char *argv[]){ vector<Pair<int,double> > vList; for(int i=0;i<10000;i++){ double Temp = (1000 * (rand() / (RAND_MAX + 1.0))); if(i% 2 == 0) vList.push_back(Pair<int,double>(i,Temp)); else vList.push_back(Pair<int,double>(i,-1*Temp)); } printf("List has %d elements\n", vList.size()); utils<Pair<int,double> > u; u.QSort(vList); for(int i=0;i<vList.size();i++){ printf("%f ", vList[i].Second); if(i > 0 && vList[i].Second < vList[i-1].Second) printf("****\n"); } printf("\n"); //Temp(vList); //for(int i=0;i<vList.size();i++) printf("%d ", vList[i]); /* cout << endl; for(int i=0;i<vList.size();i++) printf("%d ", vList[i]); cout << endl; cout << "Smallest element is " << u.kthSmallest(vList, 1) << endl; cout << "List " ; for(int i=0;i<vList.size();i++) printf("%d ", vList[i]); cout << endl; cout << "Median is " << u.median(vList) << endl; for(int i=0;i<vList.size();i++) printf("%d ", vList[i]); cout << "\n\n\nObserve from now\n\n\n" << endl; u.QSort(vList); for(int i=0;i<vList.size();i++) printf("%d ", vList[i]); cout << endl; */ }
23.017241
67
0.57603
qinliuliuqin
ae618e182a830a807ee3e2e83c7727dca25dea5c
2,205
cpp
C++
Std/Forward.cpp
asynts/picoos
5197f86ce1902fc6572cecd10f97ca68109f2f86
[ "MIT" ]
1
2021-08-24T05:59:32.000Z
2021-08-24T05:59:32.000Z
Std/Forward.cpp
asynts/picoos
5197f86ce1902fc6572cecd10f97ca68109f2f86
[ "MIT" ]
3
2021-03-31T15:36:01.000Z
2021-04-19T14:17:44.000Z
Std/Forward.cpp
asynts/picoos
5197f86ce1902fc6572cecd10f97ca68109f2f86
[ "MIT" ]
null
null
null
#include <Std/Forward.hpp> #include <Std/Format.hpp> #include <Std/Lexer.hpp> #if !defined(TEST) && !defined(KERNEL) # error "Only KERNEL and TEST are supported" #endif #if defined(TEST) # include <iostream> # include <cstdlib> #elif defined(KERNEL) # include <Kernel/ConsoleDevice.hpp> # include <Kernel/HandlerMode.hpp> #endif namespace Std { static void write_output(StringView value) { #if defined(TEST) std::cerr << std::string_view { value.data(), value.size() }; #elif defined(KERNEL) Kernel::ConsoleFileHandle handle; // We do not aquire a mutex here, because the system may not work at // this point. bool were_interrupts_enabled = Kernel::disable_interrupts(); handle.write(value.bytes()); Kernel::restore_interrupts(were_interrupts_enabled); #endif } static void write_output(usize value) { #if defined(TEST) std::cerr << value; #elif defined(KERNEL) Kernel::ConsoleFileHandle handle; StringBuilder builder; builder.appendf("{}", value); // We do not aquire a mutex here, because the system may not work at // this point. bool were_interrupts_enabled = Kernel::disable_interrupts(); handle.write(builder.bytes()); Kernel::restore_interrupts(were_interrupts_enabled); #endif } void crash(const char *format, const char *condition, const char *file, usize line) { Std::Lexer lexer { format }; while (!lexer.eof()) { if (lexer.try_consume("%condition")) { write_output(condition); continue; } if (lexer.try_consume("%file")) { write_output(file); continue; } if (lexer.try_consume("%line")) { write_output(line); continue; } write_output(lexer.consume_until('%')); if (lexer.peek_or_null() != '%') ASSERT(lexer.eof()); } write_output("\n"); #if defined(TEST) std::abort(); #else asm volatile("bkpt #0"); for(;;) asm volatile("wfi"); #endif } }
25.344828
87
0.582313
asynts
ae61fe9c0709ef23779b6f9244b31d0e26f0be26
8,667
hpp
C++
__unit_tests/gv_framework_unit_test/unit_test_display_animation.hpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
2
2018-12-03T13:17:31.000Z
2020-04-08T07:00:02.000Z
__unit_tests/gv_framework_unit_test/unit_test_display_animation.hpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
null
null
null
__unit_tests/gv_framework_unit_test/unit_test_display_animation.hpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
null
null
null
namespace unit_test_display_animation { void main(gvt_array< gv_string >& args) { bool do_compress = false; if (args.find("compress")) { do_compress = true; } gv_int idx; bool do_file = false; bool do_software_skinning = true; gv_string file_name; if (args.find("file", idx)) { do_file = true; file_name = args[idx + 1]; } bool t_pose_only = false; if (args.find("t_pose", idx)) { t_pose_only = true; } gv_string mod_file_name; if (args.find("mod", idx)) { mod_file_name = args[idx + 1]; } { gv_unit_test_context_guard context; sub_test_timer timer("unit_test_importer_exporter_fbx"); double start_time = m_sandbox->get_time_in_seconds(); m_sandbox->register_processor(gv_world::static_class(), gve_event_channel_world); gv_world* my_world = gvt_cast< gv_world >(m_sandbox->get_event_processor(gve_event_channel_world)); gv_entity* my_camera = m_sandbox->create_object< gv_entity >(gv_id("my_camera"), NULL); my_camera->add_component(gv_id("gv_com_cam_fps_fly")); gv_com_camera* camera = m_sandbox->create_object< gv_com_camera >(gv_id("main_camera"), my_camera); my_camera->add_component(camera); GVM_POST_EVENT(render_set_camera, render, (pe->camera = camera)); my_world->add_entity(my_camera); gv_module* pmod = NULL; if (!do_file) { if (mod_file_name.size()) pmod = m_sandbox->load_module(gv_id(*mod_file_name)); else pmod = m_sandbox->try_load_module(gv_id("wolf")); } else { pmod = m_sandbox->create_object< gv_module >(gv_id(MOD_WOLF)); gv_model* model = m_sandbox->create_object< gv_model >(pmod); m_sandbox->import_external_format(model, *file_name); m_sandbox->export_module(pmod->get_name_id()); } gvt_object_iterator< gv_skeletal > it(m_sandbox); gv_skeletal* my_skeletal = NULL; if (!it.is_empty()) { my_skeletal = it; }; if (!my_skeletal) { return; } GV_ASSERT(my_skeletal); gv_ani_set* my_animation = NULL; gvt_object_iterator< gv_ani_set > it_ani(m_sandbox); if (!it_ani.is_empty()) { my_animation = it_ani; if (do_compress) { } } gv_skeletal_mesh* my_skeletal_mesh = NULL; gvt_object_iterator< gv_skeletal_mesh > it_skeletal_mesh(m_sandbox); if (!it_skeletal_mesh.is_empty()) { my_skeletal_mesh = it_skeletal_mesh; my_skeletal_mesh->optimize_bones(); } if (my_skeletal_mesh) { gv_entity* my_entity = m_sandbox->create_object< gv_entity >(gv_id("entity"), NULL); gv_static_mesh* my_static_mesh = my_skeletal_mesh->m_t_pose_mesh; if (do_software_skinning) { gv_com_static_mesh* pmesh0 = m_sandbox->create_object< gv_com_static_mesh >(my_entity); //gv_texture * my_texture =m_sandbox->create_object<gv_texture>(my_static_mesh); //gv_string_tmp tex_file_name=FILE_TEX_SNOW_CUBEMAP; //my_texture->set_file_name(tex_file_name); //my_static_mesh->m_diffuse_texture=my_texture; pmesh0->set_resource(my_static_mesh); pmesh0->set_renderer_id(gve_render_pass_opaque, gv_id("gv_com_wire_frame_renderer")); //pmesh0->set_renderer_id(gve_render_pass_opaque, gv_id( "gv_com_wire_frame_renderer") ); my_entity->add_component(pmesh0); } else { gv_com_skeletal_mesh* pmesh0 = m_sandbox->create_object< gv_com_skeletal_mesh >(my_entity); pmesh0->set_resource(my_skeletal_mesh); my_entity->add_component(pmesh0); } my_world->add_entity(my_entity); float r = my_static_mesh->get_bsphere().get_radius(); camera->set_fov(60, 1.333f, 0.1f * r, 100 * r); camera->set_look_at(gv_vector3(0, 1, 5.f) * r, gv_vector3(0, 0, 0)); camera->update_projection_view_matrix(); } //============>>GO GO GO !! int loop = 1000; if (args.size()) args[0] >> loop; bool quit = false; gv_float scale_factor = 1.0f; //if (args.size()>1 ) args[1]>>scale_factor; gvt_array< gv_vector3 > original_pos; bool pause = false; while (loop-- && !quit) { static int index_seq = 0; if (loop == 1) { gv_object_event_render_uninit* pe = new gv_object_event_render_uninit; m_sandbox->post_event(pe, gve_event_channel_render); } quit = !m_sandbox->tick(); gvi_debug_renderer* pdebug = gv_global::debug_draw.get(); pdebug->draw_line_3d(gv_vector3(0, 0, 0), gv_vector3(10, 0, 0), gv_color::RED(), gv_color::RED_B()); pdebug->draw_line_3d(gv_vector3(0, 0, 0), gv_vector3(0, 10, 0), gv_color::GREEN(), gv_color::GREEN_B()); pdebug->draw_line_3d(gv_vector3(0, 0, 0), gv_vector3(0, 0, 10), gv_color::BLUE(), gv_color::BLUE_B()); gv_string_tmp info; if (my_animation) { info << " current animation "; if (index_seq >= my_animation->get_nb_sequence()) { index_seq = 0; } gv_ani_sequence* pseq = my_animation->get_sequence(index_seq); info << pseq->get_name_id() << "(" << index_seq << "/" << my_animation->get_nb_sequence(); pdebug->draw_string(*info, gv_vector2i(100, 20), gv_color::BLUE_D()); } { static bool last_key_down = false; if (m_sandbox->get_input_manager()->is_key_down(e_key_space) && !last_key_down) { index_seq++; start_time = m_sandbox->get_time_in_seconds(); } last_key_down = m_sandbox->get_input_manager()->is_key_down(e_key_space); } { static bool last_key_down = false; if (m_sandbox->get_input_manager()->is_key_down(e_key_p) && !last_key_down) { pause = !pause; } last_key_down = m_sandbox->get_input_manager()->is_key_down(e_key_p); } //====================================================== //ANIMATE THE MESH my_skeletal->m_root_tm.set_identity(); if (!t_pose_only && my_animation && my_skeletal && !pause) { gv_double time = m_sandbox->get_time_in_seconds() - start_time; gv_ulong frame = (gv_ulong)(time * 30.0); if (index_seq >= my_animation->get_nb_sequence()) { index_seq = 0; } gv_ani_sequence* pseq = my_animation->get_sequence(index_seq); if (pseq) { int nb_track = pseq->get_track_number(); if (!nb_track) continue; gv_float d = pseq->get_duration(); gv_vector3 pos, scale; gv_quat q; for (int i = 0; i < nb_track; i++) { gv_ani_track* ptrack = pseq->get_track(i); ptrack->get_trans_rot((float)time, pos, q, scale, true); pos *= scale_factor; my_skeletal->set_bone_local_rotation_trans(ptrack->get_name_id(), q, pos, scale); } } my_skeletal->update_world_matrix(); } //====================================================== //DRAW THE SKELETAL if (my_skeletal) { for (int i = 0; i < my_skeletal->m_bones.size(); i++) { gv_bone& bone = my_skeletal->m_bones[i]; if (bone.m_hierachy_depth) { gv_bone& father = my_skeletal->m_bones[bone.m_parent_idx]; pdebug->draw_line_3d(bone.m_tm.get_trans(), father.m_tm.get_trans(), gv_color::WHITE(), gv_color::BLACK()); } } } //====================================================== //MORPH THE VERTEX!! //SIN WAVE MORPH.. /* if (my_skeletal_mesh) { gv_static_mesh * pmesh=my_skeletal_mesh->m_t_pose_mesh; if (pmesh && pmesh->m_vertex_buffer) { gv_vertex_buffer *vb=pmesh->m_vertex_buffer; if (!original_pos.size()) original_pos=vb->m_raw_pos; for ( int i=0; i< vb->m_raw_pos.size(); i++) { gv_vector3 &v3=vb->m_raw_pos[i]; v3.x=original_pos[i].x+sinf(v3.y+m_sandbox->get_time_in_seconds()*10.f)*0.4f; } vb->set_dirty(); } } */ static bool draw_skin = true; if (!t_pose_only && my_skeletal_mesh && draw_skin) { gv_static_mesh* pmesh = my_skeletal_mesh->m_t_pose_mesh; if (pmesh && pmesh->m_vertex_buffer) { gv_vertex_buffer* vb = pmesh->m_vertex_buffer; if (!original_pos.size()) original_pos = vb->m_raw_pos; for (int i = 0; i < vb->m_raw_pos.size(); i++) { gv_vector3& v3 = vb->m_raw_pos[i]; v3 = 0; for (int j = 0; j < 4; j++) { gv_short bone_index = (gv_short)vb->m_raw_blend_index[i][j]; if (bone_index == -1) continue; gv_bone* pbone = NULL; if (!my_skeletal_mesh->m_bone_mapping.size()) { pbone = &my_skeletal_mesh->m_skeletal->m_bones[bone_index]; } else { pbone = &my_skeletal_mesh->m_skeletal->m_bones[my_skeletal_mesh->m_bone_inv_mapping[bone_index]]; } gv_bone& bone = *pbone; v3 += original_pos[i] * bone.m_matrix_model_to_bone * bone.m_tm * vb->m_raw_blend_weight[i][j]; } if (v3.is_almost_zero()) { int c = 1; } } vb->set_dirty(); } } //draw t-pose } //loop } //context } //main }
30.410526
113
0.646244
dragonsn
ae6c4aa0db5b1b4195204d9065598fe0b6877633
6,000
cpp
C++
sdk/MagicSoftware/FreeMagic/Source/ImageAnalysis/MgcBinary3D.cpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
10
2021-05-04T06:40:27.000Z
2022-01-20T20:24:28.000Z
sdk/MagicSoftware/FreeMagic/Source/ImageAnalysis/MgcBinary3D.cpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
sdk/MagicSoftware/FreeMagic/Source/ImageAnalysis/MgcBinary3D.cpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
2
2020-05-17T10:01:14.000Z
2020-09-11T20:17:27.000Z
// Magic Software, Inc. // http://www.magic-software.com // Copyright (c) 2000-2002. All Rights Reserved // // Source code from Magic Software is supplied under the terms of a license // agreement and may not be copied or disclosed except in accordance with the // terms of that agreement. The various license agreements may be found at // the Magic Software web site. This file is subject to the license // // FREE SOURCE CODE // http://www.magic-software.com/License/free.pdf #include "MgcBinary3D.h" using namespace Mgc; //---------------------------------------------------------------------------- Binary3D::Binary3D (int iXBound, int iYBound, int iZBound, Eint* atData) : ImageInt3D(iXBound,iYBound,iZBound,atData) { } //---------------------------------------------------------------------------- Binary3D::Binary3D (const Binary3D& rkImage) : ImageInt3D(rkImage) { } //---------------------------------------------------------------------------- Binary3D::Binary3D (const char* acFilename) : ImageInt3D(acFilename) { } //---------------------------------------------------------------------------- void Binary3D::GetComponents (int& riQuantity, ImageInt3D& rkComponents) const { // Create a temporary copy of image to store intermediate information // during component labeling. The original image is embedded in an image // with two more slices, two more rows, and two more columns so that the // image boundary pixels are properly handled. This copy is initially // zero. ImageInt3D kTemp(GetBound(0)+2,GetBound(1)+2,GetBound(2)+2); int iX, iY, iZ, iXP, iYP, iZP; for (iZ = 0, iZP = 1; iZ < GetBound(2); iZ++, iZP++) { for (iY = 0, iYP = 1; iY < GetBound(1); iY++, iYP++) { for (iX = 0, iXP = 1; iX < GetBound(0); iX++, iXP++) kTemp(iXP,iYP,iZP) = ( (*this)(iX,iY,iZ) ? 1 : 0 ); } } // label connected components in 1D array int i, iComponent = 0; for (i = 0; i < kTemp.GetQuantity(); i++) { if ( kTemp[i] ) { iComponent++; while ( kTemp[i] ) { // loop terminates since kTemp is zero on its boundaries kTemp[i++] = iComponent; } } } if ( iComponent == 0 ) { // input image is identically zero riQuantity = 0; rkComponents = (Eint)0; return; } // associative memory for merging int* aiAssoc = new int[iComponent+1]; for (i = 0; i < iComponent + 1; i++) aiAssoc[i] = i; // Merge equivalent components. Voxel (x,y,z) has previous neighbors // (x-1,y-1,z-1), (x,y-1,z-1), (x+1,y-1,z-1), (x-1,y,z-1), (x,y,z-1), // (x+1,y,z-1), (x-1,y+1,z-1), (x,y+1,z-1), (x+1,y+1,z-1), (x-1,y-1,z), // (x,y-1,z), (x+1,y-1,z), (x-1,y,z) [13 of 26 voxels visited before // (x,y,z) is visited, get component labels from them]. for (iZ = 1; iZ < kTemp.GetBound(2)-1; iZ++) { for (iY = 1; iY < kTemp.GetBound(1)-1; iY++) { for (iX = 1; iX < kTemp.GetBound(0)-1; iX++) { int iValue = kTemp(iX,iY,iZ); if ( iValue > 0 ) { AddToAssociative(iValue,kTemp(iX-1,iY-1,iZ-1),aiAssoc); AddToAssociative(iValue,kTemp(iX, iY-1,iZ-1),aiAssoc); AddToAssociative(iValue,kTemp(iX+1,iY-1,iZ-1),aiAssoc); AddToAssociative(iValue,kTemp(iX-1,iY ,iZ-1),aiAssoc); AddToAssociative(iValue,kTemp(iX ,iY ,iZ-1),aiAssoc); AddToAssociative(iValue,kTemp(iX+1,iY ,iZ-1),aiAssoc); AddToAssociative(iValue,kTemp(iX-1,iY+1,iZ-1),aiAssoc); AddToAssociative(iValue,kTemp(iX ,iY+1,iZ-1),aiAssoc); AddToAssociative(iValue,kTemp(iX+1,iY+1,iZ-1),aiAssoc); AddToAssociative(iValue,kTemp(iX-1,iY-1,iZ ),aiAssoc); AddToAssociative(iValue,kTemp(iX ,iY-1,iZ ),aiAssoc); AddToAssociative(iValue,kTemp(iX+1,iY-1,iZ ),aiAssoc); AddToAssociative(iValue,kTemp(iX-1,iY ,iZ ),aiAssoc); } } } } // replace each cycle of equivalent labels by a single label riQuantity = 0; for (i = 1; i <= iComponent; i++) { if ( i <= aiAssoc[i] ) { riQuantity++; int iCurrent = i; while ( aiAssoc[iCurrent] != i ) { int iNext = aiAssoc[iCurrent]; aiAssoc[iCurrent] = riQuantity; iCurrent = iNext; } aiAssoc[iCurrent] = riQuantity; } } // pack a relabeled image in smaller size output for (iZ = 0, iZP = 1; iZ < rkComponents.GetBound(2); iZ++, iZP++) { for (iY = 0, iYP = 1; iY < rkComponents.GetBound(1); iY++, iYP++) { for (iX = 0, iXP = 1; iX < rkComponents.GetBound(0); iX++, iXP++) rkComponents(iX,iY,iZ) = aiAssoc[kTemp(iXP,iYP,iZP)]; } } delete[] aiAssoc; } //---------------------------------------------------------------------------- void Binary3D::AddToAssociative (int i0, int i1, int* aiAssoc) const { // Adjacent voxels have labels i0 and i1. Associate them so that they // represent the same component. [assert: i0 > 0] if ( i1 == 0 || i1 == i0 ) return; int iSearch = i1; do { iSearch = aiAssoc[iSearch]; } while ( iSearch != i1 && iSearch != i0 ); if ( iSearch == i1 ) { int iSave = aiAssoc[i0]; aiAssoc[i0] = aiAssoc[i1]; aiAssoc[i1] = iSave; } } //----------------------------------------------------------------------------
35.714286
79
0.483167
acidicMercury8
ae6e0213ff0c952cb84f840c77cbc1ba9de7d712
652
hh
C++
MCDataProducts/inc/PointTrajectoryCollection.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
null
null
null
MCDataProducts/inc/PointTrajectoryCollection.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
MCDataProducts/inc/PointTrajectoryCollection.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
#ifndef MCDataProducts_PointTrajectoryCollection_hh #define MCDataProducts_PointTrajectoryCollection_hh // // Define a type for a collection of PointTrajectory objects. // The key is the simulated particle ID (same as for the // SimParticleCollection). // // $Id: PointTrajectoryCollection.hh,v 1.2 2011/05/24 20:03:31 wb Exp $ // $Author: wb $ // $Date: 2011/05/24 20:03:31 $ // // Original author Rob Kutschke // #include "MCDataProducts/inc/PointTrajectory.hh" #include "cetlib/map_vector.h" namespace mu2e { typedef cet::map_vector<mu2e::PointTrajectory> PointTrajectoryCollection; } #endif /* MCDataProducts_PointTrajectoryCollection_hh */
27.166667
76
0.769939
bonventre
ae6ef9b61390369faf96d4f3c02d4d178a350f93
2,330
cpp
C++
Sources/API/Python/Field/ConstantVectorField.cpp
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
3
2020-04-15T13:41:16.000Z
2020-12-29T11:23:59.000Z
Sources/API/Python/Field/ConstantVectorField.cpp
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
Sources/API/Python/Field/ConstantVectorField.cpp
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
/************************************************************************* > File Name: ConstantVectorField.h > Project Name: CubbyFlow > Author: Chan-Ho Chris Ohk > Purpose: ConstantVectorField functions for CubbyFlow Python API. > Created Time: 2018/02/04 > Copyright (c) 2018, Chan-Ho Chris Ohk *************************************************************************/ #include <API/Python/Field/ConstantVectorField.h> #include <API/Python/Utils/pybind11Utils.h> #include <Core/Field/ConstantVectorField2.h> #include <Core/Field/ConstantVectorField3.h> #include <pybind11/pybind11.h> using namespace CubbyFlow; void AddConstantVectorField2(pybind11::module& m) { pybind11::class_<ConstantVectorField2, ConstantVectorField2Ptr, VectorField2>(static_cast<pybind11::handle>(m), "ConstantVectorField2", R"pbdoc( 2-D constant vector field. )pbdoc") .def(pybind11::init<Vector2D>(), R"pbdoc( Constructs a constant vector field with given `value`. )pbdoc", pybind11::arg("value")) .def("Sample", [](const ConstantVectorField2& instance, pybind11::object obj) { return instance.Sample(ObjectToVector2D(obj)); }, R"pbdoc( Returns sampled value at given position `x`. )pbdoc", pybind11::arg("x")) .def("Sampler", [](const ConstantVectorField2& instance) { return instance.Sampler(); }, R"pbdoc( Returns the sampler function. This function returns the data sampler function object. The sampling function is linear. )pbdoc"); } void AddConstantVectorField3(pybind11::module& m) { pybind11::class_<ConstantVectorField3, ConstantVectorField3Ptr, VectorField3>(static_cast<pybind11::handle>(m), "ConstantVectorField3", R"pbdoc( 3-D constant vector field. )pbdoc") .def(pybind11::init<Vector3D>(), R"pbdoc( Constructs a constant vector field with given `value`. )pbdoc", pybind11::arg("value")) .def("Sample", [](const ConstantVectorField3& instance, pybind11::object obj) { return instance.Sample(ObjectToVector3D(obj)); }, R"pbdoc( Returns sampled value at given position `x`. )pbdoc", pybind11::arg("x")) .def("Sampler", [](const ConstantVectorField3& instance) { return instance.Sampler(); }, R"pbdoc( Returns the sampler function. This function returns the data sampler function object. The sampling function is linear. )pbdoc"); }
29.871795
136
0.68412
utilForever
ae70c8b906df8c9483c1f6ccf81413249959cb47
4,279
cpp
C++
src/Draw/Image.cpp
FishbowlDigital/FBDraw
4ea6198f01be5f3c9627ca34bff263245bfd3ecc
[ "MIT", "Unlicense" ]
null
null
null
src/Draw/Image.cpp
FishbowlDigital/FBDraw
4ea6198f01be5f3c9627ca34bff263245bfd3ecc
[ "MIT", "Unlicense" ]
null
null
null
src/Draw/Image.cpp
FishbowlDigital/FBDraw
4ea6198f01be5f3c9627ca34bff263245bfd3ecc
[ "MIT", "Unlicense" ]
null
null
null
// Image.cpp // Implementation file for the Image class // // Copyright(c) 2017 - 2022 Fishbowl Digital LLC // // 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 "Image.h" #include "Macros.h" namespace FBDraw { // Constructor Image::Image(int x, int y, int w, int h, color32_t* image, bool hasAlpha /* = true */) { m_location = Point(x, y); m_height = h; m_width = w; m_imageBuffer = image; m_bOwnsBuffer = false; m_bHasAlpha = hasAlpha; // Default is Visible Visible = true; } Image::Image(int x, int y, int w, int h, bool hasAlpha /* = true */) { m_location = Point(x, y); m_height = h; m_width = w; m_imageBuffer = new color32_t[w * h]; m_bOwnsBuffer = true; m_bHasAlpha = hasAlpha; // Default is Visible Visible = true; } Image::~Image() { if (m_bOwnsBuffer) delete m_imageBuffer; } void Image::ReplaceBuffer(color32_t* image) { ReplaceBuffer(image, m_location, m_width, m_height); }; void Image::ReplaceBuffer(color32_t* image, int w, int h) { ReplaceBuffer(image, m_location, w, h); } void Image::ReplaceBuffer(color32_t* image, Point loc, int w, int h) { // Clean old buffer? if (m_bOwnsBuffer) delete m_imageBuffer; // Replace m_imageBuffer = image; m_location = loc; m_width = w; m_height = h; // Set new ownership state m_bOwnsBuffer = false; // Don't cleanup this buffer on delete } #ifndef WIN32 __attribute__((optimize("unroll-loops"))) #endif void Image::Render(color32_t* backBuffer, int width, int height) { if (m_imageBuffer == NULL) return; int iCanvasStart = ((m_location.Y) * width) + m_location.X; // Copy the image to the backbuffer if (m_bHasAlpha) { ARGB_Color mixBGRA = ARGB_Color{ 0x00, 0x00, 0x00, 0x00 }; for (int iY = 0; iY < m_height; iY++) { int iCanvasRowStart = iCanvasStart + (iY * width); int iImageRowStart = (iY * m_width); for (int iX = 0; iX < m_width; iX++) { // Alpha mix the image pixel and the back buffer ARGB_Bytes imgColor, backColor, mixColor; imgColor.U32 = m_imageBuffer[iImageRowStart + iX]; backColor.U32 = backBuffer[iCanvasRowStart + iX]; mixColor.Color.Red = AlphaMix8(backColor.Color.Red, imgColor.Color.Red, imgColor.Color.Alpha); mixColor.Color.Green = AlphaMix8(backColor.Color.Green, imgColor.Color.Green, imgColor.Color.Alpha); mixColor.Color.Blue = AlphaMix8(backColor.Color.Blue, imgColor.Color.Blue, imgColor.Color.Alpha); backBuffer[iCanvasRowStart + iX] = mixColor.U32 | 0xFF000000; } } } else { for (int iY = 0; iY < m_height; iY++) { uint32_t* pBackBuffer = &backBuffer[iCanvasStart + (iY * width)]; uint32_t* pImgBuffer = &m_imageBuffer[(iY * m_width)]; for (int iX = 0; iX < m_width; iX++, pBackBuffer++, pImgBuffer++) { *pBackBuffer = *pImgBuffer | 0xFF000000; } } } } bool Image::HitTest(int x, int y) { return x > m_location.X && x < (m_location.X+m_width) && y > m_location.Y && y < (m_location.Y+m_height); } }
29.715278
106
0.649918
FishbowlDigital
ae72179e0987143289476d0dece7489e65d23ff5
3,146
cpp
C++
Lab/SavingsFucnctionPotPourri/main.cpp
salazaru/Program-Logic-Using-Cpp
e4fb97f00eb639d523b7ede0661ff1698301f46d
[ "MIT" ]
1
2015-03-06T01:03:54.000Z
2015-03-06T01:03:54.000Z
Lab/SavingsFucnctionPotPourri/main.cpp
salazaru/Salazar_Uriel_CSC5_43952
e4fb97f00eb639d523b7ede0661ff1698301f46d
[ "MIT" ]
null
null
null
Lab/SavingsFucnctionPotPourri/main.cpp
salazaru/Salazar_Uriel_CSC5_43952
e4fb97f00eb639d523b7ede0661ff1698301f46d
[ "MIT" ]
null
null
null
//File: main.cpp //========================================================================== //Programmer: Uriel Salazar //========================================================================== //Created: April 20, 2015, 8:14 PM //========================================================================== //Purpose: Functions //========================================================================== //System Libraries #include <iostream> //Input/Output Library #include <iomanip> //Parametric Library using namespace std; //Input/Output Library under standard name space //User Libraries //Global Constants //Function Prototypes float save1(float, float, int); //Power Function float save2(float, float, int); //Exponential & Log Function float save3(float, float, int); //For-Loop float save4(float, float, int); //Recursive -> Calling itself float save5(float = 100.0f, float = 0.08f, int = 9); //Defaulted Parameter void save6(float, float, int); void save7(float, float, int); float save1(float, float, float); //Execution Begins int main() { //Declare Variables float pv = 100.0f; //Present Value$'s float ir = 0.08f; //Interest Rate % / yr int nC = 9; //Number of Compounding Periods //Output the Inputs cout << setprecision(2) << showpoint; cout << "Present Value = $ " << pv <<endl; cout << "Interest Rate = " << ir * 100 << "%" << endl; cout << "Number of Compounding Periods = " << nC << "(yrs)"; //Calculate our savings cout << "Savings Function 1 = $" << save1(pv, ir, nC) << endl; float nCf = nc; cout << "Savings Function 2 = $" << save2(pv, ir, nC) << endl; cout << "Savings Function 3 = $" << save3(pv, ir, nC) << endl; cout << "Savings Function 4 = $" << save4(pv, ir, nC) << endl; cout << "Savings Function 5 = $" << save5(pv, ir, nC) << endl; cout << "Savings Function 5 = $" << save5(pv, ir) << endl; cout << "Savings Function 5 = $" << save5(pv) << endl; cout << "Savings Function 5 = $" << save5(pv, ir) << endl; float fv; save6(fv, pv, ir, nC); cout << "Savings Function 6 = $" << fv << endl; save7 () //Exit Program return 0; } //Function for Future Value Calculation //inputs // p -> Present Value $'s // i -> Interest Rate % / Compounding Period // n -> Compounding Period yr's //output // fv -> Future Value $'s float save1(float p, float i, int n); { return p * pow((1 + i), n); } float save2(float p, float i, int n); { return p * pow((1 + i), n); } float save3(float p, float i, int n); { return p * pow((1 + i), n); } float save4(float p, float i, int n); { return p * pow((1 + i), n); } float save5(float p, float i, int n); { return p * pow((1 + i), n); } float save6(float p, float i, int n) { if(n <= 0) { return p; //1st return } return save4(p, i, n - 1) * (1 + i); //2nd Return } float save6(float %f, floatp, )
30.25
79
0.494596
salazaru
ae756d793d630e0f6314299c9ae32ba2b36cef73
2,297
hpp
C++
src/geometryhandler.hpp
pannacotta98/DomeDagen
aa5ac6adbc73326e43dfa129eae11c95f7191a1d
[ "BSD-2-Clause" ]
null
null
null
src/geometryhandler.hpp
pannacotta98/DomeDagen
aa5ac6adbc73326e43dfa129eae11c95f7191a1d
[ "BSD-2-Clause" ]
null
null
null
src/geometryhandler.hpp
pannacotta98/DomeDagen
aa5ac6adbc73326e43dfa129eae11c95f7191a1d
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "modelmanager.hpp" //This class is privately inherited to classes needing models and accompanied functionality //This class is also very unorganized class GeometryHandler { public: GeometryHandler(const std::string& shaderProgramName, const std::string& objectModelName) :mShaderProgram{ sgct::ShaderManager::instance().shaderProgram(shaderProgramName) }, mModel{ &ModelManager::instance().getModel(objectModelName) }, mModelSlot{ ModelManager::instance().findModelSpot(objectModelName)} {} GeometryHandler(const GeometryHandler&) = default; GeometryHandler(GeometryHandler&&) = default; GeometryHandler& operator=(const GeometryHandler&) = delete; GeometryHandler& operator=(GeometryHandler&& src) noexcept { std::swap(mTransMatrixLoc, src.mTransMatrixLoc); std::swap(mMvpMatrixLoc, src.mMvpMatrixLoc); std::swap(mModel, src.mModel); std::swap(mModelSlot, src.mModelSlot); return *this; } //Do not remove mModel as this removes the model for all objects ~GeometryHandler() { mModel = nullptr; } //Get model pointer index int getModelPointerIndex(){return mModelSlot;} //Set new model from slot index in ModelManager void setModelFromInt(const int index) {mModel = &ModelManager::instance().getModel(index);} //Shader matrix locations GLint mTransMatrixLoc = -1; GLint mMvpMatrixLoc = -1; GLint mViewMatrixLoc = -1; GLint mNormalMatrixLoc = -1; GLint mCameraPosLoc = -1; //Reference to shader in shader pool const sgct::ShaderProgram& mShaderProgram; const sgct::ShaderProgram& getShader() { return mShaderProgram; } //POINTER to model in model pool (references are not swappable) //Needs to be swappable for collectible pooling Model* mModel; int mModelSlot = -1; //Render geometry and texture void renderModel() const { mModel->render(); }; //Set shader data void setShaderData() { mShaderProgram.bind(); mMvpMatrixLoc = glGetUniformLocation(mShaderProgram.id(), "mvp"); mTransMatrixLoc = glGetUniformLocation(mShaderProgram.id(), "transformation"); mViewMatrixLoc = glGetUniformLocation(mShaderProgram.id(), "view"); mCameraPosLoc = glGetUniformLocation(mShaderProgram.id(), "cameraPos"); mNormalMatrixLoc = glGetUniformLocation(mShaderProgram.id(), "normalMatrix"); mShaderProgram.unbind(); } };
33.779412
91
0.760993
pannacotta98
ae77f859778c1b360c7129fafbae886e03e4078c
620
hpp
C++
include/lol/def/LolPerksPerkSettingResource.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LolPerksPerkSettingResource.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LolPerksPerkSettingResource.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct LolPerksPerkSettingResource { std::vector<int32_t> perkIds; int32_t perkStyle; int32_t perkSubStyle; }; inline void to_json(json& j, const LolPerksPerkSettingResource& v) { j["perkIds"] = v.perkIds; j["perkStyle"] = v.perkStyle; j["perkSubStyle"] = v.perkSubStyle; } inline void from_json(const json& j, LolPerksPerkSettingResource& v) { v.perkIds = j.at("perkIds").get<std::vector<int32_t>>(); v.perkStyle = j.at("perkStyle").get<int32_t>(); v.perkSubStyle = j.at("perkSubStyle").get<int32_t>(); } }
32.631579
72
0.664516
Maufeat
ae793e7954aee583c7fba98fc87913e909733653
1,435
cpp
C++
library/crnd/src/api_cpp.cpp
jgsogo/cpp-inside
7b92ccd299f3c7d9f50a50ed6cfb6aeb56f04c74
[ "MIT" ]
1
2019-09-24T14:31:33.000Z
2019-09-24T14:31:33.000Z
library/crnd/src/api_cpp.cpp
jgsogo/cpp-inside
7b92ccd299f3c7d9f50a50ed6cfb6aeb56f04c74
[ "MIT" ]
2
2021-05-10T14:37:17.000Z
2022-02-10T19:24:11.000Z
library/crnd/src/api_cpp.cpp
jgsogo/cpp-inside
7b92ccd299f3c7d9f50a50ed6cfb6aeb56f04c74
[ "MIT" ]
1
2019-09-24T20:28:58.000Z
2019-09-24T20:28:58.000Z
#include "../include/api_cpp.h" #include <random> #include "spdlog/spdlog.h" #include "random_model.h" namespace { std::unique_ptr<crnd::Status> with_status(std::function<void (crnd::Status&)> f) { std::unique_ptr<crnd::Status> status = std::make_unique<crnd::Status>(); try { status->set_ok(true); // Set it to true first, so the function may modify it. f(*status); } catch (std::exception& e) { status->set_ok(false); status->set_error_code(1); status->set_error_message(e.what()); } return status; } } std::unique_ptr<crnd::Status> help(crnd::Help& help) { SPDLOG_DEBUG("> C++::help"); return with_status([&help](crnd::Status& status) { help.set_name("crnd"); help.set_description("Generate random numbers"); help.set_version("xxxx"); }); } std::unique_ptr<crnd::Status> sample(const crnd::SampleRequest& request, crnd::Sample& sample) { SPDLOG_DEBUG("> C++::sample"); return with_status([&request, &sample](crnd::Status& status) { std::mt19937 gen(request.seed()); auto model = get_random_generator<std::mt19937>(request.model()); sample.mutable_model()->CopyFrom(request.model()); sample.set_seed(request.seed()); for (int i=0; i<request.n_samples(); i++) { sample.add_samples(model(gen)); } }); }
29.895833
96
0.596516
jgsogo
ae799ce6bc16b48d7fc7ec7e33cd764f247c3cdd
1,191
hpp
C++
include/all_rounder.hpp
tomdodd4598/UCL-PHAS0100-CandamirTilesExample1
8a324462d93db49a6a2c88fb382bca110c7ec611
[ "MIT" ]
null
null
null
include/all_rounder.hpp
tomdodd4598/UCL-PHAS0100-CandamirTilesExample1
8a324462d93db49a6a2c88fb382bca110c7ec611
[ "MIT" ]
null
null
null
include/all_rounder.hpp
tomdodd4598/UCL-PHAS0100-CandamirTilesExample1
8a324462d93db49a6a2c88fb382bca110c7ec611
[ "MIT" ]
null
null
null
#ifndef ALL_ROUNDER_H #define ALL_ROUNDER_H #include "cricketer.hpp" #include <string> #include <utility> namespace cricket { class AllRounder : public Cricketer { public: template<typename NAME, typename... EQUIPMENT> AllRounder(NAME&& name, int batting_runs, int batting_balls, int dismissals, int bowling_runs, int bowling_balls, int wickets, EQUIPMENT&&... equipment) : Cricketer(std::forward<NAME>(name), std::forward<EQUIPMENT>(equipment)...) , batting_runs{batting_runs} , batting_balls{batting_balls} , dismissals{dismissals} , bowling_runs{bowling_runs} , bowling_balls{bowling_balls} , wickets{wickets} {} double get_batting_average() const; double get_batting_strike_rate() const; double get_bowling_average() const; double get_bowling_strike_rate() const; double get_bowling_economy_rate() const; virtual std::string to_string() const; int batting_runs; int batting_balls; int dismissals; int bowling_runs; int bowling_balls; int wickets; }; } #endif
25.891304
160
0.643157
tomdodd4598
ae7c7a21e5dc5122acab986da6f246109fa47696
5,339
hpp
C++
src/mge/core/stacktrace.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
src/mge/core/stacktrace.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
91
2019-03-09T11:31:29.000Z
2022-02-27T13:06:06.000Z
src/mge/core/stacktrace.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
// mge - Modern Game Engine // Copyright (c) 2021 by Alexander Schroeder // All rights reserved. /** @file */ #pragma once #include "mge/core/dllexport.hpp" #include "mge/core/string_pool.hpp" #include <string> #include <string_view> #include <vector> namespace mge { /** * @brief A stack backtrace. * */ class MGECORE_EXPORT stacktrace { public: /** * @brief A frame on the stack backtrace. */ class MGECORE_EXPORT frame { public: /** * @brief Construct a new frame object * * @param address address (program counter) * @param module module name (executable/shared library) * @param name name of frame (function) * @param file source code file * @param line source code line */ frame(const void* address, std::string_view module, std::string_view name, std::string_view file, uint32_t line); /** * @brief Copy constructor. * @param f copied frame */ frame(const frame& f) = default; ~frame() = default; /** * @brief Assignment. * * @return f assigned frame */ frame& operator=(const frame& f) = default; /** * @brief Get frame address. * * @return frame address */ const void* address() const noexcept { return m_address; } /** * @brief Frame name (method or function name) * * @return method or function name */ std::string_view name() const noexcept { return m_name; } /** * @brief Source file name. * * @return source file name */ std::string_view source_file() const noexcept { return m_source_file; } /** * @brief Source line number. * * @return source line number */ uint32_t source_line() const noexcept { return m_source_line; } /** * @brief Module name (executable or library) * * @return module name */ std::string_view module() const noexcept { return m_module; } private: const void* m_address; std::string_view m_name; std::string_view m_source_file; std::string_view m_module; uint32_t m_source_line; }; private: using frame_vector = std::vector<frame>; public: /// stack trace size using size_type = frame_vector::size_type; /// iterator on frames using const_iterator = frame_vector::const_iterator; /// iterator on frames using const_reverse_iterator = frame_vector::const_reverse_iterator; /** * @brief Construct stacktrace of current thread. */ stacktrace(); /** * @brief Copy constructor. * * @param s copied stack trace */ stacktrace(const stacktrace& s); /** * @brief Destructor. * */ ~stacktrace() = default; /** * @brief Assignment * * @param s assigned stack trace * @return @c *this */ stacktrace& operator=(const stacktrace& s); /** * @brief Number of frames. * * @return number of frames */ size_type size() const; /** * @brief Begin of frames. * * @return begin of frames */ const_iterator begin() const { return m_frames.begin(); } /** * @brief Reverse begin of frames. * * @return reverse begin of frames */ const_reverse_iterator rbegin() const { return m_frames.rbegin(); } /** * @brief End of frames. * * @return end of frames */ const_iterator end() const { return m_frames.end(); } /** * @brief Reverse end of frames. * * @return reverse end of frames */ const_iterator rend() const { return m_frames.end(); } /** * @brief Comparison. * * @param s compared stack trace * @return true if adresses match */ bool operator==(const stacktrace& s) const; /** * @brief Comparison. * * @param s compared stack trace * @return true if adresses do not match */ bool operator!=(const stacktrace& s) const; private: frame_vector m_frames; string_pool m_strings; }; /** * @brief Dump stack into stream. * * @param os output stream * @param s stack backtrace * @return @c os */ MGECORE_EXPORT std::ostream& operator<<(std::ostream& os, const stacktrace& s); } // namespace mge
27.101523
76
0.478929
mge-engine
ae7d69c4645db3634351dd9d3aa0bfa20558d263
1,637
cpp
C++
SPOJ/SAMER08F - Feynman.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
6
2018-11-26T02:38:07.000Z
2021-07-28T00:16:41.000Z
SPOJ/SAMER08F - Feynman.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
1
2021-05-30T09:25:53.000Z
2021-06-05T08:33:56.000Z
SPOJ/SAMER08F - Feynman.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
4
2020-04-16T07:15:01.000Z
2020-12-04T06:26:07.000Z
/*SAMER08F - Feynman no tags Richard Phillips Feynman was a well known American physicist and a recipient of the Nobel Prize in Physics. He worked in theoretical physics and also pioneered the field of quantum computing. He visited South America for ten months, giving lectures and enjoying life in the tropics. He is also known for his books "Surely You're Joking, Mr. Feynman!" and "What Do You Care What Other People Think?", which include some of his adventures below the equator. His life-long addiction was solving and making puzzles, locks, and cyphers. Recently, an old farmer in South America, who was a host to the young physicist in 1949, found some papers and notes that is believed to have belonged to Feynman. Among notes about mesons and electromagnetism, there was a napkin where he wrote a simple puzzle: "how many different squares are there in a grid of N ×N squares?". In the same napkin there was a drawing which is reproduced below, showing that, for N=2, the answer is 5. subir imagenes Input The input contains several test cases. Each test case is composed of a single line, containing only one integer N, representing the number of squares in each side of the grid (1 ≤ N ≤ 100). The end of input is indicated by a line containing only one zero. Output For each test case in the input, your program must print a single line, containing the number of different squares for the corresponding input. */ #include <iostream> inline int solve(int n) { return (2*n+1)*(n+1)*(n)/6; } int main() { for (int n; std::cin >> n && n != 0;) std::cout << solve(n) << std::endl; return 0; }
46.771429
455
0.745877
ravirathee
ae7d979107a95215f0032033d14e3830184e3c4b
1,802
cpp
C++
test/src/detail/offset_fetch_request_write_test.cpp
perchits/libkafka-asio
cbdced006d49a4498955a222915c6514b4ac57a7
[ "MIT" ]
77
2015-04-07T08:14:14.000Z
2022-02-14T01:07:05.000Z
test/src/detail/offset_fetch_request_write_test.cpp
perchits/libkafka-asio
cbdced006d49a4498955a222915c6514b4ac57a7
[ "MIT" ]
28
2015-04-07T08:57:41.000Z
2020-04-19T21:25:22.000Z
test/src/detail/offset_fetch_request_write_test.cpp
perchits/libkafka-asio
cbdced006d49a4498955a222915c6514b4ac57a7
[ "MIT" ]
48
2015-04-15T05:34:51.000Z
2022-03-17T11:50:20.000Z
// // detail/offset_fetch_request_write_test.cpp // ------------------------------------------ // // Copyright (c) 2015 Daniel Joos // // Distributed under MIT license. (See file LICENSE) // #include <gtest/gtest.h> #include <libkafka_asio/libkafka_asio.h> #include "StreamTest.h" using libkafka_asio::OffsetFetchRequest; class OffsetFetchRequestWriteTest : public ::testing::Test, public StreamTest { protected: void SetUp() { ResetStream(); } }; TEST_F(OffsetFetchRequestWriteTest, WriteRequestMessage) { OffsetFetchRequest request; request.set_consumer_group("TestGroup"); request.FetchOffset("Topic1", 0); request.FetchOffset("Topic1", 1); request.FetchOffset("Topic2", 1); libkafka_asio::detail::WriteRequestMessage(request, *stream); using namespace libkafka_asio::detail; ASSERT_STREQ("TestGroup", ReadString(*stream).c_str()); // ConsumerGroup ASSERT_EQ(2, ReadInt32(*stream)); // Topic array size ASSERT_STREQ("Topic1", ReadString(*stream).c_str()); // TopicName ASSERT_EQ(2, ReadInt32(*stream)); // Partition array size ASSERT_EQ(0, ReadInt32(*stream)); // Partition ASSERT_EQ(1, ReadInt32(*stream)); // Partition ASSERT_STREQ("Topic2", ReadString(*stream).c_str()); // TopicName ASSERT_EQ(1, ReadInt32(*stream)); // Partition array size ASSERT_EQ(1, ReadInt32(*stream)); // Partition // Nothing else ... ASSERT_EQ(0, streambuf->size()); } TEST_F(OffsetFetchRequestWriteTest, WriteRequestMessage_Empty) { OffsetFetchRequest request; libkafka_asio::detail::WriteRequestMessage(request, *stream); using namespace libkafka_asio::detail; ASSERT_STREQ("", ReadString(*stream).c_str()); // ConsumerGroup ASSERT_EQ(0, ReadInt32(*stream)); // Topic array size // Nothing else ... ASSERT_EQ(0, streambuf->size()); }
28.15625
75
0.705882
perchits
ae7f3c3b647c0dd8e2c9849c13dcc9266b37b3cb
270
cpp
C++
client/commands/Attack.cpp
fvazquezf/7542_TpFinal
1699d9cf97794186f7e41d3bb2d33ba9239eaa3f
[ "MIT" ]
null
null
null
client/commands/Attack.cpp
fvazquezf/7542_TpFinal
1699d9cf97794186f7e41d3bb2d33ba9239eaa3f
[ "MIT" ]
null
null
null
client/commands/Attack.cpp
fvazquezf/7542_TpFinal
1699d9cf97794186f7e41d3bb2d33ba9239eaa3f
[ "MIT" ]
null
null
null
#include "Attack.h" Attack::Attack(bool done) : done(done) { } void Attack::serialize(std::function<void(std::vector<unsigned char>)> &callback, const Protocol &protocol) { protocol.startStopCommand(done ? STOP_ATTACK : ATTACK, callback); } Attack::~Attack() { }
20.769231
109
0.707407
fvazquezf
ae7f91eead9906b48fc98847333f879acb97ad62
2,102
cpp
C++
src/er1controlapp.cpp
sfmabock/Evolution-Robot-1-Driver
47cf3d54f2b863aea75abb181ae39f1eb5b83232
[ "MIT" ]
null
null
null
src/er1controlapp.cpp
sfmabock/Evolution-Robot-1-Driver
47cf3d54f2b863aea75abb181ae39f1eb5b83232
[ "MIT" ]
null
null
null
src/er1controlapp.cpp
sfmabock/Evolution-Robot-1-Driver
47cf3d54f2b863aea75abb181ae39f1eb5b83232
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <SDL2/SDL.h> #include <er1driver/er1driver.hpp> int main(int argc, char** argv) { SDL_Event event; bool done = false; if (SDL_Init(SDL_INIT_VIDEO)!= 0) { return -1; } SDL_Window *window; window = SDL_CreateWindow( "An SDL2 window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL ); er1driver::SimpleER1Interface er1; er1.connect("/dev/serial/by-id/usb-Evolution_Robot_ER1_Control_Module_v1.0_ER1TQEG3-if00-port0"); int currentDown = 0; while (!done) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: { auto code = event.key.keysym.sym; if (code == SDLK_UP && currentDown != SDLK_UP) { currentDown = code; er1.move(er1driver::Direction::Forward); } else if (code == SDLK_DOWN && currentDown != SDLK_DOWN) { currentDown = code; er1.move(er1driver::Direction::Forward); } else if (code == SDLK_LEFT && currentDown != SDLK_LEFT) { currentDown = code; er1.turn(er1driver::Orientation::Left); } else if (code == SDLK_RIGHT && currentDown != SDLK_RIGHT){ currentDown = code; er1.turn(er1driver::Orientation::Right); } break; } case SDL_KEYUP: auto code = event.key.keysym.sym; if (code == SDLK_q) { done = true; } else if (code == currentDown) { er1.stop(); } currentDown = 0; break; } } } er1.disconnect(); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
28.405405
101
0.466698
sfmabock
ae81ca480c3a78888683d1ea42c464fd35699e3d
6,376
cpp
C++
src/view/configurator.cpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2020-04-10T14:39:00.000Z
2021-02-11T15:52:16.000Z
src/view/configurator.cpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2019-12-17T08:50:20.000Z
2020-02-03T09:37:56.000Z
src/view/configurator.cpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
1
2020-08-19T03:06:52.000Z
2020-08-19T03:06:52.000Z
#include <imgui.h> #include "utils/resource_manager.hpp" #include "view/configurator.hpp" #include "view/imgui_styles.hpp" // TODO : rendre la classe configurator statique (pas vraiment besoin de l’instancier plusieurs fois) using lang_info = std::remove_const_t<std::remove_reference_t< std::invoke_result<decltype(&utils::resource_manager::get_language_list), utils::resource_manager>::type>>::value_type; namespace { namespace idx { enum idx { general_lang, command_lang, gui_lang, log_lang, resource_pack, MAX, }; } constexpr const char window_name[] = "##configurator"; std::string display_name(const utils::resource_manager::resource_pack_info &resource_pack, const lang_info &user_lang) { if (auto it = resource_pack.names_by_shorthand_lang.find(user_lang.map_name); it != resource_pack.names_by_shorthand_lang.end()) { return it->second; } return resource_pack.default_name; } std::string display_name(const lang_info &lang) { std::string ans = lang.name; if (!lang.shorthand.empty()) { ans += " (" + lang.variant + ")"; } return ans; } template <typename T> const T *combo(std::string_view label, const std::vector<T> &choices, const lang_info &current_lang, float label_width, float combo_width) { // int idx = static_cast<int>(std::distance(langs.begin(), std::find(langs.begin(), langs.end(), current_lang))); const T *selected = nullptr; ImGui::TextUnformatted(label.data(), label.data() + label.size()); ImGui::SameLine(label_width); ImGui::PushID(label.data(), label.data() + label.size()); ImGui::SetNextItemWidth(combo_width); if (ImGui::BeginCombo("##lang_combo", display_name(current_lang).c_str(), ImGuiComboFlags_NoArrowButton)) { for (const T &current : choices) { bool is_selected = (current == current_lang); if (ImGui::Selectable(display_name(current).c_str(), is_selected)) { selected = &current; } if (is_selected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } ImGui::PopID(); return selected; } } // namespace void view::configurator::give_control() noexcept { m_graphics_changed = false; if (!m_showing) { if (m_popup_open) { if (ImGui::BeginPopupModal(window_name, nullptr, ImGuiWindowFlags_NoTitleBar)) { ImGui::CloseCurrentPopup(); ImGui::EndPopup(); m_popup_open = false; } if (m_config_must_be_saved) { m_resources.save_user_config(); m_config_must_be_saved = false; } } return; } if (!m_popup_open) { ImGui::OpenPopup(window_name); m_popup_open = true; m_resources.refresh_language_list(); m_resources.refresh_resource_pack_list(); } if (!ImGui::BeginPopupModal(window_name, nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) { m_popup_open = false; m_showing = false; return; } const ImGuiStyle &style = ImGui::GetStyle(); std::array<std::string_view, idx::MAX> labels; labels[idx::general_lang] = m_resources.gui_text_for("configurator.general_lang"); labels[idx::command_lang] = m_resources.gui_text_for("configurator.command_lang"); labels[idx::gui_lang] = m_resources.gui_text_for("configurator.gui_lang"); labels[idx::log_lang] = m_resources.gui_text_for("configurator.log_lang"); labels[idx::resource_pack] = m_resources.gui_text_for("configurator.resource_pack"); float labels_width{0}; for (const std::string_view str : labels) { labels_width = std::max(ImGui::CalcTextSize(str.data(), str.data() + str.size()).x, labels_width); } labels_width += style.ItemSpacing.x; // langs { const auto &langs = m_resources.get_language_list(); float combo_width{0}; for (const auto &lang : langs) { combo_width = std::max(ImGui::CalcTextSize(display_name(lang).c_str()).x, combo_width); } combo_width += style.ItemInnerSpacing.x; const lang_info *selection = nullptr; if (selection = combo(labels[idx::general_lang], langs, m_resources.user_general_lang(), labels_width, combo_width); selection != nullptr) { m_resources.set_user_general_lang(*selection); m_config_must_be_saved = true; } if (selection = combo(labels[idx::command_lang], langs, m_resources.user_commands_lang(), labels_width, combo_width); selection != nullptr) { m_resources.set_user_command_lang(*selection); m_config_must_be_saved = true; } if (selection = combo(labels[idx::gui_lang], langs, m_resources.user_gui_lang(), labels_width, combo_width); selection != nullptr) { m_resources.set_user_gui_lang(*selection); m_config_must_be_saved = true; } if (selection = combo(labels[idx::log_lang], langs, m_resources.user_log_lang(), labels_width, combo_width); selection != nullptr) { m_resources.set_user_log_lang(*selection); m_config_must_be_saved = true; } std::string_view import_lang = m_resources.gui_text_for("configurator.import_lang"); using_style(disabled_button) { if (ImGui::Button(import_lang.data(), {ImGui::GetContentRegionAvail().x, 0})) { } }; } ImGui::Separator(); // resource pack { const std::vector<utils::resource_manager::resource_pack_info> &resource_packs = m_resources.get_resource_pack_list(); ImGui::TextUnformatted(labels[idx::resource_pack].data(), labels[idx::resource_pack].data() + labels[idx::resource_pack].size()); ImGui::SameLine(labels_width); ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); if (ImGui::BeginCombo("##configurator.resource_pack", display_name(m_resources.user_resource_pack(), m_resources.user_gui_lang()).c_str(), ImGuiComboFlags_NoArrowButton)) { for (const auto &res_pack : resource_packs) { bool is_selected = (res_pack.file == m_resources.user_gui_lang().file); if (ImGui::Selectable(display_name(res_pack, m_resources.user_gui_lang()).c_str(), is_selected)) { m_resources.set_user_resource_pack(res_pack); m_graphics_changed = true; } if (is_selected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } std::string_view import_respack = m_resources.gui_text_for("configurator.import_respack"); using_style(disabled_button) { if (ImGui::Button(import_respack.data(), {ImGui::GetContentRegionAvail().x, 0})) { } }; } ImGui::EndPopup(); // TODO: bouton pour quitter le menu de configuration }
33.557895
140
0.715809
TiWinDeTea
ae84c70c639cb1814285852d0def8c2ee088ce16
211,852
cpp
C++
packages/data/epdl/test/tstPhotonDataProcessorShellMap.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/data/epdl/test/tstPhotonDataProcessorShellMap.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/data/epdl/test/tstPhotonDataProcessorShellMap.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file tstPhotonDataProcessorShellMap.cpp //! \author Alex Robinson //! \brief PhotonDataProcessor class electron shell map unit tests. //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> // Trilinos Includes #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_TwoDArray.hpp> // FRENSIE Includes #include "Data_PhotonDataProcessor.hpp" #include "Utility_UnitTestHarnessExtensions.hpp" #include "Utility_HDF5FileHandler.hpp" #include "Utility_Tuple.hpp" #include "HDF5DataFileNames.hpp" //---------------------------------------------------------------------------// // Test File Names. //---------------------------------------------------------------------------// std::string epdl_test_file; std::string eadl_test_file; std::string compton_test_file_prefix; //---------------------------------------------------------------------------// // Testing Structs. //---------------------------------------------------------------------------// class TestingPhotonDataProcessor : public Data::PhotonDataProcessor { public: TestingPhotonDataProcessor( const std::string epdl_file_name, const std::string eadl_file_name, const std::string compton_file_prefix, const std::string output_directory ) : Data::PhotonDataProcessor( epdl_file_name, eadl_file_name, compton_file_prefix, output_directory ) { /* ... */ } virtual ~TestingPhotonDataProcessor() { /* ... */ } using Data::PhotonDataProcessor::createShellIndexMap; }; //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=1 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_1 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 1, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=2 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_2 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 2, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=3 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_3 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 3, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=4 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_4 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 4, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=5 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_5 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 5, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=6 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_6 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 6, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=7 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_7 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 7, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=8 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_8 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 8, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=9 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_9 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 9, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=10 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_10 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 10, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=11 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_11 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 11, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=12 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_12 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 12, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=13 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_13 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 13, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=14 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_14 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 14, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=15 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_15 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 15, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=16 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_16 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 16, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=17 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_17 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 17, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=18 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_18 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 18, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=19 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_19 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 19, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 5; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=20 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_20 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 20, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 5; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=21 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_21 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 21, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=22 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_22 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 22, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=23 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_23 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 23, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=24 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_24 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 24, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=25 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_25 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 25, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=26 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_26 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 26, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=27 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_27 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 27, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=28 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_28 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 28, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=29 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_29 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 29, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=30 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_30 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 30, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=31 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_31 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 31, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 7; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=32 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_32 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 32, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 7; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=34 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_34 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 34, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 7; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=35 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_35 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 35, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 7; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=36 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_36 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 36, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=37 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_37 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 37, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 12; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=38 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_38 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 38, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 12; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=39 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_39 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 39, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 13; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=40 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_40 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 40, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 13; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=41 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_41 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 41, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 13; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=42 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_42 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 42, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=43 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_43 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 43, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=44 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_44 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 44, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=45 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_45 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 45, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=46 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_46 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 46, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=47 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_47 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 47, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=48 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_48 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 48, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=49 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_49 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 49, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 15; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=50 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_50 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 50, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 15; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=51 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_51 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 51, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 16; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=52 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_52 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 52, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 16; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=53 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_53 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 53, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 16; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=54 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_54 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 54, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 16; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=55 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_55 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 55, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 17; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=56 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_56 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 56, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 17; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=57 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_57 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 57, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 18; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=58 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_58 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 58, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 19; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=59 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_59 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 59, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 18; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=60 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_60 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 60, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 18; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=61 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_61 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 61, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 18; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=62 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_62 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 62, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 18; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=63 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_63 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 63, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 19; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=64 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_64 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 64, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 20; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=65 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_65 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 65, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 19; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=66 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_66 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 66, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 19; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=67 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_67 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 67, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 19; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=68 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_68 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 68, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 19; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=69 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_69 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 69, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 19; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=70 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_70 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 70, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 19; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=71 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_71 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 71, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 20; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=72 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_72 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 72, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 20; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=73 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_73 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 73, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 20; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=74 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_74 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 74, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 20; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=75 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_75 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 75, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=76 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_76 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 76, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=77 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_77 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 77, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=78 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_78 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 78, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=79 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_79 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 79, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=80 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_80 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 80, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=81 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_81 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 81, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 22; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=82 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_82 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 82, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 22; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=83 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_83 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 83, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 23; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=84 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_84 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 84, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 23; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=85 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_85 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 85, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 23; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=86 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_86 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 86, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 23; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=87 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_87 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 87, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 24; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=88 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_88 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 88, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 24; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=89 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_89 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 89, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 46; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 47; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 25; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=90 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_90 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 90, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 46; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 47; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 25; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=91 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_91 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 91, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 46; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 47; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 26; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=92 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_92 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 92, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 46; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 47; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 26; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=93 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_93 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 93, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 46; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 47; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 26; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=94 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_94 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 94, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 25; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=95 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_95 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 95, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 26; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=96 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_96 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 96, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 46; data_point.second = 26; map_true.push_back( data_point ); data_point.first = 47; data_point.second = 26; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 27; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=97 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_97 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 97, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 46; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 47; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 26; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=98 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_98 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 98, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 26; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=99 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_99 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 99, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 26; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // check that the PhotonDataProcessor can create the correct electron shell // index map for Z=100 TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_100 ) { TestingPhotonDataProcessor photon_data_processor( epdl_test_file, eadl_test_file, compton_test_file_prefix, "" ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map; photon_data_processor.createShellIndexMap( 100, map ); Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true; Utility::Pair<unsigned int,unsigned int> data_point; data_point.first = 1; data_point.second = 0; map_true.push_back( data_point ); data_point.first = 3; data_point.second = 1; map_true.push_back( data_point ); data_point.first = 5; data_point.second = 2; map_true.push_back( data_point ); data_point.first = 6; data_point.second = 3; map_true.push_back( data_point ); data_point.first = 8; data_point.second = 4; map_true.push_back( data_point ); data_point.first = 10; data_point.second = 5; map_true.push_back( data_point ); data_point.first = 11; data_point.second = 6; map_true.push_back( data_point ); data_point.first = 13; data_point.second = 7; map_true.push_back( data_point ); data_point.first = 14; data_point.second = 8; map_true.push_back( data_point ); data_point.first = 16; data_point.second = 9; map_true.push_back( data_point ); data_point.first = 18; data_point.second = 10; map_true.push_back( data_point ); data_point.first = 19; data_point.second = 11; map_true.push_back( data_point ); data_point.first = 21; data_point.second = 12; map_true.push_back( data_point ); data_point.first = 22; data_point.second = 13; map_true.push_back( data_point ); data_point.first = 24; data_point.second = 14; map_true.push_back( data_point ); data_point.first = 25; data_point.second = 15; map_true.push_back( data_point ); data_point.first = 27; data_point.second = 16; map_true.push_back( data_point ); data_point.first = 29; data_point.second = 17; map_true.push_back( data_point ); data_point.first = 30; data_point.second = 18; map_true.push_back( data_point ); data_point.first = 32; data_point.second = 19; map_true.push_back( data_point ); data_point.first = 33; data_point.second = 20; map_true.push_back( data_point ); data_point.first = 35; data_point.second = 21; map_true.push_back( data_point ); data_point.first = 36; data_point.second = 22; map_true.push_back( data_point ); data_point.first = 41; data_point.second = 23; map_true.push_back( data_point ); data_point.first = 43; data_point.second = 24; map_true.push_back( data_point ); data_point.first = 44; data_point.second = 25; map_true.push_back( data_point ); data_point.first = 58; data_point.second = 26; map_true.push_back( data_point ); UTILITY_TEST_COMPARE_ARRAYS( map, map_true ); } //---------------------------------------------------------------------------// // Custom main function //---------------------------------------------------------------------------// int main( int argc, char* argv[] ) { Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP(); clp.setOption( "epdl_test_file", &epdl_test_file, "EPDL test file name" ); clp.setOption( "eadl_test_file", &eadl_test_file, "EADL test file name" ); clp.setOption( "compton_test_file_prefix", &compton_test_file_prefix, "Compton profile test file prefix" ); Teuchos::GlobalMPISession mpiSession( &argc, &argv ); return Teuchos::UnitTestRepository::runUnitTestsFromMain( argc, argv ); } //---------------------------------------------------------------------------// // end tstPhotonDataProcessorShellMap.cpp //---------------------------------------------------------------------------//
25.035689
79
0.686677
lkersting
ae87152dbc2fc8a731ff4c6cbd55b802481f00d4
2,837
cpp
C++
src/io.cpp
sqt/sudoku
b536c663af5b6d6f0c8b8a728e595f3dfde499b5
[ "BSD-3-Clause" ]
null
null
null
src/io.cpp
sqt/sudoku
b536c663af5b6d6f0c8b8a728e595f3dfde499b5
[ "BSD-3-Clause" ]
null
null
null
src/io.cpp
sqt/sudoku
b536c663af5b6d6f0c8b8a728e595f3dfde499b5
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <cmath> #include <sstream> #include "io.hpp" PuzzleState readPuzzleFromFile(std::ifstream& ifs) { PuzzleState result; EntryState unknown_entry; for (uint8_t i = 1; i < 10; ++i) unknown_entry.insert(i); for (std::string line; std::getline(ifs, line); ) { if (line.empty() == false) { RowState row; std::stringstream ss(line); while (ss.good()) { uint16_t value; ss >> value; if (value == 0) { row.push_back(unknown_entry); } else { EntryState entry; entry.insert(std::min(static_cast<uint8_t>(value), static_cast<uint8_t>(9u))); row.push_back(entry); } } result.push_back(row); } } return result; } PuzzleState readPuzzleFromJSON(const std::string& json) { PuzzleState result; std::vector<size_t> values; size_t sloc = json.find_first_of("[") + 1; while (sloc != std::string::npos && sloc < json.size()) { size_t eloc = json.find_first_of(",]", sloc); size_t value = std::strtoull(json.substr(sloc, eloc - sloc).data(), NULL, 10); values.push_back(value); sloc = eloc + 1; } size_t root = static_cast<size_t>(std::sqrt(static_cast<double>(values.size()))); if (root * root != values.size()) { return result; } EntryState unknown_entry; for (size_t i = 1; i < root + 1; ++i) unknown_entry.insert(i); for (size_t i = 0; i < root; ++i) { RowState row; for (size_t j = 0; j < root; ++j) { size_t value = values[i * root + j]; if (value != 0) { EntryState entry; entry.insert(value); row.push_back(entry); } else { row.push_back(unknown_entry); } } result.push_back(row); } return result; } void printRow(const RowState& row, std::ostream& os) { for (auto j = row.cbegin(); j < row.cend(); ++j) { if (j->size() == 0) // Zero Options Remaining (Should Not Happen) { os << "- " << std::flush; } else if (j->size() == 1) { os << static_cast<uint16_t>(*(j->cbegin())) << " " << std::flush; } else { os << " " << std::flush; } } } void printJSONRow(const RowState& row, std::ostream& os) { for (auto j = row.cbegin(); j < row.cend(); ++j) { if (j != row.cbegin()) { os << ','; } if (j->size() == 0) // Zero Options Remaining (Should Not Happen) { os << '0'; } else if (j->size() == 1) { os << static_cast<uint16_t>(*(j->cbegin())); } else { os << ' '; } } } void printSolution(const PuzzleState& state, std::ostream& os) { for (auto i = state.cbegin(); i < state.cend(); ++i) { printRow(*i, os); os << std::endl; } } void printJSONSolution(const PuzzleState& state, std::ostream& os) { os << '['; for (auto i = state.cbegin(); i < state.cend(); ++i) { if (i != state.cbegin()) { os << ','; } printJSONRow(*i, os); } os << ']' << std::flush; }
17.955696
83
0.572788
sqt
ae88e50ec6eef358fdc5be75c59fd1b69f95f254
39,698
cc
C++
src/muensterTPCPhysicsList.cc
l-althueser/MuensterTPC-Simulation
7a086ab330cd5905f3c78c324936cdc36951e9bd
[ "BSD-2-Clause" ]
null
null
null
src/muensterTPCPhysicsList.cc
l-althueser/MuensterTPC-Simulation
7a086ab330cd5905f3c78c324936cdc36951e9bd
[ "BSD-2-Clause" ]
2
2017-01-24T21:18:46.000Z
2017-01-27T13:24:48.000Z
src/muensterTPCPhysicsList.cc
l-althueser/MuensterTPC-Simulation
7a086ab330cd5905f3c78c324936cdc36951e9bd
[ "BSD-2-Clause" ]
4
2017-04-28T12:18:58.000Z
2019-04-10T21:15:00.000Z
/****************************************************************** * muensterTPCsim * * Simulations of the Muenster TPC * * @author Lutz Althüser, based on muensterTPC (Levy) and Xenon100 * @date 2015-04-14 * @update 2016-02-16 * * @comment - ready for G4 V10.02 * - added some festures of the new G4 versions (modular physics lists) ******************************************************************/ #include <G4ProcessManager.hh> #include <G4ProcessVector.hh> #include <G4ParticleDefinition.hh> #include <G4ParticleWithCuts.hh> #include <G4ParticleTypes.hh> #include <G4ParticleTable.hh> #include <G4HadronCaptureProcess.hh> #include <G4UserLimits.hh> #include "G4UserSpecialCuts.hh" #include <G4ios.hh> #include <globals.hh> #include "G4SystemOfUnits.hh" #include "G4PhysicsListHelper.hh" #include <iomanip> #include <G4EmStandardPhysics.hh> #include <G4EmLivermorePhysics.hh> #include <G4EmPenelopePhysics.hh> #include "muensterTPCPhysicsList.hh" #include "muensterTPCPhysicsMessenger.hh" #include "G4VPhysicsConstructor.hh" #include "G4HadronPhysicsQGSP_BERT.hh" #include "G4HadronPhysicsQGSP_BERT_HP.hh" #include "G4EmExtraPhysics.hh" #include "G4HadronElasticPhysics.hh" #include "G4HadronElasticPhysicsHP.hh" #include "G4StoppingPhysics.hh" #include "G4IonPhysics.hh" #include "G4NeutronTrackingCut.hh" // Constructor ///////////////////////////////////////////////////////////// muensterTPCPhysicsList::muensterTPCPhysicsList():G4VUserPhysicsList() { defaultCutValue = 1.0 * mm; // cutForGamma = defaultCutValue; cutForElectron = defaultCutValue; cutForPositron = defaultCutValue; VerboseLevel = 0; OpVerbLevel = 0; SetVerboseLevel(VerboseLevel); m_pMessenger = new muensterTPCPhysicsMessenger(this); particleList = new G4DecayPhysics("decays"); } // Destructor ////////////////////////////////////////////////////////////// muensterTPCPhysicsList::~muensterTPCPhysicsList() { delete emPhysicsList; delete particleList; // delete opPhysicsList; delete m_pMessenger; for(size_t i=0; i<hadronPhys.size(); i++) { delete hadronPhys[i]; } } // Construct Particles ///////////////////////////////////////////////////// void muensterTPCPhysicsList::ConstructParticle() { // In this method, static member functions should be called // for all particles which you want to use. // This ensures that objects of these particle types will be // created in the program. //if (m_hHadronicModel == "custom"){ //G4cout << "----- ConstructMyBosons" << G4endl; ConstructMyBosons(); //G4cout << "----- ConstructMyLeptons" << G4endl; ConstructMyLeptons(); //G4cout << "----- ConstructMyHadrons" << G4endl; ConstructMyHadrons(); //G4cout << "----- ConstructMyShortLiveds" << G4endl; ConstructMyShortLiveds(); //} else if (m_hHadronicModel == "QGSP_BERT_HP") { particleList->ConstructParticle(); //} } // construct Bosons:///////////////////////////////////////////////////// void muensterTPCPhysicsList::ConstructMyBosons() { // pseudo-particles G4Geantino::GeantinoDefinition(); G4ChargedGeantino::ChargedGeantinoDefinition(); // gamma G4Gamma::GammaDefinition(); //OpticalPhotons G4OpticalPhoton::OpticalPhotonDefinition(); } // construct Leptons:///////////////////////////////////////////////////// void muensterTPCPhysicsList::ConstructMyLeptons() { // leptons G4Electron::ElectronDefinition(); G4Positron::PositronDefinition(); G4MuonPlus::MuonPlusDefinition(); G4MuonMinus::MuonMinusDefinition(); G4NeutrinoE::NeutrinoEDefinition(); G4AntiNeutrinoE::AntiNeutrinoEDefinition(); G4NeutrinoMu::NeutrinoMuDefinition(); G4AntiNeutrinoMu::AntiNeutrinoMuDefinition(); } #include "G4MesonConstructor.hh" #include "G4BaryonConstructor.hh" #include "G4IonConstructor.hh" // construct Hadrons:///////////////////////////////////////////////////// void muensterTPCPhysicsList::ConstructMyHadrons() { // mesons G4MesonConstructor mConstructor; mConstructor.ConstructParticle(); // baryons G4BaryonConstructor bConstructor; bConstructor.ConstructParticle(); // ions G4IonConstructor iConstructor; iConstructor.ConstructParticle(); } // construct Shortliveds:///////////////////////////////////////////////////// // this can be added if necessary //#include "G4ShortLivedConstructor.hh" void muensterTPCPhysicsList::ConstructMyShortLiveds() { //G4ShortLivedConstructor slConstructor; //slConstructor.ConstructParticle(); } // Construct Processes ////////////////////////////////////////////////////// void muensterTPCPhysicsList::ConstructProcess() { G4cout <<"MuensterTPCPhysicsList::MuensterTPCPhysicsList() EM physics: "<< m_hEMlowEnergyModel << G4endl; G4cout <<"MuensterTPCPhysicsList::MuensterTPCPhysicsList() Cerenkov: "<< m_bCerenkov << G4endl; AddTransportation(); // EM physics if (m_hEMlowEnergyModel == "emstandard") { emPhysicsList = new G4EmStandardPhysics(); } else if (m_hEMlowEnergyModel == "emlivermore"){ emPhysicsList = new G4EmLivermorePhysics(); } else if (m_hEMlowEnergyModel == "empenelope"){ emPhysicsList = new G4EmPenelopePhysics(); } else if (m_hEMlowEnergyModel == "old") { G4cout << "MuensterTPCPhysicsList::ConstructProcess() WARNING: Old version of low energy EM processes ... "<<G4endl; } else { G4cout <<"MuensterTPCPhysicsList::MuensterTPCPhysicsList() FATAL: Bad EM physics list chosen: "<<m_hEMlowEnergyModel<<G4endl; G4String msg = " Available choices are: <emstandard> <emlivermore (default)> <empenelope> <old>"; G4Exception("MuensterTPCPhysicsList::ConstructProcess()","PhysicsList",FatalException,msg); } // add the physics processes if (m_hEMlowEnergyModel != "old"){ emPhysicsList->ConstructProcess(); } else { ConstructEM(); // obsolete in GEANT4_VERSION > geant4.9.4.p02 } // construct optical physics...... is there a G4 standard for this one as well? ConstructOp(); //opPhysicsList = new G4OpticalPhysics(); // opPhysicsList->ConstructProcess(); // construct the Hadronic physics models hadronPhys.clear(); if (m_hHadronicModel == "custom") { // custom hadronic physics list ConstructHad(); } else if (m_hHadronicModel == "QGSP_BERT") { // implemented QGSP_BERT: is it done in the right way? // this follows the recipe from examples/extended/hadronic/Hadr01 SetBuilderList1(false); hadronPhys.push_back( new G4HadronPhysicsQGSP_BERT()); } else if (m_hHadronicModel == "QGSP_BERT_HP") { // implemented QGSP_BERT_HP: is it done in the right way? // this follows the recipe from examples/extended/hadronic/Hadr01 SetBuilderList1(true); hadronPhys.push_back( new G4HadronPhysicsQGSP_BERT_HP()); } else { G4String msg = "MuensterTPCPhysicsList::MuensterTPCPhysicsList() Available choices for Hadronic Physics are: <custom> <QGSP_BERT> <QGSP_BERT_HP>"; G4Exception("MuensterTPCPhysicsList::ConstructProcess()","PhysicsList",FatalException,msg); } // construct processes for(size_t i=0; i<hadronPhys.size(); i++) { hadronPhys[i]->ConstructProcess(); } // some other stuff if (m_hHadronicModel == "custom"){ ConstructGeneral(); } else if (m_hHadronicModel == "QGSP_BERT_HP" || m_hHadronicModel == "QGSP_BERT" ) { particleList->ConstructProcess(); ConstructGeneral(); } } void muensterTPCPhysicsList::SetBuilderList1(G4bool flagHP) { hadronPhys.push_back( new G4EmExtraPhysics()); if(flagHP) { hadronPhys.push_back( new G4HadronElasticPhysicsHP() ); } else { hadronPhys.push_back( new G4HadronElasticPhysics() ); } hadronPhys.push_back( new G4StoppingPhysics()); hadronPhys.push_back( new G4IonPhysics()); hadronPhys.push_back( new G4NeutronTrackingCut()); } // Transportation /////////////////////////////////////////////////////////// //#include "XeMaxTimeCuts.hh" //#include "XeMinEkineCuts.hh" void muensterTPCPhysicsList::AddTransportation() { //G4cout << "----- AddTransportation" << G4endl; G4VUserPhysicsList::AddTransportation(); // theParticleIterator->reset(); // while((*theParticleIterator) ()) // { // G4ParticleDefinition *particle = theParticleIterator->value(); // G4ProcessManager *pmanager = particle->GetProcessManager(); // G4String particleName = particle->GetParticleName(); // if(particleName == "neutron") // pmanager->AddDiscreteProcess(new XeMaxTimeCuts()); // pmanager->AddDiscreteProcess(new XeMinEkineCuts()); // } } // Electromagnetic Processes //////////////////////////////////////////////// // all charged particles // gamma #include "G4PhotoElectricEffect.hh" #include "G4LivermorePhotoElectricModel.hh" #include "G4ComptonScattering.hh" #include "G4LivermoreComptonModel.hh" #include "G4GammaConversion.hh" #include "G4LivermoreGammaConversionModel.hh" #include "G4RayleighScattering.hh" #include "G4LivermoreRayleighModel.hh" // e- #include "G4eMultipleScattering.hh" #include "G4eIonisation.hh" #include "G4LivermoreIonisationModel.hh" #include "G4eBremsstrahlung.hh" #include "G4LivermoreBremsstrahlungModel.hh" // e+ #include "G4eIonisation.hh" #include "G4eBremsstrahlung.hh" #include "G4eplusAnnihilation.hh" // alpha and GenericIon and deuterons, triton, He3: //muon: #include "G4MuIonisation.hh" #include "G4MuBremsstrahlung.hh" #include "G4MuPairProduction.hh" #include "G4MuonMinusCapture.hh" //OTHERS: #include "G4hIonisation.hh" #include "G4hMultipleScattering.hh" #include "G4hBremsstrahlung.hh" #include "G4ionIonisation.hh" #include "G4IonParametrisedLossModel.hh" //em process options to allow msc step-limitation to be switched off #include "G4EmProcessOptions.hh" void muensterTPCPhysicsList::ConstructEM() { //G4cout << "----- ConstructEM" << G4endl; // Is there a fluorcut missing? // at the end the fluorescence is switched to off (end of this chapter) //G4double fluorcut = 250 * eV; //set a finer grid of the physic tables in order to improve precision //former LowEnergy models have 200 bins up to 100 GeV G4EmProcessOptions opt; opt.SetMaxEnergy(100*GeV); opt.SetDEDXBinning(200); opt.SetLambdaBinning(200); theParticleIterator->reset(); while((*theParticleIterator) ()) { G4ParticleDefinition *particle = theParticleIterator->value(); G4ProcessManager *pmanager = particle->GetProcessManager(); G4String particleName = particle->GetParticleName(); G4String particleType = particle->GetParticleType(); G4double charge = particle->GetPDGCharge(); //the Livermore models are not strictly necessary if(particleName == "gamma") { //gamma G4RayleighScattering* theRayleigh = new G4RayleighScattering(); //theRayleigh->SetEmModel(new G4LivermoreRayleighModel()); pmanager->AddDiscreteProcess(theRayleigh); G4PhotoElectricEffect* thePhotoElectricEffect = new G4PhotoElectricEffect(); //thePhotoElectricEffect->SetEmModel(new G4LivermorePhotoElectricModel()); //thePhotoElectricEffect->SetCutForLowEnSecPhotons(fluorcut); pmanager->AddDiscreteProcess(thePhotoElectricEffect); G4ComptonScattering* theComptonScattering = new G4ComptonScattering(); //theComptonScattering->SetEmModel(new G4LivermoreComptonModel()); pmanager->AddDiscreteProcess(theComptonScattering); G4GammaConversion* theGammaConversion = new G4GammaConversion(); //theGammaConversion->SetEmModel(new G4LivermoreGammaConversionModel()); pmanager->AddDiscreteProcess(theGammaConversion); } else if(particleName == "e-") { //electron // process ordering: AddProcess(name, at rest, along step, post step) // -1 = not implemented, then ordering // Multiple scattering G4eMultipleScattering* msc = new G4eMultipleScattering(); msc->SetStepLimitType(fUseDistanceToBoundary); pmanager->AddProcess(msc,-1, 1, 1); // Ionisation G4eIonisation* eIonisation = new G4eIonisation(); //eIonisation->SetCutForLowEnSecPhotons(fluorcut); //eIonisation->SetEmModel(new G4LivermoreIonisationModel()); eIonisation->SetStepFunction(0.2, 100*um); //improved precision in tracking pmanager->AddProcess(eIonisation,-1, 2, 2); // Bremsstrahlung G4eBremsstrahlung* eBremsstrahlung = new G4eBremsstrahlung(); //eBremsstrahlung->SetEmModel(new G4LivermoreBremsstrahlungModel()); //eBremsstrahlung->SetCutForLowEnSecPhotons(fluorcut); pmanager->AddProcess(eBremsstrahlung, -1,-1, 3); } else if(particleName == "e+") { //positron G4eMultipleScattering* msc = new G4eMultipleScattering(); msc->SetStepLimitType(fUseDistanceToBoundary); pmanager->AddProcess(msc,-1, 1, 1); // Ionisation G4eIonisation* eIonisation = new G4eIonisation(); eIonisation->SetStepFunction(0.2, 100*um); pmanager->AddProcess(eIonisation, -1, 2, 2); //Bremsstrahlung (use default, no low-energy available) pmanager->AddProcess(new G4eBremsstrahlung(), -1,-1, 3); //Annihilation pmanager->AddProcess(new G4eplusAnnihilation(), 0, -1, 4); } else if(particleName == "mu+" || particleName == "mu-") { //muon pmanager->AddProcess(new G4eMultipleScattering,-1, 1, 1); pmanager->AddProcess(new G4MuIonisation(),-1, 2, 2); pmanager->AddProcess(new G4MuBremsstrahlung(),-1,-1, 3); pmanager->AddProcess(new G4MuPairProduction(),-1,-1, 4); if( particleName == "mu-" ) pmanager->AddProcess(new G4MuonMinusCapture(), 0,-1,-1); } // nucleus is not used yet // (particleType == "nucleus" && charge != 0) else if (particleName == "proton" || particleName == "pi+" || particleName == "pi-") { //multiple scattering pmanager->AddProcess(new G4hMultipleScattering, -1, 1, 1); //ionisation G4hIonisation* hIonisation = new G4hIonisation(); hIonisation->SetStepFunction(0.2, 50*um); pmanager->AddProcess(hIonisation,-1, 2, 2); //bremmstrahlung pmanager->AddProcess(new G4hBremsstrahlung,-1,-3, 3); } else if (particleName == "alpha" || particleName == "deuteron" || particleName == "triton" || particleName == "He3") { //multiple scattering pmanager->AddProcess(new G4hMultipleScattering,-1,1,1); //ionisation G4ionIonisation* ionIoni = new G4ionIonisation(); ionIoni->SetStepFunction(0.1, 20*um); pmanager->AddProcess(ionIoni,-1, 2, 2); } else if (particleName == "GenericIon") { // OBJECT may be dynamically created as either a GenericIon or nucleus // G4Nucleus exists and therefore has particle type nucleus // genericIon: //multiple scattering pmanager->AddProcess(new G4hMultipleScattering,-1,1,1); //ionisation G4ionIonisation* ionIoni = new G4ionIonisation(); ionIoni->SetEmModel(new G4IonParametrisedLossModel()); ionIoni->SetStepFunction(0.1, 20*um); pmanager->AddProcess(ionIoni,-1, 2, 2); } else if ((!particle->IsShortLived()) && (charge != 0.0) && (particle->GetParticleName() != "chargedgeantino")) { //all others charged particles except geantino G4hMultipleScattering* aMultipleScattering = new G4hMultipleScattering(); G4hIonisation* ahadronIon = new G4hIonisation(); //multiple scattering pmanager->AddProcess(aMultipleScattering,-1,1,1); //ionisation pmanager->AddProcess(ahadronIon,-1,2,2); } } // turn off msc step-limitation - especially as electron cut 1nm opt.SetMscStepLimitation(fMinimal); // switch on fluorescence, PIXE and Auger: opt.SetFluo(false); opt.SetPIXE(false); opt.SetAuger(false); } // Optical Processes //////////////////////////////////////////////////////// #include "G4Scintillation.hh" #include "G4OpAbsorption.hh" #include "G4OpRayleigh.hh" #include "G4OpBoundaryProcess.hh" #include "G4Cerenkov.hh" void muensterTPCPhysicsList::ConstructOp() { //G4cout << "----- ConstructOp" << G4endl; // default scintillation process G4Scintillation *theScintProcessDef = new G4Scintillation("Scintillation"); // theScintProcessDef->DumpPhysicsTable(); theScintProcessDef->SetTrackSecondariesFirst(true); theScintProcessDef->SetScintillationYieldFactor(1.0); theScintProcessDef->SetScintillationExcitationRatio(0.0); theScintProcessDef->SetVerboseLevel(OpVerbLevel); // scintillation process for alpha: G4Scintillation *theScintProcessAlpha = new G4Scintillation("Scintillation"); // theScintProcessNuc->DumpPhysicsTable(); theScintProcessAlpha->SetTrackSecondariesFirst(true); theScintProcessAlpha->SetScintillationYieldFactor(1.1); theScintProcessAlpha->SetScintillationExcitationRatio(1.0); theScintProcessAlpha->SetVerboseLevel(OpVerbLevel); // scintillation process for heavy nuclei G4Scintillation *theScintProcessNuc = new G4Scintillation("Scintillation"); // theScintProcessNuc->DumpPhysicsTable(); theScintProcessNuc->SetTrackSecondariesFirst(true); theScintProcessNuc->SetScintillationYieldFactor(0.2); theScintProcessNuc->SetScintillationExcitationRatio(1.0); theScintProcessNuc->SetVerboseLevel(OpVerbLevel); // add Cerenkov G4Cerenkov *fCerenkovProcess = new G4Cerenkov("Cerenkov"); if (m_bCerenkov) { G4cout <<"muensterTPCPhysicsList::ConstructOp() Define Cerenkov .... "<<G4endl; // the maximum numer of photons per GEANT4 step.... G4double fMaxNumPhotons = 100; // same as in G4OpticalPhysics.cc I think, but no guarantees // the maximum change in beta=v/c in percent G4double fMaxBetaChange = 10; // same as in G4OpticalPhysics.cc // tracks secondaries before continuing with the original particle G4bool fTrackSecondariesFirst = true; // same as in G4OpticalPhysics.cc fCerenkovProcess->SetMaxNumPhotonsPerStep(fMaxNumPhotons); fCerenkovProcess->SetMaxBetaChangePerStep(fMaxBetaChange); fCerenkovProcess->SetTrackSecondariesFirst(fTrackSecondariesFirst); } else { G4cout <<"muensterTPCPhysicsList::ConstructOp() Disable Cerenkov .... "<<G4endl; } // optical processes G4OpAbsorption *theAbsorptionProcess = new G4OpAbsorption(); G4OpRayleigh *theRayleighScatteringProcess = new G4OpRayleigh(); G4OpBoundaryProcess *theBoundaryProcess = new G4OpBoundaryProcess(); //theAbsorptionProcess->DumpPhysicsTable(); //theRayleighScatteringProcess->DumpPhysicsTable(); theAbsorptionProcess->SetVerboseLevel(OpVerbLevel); theRayleighScatteringProcess->SetVerboseLevel(OpVerbLevel); theBoundaryProcess->SetVerboseLevel(OpVerbLevel); //20th Jun 2012 P.Gumplinger (op-V09-05-04) //remove methods: SetModel/GetModel from G4OpBoundaryProcess class // -> remove: //G4OpticalSurfaceModel themodel = unified; //theBoundaryProcess->SetModel(themodel); theParticleIterator->reset(); while((*theParticleIterator) ()) { G4ParticleDefinition *particle = theParticleIterator->value(); G4ProcessManager *pmanager = particle->GetProcessManager(); G4String particleName = particle->GetParticleName(); if(theScintProcessDef->IsApplicable(*particle)) { // if(particle->GetPDGMass() > 5.0*GeV) if(particle->GetParticleName() == "GenericIon") { pmanager->AddProcess(theScintProcessNuc); // AtRestDiscrete pmanager->SetProcessOrderingToLast(theScintProcessNuc, idxAtRest); pmanager->SetProcessOrderingToLast(theScintProcessNuc, idxPostStep); } else if(particle->GetParticleName() == "alpha") { pmanager->AddProcess(theScintProcessAlpha); pmanager->SetProcessOrderingToLast(theScintProcessAlpha, idxAtRest); pmanager->SetProcessOrderingToLast(theScintProcessAlpha, idxPostStep); } else { pmanager->AddProcess(theScintProcessDef); pmanager->SetProcessOrderingToLast(theScintProcessDef, idxAtRest); pmanager->SetProcessOrderingToLast(theScintProcessDef, idxPostStep); } } if(particleName == "opticalphoton") { // Step limitation seen as a process pmanager->AddProcess(new G4UserSpecialCuts(),-1,-1,1); pmanager->AddDiscreteProcess(theAbsorptionProcess); pmanager->AddDiscreteProcess(theRayleighScatteringProcess); pmanager->AddDiscreteProcess(theBoundaryProcess); } // ... and give those particles that need it a bit of Cerenkov.... and only if you want to if(fCerenkovProcess->IsApplicable(*particle) && m_bCerenkov){ pmanager->AddProcess(fCerenkovProcess); pmanager->SetProcessOrdering(fCerenkovProcess,idxPostStep); } } } // Hadronic processes //////////////////////////////////////////////////////// // for more information see: DMXPhysicsList.cc (Geant4.10 example source) // Elastic processes: #include "G4HadronElasticProcess.hh" #include "G4ChipsElasticModel.hh" #include "G4ElasticHadrNucleusHE.hh" // Inelastic processes: #include "G4PionPlusInelasticProcess.hh" #include "G4PionMinusInelasticProcess.hh" #include "G4KaonPlusInelasticProcess.hh" #include "G4KaonZeroSInelasticProcess.hh" #include "G4KaonZeroLInelasticProcess.hh" #include "G4KaonMinusInelasticProcess.hh" #include "G4ProtonInelasticProcess.hh" #include "G4AntiProtonInelasticProcess.hh" #include "G4NeutronInelasticProcess.hh" #include "G4AntiNeutronInelasticProcess.hh" #include "G4DeuteronInelasticProcess.hh" #include "G4TritonInelasticProcess.hh" #include "G4AlphaInelasticProcess.hh" // High energy FTFP model and Bertini cascade #include "G4FTFModel.hh" #include "G4LundStringFragmentation.hh" #include "G4ExcitedStringDecay.hh" #include "G4PreCompoundModel.hh" #include "G4GeneratorPrecompoundInterface.hh" #include "G4TheoFSGenerator.hh" #include "G4CascadeInterface.hh" // Cross sections #include "G4VCrossSectionDataSet.hh" #include "G4CrossSectionDataSetRegistry.hh" #include "G4CrossSectionElastic.hh" #include "G4BGGPionElasticXS.hh" #include "G4AntiNuclElastic.hh" #include "G4CrossSectionInelastic.hh" #include "G4PiNuclearCrossSection.hh" #include "G4CrossSectionPairGG.hh" #include "G4BGGNucleonInelasticXS.hh" #include "G4ComponentAntiNuclNuclearXS.hh" //Version check 10.01, 10.01.p01, 10.01.p02, > 10.02 #ifdef G4VERSION_NUMBER <= 1020 #include "G4GGNuclNuclCrossSection.hh" #else #include "G4ComponentGGNuclNuclXsc.hh" #endif #include "G4HadronElastic.hh" #include "G4HadronCaptureProcess.hh" // Neutron high-precision models: <20 MeV #include "G4NeutronHPElastic.hh" #include "G4NeutronHPElasticData.hh" #include "G4NeutronHPCapture.hh" #include "G4NeutronHPCaptureData.hh" #include "G4NeutronHPInelastic.hh" #include "G4NeutronHPInelasticData.hh" // Stopping processes #include "G4PiMinusAbsorptionBertini.hh" #include "G4KaonMinusAbsorptionBertini.hh" #include "G4AntiProtonAbsorptionFritiof.hh" void muensterTPCPhysicsList::ConstructHad() { //G4cout << "----- ConstructHad" << G4endl; //Elastic models const G4double elastic_elimitPi = 1.0*GeV; G4HadronElastic* elastic_lhep0 = new G4HadronElastic(); G4HadronElastic* elastic_lhep1 = new G4HadronElastic(); elastic_lhep1->SetMaxEnergy( elastic_elimitPi ); G4ChipsElasticModel* elastic_chip = new G4ChipsElasticModel(); G4ElasticHadrNucleusHE* elastic_he = new G4ElasticHadrNucleusHE(); elastic_he->SetMinEnergy( elastic_elimitPi ); // Inelastic scattering const G4double theFTFMin0 = 0.0*GeV; const G4double theFTFMin1 = 4.0*GeV; const G4double theFTFMax = 100.0*TeV; const G4double theBERTMin0 = 0.0*GeV; const G4double theBERTMin1 = 19.0*MeV; const G4double theBERTMax = 5.0*GeV; const G4double theHPMin = 0.0*GeV; const G4double theHPMax = 20.0*MeV; G4FTFModel * theStringModel = new G4FTFModel; G4ExcitedStringDecay * theStringDecay = new G4ExcitedStringDecay( new G4LundStringFragmentation ); theStringModel->SetFragmentationModel( theStringDecay ); G4PreCompoundModel * thePreEquilib = new G4PreCompoundModel( new G4ExcitationHandler ); G4GeneratorPrecompoundInterface * theCascade = new G4GeneratorPrecompoundInterface( thePreEquilib ); G4TheoFSGenerator * theFTFModel0 = new G4TheoFSGenerator( "FTFP" ); theFTFModel0->SetHighEnergyGenerator( theStringModel ); theFTFModel0->SetTransport( theCascade ); theFTFModel0->SetMinEnergy( theFTFMin0 ); theFTFModel0->SetMaxEnergy( theFTFMax ); G4TheoFSGenerator * theFTFModel1 = new G4TheoFSGenerator( "FTFP" ); theFTFModel1->SetHighEnergyGenerator( theStringModel ); theFTFModel1->SetTransport( theCascade ); theFTFModel1->SetMinEnergy( theFTFMin1 ); theFTFModel1->SetMaxEnergy( theFTFMax ); G4CascadeInterface * theBERTModel0 = new G4CascadeInterface; theBERTModel0->SetMinEnergy( theBERTMin0 ); theBERTModel0->SetMaxEnergy( theBERTMax ); G4CascadeInterface * theBERTModel1 = new G4CascadeInterface; theBERTModel1->SetMinEnergy( theBERTMin1 ); theBERTModel1->SetMaxEnergy( theBERTMax ); G4VCrossSectionDataSet * thePiData = new G4CrossSectionPairGG( new G4PiNuclearCrossSection, 91*GeV ); G4VCrossSectionDataSet * theAntiNucleonData = new G4CrossSectionInelastic( new G4ComponentAntiNuclNuclearXS ); //Version check 10.01, 10.01.p01, 10.01.p02, > 10.02 #ifdef G4VERSION_NUMBER <= 1020 G4VCrossSectionDataSet * theGGNuclNuclData = G4CrossSectionDataSetRegistry::Instance()-> GetCrossSectionDataSet(G4ComponentGGNuclNuclXsc::Default_Name()); #else // name changed to G4ComponentGGNuclNuclXsc due to v10.02 G4ComponentGGNuclNuclXsc* ionElasticXS = new G4ComponentGGNuclNuclXsc; G4VCrossSectionDataSet* theGGNuclNuclData = new G4CrossSectionElastic(ionElasticXS); #endif theParticleIterator->reset(); while ((*theParticleIterator)()) { G4ParticleDefinition* particle = theParticleIterator->value(); G4ProcessManager* pmanager = particle->GetProcessManager(); G4String particleName = particle->GetParticleName(); if (particleName == "pi+") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->AddDataSet( new G4BGGPionElasticXS( particle ) ); theElasticProcess->RegisterMe( elastic_lhep1 ); theElasticProcess->RegisterMe( elastic_he ); pmanager->AddDiscreteProcess( theElasticProcess ); //Inelastic scattering G4PionPlusInelasticProcess* theInelasticProcess = new G4PionPlusInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( thePiData ); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); } else if (particleName == "pi-") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->AddDataSet( new G4BGGPionElasticXS( particle ) ); theElasticProcess->RegisterMe( elastic_lhep1 ); theElasticProcess->RegisterMe( elastic_he ); pmanager->AddDiscreteProcess( theElasticProcess ); //Inelastic scattering G4PionMinusInelasticProcess* theInelasticProcess = new G4PionMinusInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( thePiData ); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); //Absorption pmanager->AddRestProcess(new G4PiMinusAbsorptionBertini, ordDefault); } else if (particleName == "kaon+") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->RegisterMe( elastic_lhep0 ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering G4KaonPlusInelasticProcess* theInelasticProcess = new G4KaonPlusInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( G4CrossSectionDataSetRegistry::Instance()-> GetCrossSectionDataSet(G4ChipsKaonPlusInelasticXS::Default_Name())); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); } else if (particleName == "kaon0S") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->RegisterMe( elastic_lhep0 ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering G4KaonZeroSInelasticProcess* theInelasticProcess = new G4KaonZeroSInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( G4CrossSectionDataSetRegistry::Instance()-> GetCrossSectionDataSet(G4ChipsKaonZeroInelasticXS::Default_Name())); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); } else if (particleName == "kaon0L") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->RegisterMe( elastic_lhep0 ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering G4KaonZeroLInelasticProcess* theInelasticProcess = new G4KaonZeroLInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( G4CrossSectionDataSetRegistry::Instance()-> GetCrossSectionDataSet(G4ChipsKaonZeroInelasticXS::Default_Name())); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); } else if (particleName == "kaon-") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->RegisterMe( elastic_lhep0 ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering G4KaonMinusInelasticProcess* theInelasticProcess = new G4KaonMinusInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( G4CrossSectionDataSetRegistry::Instance()-> GetCrossSectionDataSet(G4ChipsKaonMinusInelasticXS::Default_Name())); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); pmanager->AddRestProcess(new G4KaonMinusAbsorptionBertini, ordDefault); } else if (particleName == "proton") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->AddDataSet(G4CrossSectionDataSetRegistry::Instance()-> GetCrossSectionDataSet(G4ChipsProtonElasticXS::Default_Name())); theElasticProcess->RegisterMe( elastic_chip ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering G4ProtonInelasticProcess* theInelasticProcess = new G4ProtonInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( new G4BGGNucleonInelasticXS( G4Proton::Proton() ) ); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); } else if (particleName == "anti_proton") { // Elastic scattering const G4double elastic_elimitAntiNuc = 100.0*MeV; G4AntiNuclElastic* elastic_anuc = new G4AntiNuclElastic(); elastic_anuc->SetMinEnergy( elastic_elimitAntiNuc ); G4CrossSectionElastic* elastic_anucxs = new G4CrossSectionElastic( elastic_anuc->GetComponentCrossSection() ); G4HadronElastic* elastic_lhep2 = new G4HadronElastic(); elastic_lhep2->SetMaxEnergy( elastic_elimitAntiNuc ); G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->AddDataSet( elastic_anucxs ); theElasticProcess->RegisterMe( elastic_lhep2 ); theElasticProcess->RegisterMe( elastic_anuc ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering G4AntiProtonInelasticProcess* theInelasticProcess = new G4AntiProtonInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( theAntiNucleonData ); theInelasticProcess->RegisterMe( theFTFModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); // Absorption pmanager->AddRestProcess(new G4AntiProtonAbsorptionFritiof, ordDefault); } else if (particleName == "neutron") { // elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->AddDataSet(G4CrossSectionDataSetRegistry::Instance()-> GetCrossSectionDataSet(G4ChipsNeutronElasticXS::Default_Name())); G4HadronElastic* elastic_neutronChipsModel = new G4ChipsElasticModel(); elastic_neutronChipsModel->SetMinEnergy( 19.0*MeV ); theElasticProcess->RegisterMe( elastic_neutronChipsModel ); G4NeutronHPElastic * theElasticNeutronHP = new G4NeutronHPElastic; theElasticNeutronHP->SetMinEnergy( theHPMin ); theElasticNeutronHP->SetMaxEnergy( theHPMax ); theElasticProcess->RegisterMe( theElasticNeutronHP ); theElasticProcess->AddDataSet( new G4NeutronHPElasticData ); pmanager->AddDiscreteProcess( theElasticProcess ); // inelastic scattering G4NeutronInelasticProcess* theInelasticProcess = new G4NeutronInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( new G4BGGNucleonInelasticXS( G4Neutron::Neutron() ) ); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel1 ); G4NeutronHPInelastic * theNeutronInelasticHPModel = new G4NeutronHPInelastic; theNeutronInelasticHPModel->SetMinEnergy( theHPMin ); theNeutronInelasticHPModel->SetMaxEnergy( theHPMax ); theInelasticProcess->RegisterMe( theNeutronInelasticHPModel ); theInelasticProcess->AddDataSet( new G4NeutronHPInelasticData ); pmanager->AddDiscreteProcess(theInelasticProcess); // capture G4HadronCaptureProcess* theCaptureProcess = new G4HadronCaptureProcess; G4NeutronHPCapture * theLENeutronCaptureModel = new G4NeutronHPCapture; theLENeutronCaptureModel->SetMinEnergy(theHPMin); theLENeutronCaptureModel->SetMaxEnergy(theHPMax); theCaptureProcess->RegisterMe(theLENeutronCaptureModel); theCaptureProcess->AddDataSet( new G4NeutronHPCaptureData); pmanager->AddDiscreteProcess(theCaptureProcess); } else if (particleName == "anti_neutron") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->RegisterMe( elastic_lhep0 ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering (include annihilation on-fly) G4AntiNeutronInelasticProcess* theInelasticProcess = new G4AntiNeutronInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( theAntiNucleonData ); theInelasticProcess->RegisterMe( theFTFModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); } else if (particleName == "deuteron") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->RegisterMe( elastic_lhep0 ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering G4DeuteronInelasticProcess* theInelasticProcess = new G4DeuteronInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( theGGNuclNuclData ); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); } else if (particleName == "triton") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->RegisterMe( elastic_lhep0 ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering G4TritonInelasticProcess* theInelasticProcess = new G4TritonInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( theGGNuclNuclData ); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); } else if (particleName == "alpha") { // Elastic scattering G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; theElasticProcess->RegisterMe( elastic_lhep0 ); pmanager->AddDiscreteProcess( theElasticProcess ); // Inelastic scattering G4AlphaInelasticProcess* theInelasticProcess = new G4AlphaInelasticProcess("inelastic"); theInelasticProcess->AddDataSet( theGGNuclNuclData ); theInelasticProcess->RegisterMe( theFTFModel1 ); theInelasticProcess->RegisterMe( theBERTModel0 ); pmanager->AddDiscreteProcess( theInelasticProcess ); } } } // Decays /////////////////////////////////////////////////////////////////// #include "G4Decay.hh" #include "G4RadioactiveDecay.hh" #include "G4IonTable.hh" #include "G4Ions.hh" void muensterTPCPhysicsList::ConstructGeneral() { //G4cout << "----- ConstructGeneral" << G4endl; // Add Decay Process G4Decay *theDecayProcess = new G4Decay(); theParticleIterator->reset(); while((*theParticleIterator) ()) { G4ParticleDefinition *particle = theParticleIterator->value(); G4ProcessManager *pmanager = particle->GetProcessManager(); if(theDecayProcess->IsApplicable(*particle) && !particle->IsShortLived()) { pmanager->AddProcess(theDecayProcess); // set ordering for PostStepDoIt and AtRestDoIt pmanager->SetProcessOrdering(theDecayProcess, idxPostStep); pmanager->SetProcessOrdering(theDecayProcess, idxAtRest); } } // Declare radioactive decay to the GenericIon in the IonTable. const G4IonTable *theIonTable = G4ParticleTable::GetParticleTable()->GetIonTable(); G4RadioactiveDecay *theRadioactiveDecay = new G4RadioactiveDecay(); for(G4int i = 0; i < theIonTable->Entries(); i++) { G4String particleName = theIonTable->GetParticle(i)->GetParticleName(); G4String particleType = theIonTable->GetParticle(i)->GetParticleType(); if(particleName == "GenericIon") { G4ProcessManager *pmanager = theIonTable->GetParticle(i)->GetProcessManager(); pmanager->SetVerboseLevel(VerboseLevel); pmanager->AddProcess(theRadioactiveDecay); pmanager->SetProcessOrdering(theRadioactiveDecay, idxPostStep); pmanager->SetProcessOrdering(theRadioactiveDecay, idxAtRest); } } } // Cuts ///////////////////////////////////////////////////////////////////// void muensterTPCPhysicsList::SetCuts() { if(verboseLevel > 1) G4cout << "muensterTPCPhysicsList::SetCuts:"; if(verboseLevel > 0) { G4cout << "muensterTPCPhysicsList::SetCuts:"; G4cout << "CutLength : " << G4BestUnit(defaultCutValue, "Length") << G4endl; } //special for low energy physics G4double lowlimit = 250 * eV; G4ProductionCutsTable::GetProductionCutsTable()->SetEnergyRange(lowlimit, 100. * GeV); // set cut values for gamma at first and for e- second and next for e+, // because some processes for e+/e- need cut values for gamma SetCutValue(cutForGamma, "gamma"); SetCutValue(cutForElectron, "e-"); SetCutValue(cutForPositron, "e+"); if(verboseLevel > 0) DumpCutValuesTable(); }
37.170412
150
0.719961
l-althueser
ae8ae3cf60187deee3488ff23dcd56ed2c0297ae
15,125
cpp
C++
src/NameResolver.cpp
skylang/sky
518add25e6a101ca2701b3c6bea977b0e76b340e
[ "MIT" ]
3
2020-07-17T05:10:56.000Z
2020-08-02T22:13:50.000Z
src/NameResolver.cpp
skylang/sky
518add25e6a101ca2701b3c6bea977b0e76b340e
[ "MIT" ]
null
null
null
src/NameResolver.cpp
skylang/sky
518add25e6a101ca2701b3c6bea977b0e76b340e
[ "MIT" ]
null
null
null
// Copyright (c) 2018 Stephan Unverwerth // This code is licensed under MIT license (See LICENSE for details) #include "NameResolver.h" #include "ast/nodes.h" #include "exceptions.h" #include "Scope.h" #include "SourceFile.h" namespace Sky { NameResolver::NameResolver(Scope* globals): scope(globals) { } int NameResolver::resolveGenerics(ModuleDeclaration& n) { int numGenerics = 0; auto oldscope = scope; scope = new Scope(scope); for (auto&& imp: n.imports) { if (imp->all) { for (auto&& fun: imp->module->functions) { if (fun->isExported) { scope->add(fun->name, fun); } } for (auto&& cls: imp->module->classes) { if (cls->isExported) { scope->add(cls->_name, cls); } } for (auto&& iface: imp->module->interfaces) { if (iface->isExported) { scope->add(iface->_name, iface); } } for (auto&& en: imp->module->enums) { if (en->isExported) { scope->add(en->_name, en); } } } else if (imp->importModule) { scope->add(imp->parts.back(), imp->module); } else { auto cls = imp->module->getClass(imp->parts.back()); if (cls) { if (cls->isExported) { scope->add(cls->_name, cls); continue; } else { throw Exception(cls->_name + " is not exported."); } } auto en = imp->module->getEnum(imp->parts.back()); if (en) { if (en->isExported) { scope->add(en->_name, en); continue; } else { throw Exception(en->_name + " is not exported."); } } auto funs = imp->module->getFunctions(imp->parts.back()); if (!funs.empty()) { for (auto&& fun: funs) { if (fun->isExported) { scope->add(fun->name, fun); } } } } } for (auto&& fun: n.functions) { scope->add(fun->name, fun); } for (auto&& cls: n.classes) { scope->add(cls->_name, cls); } for (auto&& iface: n.interfaces) { scope->add(iface->_name, iface); } for (auto&& en: n.enums) { scope->add(en->_name, en); } for (auto&& ta: n.typeAliases) { scope->add(ta->_name, ta); } for (auto& cls: n.classes) { for (auto& gen: cls->reifiedClasses) { if (!gen->isResolved) { resolve(*gen); numGenerics++; } } } delete scope; scope = oldscope; return numGenerics; } void NameResolver::resolve(ModuleDeclaration& n) { auto oldscope = scope; scope = new Scope(scope); for (auto& import: n.imports) { resolve(*import); } for (auto&& fun: n.functions) { scope->add(fun->name, fun); } for (auto&& cls: n.classes) { scope->add(cls->_name, cls); } for (auto&& iface: n.interfaces) { scope->add(iface->_name, iface); } for (auto&& en: n.enums) { scope->add(en->_name, en); } for (auto&& ta: n.typeAliases) { scope->add(ta->_name, ta); } for (auto&& fun: n.functions) { resolve(*fun); } for (auto&& iface: n.interfaces) { resolve(*iface); } for (auto&& cls: n.classes) { resolve(*cls); } for (auto&& ta: n.typeAliases) { resolve(*ta); } delete scope; scope = oldscope; } void NameResolver::resolve(ClassDeclaration& n) { // is generic if (n.genericParams.size() > 0 && n.genericArguments.empty()) return; // is reified generic if (n.genericParams.size() > 0 && n.genericArguments.size() > 0) { if (n.isResolved) return; n.isResolved = true; } auto oldscope = scope; scope = new Scope(scope); for (int i = 0; i < n.genericParams.size(); ++i) { scope->add(n.genericParams[i]->_name, n.genericArguments[i]); } for (auto&& field: n.fields) { resolve(*field); } for (auto&& method: n.methods) { resolve(*method); } delete scope; scope = oldscope; } void NameResolver::resolve(FunctionDeclaration& n) { auto oldscope = scope; scope = new Scope(scope); if (n.returnTypeExpression) visitChild(n.returnTypeExpression); for (auto& param: n.parameters) { resolve(*param); } visitChildren(n.statements); std::vector<TypeDeclaration*> parameterTypes; for (auto&& param: n.parameters) { parameterTypes.push_back(param->typeExpression->typeValue); } n.declarationType = FunctionType::get(n.returnTypeExpression ? n.returnTypeExpression->typeValue : &VoidType::instance, parameterTypes); delete scope; scope = oldscope; } void NameResolver::resolve(Parameter& n) { visitChild(n.typeExpression); n.declarationType = n.typeExpression->typeValue; scope->add(n.name, &n); } void NameResolver::visit(VarDeclaration& n) { if (n.typeExpression) { visitChild(n.typeExpression); n.declarationType = n.typeExpression->typeValue; } if (n.initializer) { visitChild(n.initializer); } try { scope->add(n.name, &n); } catch (const DuplicateSymbolException& e) { error(n, e.what()); } } void NameResolver::visit(IsExpression& n) { visitChild(n.target); visitChild(n.typeExpression); } void NameResolver::visit(UnionTypeExpression& n) { visitChild(n.base); visitChild(n.next); n.type = &TypeType::instance; n.typeValue = UnionType::get(n.base->typeValue, n.next->typeValue); } void NameResolver::visit(IdExpression& n) { auto symbol = scope->find(n.name); if (!symbol) { error(n, "Unresolved symbol '" + n.name + "'."); return; } if (auto td = symbol->node->as<TypeDeclaration>()) { n.type = &TypeType::instance; n.typeValue = td; } else if (auto var = symbol->node->as<VarDeclaration>()) { n.node = var; n.type = var->declarationType; } else if (auto par = symbol->node->as<Parameter>()) { n.node = par; n.type = par->declarationType; } else if (auto fun = symbol->node->as<FunctionDeclaration>()) { if (symbol->next) { auto cur = symbol; while (cur) { n.candidates.push_back(cur->node->as<FunctionDeclaration>()); cur = cur->next; } n.type = &OverloadedFunctionType::instance; n.node = nullptr; } else { n.node = fun; n.type = fun->declarationType; } } else { error(n, "Unhandled symbol kind."); return; } } void NameResolver::visit(ReturnStatement& n) { if (n.expression) { visitChild(n.expression); } } void NameResolver::visit(ExpressionStatement& n) { visitChild(n.expression); } void NameResolver::visit(CallExpression& n) { visitChild(n.callTarget); visitChildren(n.arguments); } void NameResolver::visit(BlockStatement& n) { auto oldscope = scope; scope = new Scope(scope); visitChildren(n.statements); delete scope; scope = oldscope; } void NameResolver::visit(BinopExpression& n) { visitChild(n.left); visitChild(n.right); } void NameResolver::visit(CastExpression& n) { visitChild(n.sourceExpression); visitChild(n.targetTypeExpression); } void NameResolver::visit(ScopeExpression& n) { visitChild(n.scopeTarget); } void NameResolver::visit(IfStatement& n) { visitChild(n.condition); visitChild(n.trueBranch); if (n.falseBranch) { visitChild(n.falseBranch); } } void NameResolver::resolve(FieldDeclaration& n) { visitChild(n.typeExpression); n.declarationType = n.typeExpression->typeValue; } void NameResolver::visit(NewExpression& n) { visitChild(n.typeExpression); visitChildren(n.arguments); } void NameResolver::visit(AssignExpression& n) { visitChild(n.left); visitChild(n.right); } void NameResolver::visit(WhileStatement& n) { visitChild(n.condition); visitChild(n.body); } void NameResolver::visit(PostfixExpression& n) { visitChild(n.target); } void NameResolver::visit(ArrayTypeExpression& n) { visitChild(n.baseTypeExpression); n.type = &TypeType::instance; if (n.baseTypeExpression->typeValue == &InvalidType::instance) { return; } n.typeValue = ArrayType::get(n.baseTypeExpression->typeValue); } void NameResolver::resolve(ImportStatement& n) { if (n.all) { for (auto&& fun: n.module->functions) { if (fun->isExported) { scope->add(fun->name, fun); } } for (auto&& cls: n.module->classes) { if (cls->isExported) { scope->add(cls->_name, cls); } } for (auto&& iface: n.module->interfaces) { if (iface->isExported) { scope->add(iface->_name, iface); } } for (auto&& en: n.module->enums) { if (en->isExported) { scope->add(en->_name, en); } } for (auto&& alias: n.module->typeAliases) { if (alias->isExported) { scope->add(alias->_name, alias); } } } else if (n.importModule) { scope->add(n.parts.back(), n.module); } else { auto cls = n.module->getClass(n.parts.back()); if (cls) { if (cls->isExported) { scope->add(cls->_name, cls); return; } } auto en = n.module->getEnum(n.parts.back()); if (en) { if (en->isExported) { scope->add(en->_name, en); return; } } auto funs = n.module->getFunctions(n.parts.back()); if (!funs.empty()) { for (auto&& fun: funs) { if (fun->isExported) { scope->add(fun->name, fun); } } return; } auto alias = n.module->getAlias(n.parts.back()); if (alias) { if (alias->isExported) { scope->add(alias->_name, alias); return; } } // nothing found error(n, "Symbol '" + n.parts.back() + "' not found in module '" + n.getBaseName() + "'"); } } void NameResolver::visit(UnaryExpression& n) { visitChild(n.target); } void NameResolver::visit(ArrayLitExpression& n) { visitChildren(n.elements); } void NameResolver::visit(MapLitExpression& n) { visitChildren(n.keys); visitChildren(n.values); } void NameResolver::visit(SubscriptExpression& n) { visitChildren(n.arguments); visitChild(n.callTarget); } void NameResolver::resolve(InterfaceDeclaration& n) { for (auto& field: n.fields) { resolve(*field); } for (auto& method: n.methods) { resolve(*method); } } void NameResolver::visit(NullableTypeExpression& n) { visitChild(n.baseTypeExpression); n.type = &TypeType::instance; n.typeValue = UnionType::get(n.baseTypeExpression->typeValue, &NullType::instance); } void NameResolver::visit(GenericReificationExpression& n) { visitChild(n.baseTypeExpression); visitChildren(n.genericArguments); auto cls = n.baseTypeExpression->typeValue->as<ClassDeclaration>(); if (!cls) { error(n, "Can not reify non-class type '" + n.baseTypeExpression->typeValue->getFullName() + "'."); return; } if (cls->genericParams.empty()) { error(n, "Can not reify non-generic class '" + n.baseTypeExpression->typeValue->getFullName() + "'."); return; } if (cls->genericParams.size() != n.genericArguments.size()) { error(n, "Expected " + std::to_string(cls->genericParams.size()) + " type arguments, " + std::to_string(n.genericArguments.size()) + " given."); return; } std::vector<TypeDeclaration*> types; for (auto&& tex: n.genericArguments) { types.push_back(tex->typeValue); } n.type = &TypeType::instance; n.typeValue = cls->getReifiedClass(types); } void NameResolver::resolve(InterfaceFieldDeclaration& n) { visitChild(n.typeExpression); n.declarationType = n.typeExpression->typeValue; } void NameResolver::resolve(InterfaceMethodDeclaration& n) { visitChild(n.returnTypeExpression); for (auto& param: n.parameters) { resolve(*param); } std::vector<TypeDeclaration*> parameterTypes; for (auto&& param: n.parameters) { parameterTypes.push_back(param->typeExpression->typeValue); } n.type = FunctionType::get(n.returnTypeExpression ? n.returnTypeExpression->typeValue : &VoidType::instance, parameterTypes); } void NameResolver::resolve(TypeAliasDeclaration& n) { visitChild(n.typeExpression); } }
29.656863
156
0.489388
skylang
ae8da0f633c84e056401b447894eb1c5946eb348
5,127
cpp
C++
saber/funcs/impl/x86/saber_sequence_pool_concat.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
533
2018-05-18T06:14:04.000Z
2022-03-23T11:46:30.000Z
saber/funcs/impl/x86/saber_sequence_pool_concat.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
100
2018-05-26T08:32:48.000Z
2022-03-17T03:26:25.000Z
saber/funcs/impl/x86/saber_sequence_pool_concat.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
167
2018-05-18T06:14:35.000Z
2022-02-14T01:44:20.000Z
#include "saber/funcs/impl/x86/saber_sequence_pool_concat.h" #include "saber/funcs/impl/x86/saber_avx2_expand.h" #include "saber/funcs/impl/x86/saber_avx512_expand.h" namespace anakin { namespace saber { template <> SaberStatus SaberSequencePoolConcat<X86, AK_FLOAT>::create(const std::vector<Tensor<X86>*>& inputs, std::vector<Tensor<X86>*>& outputs, SequencePoolConcatParam<X86>& param, Context<X86>& ctx) { return SaberSuccess; }; template <> SaberStatus SaberSequencePoolConcat<X86, AK_FLOAT>::init(const std::vector<Tensor<X86>*>& inputs, std::vector<Tensor<X86>*>& outputs, SequencePoolConcatParam<X86>& param, Context<X86>& ctx) { this->_ctx = &ctx; return create(inputs, outputs, param, ctx); }; #if defined(__AVX2__) static void avx2_sequence_pool_sum_concat(const float* data, std::vector<int>& seq_offset, int dim, float* out) { int round_dim = dim / 8 * 8; int remainder = dim % 8; __m256i mask_m256i = _m256_continue_mask_m256i(remainder); #pragma omp parallel for for (int i = 0; i < seq_offset.size() - 1; i++) { for (int k = 0; k < round_dim; k += 8) { __m256 temp_out = _mm256_setzero_ps(); for (int j = seq_offset[i]; j < seq_offset[i + 1]; j++) { const float* tmp_data = data + j * dim; __m256 temp_in = _mm256_loadu_ps(&tmp_data[k]); temp_out += temp_in; } _mm256_storeu_ps(out + i * dim + k, temp_out); } if (remainder > 0) { __m256 temp_out = _mm256_setzero_ps(); for (int j = seq_offset[i]; j < seq_offset[i + 1]; j++) { const float* tmp_data = data + j * dim; __m256 temp_in = _mm256_maskload_ps(&tmp_data[round_dim], mask_m256i); temp_out += temp_in; } _mm256_maskstore_ps(out + i * dim + round_dim, mask_m256i, temp_out); } } } #endif #if defined(__AVX512F__) static void avx512_sequence_pool_sum_concat(const float* data, std::vector<int>& seq_offset, int dim, float* out) { int round_dim = dim / 16 * 16; int remainder = dim % 16; __mmask16 remain_mask = __mm512_get_mask(remainder); const int seq_number = seq_offset.size() - 1; if (round_dim == 0) { #pragma omp parallel for for (int i = 0; i < seq_number; i++) { __m512 temp_out = _mm512_setzero_ps(); for (int j = seq_offset[i]; j < seq_offset[i + 1]; j++) { const float* tmp_data = data + j * dim; temp_out = _mm512_add_ps(temp_out, _mm512_mask_loadu_ps(temp_out, remain_mask, tmp_data)); } _mm512_mask_storeu_ps(out + i * dim, remain_mask, temp_out); } } else { #pragma omp parallel for for (int i = 0; i < seq_number; i++) { for (int k = 0; k < round_dim; k += 16) { __m512 temp_out = _mm512_setzero_ps(); for (int j = seq_offset[i]; j < seq_offset[i + 1]; j++) { const float* tmp_data = data + j * dim; __m512 temp_in = _mm512_loadu_ps(&tmp_data[k]); temp_out += temp_in; } _mm512_storeu_ps(out + i * dim + k, temp_out); } if (remainder > 0) { __m512 temp_out = _mm512_setzero_ps(); for (int j = seq_offset[i]; j < seq_offset[i + 1]; j++) { const float* tmp_data = data + j * dim; temp_out = _mm512_add_ps(temp_out, _mm512_mask_loadu_ps(temp_out, remain_mask, &tmp_data[round_dim])); } _mm512_mask_storeu_ps(out + i * dim + round_dim, remain_mask, temp_out); } } } } #endif template <> SaberStatus SaberSequencePoolConcat<X86, AK_FLOAT>::dispatch(const std::vector<Tensor<X86>*>& inputs, std::vector<Tensor<X86>*>& outputs, SequencePoolConcatParam<X86>& param) { CHECK_GE(inputs[0]->get_seq_offset().size(), 1); SequencePoolParam<X86> seq_param = param.sequence_pool_param; auto seq_vec = inputs[0]->get_seq_offset()[0]; int seq_num = seq_vec.back(); float* input_ptr = static_cast<float*>(inputs[0]->data()); float* output_ptr = static_cast<float*>(outputs[0]->data()); int out_channel = inputs[0]->valid_size() / seq_num; if (seq_param.sequence_pool_type == Sequence_pool_sum) { #if defined(__AVX512F__) avx512_sequence_pool_sum_concat(input_ptr, seq_vec, out_channel, output_ptr); #elif defined(__AVX2__) avx2_sequence_pool_sum_concat(input_ptr, seq_vec, out_channel, output_ptr); #else LOG(FATAL) << "not support for not open avx2"; #endif } else { LOG(FATAL) << "not support " << seq_param.sequence_pool_type; } return SaberSuccess; }; DEFINE_OP_TEMPLATE(SaberSequencePoolConcat, SequencePoolConcatParam, X86, AK_HALF); DEFINE_OP_TEMPLATE(SaberSequencePoolConcat, SequencePoolConcatParam, X86, AK_INT8); } }
33.953642
106
0.59645
baajur
ae966daf56d5b9fd56f6bc3fa28312b51d6ed63d
6,467
cpp
C++
submods/amrex/Src/EB/AMReX_EB2.cpp
ndevelder/amr-wind-channel-les
51b048ba30a5ed3ac1bd055e807f4d59a64a45ea
[ "BSD-3-Clause" ]
null
null
null
submods/amrex/Src/EB/AMReX_EB2.cpp
ndevelder/amr-wind-channel-les
51b048ba30a5ed3ac1bd055e807f4d59a64a45ea
[ "BSD-3-Clause" ]
null
null
null
submods/amrex/Src/EB/AMReX_EB2.cpp
ndevelder/amr-wind-channel-les
51b048ba30a5ed3ac1bd055e807f4d59a64a45ea
[ "BSD-3-Clause" ]
null
null
null
#include <AMReX_EB2_IF_AllRegular.H> #include <AMReX_EB2_IF_Box.H> #include <AMReX_EB2_IF_Cylinder.H> #include <AMReX_EB2_IF_Ellipsoid.H> #include <AMReX_EB2_IF_Plane.H> #include <AMReX_EB2_IF_Sphere.H> #include <AMReX_EB2_IF_Torus.H> #include <AMReX_EB2_IF_Spline.H> #include <AMReX_EB2_IF_Parser.H> #include <AMReX_EB2_GeometryShop.H> #include <AMReX_EB2.H> #include <AMReX_ParmParse.H> #include <AMReX.H> #include <algorithm> namespace amrex { namespace EB2 { AMREX_EXPORT Vector<std::unique_ptr<IndexSpace> > IndexSpace::m_instance; AMREX_EXPORT int max_grid_size = 64; AMREX_EXPORT bool extend_domain_face = true; void Initialize () { ParmParse pp("eb2"); pp.query("max_grid_size", max_grid_size); pp.query("extend_domain_face", extend_domain_face); amrex::ExecOnFinalize(Finalize); } void Finalize () { IndexSpace::clear(); } bool ExtendDomainFace () { return extend_domain_face; } void IndexSpace::push (IndexSpace* ispace) { auto r = std::find_if(m_instance.begin(), m_instance.end(), [=] (const std::unique_ptr<IndexSpace>& x) -> bool { return x.get() == ispace; }); if (r == m_instance.end()) { m_instance.emplace_back(ispace); } else if (r+1 != m_instance.end()) { std::rotate(r, r+1, m_instance.end()); } } void IndexSpace::erase (IndexSpace* ispace) { auto r = std::find_if(m_instance.begin(), m_instance.end(), [=] (const std::unique_ptr<IndexSpace>& x) -> bool { return x.get() == ispace; }); if (r != m_instance.end()) { m_instance.erase(r); } } const IndexSpace* TopIndexSpaceIfPresent() noexcept { if (IndexSpace::size() > 0) { return &IndexSpace::top(); } return nullptr; } void Build (const Geometry& geom, int required_coarsening_level, int max_coarsening_level, int ngrow, bool build_coarse_level_by_coarsening) { ParmParse pp("eb2"); std::string geom_type; pp.get("geom_type", geom_type); if (geom_type == "all_regular") { EB2::AllRegularIF rif; EB2::GeometryShop<EB2::AllRegularIF> gshop(rif); EB2::Build(gshop, geom, required_coarsening_level, max_coarsening_level, ngrow, build_coarse_level_by_coarsening); } else if (geom_type == "box") { RealArray lo; pp.get("box_lo", lo); RealArray hi; pp.get("box_hi", hi); bool has_fluid_inside; pp.get("box_has_fluid_inside", has_fluid_inside); EB2::BoxIF bf(lo, hi, has_fluid_inside); EB2::GeometryShop<EB2::BoxIF> gshop(bf); EB2::Build(gshop, geom, required_coarsening_level, max_coarsening_level, ngrow, build_coarse_level_by_coarsening); } else if (geom_type == "cylinder") { RealArray center; pp.get("cylinder_center", center); Real radius; pp.get("cylinder_radius", radius); Real height = -1.0; pp.query("cylinder_height", height); int direction; pp.get("cylinder_direction", direction); AMREX_ALWAYS_ASSERT_WITH_MESSAGE(direction >=0 && direction < 3, "eb2.cylinder_direction is invalid"); bool has_fluid_inside; pp.get("cylinder_has_fluid_inside", has_fluid_inside); EB2::CylinderIF cf(radius, height, direction, center, has_fluid_inside); EB2::GeometryShop<EB2::CylinderIF> gshop(cf); EB2::Build(gshop, geom, required_coarsening_level, max_coarsening_level, ngrow, build_coarse_level_by_coarsening); } else if (geom_type == "plane") { RealArray point; pp.get("plane_point", point); RealArray normal; pp.get("plane_normal", normal); EB2::PlaneIF pf(point, normal); EB2::GeometryShop<EB2::PlaneIF> gshop(pf); EB2::Build(gshop, geom, required_coarsening_level, max_coarsening_level, ngrow, build_coarse_level_by_coarsening); } else if (geom_type == "sphere") { RealArray center; pp.get("sphere_center", center); Real radius; pp.get("sphere_radius", radius); bool has_fluid_inside; pp.get("sphere_has_fluid_inside", has_fluid_inside); EB2::SphereIF sf(radius, center, has_fluid_inside); EB2::GeometryShop<EB2::SphereIF> gshop(sf); EB2::Build(gshop, geom, required_coarsening_level, max_coarsening_level, ngrow, build_coarse_level_by_coarsening); } else if (geom_type == "torus") { RealArray center; pp.get("torus_center", center); Real small_radius; pp.get("torus_small_radius", small_radius); Real large_radius; pp.get("torus_large_radius", large_radius); bool has_fluid_inside = true; EB2::TorusIF sf(large_radius, small_radius, center, has_fluid_inside); EB2::GeometryShop<EB2::TorusIF> gshop(sf); EB2::Build(gshop, geom, required_coarsening_level, max_coarsening_level, ngrow, build_coarse_level_by_coarsening); } else if (geom_type == "parser") { std::string fn_string; pp.get("parser_function", fn_string); Parser parser(fn_string); parser.registerVariables({"x","y","z"}); EB2::ParserIF pif(parser.compile<3>()); EB2::GeometryShop<EB2::ParserIF,Parser> gshop(pif,parser); EB2::Build(gshop, geom, required_coarsening_level, max_coarsening_level, ngrow, build_coarse_level_by_coarsening); } else { amrex::Abort("geom_type "+geom_type+ " not supported"); } } namespace { static int comp_max_crse_level (Box cdomain, const Box& domain) { int ilev; for (ilev = 0; ilev < 30; ++ilev) { if (cdomain.contains(domain)) break; cdomain.refine(2); } if (cdomain != domain) ilev = -1; return ilev; } } int maxCoarseningLevel (const Geometry& geom) { const Box& domain = amrex::enclosedCells(geom.Domain()); const Box& cdomain = IndexSpace::top().coarsestDomain(); return comp_max_crse_level(cdomain, domain); } int maxCoarseningLevel (IndexSpace const* ebis, const Geometry& geom) { const Box& domain = amrex::enclosedCells(geom.Domain()); const Box& cdomain = ebis->coarsestDomain(); return comp_max_crse_level(cdomain,domain); } }}
28.364035
82
0.634916
ndevelder
ae9a13d3156789aad35cc8543f005084e5810bf1
637
hpp
C++
mc/util/util.hpp
ShamylZakariya/MarchingCubes
27f375d5d25df2246095d65c11127aac82a24211
[ "MIT" ]
2
2019-12-03T05:52:57.000Z
2021-05-21T18:17:52.000Z
mc/util/util.hpp
ShamylZakariya/MarchingCubes
27f375d5d25df2246095d65c11127aac82a24211
[ "MIT" ]
null
null
null
mc/util/util.hpp
ShamylZakariya/MarchingCubes
27f375d5d25df2246095d65c11127aac82a24211
[ "MIT" ]
null
null
null
// // util.h // MarchingCubes // // Created by Shamyl Zakariya on 11/23/19. // Copyright © 2019 Shamyl Zakariya. All rights reserved. // #ifndef mc_util_h #define mc_util_h #include <limits> #include <epoxy/gl.h> #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #define GLM_ENABLE_EXPERIMENTAL #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/hash.hpp> #include <glm/gtx/norm.hpp> #include "aabb.hpp" #include "color.hpp" #include "io.hpp" #include "lines.hpp" #include "storage.hpp" #include "thread_pool.hpp" #include "unowned_ptr.hpp" #endif /* mc_util_h */
18.2
58
0.723705
ShamylZakariya
ae9b27522e2872325c204e78afd9a852cb3d1b01
376
cpp
C++
Ch_15_On_the_Importance_of_Sampling/ao_sampler.cpp
BobLChen/ray-tracing-gems
76f81fc9d575be0ff30665f659341e97d1d434ad
[ "MIT" ]
2
2021-08-19T08:49:25.000Z
2021-12-25T15:35:35.000Z
Ch_15_On_the_Importance_of_Sampling/ao_sampler.cpp
RobertBeckebans/ray-tracing-gems
32f067d162041a400f50ae598a7177b2ee6b37a0
[ "MIT" ]
null
null
null
Ch_15_On_the_Importance_of_Sampling/ao_sampler.cpp
RobertBeckebans/ray-tracing-gems
32f067d162041a400f50ae598a7177b2ee6b37a0
[ "MIT" ]
1
2021-08-19T08:49:26.000Z
2021-08-19T08:49:26.000Z
float ao(float3 p, float3 n, int nSamples) { float a = 0; for (int i = 0; i < nSamples; ++i) { float xi[2] = { rng(), rng() }; float3 dir(sqrt(xi[0]) * cos(2 * Pi * xi[1]), sqrt(xi[0]) * sin(2 * Pi * xi[1]), sqrt(1 - xi[0])); dir = transformToFrame(n, dir); if (visible(p, dir)) a += 1; } return a / nSamples; }
28.923077
50
0.460106
BobLChen
ae9bdb650abb4ef1eb056d8cb4836dfce392d1f8
35
cpp
C++
Ciao/src/utils/bvh/Bbox.cpp
dfnzhc/Ciao
751501b69e9d2eb3e9cf53be07def8989e921b92
[ "MIT" ]
1
2021-07-15T14:19:27.000Z
2021-07-15T14:19:27.000Z
Ciao/src/utils/bvh/Bbox.cpp
dfnzhc/OpenGL-Renderer
751501b69e9d2eb3e9cf53be07def8989e921b92
[ "MIT" ]
null
null
null
Ciao/src/utils/bvh/Bbox.cpp
dfnzhc/OpenGL-Renderer
751501b69e9d2eb3e9cf53be07def8989e921b92
[ "MIT" ]
null
null
null
#include "pch.h" #include "Bbox.h"
11.666667
17
0.657143
dfnzhc
ae9df64e32d6be64b6d00500ab69678b9fd0bf02
7,754
cpp
C++
Project/sources/obj_loader.cpp
bachp2/FEASE
07bcfa95532543a78fce028d1421925769aa21da
[ "BSD-3-Clause" ]
null
null
null
Project/sources/obj_loader.cpp
bachp2/FEASE
07bcfa95532543a78fce028d1421925769aa21da
[ "BSD-3-Clause" ]
null
null
null
Project/sources/obj_loader.cpp
bachp2/FEASE
07bcfa95532543a78fce028d1421925769aa21da
[ "BSD-3-Clause" ]
null
null
null
#include "obj_loader.h" #include <fstream> #include <iostream> #include <algorithm> #include <map> // Inspired from BennyQBD's obj loader code : https://github.com/BennyQBD/ModernOpenGLTutorial/blob/master/shader.cpp static bool CompareOBJIndexPtr(const OBJIndex* a, const OBJIndex* b); static inline unsigned int FindNextChar(unsigned int start, const char* str, unsigned int length, char token); static inline unsigned int ParseOBJIndexValue(const std::string& token, unsigned int start, unsigned int end); unsigned int ParseOBJIndexValue(const std::string& token); static inline float ParseOBJFloatValue(const std::string& token, unsigned int start, unsigned int end); static inline std::vector<std::string> SplitString(const std::string &s, char delim); void OBJModel::render(Shader* shader) { shader->use(); shader->setMat4("model", this->Model); shader->setColor("color", configTable.color("line")); glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glBindVertexArray(face_vao); //glBindBuffer(GL_ARRAY_BUFFER, VBO); glDrawElements(GL_TRIANGLES, face_indices.size(), GL_UNSIGNED_INT, 0); if(!line_indices.empty()) { glBindVertexArray(line_vao); //glBindBuffer(GL_ARRAY_BUFFER, VBO); shader->setColor("color", configTable.color("arrow_line")); glDrawElements(GL_LINES, line_indices.size(), GL_UNSIGNED_INT, 0); } glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glBindVertexArray(0); } void OBJModel::render_setup() { glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glGenVertexArrays(1, &face_vao); glBindVertexArray(face_vao); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glGenBuffers(1, &face_ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, face_ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int)*face_indices.size(), &face_indices[0], GL_STATIC_DRAW); glGenVertexArrays(1, &line_vao); glBindVertexArray(line_vao); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); if(!line_indices.empty()) { glGenBuffers(1, &line_ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, line_ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int)*line_indices.size(), &line_indices[0], GL_STATIC_DRAW); } glBindVertexArray(0); } OBJModel::OBJModel(const std::string& fileName) { hasUVs = false; hasNormals = false; std::ifstream file; file.open(fileName.c_str()); std::string line; if(file.is_open()) { while(file.good()) { getline(file, line); unsigned int lineLength = line.length(); if(lineLength < 2) continue; const char* lineCStr = line.c_str(); switch(lineCStr[0]) { case 'v': if(lineCStr[1] == 't') this->uvs.push_back(ParseOBJVec2(line)); else if(lineCStr[1] == 'n') this->normals.push_back(ParseOBJVec3(line)); else if(lineCStr[1] == ' ' || lineCStr[1] == '\t') this->vertices.push_back(ParseOBJVec3(line)); break; case 'f': CreateOBJFace(line); break; case 'l': CreateOBJLine(line); break; default: break; }; } } else { std::cerr << "Unable to load mesh: " << fileName << std::endl; } if (uvs.size() != 0) hasUVs = true; if (normals.size() != 0) hasNormals = true; for(auto& c : OBJIndices){ face_indices.push_back(c.vertexIndex); normal_indices.push_back(c.normalIndex); uv_indices.push_back(c.uvIndex); } } void OBJModel::CreateOBJLine(const std::string& line) { std::vector<std::string> tokens = SplitString(line, ' '); line_indices.push_back(ParseOBJIndexValue(tokens[1])); line_indices.push_back(ParseOBJIndexValue(tokens[2])); } void OBJModel::CreateOBJFace(const std::string& line) { std::vector<std::string> tokens = SplitString(line, ' '); this->OBJIndices.push_back(ParseOBJIndex(tokens[1])); this->OBJIndices.push_back(ParseOBJIndex(tokens[2])); this->OBJIndices.push_back(ParseOBJIndex(tokens[3])); if((int)tokens.size() > 4) { this->OBJIndices.push_back(ParseOBJIndex(tokens[1])); this->OBJIndices.push_back(ParseOBJIndex(tokens[3])); this->OBJIndices.push_back(ParseOBJIndex(tokens[4])); } } OBJIndex OBJModel::ParseOBJIndex(const std::string& token) { OBJIndex result; result.vertexIndex = 0; result.uvIndex = 0; result.normalIndex = 0; std::string buff; int i = 0; unsigned int buf[3]; for(const char& c : token) { if(c == '/'){ buf[i] = ParseOBJIndexValue(buff); //printf("%d -- %d\n", i, buf[i]); i++; buff.clear(); } else buff += c; } if(i == 3) std::cerr << "invalid face format" << std::endl; buf[i] = ParseOBJIndexValue(buff); result.vertexIndex = buf[0]; result.uvIndex = buf[1]; result.normalIndex = buf[2]; return result; } glm::vec3 OBJModel::ParseOBJVec3(const std::string& line) { unsigned int tokenLength = line.length(); const char* tokenString = line.c_str(); unsigned int vertIndexStart = 2; while(vertIndexStart < tokenLength) { if(tokenString[vertIndexStart] != ' ') break; vertIndexStart++; } unsigned int vertIndexEnd = FindNextChar(vertIndexStart, tokenString, tokenLength, ' '); float x = ParseOBJFloatValue(line, vertIndexStart, vertIndexEnd); vertIndexStart = vertIndexEnd + 1; vertIndexEnd = FindNextChar(vertIndexStart, tokenString, tokenLength, ' '); float y = ParseOBJFloatValue(line, vertIndexStart, vertIndexEnd); vertIndexStart = vertIndexEnd + 1; vertIndexEnd = FindNextChar(vertIndexStart, tokenString, tokenLength, ' '); float z = ParseOBJFloatValue(line, vertIndexStart, vertIndexEnd); return glm::vec3(x,y,z); //glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str())) } glm::vec2 OBJModel::ParseOBJVec2(const std::string& line) { unsigned int tokenLength = line.length(); const char* tokenString = line.c_str(); unsigned int vertIndexStart = 3; while(vertIndexStart < tokenLength) { if(tokenString[vertIndexStart] != ' ') break; vertIndexStart++; } unsigned int vertIndexEnd = FindNextChar(vertIndexStart, tokenString, tokenLength, ' '); float x = ParseOBJFloatValue(line, vertIndexStart, vertIndexEnd); vertIndexStart = vertIndexEnd + 1; vertIndexEnd = FindNextChar(vertIndexStart, tokenString, tokenLength, ' '); float y = ParseOBJFloatValue(line, vertIndexStart, vertIndexEnd); return glm::vec2(x,y); } static bool CompareOBJIndexPtr(const OBJIndex* a, const OBJIndex* b) { return a->vertexIndex < b->vertexIndex; } static inline unsigned int FindNextChar(unsigned int start, const char* str, unsigned int length, char token) { unsigned int result = start; while(result < length) { result++; if(str[result] == token) break; //if(str[result-1] == token && ) } return result; } static inline unsigned int ParseOBJIndexValue(const std::string& token, unsigned int start, unsigned int end) { return atoi(token.substr(start, end - start).c_str()) - 1; } static inline unsigned int ParseOBJIndexValue(const std::string& token) { unsigned int a = atoi(token.c_str()); if (a == 0) return 0; return a - 1; } static inline float ParseOBJFloatValue(const std::string& token, unsigned int start, unsigned int end) { return atof(token.substr(start, end - start).c_str()); } static inline std::vector<std::string> SplitString(const std::string &s, char delim) { std::vector<std::string> elems; const char* cstr = s.c_str(); unsigned int strLength = s.length(); unsigned int start = 0; unsigned int end = 0; while(end <= strLength) { while(end <= strLength) { if(cstr[end] == delim) break; end++; } elems.push_back(s.substr(start, end - start)); start = end + 1; end = start; } return elems; }
26.020134
117
0.710214
bachp2
ae9ec94361a04c9a5cea2d7fe9666d5b8e2c8df9
1,365
cpp
C++
LeetCode/34.Find_First_and_Last_Position_of_Element_in_Sorted_Array.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
9
2017-10-08T16:22:03.000Z
2021-08-20T09:32:17.000Z
LeetCode/34.Find_First_and_Last_Position_of_Element_in_Sorted_Array.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
null
null
null
LeetCode/34.Find_First_and_Last_Position_of_Element_in_Sorted_Array.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
2
2018-01-15T16:35:44.000Z
2019-03-21T18:30:04.000Z
// 二分搜兩次(左,右) class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int l = 0, r = nums.size() - 1; vector<int>ans; while(l <= r) { int m = (l + r) >> 1; if(nums[m] == target) { if(m > 0 && nums[m - 1] == target) { r = m; } else { ans.push_back(m); break; } } else if(nums[m] < target) { l = m + 1; } else { r = m; } if(l == r && nums[l] != target) break; } if(nums.size() == 0 || l > r || (l == r && nums[l] != target)) { ans.push_back(-1); ans.push_back(-1); return ans; } l = 0; r = nums.size() - 1; while(l <= r) { int m = (l + r) >> 1; if(nums[m] == target) { if(m < nums.size() - 1 && nums[m + 1] == target) { l = m + 1; } else { ans.push_back(m); break; } } else if(nums[m] < target) { l = m + 1; } else { r = m; } if(l == r && nums[l] != target) break; } return ans; } };
27.857143
72
0.301832
w181496
aea1a9b1eec06c63097cc1170044f0e860f13f35
1,800
cpp
C++
gloo/gl_wrapper/Framebuffer.cpp
LongerZrLong/gloo
a198ef25a6a6a495be4aaa8182121201cd9eafa1
[ "MIT" ]
null
null
null
gloo/gl_wrapper/Framebuffer.cpp
LongerZrLong/gloo
a198ef25a6a6a495be4aaa8182121201cd9eafa1
[ "MIT" ]
null
null
null
gloo/gl_wrapper/Framebuffer.cpp
LongerZrLong/gloo
a198ef25a6a6a495be4aaa8182121201cd9eafa1
[ "MIT" ]
null
null
null
#include "Framebuffer.h" #include <stdexcept> #include "gloo/utils.h" namespace GLOO { Framebuffer::Framebuffer() { GL_CHECK(glGenFramebuffers(1, &handle_)); } Framebuffer::~Framebuffer() { if (handle_ != GLuint(-1)) GL_CHECK(glDeleteFramebuffers(1, &handle_)); } Framebuffer::Framebuffer(Framebuffer &&other) noexcept { handle_ = other.handle_; other.handle_ = GLuint(-1); } Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { handle_ = other.handle_; other.handle_ = GLuint(-1); return *this; } void Framebuffer::Bind() const { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, handle_)); } void Framebuffer::Unbind() const { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); } void Framebuffer::AssociateTexture(const Texture &texture, GLenum attachment) { Bind(); // Make sure you use GL_CHECK to detect potential errors. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, texture.GetHandle(), 0)); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { throw std::runtime_error("Incomplete framebuffer!"); } Unbind(); } static_assert(std::is_move_constructible<Framebuffer>(), ""); static_assert(std::is_move_assignable<Framebuffer>(), ""); static_assert(!std::is_copy_constructible<Framebuffer>(), ""); static_assert(!std::is_copy_assignable<Framebuffer>(), ""); } // namespace GLOO
26.086957
81
0.579444
LongerZrLong
aea44d8f3f8d0f8b62ad167bda0144027515dae4
688
hh
C++
src/codegen/ninja.hh
Kuree/fsim
9d175e0bd835d6513d903b6f2878a5bb97bdb3d2
[ "BSD-2-Clause" ]
12
2022-03-31T03:08:59.000Z
2022-03-31T20:59:41.000Z
src/codegen/ninja.hh
Kuree/fsim
9d175e0bd835d6513d903b6f2878a5bb97bdb3d2
[ "BSD-2-Clause" ]
2
2022-03-20T23:51:25.000Z
2022-03-31T03:05:55.000Z
src/codegen/ninja.hh
Kuree/xsim
9d175e0bd835d6513d903b6f2878a5bb97bdb3d2
[ "BSD-2-Clause" ]
null
null
null
#ifndef FSIM_NINJA_HH #define FSIM_NINJA_HH #include "../ir/ir.hh" namespace fsim { class DPILocator; struct NinjaCodeGenOptions { uint8_t optimization_level = 3; std::string cxx_path; std::string binary_name; std::vector<std::string> sv_libs; }; class NinjaCodeGen { // generates native ninja code (bypass cmake) public: NinjaCodeGen(const Module *top, NinjaCodeGenOptions &options, const DPILocator *dpi) : top_(top), options_(options), dpi_(dpi) {} void output(const std::string &dir); private: const Module *top_; NinjaCodeGenOptions &options_; const DPILocator *dpi_ = nullptr; }; } // namespace fsim #endif // FSIM_NINJA_HH
20.848485
88
0.700581
Kuree
0006e7d41b8c2c9f13cd8badcd7dd5a8f46a92f2
1,591
cpp
C++
samples/vxSobel3x3Node/vxSobel3x3Node.cpp
HipaccVX/HipaccVX
0d469748df11c95f916b5a70f0006878f8550e3c
[ "MIT" ]
1
2021-06-08T08:58:54.000Z
2021-06-08T08:58:54.000Z
samples/vxSobel3x3Node/vxSobel3x3Node.cpp
HipaccVX/HipaccVX
0d469748df11c95f916b5a70f0006878f8550e3c
[ "MIT" ]
1
2021-11-13T14:55:55.000Z
2021-11-13T14:55:55.000Z
samples/vxSobel3x3Node/vxSobel3x3Node.cpp
HipaccVX/HipaccVX
0d469748df11c95f916b5a70f0006878f8550e3c
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "VX/vx.h" #include "VX/vx_compatibility.h" #include "hipaVX/domVX_extensions.hpp" #define GEN_TEST_IMAGE #ifdef GEN_TEST_IMAGE #define IMAGE "" #ifndef WIDTH #define WIDTH 4032 #endif #ifndef HEIGHT #define HEIGHT 3024 #endif #else #define IMAGE "img/fuerte_ship.jpg" #define WIDTH 4032 #define HEIGHT 3024 #endif int main(int argc, char *argv[]) { #ifdef HIPAVX_OUTPUT_FILENAME set_output_filename(HIPAVX_OUTPUT_FILENAME); #endif vx_context context = vxCreateContext(); vx_status status = VX_FAILURE; if (context) { vx_graph graph = vxCreateGraph(context); vx_image img[] = { vxCreateImageFromFile(context, WIDTH, HEIGHT, VX_DF_IMAGE_U8, IMAGE), vxCreateImage(context, WIDTH, HEIGHT, VX_DF_IMAGE_S16), vxCreateImage(context, WIDTH, HEIGHT, VX_DF_IMAGE_S16) }; if (graph) { vx_node nodes[] = { vxSobel3x3Node(graph, img[0], img[1], img[2]), }; } status = vxVerifyGraph(graph); if (status == VX_SUCCESS) { vxWriteImageAfterGraphCompletion(graph, img[1], "./vxSobel3x3Node_1.png"); vxWriteImageAfterGraphCompletion(graph, img[2], "./vxSobel3x3Node_2.png"); status = vxProcessGraph(graph); } else { printf("VERIFICATION ERROR: %d\n", status); } for (int i = 0; i < 3; i++) vxReleaseImage(&img[i]); } vxReleaseContext(&context); return status; }
24.476923
86
0.626021
HipaccVX