text
string
size
int64
token_count
int64
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qeglfsvivwlintegration.h" #include <EGL/eglvivante.h> #include <QDebug> #include <wayland-server.h> QT_BEGIN_NAMESPACE void QEglFSVivWaylandIntegration::platformInit() { QEglFSDeviceIntegration::platformInit(); int width, height; bool multiBufferNotEnabledYet = qEnvironmentVariableIsEmpty("FB_MULTI_BUFFER"); bool multiBuffer = qEnvironmentVariableIsEmpty("QT_EGLFS_IMX6_NO_FB_MULTI_BUFFER"); if (multiBufferNotEnabledYet && multiBuffer) { qWarning() << "QEglFSVivWaylandIntegration will set environment variable FB_MULTI_BUFFER=2 to enable double buffering and vsync.\n" << "If this is not desired, you can override this via: export QT_EGLFS_IMX6_NO_FB_MULTI_BUFFER=1"; qputenv("FB_MULTI_BUFFER", "2"); } mWaylandDisplay = wl_display_create(); mNativeDisplay = fbGetDisplay(mWaylandDisplay); fbGetDisplayGeometry(mNativeDisplay, &width, &height); mScreenSize.setHeight(height); mScreenSize.setWidth(width); } QSize QEglFSVivWaylandIntegration::screenSize() const { return mScreenSize; } EGLNativeDisplayType QEglFSVivWaylandIntegration::platformDisplay() const { return mNativeDisplay; } EGLNativeWindowType QEglFSVivWaylandIntegration::createNativeWindow(QPlatformWindow *window, const QSize &size, const QSurfaceFormat &format) { Q_UNUSED(window) Q_UNUSED(format) EGLNativeWindowType eglWindow = fbCreateWindow(mNativeDisplay, 0, 0, size.width(), size.height()); return eglWindow; } void QEglFSVivWaylandIntegration::destroyNativeWindow(EGLNativeWindowType window) { fbDestroyWindow(window); } void *QEglFSVivWaylandIntegration::wlDisplay() const { return mWaylandDisplay; } QT_END_NAMESPACE
3,646
1,124
/* * param_array.cc * * Created on: Jan 14, 2014 * Author: nsoblath */ #define PARAM_API_EXPORTS #include <sstream> using std::string; using std::stringstream; #include "param_array.hh" #include "param_base_impl.hh" #include "param_node.hh" namespace param { param_array::param_array() : param(), f_contents() { } param_array::param_array( const param_array& orig ) : param( orig ), f_contents( orig.f_contents.size() ) { for( unsigned ind = 0; ind < f_contents.size(); ++ind ) { f_contents[ind] = orig.f_contents[ ind ]->clone(); } } param_array::param_array( param_array&& orig ) : param( std::move(orig) ), f_contents( orig.f_contents.size() ) { for( unsigned ind = 0; ind < f_contents.size(); ++ind ) { f_contents[ind] = orig.f_contents[ ind ]->move_clone(); } orig.clear(); } param_array::~param_array() { } param_array& param_array::operator=( const param_array& rhs ) { this->param::operator=( rhs ); clear(); resize( rhs.size()) ; for( unsigned ind = 0; ind < rhs.f_contents.size(); ++ind ) { f_contents[ind] = rhs.f_contents[ ind ]->clone(); } return *this; } param_array& param_array::operator=( param_array&& rhs ) { this->param::operator=( std::move(rhs) ); clear(); resize( rhs.size()) ; for( unsigned ind = 0; ind < rhs.f_contents.size(); ++ind ) { f_contents[ind] = rhs.f_contents[ ind ]->move_clone(); } rhs.clear(); return *this; } void param_array::resize( unsigned a_size ) { f_contents.resize( a_size ); for( auto it = f_contents.begin(); it != f_contents.end(); ++it ) { if( ! *it ) it->reset( new param() ); } return; } bool param_array::has_subset( const param& a_subset ) const { if( ! a_subset.is_array() ) return false; const param_array& t_subset_array = a_subset.as_array(); if( t_subset_array.size() > f_contents.size() ) return false; contents::const_iterator t_this_it = f_contents.begin(); contents::const_iterator t_that_it = t_subset_array.f_contents.begin(); while( t_that_it != t_subset_array.f_contents.end() ) // loop condition is on a_subset because it's smaller or equal to this { if( ! (*t_this_it)->has_subset( **t_that_it ) ) return false; ++t_this_it; ++t_that_it; } return true; } void param_array::merge( const param_array& a_object ) { //LDEBUG( dlog, "merging array with " << a_object.size() << " items:\n" << a_object ); if( size() < a_object.size() ) resize( a_object.size() ); for( unsigned index = 0; index < size(); ++index ) { if( f_contents.at( index )->is_null() ) { //LDEBUG( dlog, "have a null object at <" << index << ">; adding <" << a_object[index] << ">" ); assign( index, a_object[index] ); continue; } param& t_param = (*this)[index]; if( t_param.is_value() && a_object[index].is_value() ) { //LDEBUG( dlog, "replacing the value at <" << index << "> with <" << a_object[index] << ">" ); t_param.as_value() = a_object[index].as_value(); continue; } if( t_param.is_node() && a_object[index].is_node() ) { //LDEBUG( dlog, "merging nodes at <" << index << ">" ) t_param.as_node().merge( a_object[index].as_node() ); continue; } if( t_param.is_array() && a_object[index].is_array() ) { //LDEBUG( dlog, "merging array at <" << index << ">" ); t_param.as_array().merge( a_object[index].as_array() ); continue; } //LDEBUG( dlog, "generic replace" ); assign( index, a_object[index] ); } return; } std::string param_array::to_string() const { stringstream out; string indentation; for ( unsigned i=0; i<param::s_indent_level; ++i ) indentation += " "; out << '\n' << indentation << "[\n"; param::s_indent_level++; for( contents::const_iterator it = f_contents.begin(); it != f_contents.end(); ++it ) { out << indentation << " " << **it << '\n'; } param::s_indent_level--; out << indentation << "]\n"; return out.str(); } PARAM_API std::ostream& operator<<(std::ostream& out, const param_array& a_value) { return out << a_value.to_string(); } } /* namespace param */
4,989
1,594
#include "main.hpp" //$(sej$(aaa){AAA}$(bajs$(moa){kmkd}){tej$(haha){kmkm}}){kukens fitta} //$(bajskmkd){tej$(haha){kmkd}} //template <bool DO_LOUD = true> struct Process { vector <pair <string, string>> declaredVariables; Context declVar; // Context pasteVar; // comment::Context commentVal; // string str; Process () : declVar {nullptr, declaredVariables, new STATE ("begin")} { // declVar.state -> context = &declVar; // pasteVar.state -> context = &pasteVar; // commentVal.state -> context = &commentVal; } string process (string str) { // cout << endl << "input: " << endl << str << endl; for (auto i = str.begin(); i < str.end(); ++i) { declVar.process (i); } str = declVar.result; if(STATE ("done")* d = dynamic_cast<STATE ("done")*>(declVar.state)) { } else { str += declVar.potential; } // cout << endl << "declare: " << endl << str << endl; // cout << endl << "variables: " << endl; // for (auto& i : declaredVariables) // { // cout << i.first << " = " << i.second << endl; // } declVar.result.clear (); return str; } }; void fileApp (Process& p, filesystem::path const& inputPath, filesystem::path const& outputPath) { string input = readFileIntoString (inputPath); ofstream outputFile (outputPath); if (!outputFile.is_open ()) throw runtime_error ("could not open file " + outputPath.string()); outputFile << p.process (input); outputFile.close (); } void folderApp (Process& p, filesystem::path inputPath) { filesystem::rename (inputPath, filesystem::path{inputPath}.replace_filename (p.process (inputPath.filename ()))); inputPath = filesystem::path{inputPath}.replace_filename (p.process (inputPath.filename ())); set <filesystem::path> all; set <filesystem::path> subdirs; set <filesystem::path> subfiles; for (auto& i : filesystem::directory_iterator (inputPath)) { auto renamed = filesystem::path {i.path().parent_path()} /= p.process (i.path().filename()); all.insert (renamed); filesystem::rename (i.path(), renamed); if (filesystem::is_directory (renamed)) { subdirs.insert (renamed); } else if (filesystem::is_regular_file (renamed)) { if (renamed.extension() == ".ph") { p.process (readFileIntoString (renamed)); filesystem::remove (renamed); } else { subfiles.insert (renamed); } } } for (auto const& filename : subfiles) { fileApp (p, filename, filename); } for (auto const& dirname : subdirs) { folderApp (p, dirname); } } //template <bool DO_LOUD = true> void app (filesystem::path const& inputPath, filesystem::path outputPath) { // filesystem::path p {inputPath}; // cout << filesystem::exists(inputPath) << endl; // cout << filesystem::is_directory (p) << endl; // cout << p.extension() << endl; // cout << p.stem() << endl; // cout << p.filename() << endl; if (not filesystem::exists (inputPath)) { // string warn = "file " + inputPath + "does not exists"; throw runtime_error ("file " + inputPath.string() + "does not exists"); } if (filesystem::exists (outputPath)) { // throw runtime_error ("file already exists"); } Process p; // outputPath.replace_filename (p.process (inputPath.filename ())); // outputPath += p.process (inputPath.stem()); if (filesystem::is_directory (inputPath)) { // cout << outputPath << endl; outputPath/=inputPath.filename (); outputPath = filesystem::path{outputPath}.replace_filename (p.process (outputPath.filename ())); // cout << outputPath << endl; // return; filesystem::copy (inputPath, outputPath, std::filesystem::copy_options::recursive); folderApp (p, outputPath); } else if (filesystem::is_regular_file (inputPath)) { fileApp (p, inputPath, outputPath); } else { throw runtime_error (""); } } string warning = ""; void assert_folder(string const& inputPath, string const& outputPath, string& warning) { // cout << inputPath << endl; app (inputPath, outputPath); } template <bool DO_LOUD = true> void assert_file(string const& inputPath, string const& outputPath, string const& facitPath, string& warning) { app (inputPath, outputPath); string result = readFileIntoString (outputPath); string facit = readFileIntoString (facitPath); if constexpr (not DO_LOUD) { if (result != facit) { string warn = "\n\n\t" + outputPath + "\n\t != " + "\n\t" + facitPath + "\n\n\n"; throw runtime_error (warn); } } else { if (result != facit) { warning += "\n\n\t" + outputPath + "\n\t != " + "\n\t" + facitPath + "\n\n\n"; } } } #define LOUD(x) x #define ASSERT_FILE(file, DO_LOUD) assert_file <DO_LOUD> (string (TEST_FILES_PRE_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_POST_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_FACIT_PATH) + string (BOOST_PP_STRINGIZE (file)), warning); #define ASSERT_FOLDER(folder, DO_LOUD) assert_folder (string (TEST_FOLDERS_PRE_PATH) + string (BOOST_PP_STRINGIZE (folder)), string (TEST_FOLDERS_POST_PATH), warning); #define ASSERT_FILE_SEQ(r, data, file) assert_file (string (TEST_FILES_PRE_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_POST_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_FACIT_PATH) + string (BOOST_PP_STRINGIZE (file)), warning); #define ASSERT_FILES_2(seqFiles) BOOST_PP_SEQ_FOR_EACH(ASSERT_FILE_SEQ, -, seqFiles); #define ASSERT_FILES(...) ASSERT_FILES_2 (BOOST_PP_TUPLE_TO_SEQ (__VA_ARGS__)); #define PSTR(x) decltype (const_str {x}) template <class T0, class T1> concept same = std::is_same_v<T0, T1>; //byte namespace input{ struct Context; struct State { virtual void process (char const* str, Context& ctx) {} }; struct Context { State* state {nullptr}; string input; vector <string> outputs; void process (char const* str); }; struct Begin : State { virtual void process (char const* str, Context& ctx); }; struct Input : State { virtual void process (char const* str, Context& ctx) { // cout << "Input::process" << endl; ctx.input = str; ctx.state = new Begin; // delete this; } }; struct Output : State { virtual void process (char const* str, Context& ctx) { // cout << "Output::process" << endl; if (strcmp (str, "--input") == 0) { ctx.state = new Input; // delete this; } else { ctx.outputs.push_back (string {str}); } } }; void Context::process (char const* str) { // cout << "Context::process" << endl; state -> process (str, *this); } void Begin::process (char const* str, Context& ctx) { // cout << "Begin::process" << endl; if (strcmp (str, "--input") == 0) { cout << "--input" << endl; ctx.state = new Input; // ctx.state = static_cast <Input*> (ctx.state); // delete this; } else if (strcmp (str, "--output") == 0) { ctx.state = new Output; } else { throw runtime_error (""); } } } #if defined (Debug) auto main (int, char**) -> int { int argc = 5; char** argv = new char*[argc]{new char[]{}, new char[]{"--input"}, new char[]{"/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_pre/1.hpp"}, new char[]{"--output"}, new char[]{"/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_post/1.hpp"}}; input::Context ctx {new input::Begin}; #elif defined (Release) auto main (int argc, char** argv) -> int { #endif for (char** it = argv + 1; it < argv + argc; ++it) { ctx.process (*it); } if (ctx.input.empty ()) { throw runtime_error ("must provide an input file"); } else if (ctx.outputs.empty ()) { throw runtime_error ("must provide one or more output file"); } app (ctx.input, ctx.outputs.front ()); return 0; // int argc = 2; // auto** argv = new char*[argc]{new char*{"bajs"}, new char*{"--input"}, new char*{"dรฅ"}, new char*{"--output"}, new char*{"ssss"}}; #if defined (Release) #endif // string ss; // getline(cin, ss); #if defined (Debug) cout << "kuk" << endl; removeFolderContent (TEST_FOLDERS_POST_PATH); ASSERT_FILE (4.hpp, LOUD (1)) ASSERT_FOLDER (&(root){philips bibliotek}, LOUD(1)) return 0; ASSERT_FOLDER ($(root){philip}, LOUD(1)) ASSERT_FILE (1.hpp, LOUD (0)) ASSERT_FILE (declare.hpp, LOUD (0)) ASSERT_FILE (4.hpp, LOUD (0)) ASSERT_FILE (paste.hpp, LOUD (0)) #else cout << "kiss" << endl; app (argv [1], argv [2]); #endif #ifdef Debug #define ANTAL TEST_FILE_COUNT // #define TEST_SINGEL_FILE paste.hpp #ifdef TEST_SINGEL_FILE string inputPath = string (TEST_FILES_PRE_PATH) + string (BOOST_PP_STRINGIZE (TEST_SINGEL_FILE)); string outputPath = string (TEST_FILES_POST_PATH) + string (BOOST_PP_STRINGIZE (TEST_SINGEL_FILE)); string facitPath = string (TEST_FILES_FACIT_PATH) + string (BOOST_PP_STRINGIZE (TEST_SINGEL_FILE)); app (inputPath, outputPath); string result = readFileIntoString (outputPath); string facit = readFileIntoString (facitPath); if (result != facit) { warning += "\n\n\t" + outputPath + "\n\t != " + "\n\t" + facitPath + "\n\n\n"; } #endif #ifdef TEST_ALL_FILES array <string, TEST_FILE_COUNT> test_files_pre; array <string, TEST_FILE_COUNT> test_files_post; array <string, TEST_FILE_COUNT> test_files_facit; #define PRE(z, n, text) test_files_pre [n] = BOOST_PP_CAT (text, n); #define POST(z, n, text) test_files_post [n] = BOOST_PP_CAT (text, n); #define FACIT(z, n, text) test_files_facit [n] = BOOST_PP_CAT (text, n); BOOST_PP_REPEAT (TEST_FILE_COUNT, PRE, TEST_FILE_PRE_) BOOST_PP_REPEAT (TEST_FILE_COUNT, POST, TEST_FILE_POST_) BOOST_PP_REPEAT (TEST_FILE_COUNT, FACIT, TEST_FILE_FACIT_) for (int i = 0; i < ANTAL; ++i) { string inputPath = test_files_pre [i]; string outputPath = test_files_post [i]; string facitPath = test_files_facit [i]; app (inputPath, outputPath); string result = readFileIntoString (outputPath); string facit = readFileIntoString (facitPath); // string post = readFileIntoString (test_files_post[i]); // string facit = readFileIntoString (test_files_facit[i]); if (result != facit) { warning += "\n\n\t" + test_files_post[i] + "\n\t != " + "\n\t" + test_files_facit[i] + "\n\n\n"; } } #endif if (warning != "") { // throw runtime_error (warning); cout << warning << endl; } return 0; #endif #ifdef DEBUGGING ifstream infile; infile.open ("/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_pre/test0.hpp"); ofstream outfile; outfile.open ("/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_post/test0.hpp"); #else ifstream infile; infile.open (argv[1]); ofstream outfile; outfile.open (argv[2]); #endif auto remove_beginning_spaces = bind (remove_beginning_chars, _1, ' '); auto remove_beginning_newlines = bind (remove_beginning_chars, _1, '\n'); string outtext = readFileIntoString(infile); // auto extractors = array <extractor, 1> {extractor{"${", "}"}}; // auto extractors = array <extractor, 1> {extractor{"${", "}"}}; auto stringVariableDeclerationExtractor = extractor {"$(", ")"}; auto stringValueDeclerationExtractor = extractor {"{", "}"}; auto stringVariablePasterExtractor = extractor {"${", "}"}; // auto stringVariablePasteExtractor = extractor {"${", "}"}; vector <pair <string, string>> declaredVariables; { // Process p; // p.process (outtext); } outfile << outtext; // cout << first_signature (str, first_parser) << endl; PROCC (( template <int> struct gpu; $(1) { a # = comment # ?(name)?{explanation} โ‚ฌ = _function (_anonymous/_non-anonymous) # ?[?_scope_var = @(_var)?]?(0 ?i? 0)?{}??(_function_name)? $ = _variable (_non-anonymous){_code} # (_name){} @ = _paste template <> struct gpu <${0 i 10}> # {_public change all in scope} { $(0 i 4) # {everyting refering to i will clone for times} // # int i${i} -> int i0123 @(i)<1 10> @(i)<1 10> -> {@} 12345678910 @<0 2> -> {ph} phph 2 @(hej) <-> ${0#} 02 02 -1 @(hej#) <-> ${0#} -10 0-1 2 @(#hej) <-> ${0#} 022 02 2 ${0#} -> @(#hej) 002 02 kuk @<1 3> &{ph&} kuk ph1ph2ph3 fitta @<1 3> -> {ph&} kuk fitta ph123 kuk @<1 3> -> &{ph} phphph @(hej) <-> {0} 0 0 @(hej) () 0 @(hej) <- {1} 1 () @(hej) -> {2@} () 21 @(hej) 1 () @(hej) <-> {3@} 3 31 @(hej@) <-> {kuk} "snopphejkuk" @(hej) {philip@} philipkuk @{i} -> {int i} kommer bli int i int i int i int i @{i} -> {int@ i@} int0 i0 int1 i1 int2 i2 int3 i3 ${i} 0123 $(str){philip} "philip" ${str} -> {int i@} -> {kuk @ hora} "kuk int iphilip hora" $(hej){kukens fitta} kukens fitta ${hej} kukens fitta int i${0 10} = 0; #{_private} int jโ‚ฌ(0 5)(k) = 3; #{public} โ‚ฌ[j = @(i)](0 i 3){int i@(i + 1) = @(j);}(myFun) // โ‚ฌ[j = @(i)](0 i 3){int i@(i) = @(j);} anonymous // 0 i 3 prio fรถre 0 i 10 -> dรคrfรถr sรคtter vi om namnet till j // 0 i 3 is internal dvs endast inne i {} och i refererar inget utanfรถr $(_stat_int){static $(con){constexpr} int} fitta = GPU_COUNT; ERROR-> $(_stat){kiss} @(_stat_int) count = GPU_COUNT; ${static} constexpr uint32_t max_image_dimension_1D = GPU_${i}_MAX_IMAGE_DIMENSION_1D; @(st) int i = 3; }; } )(0)(string s)); // cout << s << endl; // PROCC (( // template <int> // struct gpu; // // $(1) // { // โ‚ฌ = inline // $ = declare variable, only visible to the current scope // and to those below // // template <> // struct gpu <$(0 i 10)> // { // int $(0 j 10) = 0; // // โ‚ฌ[j = @(i)](0 i 3){int i@(i) = @(j);}(myFun) // 0 i 3 prio fรถre 0 i 10 -> dรคrfรถr sรคtter vi om namnet till j // 0 i 3 is internal dvs endast inne i {} och i refererar inget utanfรถr // $(stat){static $(con){constexpr} int} fitta = GPU_COUNT; // ERROR-> $(stat){kiss} // @(stat) count = GPU_COUNT; // ${static} constexpr uint32_t max_image_dimension_1D = GPU_${i}_MAX_IMAGE_DIMENSION_1D; // @(st) int i = 3; // }; // } // )(0)(string s)); // cout << s << endl; std::vector<double> input = {1.2, 2.3, 3.4, 4.5}; // cout << "hello world" << endl; return 0; } string first_signature (string const& first, string const& second, string str, auto&& fun) { auto a1 = str.find(first); while (a1 != string::npos) { if (int a2 = str.find (second); a2 != string::npos) { string replac = fun (string (str.begin() + a1, str.begin() + a2 + 1)); str.replace (str.begin() + a1, str.begin() + a2 + 1, replac); } else { break; } a1 = str.find ("${"); } // string res; // for (auto const& i : str) // res += i; return str; }
17,317
5,993
/* * This file is mostly based on pudelkoMs FlowScope project, specifically of this file: * https://github.com/pudelkoM/FlowScope/blob/7beb980e2cb64284666ba2d62dda5727c7bfd499/src/var_hashmap.cpp * * Most important distinction is the use of a different hash function which is more relaxed about * different digest sizes. */ #include <array> #include <cstring> #include <tbb/concurrent_hash_map.h> #include <cstdint> #include <iostream> #include <c_bindings.h> #include <deque> namespace hash_map { /* Secret hash cookie */ constexpr uint32_t secret = 0xF00BA; constexpr uint64_t sip_secret[2] = {1, 2}; // 128 bit secret template<typename K, typename std::enable_if<std::is_pod<K>::value>::type * = nullptr> struct var_sip_hash { var_sip_hash() = default; var_sip_hash(const var_sip_hash &h) = default; inline bool equal(const K &j, const K &k) const noexcept { return j == k; } // Safety check static_assert(sizeof(K) == K::size, "sizeof(K) != K::size"); /* Hash function to be used by TBB */ inline size_t hash(const K &k) const noexcept { return SipHashC(sip_secret, reinterpret_cast<const char *>(k.data + 0), k.size); } }; template<size_t key_size> struct key_buf { static constexpr size_t size = key_size; uint8_t data[key_size]; } __attribute__((__packed__)); template<size_t key_size> inline bool operator==(const key_buf<key_size> &lhs, const key_buf<key_size> &rhs) noexcept { return std::memcmp(lhs.data, rhs.data, key_size) == 0; } template<size_t key_size> using K = key_buf<key_size>; template<size_t value_size> using V = std::array<std::uint8_t, value_size>; } extern "C" { using namespace hash_map; #define MAP_IMPL(key_size, value_size) \ template class tbb::concurrent_hash_map<K<key_size>, V<value_size>, var_sip_hash<K<key_size>>>; \ using hmapk##key_size##v##value_size = tbb::concurrent_hash_map<K<key_size>, V<value_size>, var_sip_hash<K<key_size>>>; \ hmapk##key_size##v##value_size* hmapk##key_size##v##value_size##_create() { \ return new hmapk##key_size##v##value_size; \ } \ void hmapk##key_size##v##value_size##_delete(hmapk##key_size##v##value_size* map) { \ delete map; \ } \ void hmapk##key_size##v##value_size##_clear(hmapk##key_size##v##value_size* map) { \ map->clear(); \ } \ hmapk##key_size##v##value_size::accessor* hmapk##key_size##v##value_size##_new_accessor() { \ return new hmapk##key_size##v##value_size::accessor; \ } \ void hmapk##key_size##v##value_size##_accessor_free(hmapk##key_size##v##value_size::accessor* a) { \ a->release(); \ delete a; \ } \ void hmapk##key_size##v##value_size##_accessor_release(hmapk##key_size##v##value_size::accessor* a) { \ a->release(); \ } \ bool hmapk##key_size##v##value_size##_access(hmapk##key_size##v##value_size* map, hmapk##key_size##v##value_size::accessor* a, const void* key) { \ return map->insert(*a, *static_cast<const K<key_size>*>(key)); \ } \ std::uint8_t* hmapk##key_size##v##value_size##_accessor_get_value(hmapk##key_size##v##value_size::accessor* a) { \ return (*a)->second.data(); \ } \ bool hmapk##key_size##v##value_size##_erase(hmapk##key_size##v##value_size* map, hmapk##key_size##v##value_size::accessor* a) { \ if (a->empty()) std::terminate();\ return map->erase(*a); \ } \ bool hmapk##key_size##v##value_size##_find(hmapk##key_size##v##value_size* map, hmapk##key_size##v##value_size::accessor* a, const void* key) { \ return map->find(*a, *static_cast<const K<key_size>*>(key)); \ } \ uint32_t hmapk##key_size##v##value_size##_clean(hmapk##key_size##v##value_size* map, uint64_t thresh) { \ int ctr = 0; \ std::deque<hash_map::key_buf<key_size>> deque; \ for (hmapk##key_size##v##value_size::iterator it = map->begin(); it != map->end();) { \ uint64_t ts = *reinterpret_cast<uint64_t *>( &(*it).second); \ if(ts < thresh) { \ deque.push_front(it->first); \ } \ it++; \ for(auto it = deque.begin(); it != deque.end(); it++) { \ map->erase(*it); \ ++ctr; \ } \ } \ deque.clear(); \ return ctr; \ } #define MAP_VALUES(value_size) \ MAP_IMPL(8, value_size) \ MAP_IMPL(16, value_size) \ MAP_IMPL(32, value_size) \ MAP_IMPL(64, value_size) // Values are the 64 bit timestamps MAP_VALUES(8) MAP_VALUES(16) MAP_VALUES(32) MAP_VALUES(64) MAP_VALUES(128) }
4,584
1,850
/*! \brief Implementation of methods of TTClusterAlgorithm_official * \details Here, in the source file, the methods which do depend * on the specific type <T> that can fit the template. * * \author Nicola Pozzobon * \date 2013, Jul 12 * */ #include "L1Trigger/TrackTrigger/interface/TTClusterAlgorithm_official.h" /// Function to compare clusters and sort them by row template <> bool TTClusterAlgorithm_official<Ref_Phase2TrackerDigi_>::CompareClusters(const Ref_Phase2TrackerDigi_& a, const Ref_Phase2TrackerDigi_& b) { return (a->row() < b->row()); } /// Clustering operations template <> void TTClusterAlgorithm_official<Ref_Phase2TrackerDigi_>::Cluster( std::vector<std::vector<Ref_Phase2TrackerDigi_> >& output, const std::vector<Ref_Phase2TrackerDigi_>& input, bool isPS) const { /// Prepare the output output.clear(); /// Prepare a proper hit container std::map<unsigned int, std::vector<Ref_Phase2TrackerDigi_> > mapHitsByColumn; /// Map all the hits by column index typename std::vector<Ref_Phase2TrackerDigi_>::const_iterator inputIterator; inputIterator = input.begin(); while (inputIterator != input.end()) { mapHitsByColumn[(**inputIterator).column()].push_back(*inputIterator); ++inputIterator; } /// 1D Clusters must be stored properly <column, first row index> std::map<std::pair<unsigned int, unsigned int>, std::vector<Ref_Phase2TrackerDigi_> > map1DCluByColRow; /// Loop over the mapped hits typename std::map<unsigned int, std::vector<Ref_Phase2TrackerDigi_> >::iterator mapIterHbC; mapIterHbC = mapHitsByColumn.begin(); while (mapIterHbC != mapHitsByColumn.end()) { /// Collect hits sharing column index and /// differing by 1 in row index typename std::vector<Ref_Phase2TrackerDigi_>::iterator inputIterator; inputIterator = mapIterHbC->second.begin(); /// Loop over single column while (inputIterator != mapIterHbC->second.end()) { std::vector<Ref_Phase2TrackerDigi_> temp; temp.push_back(*inputIterator); inputIterator = mapIterHbC->second.erase(inputIterator); typename std::vector<Ref_Phase2TrackerDigi_>::iterator inputIterator2; inputIterator2 = inputIterator; /// Nested loop while (inputIterator2 != mapIterHbC->second.end()) { /// Check col/row and add to the cluster if ((temp.back()->column() == (**inputIterator2).column()) && ((**inputIterator2).row() - temp.back()->row() == 1)) { temp.push_back(*inputIterator2); inputIterator2 = mapIterHbC->second.erase(inputIterator2); } else break; } /// End of nested loop /// Sort the vector elements by row index std::sort(temp.begin(), temp.end(), CompareClusters); /// Put the cluster in the map map1DCluByColRow.insert(std::make_pair(std::make_pair(mapIterHbC->first, temp.at(0)->row()), temp)); inputIterator = inputIterator2; } /// End of loop over single column ++mapIterHbC; } /// End of loop over mapped hits /// Cluster over the second dimension /// only in PS modules! typename std::map<std::pair<unsigned int, unsigned int>, std::vector<Ref_Phase2TrackerDigi_> >::iterator mapIter1DCbCR0; typename std::map<std::pair<unsigned int, unsigned int>, std::vector<Ref_Phase2TrackerDigi_> >::iterator mapIter1DCbCR1; mapIter1DCbCR0 = map1DCluByColRow.begin(); unsigned int lastCol = mapIter1DCbCR0->first.first; while (mapIter1DCbCR0 != map1DCluByColRow.end()) { /// Add the hits std::vector<Ref_Phase2TrackerDigi_> candCluster; candCluster.insert(candCluster.end(), mapIter1DCbCR0->second.begin(), mapIter1DCbCR0->second.end()); if (isPS) { /// Loop over the other elements of the map mapIter1DCbCR1 = map1DCluByColRow.begin(); while (mapIter1DCbCR1 != map1DCluByColRow.end()) { /// Skip same element if (mapIter1DCbCR1 == mapIter1DCbCR0) { ++mapIter1DCbCR1; continue; } /// Skip non-contiguous column if (std::abs((int)(mapIter1DCbCR1->first.first) - (int)lastCol) != 1) { ++mapIter1DCbCR1; continue; } /// Column is contiguous /// Update the "last column index" /// This should be safe as maps are sorted structures by construction lastCol = mapIter1DCbCR1->first.first; /// Check that the cluster is good to be clustered /// Get first row unsigned int iRow0 = mapIter1DCbCR0->first.second; unsigned int iRow1 = mapIter1DCbCR1->first.second; /// Get the max row in the cluster unsigned int jRow0 = mapIter1DCbCR0->second.back()->row(); unsigned int jRow1 = mapIter1DCbCR1->second.back()->row(); /// Check if they overlap if ((iRow1 >= iRow0 && iRow1 <= jRow0) || (jRow1 >= iRow0 && jRow1 <= jRow0)) { /// If so, add the hits to the cluster! candCluster.insert(candCluster.end(), mapIter1DCbCR1->second.begin(), mapIter1DCbCR1->second.end()); map1DCluByColRow.erase(mapIter1DCbCR1++); } else { ++mapIter1DCbCR1; } } /// End of nested loop map1DCluByColRow.erase(mapIter1DCbCR0++); /// Check output /// Sort the vector by row index std::sort(candCluster.begin(), candCluster.end(), CompareClusters); /* std::cout << candCluster.at(0)->row() - candCluster.back()->row() << " / " << static_cast<int>(candCluster.at(0)->row() - candCluster.back()->row()) << " / " << abs( candCluster.at(0)->row() - candCluster.back()->row() ) << " / " << std::abs( candCluster.at(0)->row() - candCluster.back()->row() ) << " / " << mWidthCut << std::endl; */ if (std::abs(static_cast<int>(candCluster.at(0)->row() - candCluster.back()->row())) < mWidthCut || /// one should add 1 to use <= mWidthCut < 1) { output.push_back(candCluster); } } /// End of isPS else { map1DCluByColRow.erase(mapIter1DCbCR0++); /// Check output /// Sort the vector by row index std::sort(candCluster.begin(), candCluster.end(), CompareClusters); if (std::abs(static_cast<int>(candCluster.at(0)->row() - candCluster.back()->row())) < mWidthCut || /// one should add 1 to use <= mWidthCut < 1) { output.push_back(candCluster); } } /// End of non-PS case } /// End of loop over mapped 1D Clusters }
6,601
2,201
/******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_s16.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx512_core_s16_copy_an_kern::jit_avx512_core_s16_copy_an_kern() : jit_generator(nullptr, S16_COPY_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rax #define B rdi #define I rax #define A1 rsi #define A2 r10 #define LDA3 r11 #define ARG_ALPHA 40+stacksize+rsp #define ARG_B 48+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l1e8; Xbyak::Label l24; Xbyak::Label l2c8; Xbyak::Label l2fc; Xbyak::Label l30c; Xbyak::Label l318; Xbyak::Label l32c; Xbyak::Label l38; Xbyak::Label l44c; Xbyak::Label l4e8; Xbyak::Label l510; Xbyak::Label l520; Xbyak::Label l52c; Xbyak::Label l540; Xbyak::Label l5dc; Xbyak::Label l630; Xbyak::Label l658; Xbyak::Label l668; Xbyak::Label l674; Xbyak::Label l688; Xbyak::Label l730; Xbyak::Label l78c; Xbyak::Label l7c0; Xbyak::Label l7dc; Xbyak::Label l7ec; Xbyak::Label l7f8; Xbyak::Label l808; Xbyak::Label l884; Xbyak::Label l8cc; Xbyak::Label l8f8; Xbyak::Label l914; Xbyak::Label l924; Xbyak::Label l930; Xbyak::Label l940; Xbyak::Label l9b8; Xbyak::Label l9fc; Xbyak::Label la28; Xbyak::Label la44; Xbyak::Label la52; Xbyak::Label la5c; Xbyak::Label la6c; Xbyak::Label lae4; Xbyak::Label lb2c; Xbyak::Label lb5c; Xbyak::Label lb74; Xbyak::Label lb84; preamble(); #ifdef _WIN32 auto stacksize = get_size_of_abi_save_regs(); mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif mov(M, qword[M]); mov(N, qword[N]); mov(LDA, qword[LDA]); shl(LDA, 1); lea(LDA3, ptr[LDA+LDA*2]); sub(A, -128); sub(B, -128); cmp(N, 0x30); jl(l30c, T_NEAR); align(4); L(l24); mov(A1, A); add(A, 0x60); mov(I, M); sar(I, 0x2); jle(l1e8, T_NEAR); align(4); L(l38); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); vmovdqu(xmm0, xword[A1-0x40]); vmovdqu(xmm1, xword[A1+LDA*1-0x40]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B], ymm2); vmovdqu(xmm0, xword[A1-0x30]); vmovdqu(xmm1, xword[A1+LDA*1-0x30]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x20], ymm2); lea(A1, ptr[A1+LDA*2]); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x40], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x80], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0xa0], ymm2); vmovdqu(xmm0, xword[A1-0x40]); vmovdqu(xmm1, xword[A1+LDA*1-0x40]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0xc0], ymm2); vmovdqu(xmm0, xword[A1-0x30]); vmovdqu(xmm1, xword[A1+LDA*1-0x30]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0xe0], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -384); dec(I); jg(l38, T_NEAR); align(4); L(l1e8); test(M, 0x2); jle(l2c8, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); vmovdqu(xmm0, xword[A1-0x40]); vmovdqu(xmm1, xword[A1+LDA*1-0x40]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B], ymm2); vmovdqu(xmm0, xword[A1-0x30]); vmovdqu(xmm1, xword[A1+LDA*1-0x30]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x20], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -192); align(4); L(l2c8); test(M, 0x1); jle(l2fc, T_NEAR); vmovdqu(ymm0, yword[A1-0x80]); vmovdqu(ymm1, yword[A1-0x60]); vmovdqu(ymm2, yword[A1-0x40]); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm1); vmovdqu(yword[B-0x40], ymm2); sub(B, -96); align(4); L(l2fc); sub(N, 0x30); cmp(N, 0x30); jge(l24, T_NEAR); align(4); L(l30c); cmp(N, 0x20); jl(l520, T_NEAR); align(4); L(l318); mov(A1, A); add(A, 0x40); mov(I, M); sar(I, 0x2); jle(l44c, T_NEAR); align(4); L(l32c); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); lea(A1, ptr[A1+LDA*2]); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x20], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x60], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -256); dec(I); jg(l32c, T_NEAR); align(4); L(l44c); test(M, 0x2); jle(l4e8, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -128); align(4); L(l4e8); test(M, 0x1); jle(l510, T_NEAR); vmovdqu(ymm0, yword[A1-0x80]); vmovdqu(ymm1, yword[A1-0x60]); add(A1, LDA); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm1); sub(B, -64); align(4); L(l510); sub(N, 0x20); cmp(N, 0x20); jge(l318, T_NEAR); align(4); L(l520); cmp(N, 0x10); jl(l668, T_NEAR); align(4); L(l52c); mov(A1, A); add(A, 0x20); mov(I, M); sar(I, 0x2); jle(l5dc, T_NEAR); align(4); L(l540); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); lea(A1, ptr[A1+LDA*2]); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -128); dec(I); jg(l540, T_NEAR); align(4); L(l5dc); test(M, 0x2); jle(l630, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -64); align(4); L(l630); test(M, 0x1); jle(l658, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1-0x70]); vmovdqu(xword[B-0x80], xmm0); vmovdqu(xword[B-0x70], xmm1); sub(B, -32); align(4); L(l658); sub(N, 0x10); cmp(N, 0x10); jge(l52c, T_NEAR); align(4); L(l668); cmp(N, 0x8); jl(l7ec, T_NEAR); align(4); L(l674); mov(A1, A); add(A, 0x10); mov(I, M); sar(I, 0x3); jle(l730, T_NEAR); align(4); L(l688); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm2, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm3, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm4, xmm0, xmm1); vpunpckhwd(xmm5, xmm0, xmm1); vperm2f128(ymm0, ymm4, ymm5, 0x20); vpunpcklwd(xmm4, xmm2, xmm3); vpunpckhwd(xmm5, xmm2, xmm3); vperm2f128(ymm2, ymm4, ymm5, 0x20); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm2, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm3, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm4, xmm0, xmm1); vpunpckhwd(xmm5, xmm0, xmm1); vperm2f128(ymm0, ymm4, ymm5, 0x20); vpunpcklwd(xmm4, xmm2, xmm3); vpunpckhwd(xmm5, xmm2, xmm3); vperm2f128(ymm2, ymm4, ymm5, 0x20); vmovdqu(yword[B-0x40], ymm0); vmovdqu(yword[B-0x20], ymm2); sub(B, -128); dec(I); jg(l688, T_NEAR); align(4); L(l730); test(M, 0x4); jle(l78c, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm2, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm3, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm4, xmm0, xmm1); vpunpckhwd(xmm5, xmm0, xmm1); vperm2f128(ymm0, ymm4, ymm5, 0x20); vpunpcklwd(xmm4, xmm2, xmm3); vpunpckhwd(xmm5, xmm2, xmm3); vperm2f128(ymm2, ymm4, ymm5, 0x20); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm2); sub(B, -64); align(4); L(l78c); test(M, 0x2); jle(l7c0, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm0, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm0); sub(B, -32); align(4); L(l7c0); test(M, 0x1); jle(l7dc, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l7dc); sub(N, 0x8); cmp(N, 0x8); jge(l674, T_NEAR); align(4); L(l7ec); cmp(N, 0x4); jl(l924, T_NEAR); align(4); L(l7f8); mov(A1, A); add(A, 0x8); mov(I, M); sar(I, 0x3); jle(l884, T_NEAR); align(4); L(l808); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vmovq(xmm2, qword[A1-0x80]); add(A1, LDA); vmovq(xmm3, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vperm2f128(ymm0, ymm0, ymm2, 0x20); vmovdqu(yword[B-0x80], ymm0); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vmovq(xmm2, qword[A1-0x80]); add(A1, LDA); vmovq(xmm3, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vperm2f128(ymm0, ymm0, ymm2, 0x20); vmovdqu(yword[B-0x60], ymm0); sub(B, -64); dec(I); jg(l808, T_NEAR); align(4); L(l884); test(M, 0x4); jle(l8cc, T_NEAR); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vmovq(xmm2, qword[A1-0x80]); add(A1, LDA); vmovq(xmm3, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vmovdqu(xword[B-0x80], xmm0); vmovdqu(xword[B-0x70], xmm2); sub(B, -32); align(4); L(l8cc); test(M, 0x2); jle(l8f8, T_NEAR); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l8f8); test(M, 0x1); jle(l914, T_NEAR); vmovq(xmm0, qword[A1-0x80]); vmovq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l914); sub(N, 0x4); cmp(N, 0x4); jge(l7f8, T_NEAR); align(4); L(l924); cmp(N, 0x2); jl(la52, T_NEAR); align(4); L(l930); mov(A1, A); add(A, 0x4); mov(I, M); sar(I, 0x3); jle(l9b8, T_NEAR); align(4); L(l940); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vmovd(xmm2, dword[A1-0x80]); add(A1, LDA); vmovd(xmm3, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x80], xmm0); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vmovd(xmm2, dword[A1-0x80]); add(A1, LDA); vmovd(xmm3, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x70], xmm0); sub(B, -32); dec(I); jg(l940, T_NEAR); align(4); L(l9b8); test(M, 0x4); jle(l9fc, T_NEAR); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vmovd(xmm2, dword[A1-0x80]); add(A1, LDA); vmovd(xmm3, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l9fc); test(M, 0x2); jle(la28, T_NEAR); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vmovq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(la28); test(M, 0x1); jle(la44, T_NEAR); vmovd(xmm0, dword[A1-0x80]); vmovd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(la44); sub(N, 0x2); cmp(N, 0x2); jge(l930, T_NEAR); align(4); L(la52); cmp(N, 0x1); jl(lb84, T_NEAR); align(4); L(la5c); mov(A1, A); add(A, 0x2); mov(LDA3, M); sar(LDA3, 0x3); jle(lae4, T_NEAR); align(4); L(la6c); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x3); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x4); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x5); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x6); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x7); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); dec(LDA3); jg(la6c, T_NEAR); align(4); L(lae4); test(M, 0x4); jle(lb2c, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x3); vmovq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(lb2c); test(M, 0x2); jle(lb5c, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x1); vmovd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(lb5c); test(M, 0x1); jle(lb74, T_NEAR); mov(ax, word[A1-0x80]); mov(word[B-0x80], ax); sub(B, -2); align(4); L(lb74); sub(N, 0x1); cmp(N, 0x1); jge(la5c, T_NEAR); align(4); L(lb84); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif } } } }
20,822
12,702
๏ปฟ//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <tchar.h> //--------------------------------------------------------------------------- USEFORM("UAbout.cpp", AboutBox); USEFORM("UEdit.cpp", EditFile); USEFORM("URegInf.cpp", RegInf); USEFORM("UReg.cpp", Regist); USEFORM("UMain.cpp", Main); USEFORM("UEnv.cpp", Env); //--------------------------------------------------------------------------- int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) { HANDLE mx = CreateMutex(NULL, true, L"SingleInstanceProgram"); if (GetLastError()) { ShowMessage("CWTW-Proใฏๆ—ขใซๅฎŸ่กŒใ•ใ‚Œใฆใ„ใพใ™๏ผ"); return -1; } try { Application->Initialize(); Application->MainFormOnTaskBar = true; Application->CreateForm(__classid(TMain), &Main); Application->CreateForm(__classid(TAboutBox), &AboutBox); Application->CreateForm(__classid(TEditFile), &EditFile); Application->CreateForm(__classid(TRegist), &Regist); Application->CreateForm(__classid(TRegInf), &RegInf); Application->CreateForm(__classid(TEnv), &Env); Application->Run(); } catch (Exception &exception) { Application->ShowException(&exception); } catch (...) { try { throw Exception(""); } catch (Exception &exception) { Application->ShowException(&exception); } } ReleaseMutex(mx); return 0; } //---------------------------------------------------------------------------
1,436
477
// Merge two Linked List #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; } *first = NULL, *second = NULL, *third = NULL; void Display(struct Node *p) { while (p != NULL) { printf("%d ", p->data); p = p->next; } } void create(int A[], int n) { int i; struct Node *t, *last; first = (struct Node *)malloc(sizeof(struct Node)); first->data = A[0]; first->next = NULL; last = first; } for (int i = 1; i < n; i++) { t = (struct Node *)malloc(sizeof(struct Node)); t->data = A[i]; t->next = NULL; last->next = t; last = t; } void create2(int A[], int n) { int i; struct Node *t, *last; second = (struct Node *)malloc(sizeof(struct Node)); second->data = A[0]; second->next = NULL; last = second; } for (i = 1; i < n; i++) { t = (struct Node *)malloc(sizeof(struct Node)); t->data = A[i]; t->next = NULL; last->next = t; last = t; } void Merge(struct Node *p, struct Node *q) { struct Node *last; if (p->data < q->data) { third = last = p; p = p->next; third->next = NULL; } else { third = last = q; q = q->next; third->next = NULL; } while (p && q) { if (p->data < q->data) { last->next = p; last = p; p = p->next; last->next = NULL; } else { last->next = q; last = q; q = q->next; last->next = NULL; } } if (p) { last->next = p; } if (q) { last->next = q; } } int main() { int A[] = {10, 20, 40, 50, 60}; int B[] = {15, 18, 25, 30, 55}; create(A, 5); create2(B, 5); Merge(frist, second); Display(third); } return 0;
1,865
716
/* ============================================================================ * Copyright (c) 2010, Michael A. Jackson (BlueQuartz Software) * Copyright (c) 2010, Dr. Michael A. Groeber (US Air Force Research Laboratories * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of Michael A. Groeber, Michael A. Jackson, the US Air Force, * BlueQuartz Software nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This code was written under United States Air Force Contract number * FA8650-07-D-5800 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "MicFields.h" #include "MicConstants.h" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MicFields::MicFields() = default; // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MicFields::~MicFields() = default; // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- std::vector<std::string> MicFields::getFieldNames() { std::vector<std::string> features; features.push_back(Mic::Euler1); features.push_back(Mic::Euler2); features.push_back(Mic::Euler3); features.push_back(Mic::Confidence); features.push_back(Mic::Phase); features.push_back(Mic::X); features.push_back(Mic::Y); return features; }
2,973
879
// Copyright 2021 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <grpc/impl/codegen/port_platform.h> #include "src/core/lib/config/core_configuration.h" namespace grpc_core { std::atomic<CoreConfiguration*> CoreConfiguration::config_{nullptr}; CoreConfiguration::Builder::Builder() = default; CoreConfiguration* CoreConfiguration::Builder::Build() { return new CoreConfiguration(this); } CoreConfiguration::CoreConfiguration(Builder* builder) : handshaker_registry_(builder->handshaker_registry_.Build()) {} const CoreConfiguration& CoreConfiguration::BuildNewAndMaybeSet() { // Construct builder, pass it up to code that knows about build configuration Builder builder; BuildCoreConfiguration(&builder); // Use builder to construct a confguration CoreConfiguration* p = builder.Build(); // Try to set configuration global - it's possible another thread raced us // here, in which case we drop the work we did and use the one that got set // first CoreConfiguration* expected = nullptr; if (!config_.compare_exchange_strong(expected, p, std::memory_order_acq_rel, std::memory_order_acquire)) { delete p; return *expected; } return *p; } void CoreConfiguration::Reset() { delete config_.exchange(nullptr, std::memory_order_acquire); } } // namespace grpc_core
1,883
529
/** * Algorithm and estimation function regarding transform. * \author Christian Merkl (knueppl@gmx.de) * \date 2. November 2019 */ #include "francor_base/algorithm/transform.h" #include "francor_base/transform.h" namespace francor { namespace base { namespace algorithm { namespace transform { void transformPointVector(const Transform2d& transform, Point2dVector& points) { for (auto& point : points) point = transform * point; } } // end namespace transform } // end namespace algorithm } // end namespace base } // end namespace francor
560
167
// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates simple use of the PxSpatialIndex data structure // // Note that spatial index has been marked as deprecated and will be removed // in future releases // // We create a number of spheres, and raycast against them in a random direction // from the origin. When a raycast hits a sphere, we teleport it to a random // location // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../SnippetCommon/SnippetPrint.h" #include "../SnippetUtils/SnippetUtils.h" using namespace physx; PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; static const PxU32 SPHERE_COUNT = 500; float rand01() { return float(rand())/RAND_MAX; } struct Sphere : public PxSpatialIndexItem { Sphere() { radius = 1; resetPosition(); } Sphere(PxReal r) : radius(r) { resetPosition(); } void resetPosition() { do { position = PxVec3(rand01()-0.5f, rand01()-0.5f, rand01()-0.5f)*(5+rand01()*5); } while (position.normalize()==0.0f); } PxBounds3 getBounds() { // Geometry queries err on the side of reporting positive results in the face of floating point inaccuracies. // To ensure that a geometry query only reports true when the bounding boxes in the BVH overlap, use // getWorldBounds, which has a third parameter that scales the bounds slightly (default is scaling by 1.01f) return PxGeometryQuery::getWorldBounds(PxSphereGeometry(radius), PxTransform(position)); } PxVec3 position; PxReal radius; PxSpatialIndexItemId id; }; Sphere gSpheres[SPHERE_COUNT]; PxSpatialIndex* gBvh; void init() { gFoundation = PxCreateFoundation(PX_FOUNDATION_VERSION, gAllocator, gErrorCallback); gBvh = PxCreateSpatialIndex(); // insert the spheres into the BVH, recording the ID so we can later update them for(PxU32 i=0;i<SPHERE_COUNT;i++) gSpheres[i].id = gBvh->insert(gSpheres[i], gSpheres[i].getBounds()); // force a full rebuild of the BVH gBvh->rebuildFull(); // hint that should rebuild over the course of approximately 20 rebuildStep() calls gBvh->setIncrementalRebuildRate(20); } struct HitCallback : public PxSpatialLocationCallback { HitCallback(const PxVec3 p, const PxVec3& d): position(p), direction(d), closest(FLT_MAX), hitSphere(NULL) {} PxAgain onHit(PxSpatialIndexItem& item, PxReal distance, PxReal& shrunkDistance) { PX_UNUSED(distance); Sphere& s = static_cast<Sphere&>(item); PxRaycastHit hitData; // the ray hit the sphere's AABB, now we do a ray-sphere intersection test to find out if the ray hit the sphere PxU32 hit = PxGeometryQuery::raycast(position, direction, PxSphereGeometry(s.radius), PxTransform(s.position), 1e6, PxHitFlag::eDEFAULT, 1, &hitData); // if the raycast hit and it's closer than what we had before, shrink the maximum length of the raycast if(hit && hitData.distance < closest) { closest = hitData.distance; hitSphere = &s; shrunkDistance = hitData.distance; } // and continue the query return true; } PxVec3 position, direction; PxReal closest; Sphere* hitSphere; }; void step() { for(PxU32 hits=0; hits<10;) { // raycast in a random direction from the origin, and teleport the closest sphere we find PxVec3 dir = PxVec3(rand01()-0.5f, rand01()-0.5f, rand01()-0.5f).getNormalized(); HitCallback callback(PxVec3(0), dir); gBvh->raycast(PxVec3(0), dir, FLT_MAX, callback); Sphere* hit = callback.hitSphere; if(hit) { hit->resetPosition(); gBvh->update(hit->id, hit->getBounds()); hits++; } } // run an incremental rebuild step in the background gBvh->rebuildStep(); } void cleanup() { gBvh->release(); gFoundation->release(); printf("SnippetSpatialIndex done.\n"); } int snippetMain(int, const char*const*) { static const PxU32 frameCount = 100; init(); for(PxU32 i=0; i<frameCount; i++) step(); cleanup(); return 0; }
5,782
2,178
#include <array> #include <cstdlib> #include <filesystem> #include <numeric> #ifdef __linux__ #include <unistd.h> #include <limits.h> #endif #include "util_env.h" #include "./com/com_include.h" namespace dxvk::env { std::string getEnvVar(const char* name) { #ifdef _WIN32 std::vector<WCHAR> result; result.resize(MAX_PATH + 1); DWORD len = ::GetEnvironmentVariableW(str::tows(name).c_str(), result.data(), MAX_PATH); result.resize(len); return str::fromws(result.data()); #else const char* result = std::getenv(name); return result ? result : ""; #endif } size_t matchFileExtension(const std::string& name, const char* ext) { auto pos = name.find_last_of('.'); if (pos == std::string::npos) return pos; bool matches = std::accumulate(name.begin() + pos + 1, name.end(), true, [&ext] (bool current, char a) { if (a >= 'A' && a <= 'Z') a += 'a' - 'A'; return current && *ext && a == *(ext++); }); return matches ? pos : std::string::npos; } std::string getExeName() { std::string fullPath = getExePath(); auto n = fullPath.find_last_of(env::PlatformDirSlash); return (n != std::string::npos) ? fullPath.substr(n + 1) : fullPath; } std::string getExeBaseName() { auto exeName = getExeName(); #ifdef _WIN32 auto extp = matchFileExtension(exeName, "exe"); if (extp != std::string::npos) exeName.erase(extp); #endif return exeName; } std::string getExePath() { #if defined(_WIN32) std::vector<WCHAR> exePath; exePath.resize(MAX_PATH + 1); DWORD len = ::GetModuleFileNameW(NULL, exePath.data(), MAX_PATH); exePath.resize(len); return str::fromws(exePath.data()); #elif defined(__linux__) std::array<char, PATH_MAX> exePath = {}; size_t count = readlink("/proc/self/exe", exePath.data(), exePath.size()); return std::string(exePath.begin(), exePath.begin() + count); #endif } void setThreadName(const std::string& name) { #ifdef _WIN32 using SetThreadDescriptionProc = HRESULT (WINAPI *) (HANDLE, PCWSTR); static auto proc = reinterpret_cast<SetThreadDescriptionProc>( ::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "SetThreadDescription")); if (proc != nullptr) { auto wideName = std::vector<WCHAR>(name.length() + 1); str::tows(name.c_str(), wideName.data(), wideName.size()); (*proc)(::GetCurrentThread(), wideName.data()); } #else std::array<char, 16> posixName = {}; dxvk::str::strlcpy(posixName.data(), name.c_str(), 16); ::pthread_setname_np(pthread_self(), posixName.data()); #endif } bool createDirectory(const std::string& path) { #ifdef _WIN32 WCHAR widePath[MAX_PATH]; str::tows(path.c_str(), widePath); return !!CreateDirectoryW(widePath, nullptr); #else return std::filesystem::create_directories(path); #endif } }
2,932
1,077
//https://codeforces.com/contest/66/problem/B #include<bits/stdc++.h> using namespace std ; #define aakriti long long int int main() { ios_base::sync_with_stdio(false); cin.tie(0); aakriti number ; cin >> number ; aakriti arr[number], ans = 1 ; for(int i = 0; i <number ; i++) cin >> arr[i] ; for(int i = 0; i < number; i++) { aakriti cnt = 1 ; for(int j = i -1; j >= 0; j--) { if(arr[j] <= arr[j + 1]) cnt++; else break; } for(int j = i + 1; j < number; j++) { if(arr[j] <= arr[j - 1]) cnt++; else break; } ans = max(ans, cnt); } cout << ans ; }
805
306
#include "model.h" #include <gfx.h> #include <glad/glad.h> #include <tiny_obj_loader.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <shader.h> /** Constants for vertex attribute locations */ constexpr auto va_position = 0; constexpr auto va_normal = 1; constexpr auto va_texcoord = 2; /** Constants for texture sampler bindings */ constexpr auto tb_diffuse = 0; Model::~Model() noexcept { glDeleteBuffers(1, &m_vbo); glDeleteBuffers(1, &m_ebo); glDeleteVertexArrays(1, &m_vao); } Model::Model(Model &&other) : m_vbo(other.m_vbo), m_ebo(other.m_ebo), m_vao(other.m_vao), m_texture(std::move(other.m_texture)), m_index_count(other.m_index_count) { other.m_vbo = 0u; other.m_ebo = 0u; other.m_vao = 0u; other.m_index_count = 0u; } Model &Model::operator=(Model &&other) { /** Protect */ if (this == &other) { return *this; } /** Destroy */ glDeleteBuffers(1, &m_vbo); glDeleteBuffers(1, &m_ebo); glDeleteVertexArrays(1, &m_vao); /** Steal */ m_vbo = other.m_vbo; m_ebo = other.m_ebo; m_vao = other.m_vao; m_texture = std::move(other.m_texture); m_index_count = other.m_index_count; /** Clean */ other.m_vbo = 0u; other.m_ebo = 0u; other.m_vao = 0u; other.m_index_count = 0u; return *this; } void Model::load(const std::string &filepath_obj, const std::string &diffuse_path) { m_texture.load_texture(diffuse_path); /** Load OBJ Data */ tinyobj::attrib_t attributes{}; std::vector<tinyobj::shape_t> shapes{}; std::vector<tinyobj::material_t> materials{}; std::string warning{}, error{}; if (!tinyobj::LoadObj(&attributes, &shapes, &materials, &error, filepath_obj.c_str())) { GFX_ERROR("Could not load model: W(%s) E(%s)", warning.c_str(), error.c_str()); } /** Success loading, so we can extract data here */ std::vector<Vertex> out_vertices{}; std::vector<unsigned> out_indices{}; for (const auto &shape : shapes) { for (const auto &index : shape.mesh.indices) { /** Uses non-deal index loading, this does not remove duplicate vertices, it's naive, but works for demo purposes */ out_vertices.push_back({}); out_indices.push_back(out_indices.size()); auto &vertex = out_vertices.back(); vertex.position = {attributes.vertices[3 * index.vertex_index + 0], attributes.vertices[3 * index.vertex_index + 1], attributes.vertices[3 * index.vertex_index + 2]}; vertex.normals = {attributes.normals[3 * index.normal_index + 0], attributes.normals[3 * index.normal_index + 1], attributes.normals[3 * index.normal_index + 2]}; vertex.texcoord = {attributes.texcoords[2 * index.texcoord_index + 0], attributes.texcoords[2 * index.texcoord_index + 1]}; } } /** Set index count */ m_index_count = out_indices.size(); /** Create VAO / VBO / EBO */ glGenVertexArrays(1, &m_vao); glBindVertexArray(m_vao); glGenBuffers(1, &m_vbo); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glGenBuffers(1, &m_ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * out_vertices.size(), out_vertices.data(), GL_STATIC_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned) * out_indices.size(), out_indices.data(), GL_STATIC_DRAW); glVertexAttribPointer(va_position, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *)offsetof(Vertex, position)); glVertexAttribPointer(va_normal, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *)offsetof(Vertex, normals)); glVertexAttribPointer(va_texcoord, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *)offsetof(Vertex, texcoord)); glEnableVertexAttribArray(va_position); glEnableVertexAttribArray(va_normal); glEnableVertexAttribArray(va_texcoord); GFX_INFO("Loaded model %s (%u vertices).", filepath_obj.c_str(), out_vertices.size()); } void Model::draw(glm::vec3 position, float scale, glm::vec3 rotation, Shader shader) { auto model = glm::translate(glm::mat4(1.f), position); model = glm::scale(model, glm::vec3(scale)); model = glm::rotate(model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); auto normal_matrix = glm::mat3(model); shader.setMat4("model", model); shader.setMat3("normal_matrix", normal_matrix); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo); glBindVertexArray(m_vao); m_texture.bind(tb_diffuse); glDrawElements(GL_TRIANGLES, m_index_count, GL_UNSIGNED_INT, nullptr); // set everything to default glBindVertexArray(0); glActiveTexture(GL_TEXTURE0); }
4,844
1,947
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "UnrealEd.h" #include "StructureEditorUtils.h" #include "ScopedTransaction.h" #include "Kismet2NameValidators.h" #include "Kismet2/BlueprintEditorUtils.h" #include "EdGraphSchema_K2.h" #include "ObjectTools.h" #include "Editor/UnrealEd/Public/Kismet2/CompilerResultsLog.h" #include "Editor/UnrealEd/Public/EditorModes.h" #include "Editor/KismetCompiler/Public/KismetCompilerModule.h" #include "Toolkits/AssetEditorManager.h" #include "Editor/DataTableEditor/Public/IDataTableEditor.h" #include "Engine/UserDefinedStruct.h" #include "Engine/DataTable.h" #define LOCTEXT_NAMESPACE "Structure" ////////////////////////////////////////////////////////////////////////// // FStructEditorManager FStructureEditorUtils::FStructEditorManager& FStructureEditorUtils::FStructEditorManager::Get() { static TSharedRef< FStructEditorManager > EditorManager( new FStructEditorManager() ); return *EditorManager; } ////////////////////////////////////////////////////////////////////////// // FStructureEditorUtils UUserDefinedStruct* FStructureEditorUtils::CreateUserDefinedStruct(UObject* InParent, FName Name, EObjectFlags Flags) { UUserDefinedStruct* Struct = NULL; if (UserDefinedStructEnabled()) { Struct = NewObject<UUserDefinedStruct>(InParent, Name, Flags); check(Struct); Struct->EditorData = NewObject<UUserDefinedStructEditorData>(Struct, NAME_None, RF_Transactional); check(Struct->EditorData); Struct->Guid = FGuid::NewGuid(); Struct->SetMetaData(TEXT("BlueprintType"), TEXT("true")); Struct->Bind(); Struct->StaticLink(true); Struct->Status = UDSS_Error; { const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>(); AddVariable(Struct, FEdGraphPinType(K2Schema->PC_Boolean, FString(), NULL, false, false)); } } return Struct; } FStructureEditorUtils::EStructureError FStructureEditorUtils::IsStructureValid(const UScriptStruct* Struct, const UStruct* RecursionParent, FString* OutMsg) { check(Struct); if (Struct == RecursionParent) { if (OutMsg) { *OutMsg = FString::Printf(*LOCTEXT("StructureRecursion", "Recursion: Struct cannot have itself as a member variable. Struct '%s', recursive parent '%s'").ToString(), *Struct->GetFullName(), *RecursionParent->GetFullName()); } return EStructureError::Recursion; } const UScriptStruct* FallbackStruct = GetFallbackStruct(); if (Struct == FallbackStruct) { if (OutMsg) { *OutMsg = LOCTEXT("StructureUnknown", "Struct unknown (deleted?)").ToString(); } return EStructureError::FallbackStruct; } if (Struct->GetStructureSize() <= 0) { if (OutMsg) { *OutMsg = FString::Printf(*LOCTEXT("StructureSizeIsZero", "Struct '%s' is empty").ToString(), *Struct->GetFullName()); } return EStructureError::EmptyStructure; } if (const UUserDefinedStruct* UDStruct = Cast<const UUserDefinedStruct>(Struct)) { if (UDStruct->Status != EUserDefinedStructureStatus::UDSS_UpToDate) { if (OutMsg) { *OutMsg = FString::Printf(*LOCTEXT("StructureNotCompiled", "Struct '%s' is not compiled").ToString(), *Struct->GetFullName()); } return EStructureError::NotCompiled; } for (const UProperty* P = Struct->PropertyLink; P; P = P->PropertyLinkNext) { const UStructProperty* StructProp = Cast<const UStructProperty>(P); if (NULL == StructProp) { if (const UArrayProperty* ArrayProp = Cast<const UArrayProperty>(P)) { StructProp = Cast<const UStructProperty>(ArrayProp->Inner); } } if (StructProp) { if ((NULL == StructProp->Struct) || (FallbackStruct == StructProp->Struct)) { if (OutMsg) { *OutMsg = FString::Printf(*LOCTEXT("StructureUnknownProperty", "Struct unknown (deleted?). Parent '%s' Property: '%s'").ToString(), *Struct->GetFullName(), *StructProp->GetName()); } return EStructureError::FallbackStruct; } FString OutMsgInner; const EStructureError Result = IsStructureValid( StructProp->Struct, RecursionParent ? RecursionParent : Struct, OutMsg ? &OutMsgInner : NULL); if (EStructureError::Ok != Result) { if (OutMsg) { *OutMsg = FString::Printf(*LOCTEXT("StructurePropertyErrorTemplate", "Struct '%s' Property '%s' Error ( %s )").ToString(), *Struct->GetFullName(), *StructProp->GetName(), *OutMsgInner); } return Result; } } } } return EStructureError::Ok; } bool FStructureEditorUtils::CanHaveAMemberVariableOfType(const UUserDefinedStruct* Struct, const FEdGraphPinType& VarType, FString* OutMsg) { const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>(); if ((VarType.PinCategory == K2Schema->PC_Struct) && Struct) { if (const UScriptStruct* SubCategoryStruct = Cast<const UScriptStruct>(VarType.PinSubCategoryObject.Get())) { const EStructureError Result = IsStructureValid(SubCategoryStruct, Struct, OutMsg); if (EStructureError::Ok != Result) { return false; } } else { if (OutMsg) { *OutMsg = LOCTEXT("StructureIncorrectStructType", "Incorrect struct type in a structure member variable.").ToString(); } return false; } } else if ((VarType.PinCategory == K2Schema->PC_Exec) || (VarType.PinCategory == K2Schema->PC_Wildcard) || (VarType.PinCategory == K2Schema->PC_MCDelegate) || (VarType.PinCategory == K2Schema->PC_Delegate)) { if (OutMsg) { *OutMsg = LOCTEXT("StructureIncorrectTypeCategory", "Incorrect type for a structure member variable.").ToString(); } return false; } else { const auto PinSubCategoryClass = Cast<const UClass>(VarType.PinSubCategoryObject.Get()); if (PinSubCategoryClass && PinSubCategoryClass->IsChildOf(UBlueprint::StaticClass())) { if (OutMsg) { *OutMsg = LOCTEXT("StructureUseBlueprintReferences", "Struct cannot use any blueprint references").ToString(); } return false; } } return true; } struct FMemberVariableNameHelper { static FName Generate(UUserDefinedStruct* Struct, const FString& NameBase, const FGuid Guid, FString* OutFriendlyName = NULL) { check(Struct); FString Result; if (!NameBase.IsEmpty()) { const FName NewNameBase(*NameBase); if (ensure(NewNameBase.IsValidXName(INVALID_OBJECTNAME_CHARACTERS))) { Result = NameBase; } } if (Result.IsEmpty()) { Result = TEXT("MemberVar"); } const uint32 UniqueNameId = CastChecked<UUserDefinedStructEditorData>(Struct->EditorData)->GenerateUniqueNameIdForMemberVariable(); const FString FriendlyName = FString::Printf(TEXT("%s_%u"), *Result, UniqueNameId); if (OutFriendlyName) { *OutFriendlyName = FriendlyName; } const FName NameResult = *FString::Printf(TEXT("%s_%s"), *FriendlyName, *Guid.ToString(EGuidFormats::Digits)); check(NameResult.IsValidXName(INVALID_OBJECTNAME_CHARACTERS)); return NameResult; } static FGuid GetGuidFromName(const FName Name) { const FString NameStr = Name.ToString(); const int32 GuidStrLen = 32; if (NameStr.Len() > (GuidStrLen + 1)) { const int32 UnderscoreIndex = NameStr.Len() - GuidStrLen - 1; if (TCHAR('_') == NameStr[UnderscoreIndex]) { const FString GuidStr = NameStr.Right(GuidStrLen); FGuid Guid; if (FGuid::ParseExact(GuidStr, EGuidFormats::Digits, Guid)) { return Guid; } } } return FGuid(); } }; bool FStructureEditorUtils::AddVariable(UUserDefinedStruct* Struct, const FEdGraphPinType& VarType) { if (Struct) { const FScopedTransaction Transaction( LOCTEXT("AddVariable", "Add Variable") ); ModifyStructData(Struct); FString ErrorMessage; if (!CanHaveAMemberVariableOfType(Struct, VarType, &ErrorMessage)) { UE_LOG(LogBlueprint, Warning, TEXT("%s"), *ErrorMessage); return false; } const FGuid Guid = FGuid::NewGuid(); FString DisplayName; const FName VarName = FMemberVariableNameHelper::Generate(Struct, FString(), Guid, &DisplayName); check(NULL == GetVarDesc(Struct).FindByPredicate(FStructureEditorUtils::FFindByNameHelper<FStructVariableDescription>(VarName))); check(IsUniqueVariableDisplayName(Struct, DisplayName)); FStructVariableDescription NewVar; NewVar.VarName = VarName; NewVar.FriendlyName = DisplayName; NewVar.SetPinType(VarType); NewVar.VarGuid = Guid; NewVar.bDontEditoOnInstance = false; NewVar.bInvalidMember = false; GetVarDesc(Struct).Add(NewVar); OnStructureChanged(Struct); return true; } return false; } bool FStructureEditorUtils::RemoveVariable(UUserDefinedStruct* Struct, FGuid VarGuid) { if(Struct) { const auto OldNum = GetVarDesc(Struct).Num(); const bool bAllowToMakeEmpty = false; if (bAllowToMakeEmpty || (OldNum > 1)) { const FScopedTransaction Transaction(LOCTEXT("RemoveVariable", "Remove Variable")); ModifyStructData(Struct); GetVarDesc(Struct).RemoveAll(FFindByGuidHelper<FStructVariableDescription>(VarGuid)); if (OldNum != GetVarDesc(Struct).Num()) { OnStructureChanged(Struct); return true; } } else { UE_LOG(LogBlueprint, Log, TEXT("Member variable cannot be removed. User Defined Structure cannot be empty")); } } return false; } bool FStructureEditorUtils::RenameVariable(UUserDefinedStruct* Struct, FGuid VarGuid, const FString& NewDisplayNameStr) { if (Struct) { auto VarDesc = GetVarDescByGuid(Struct, VarGuid); if (VarDesc && !NewDisplayNameStr.IsEmpty() && FName(*NewDisplayNameStr).IsValidXName(INVALID_OBJECTNAME_CHARACTERS) && IsUniqueVariableDisplayName(Struct, NewDisplayNameStr)) { const FScopedTransaction Transaction(LOCTEXT("RenameVariable", "Rename Variable")); ModifyStructData(Struct); VarDesc->FriendlyName = NewDisplayNameStr; //>>> TEMPORARY it's more important to prevent changes in structs instances, than to have consistent names if (GetGuidFromPropertyName(VarDesc->VarName).IsValid()) //<<< TEMPORARY { const FName NewName = FMemberVariableNameHelper::Generate(Struct, NewDisplayNameStr, VarGuid); check(NULL == GetVarDesc(Struct).FindByPredicate(FFindByNameHelper<FStructVariableDescription>(NewName))) VarDesc->VarName = NewName; } OnStructureChanged(Struct); return true; } } return false; } bool FStructureEditorUtils::ChangeVariableType(UUserDefinedStruct* Struct, FGuid VarGuid, const FEdGraphPinType& NewType) { if (Struct) { FString ErrorMessage; if(!CanHaveAMemberVariableOfType(Struct, NewType, &ErrorMessage)) { UE_LOG(LogBlueprint, Warning, TEXT("%s"), *ErrorMessage); return false; } auto VarDesc = GetVarDescByGuid(Struct, VarGuid); if(VarDesc) { const bool bChangedType = (VarDesc->ToPinType() != NewType); if (bChangedType) { const FScopedTransaction Transaction(LOCTEXT("ChangeVariableType", "Change Variable Type")); ModifyStructData(Struct); VarDesc->VarName = FMemberVariableNameHelper::Generate(Struct, VarDesc->FriendlyName, VarDesc->VarGuid); VarDesc->DefaultValue = FString(); VarDesc->SetPinType(NewType); OnStructureChanged(Struct); return true; } } } return false; } bool FStructureEditorUtils::ChangeVariableDefaultValue(UUserDefinedStruct* Struct, FGuid VarGuid, const FString& NewDefaultValue) { auto ValidateDefaultValue = [](const FStructVariableDescription& VarDesc, const FString& InNewDefaultValue) -> bool { const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>(); const FEdGraphPinType PinType = VarDesc.ToPinType(); bool bResult = false; //TODO: validation for values, that are not passed by string if (PinType.PinCategory == K2Schema->PC_Text) { bResult = true; } else if ((PinType.PinCategory == K2Schema->PC_Object) || (PinType.PinCategory == K2Schema->PC_Interface) || (PinType.PinCategory == K2Schema->PC_Class) || (PinType.PinCategory == K2Schema->PC_AssetClass) || (PinType.PinCategory == K2Schema->PC_Asset)) { // K2Schema->DefaultValueSimpleValidation finds an object, passed by path, invalid bResult = true; } else { bResult = K2Schema->DefaultValueSimpleValidation(PinType, FString(), InNewDefaultValue, NULL, FText::GetEmpty()); } return bResult; }; auto VarDesc = GetVarDescByGuid(Struct, VarGuid); if (VarDesc && (NewDefaultValue != VarDesc->DefaultValue) && ValidateDefaultValue(*VarDesc, NewDefaultValue)) { bool bAdvancedValidation = true; if (!NewDefaultValue.IsEmpty()) { const auto Property = FindField<UProperty>(Struct, VarDesc->VarName); FStructOnScope StructDefaultMem(Struct); bAdvancedValidation = StructDefaultMem.IsValid() && Property && FBlueprintEditorUtils::PropertyValueFromString(Property, NewDefaultValue, StructDefaultMem.GetStructMemory()); } if (bAdvancedValidation) { const FScopedTransaction Transaction(LOCTEXT("ChangeVariableDefaultValue", "Change Variable Default Value")); ModifyStructData(Struct); VarDesc->DefaultValue = NewDefaultValue; OnStructureChanged(Struct); return true; } } return false; } bool FStructureEditorUtils::IsUniqueVariableDisplayName(const UUserDefinedStruct* Struct, const FString& DisplayName) { if(Struct) { for (auto& VarDesc : GetVarDesc(Struct)) { if (VarDesc.FriendlyName == DisplayName) { return false; } } return true; } return false; } FString FStructureEditorUtils::GetVariableDisplayName(const UUserDefinedStruct* Struct, FGuid VarGuid) { const auto VarDesc = GetVarDescByGuid(Struct, VarGuid); return VarDesc ? VarDesc->FriendlyName : FString(); } bool FStructureEditorUtils::UserDefinedStructEnabled() { static FBoolConfigValueHelper UseUserDefinedStructure(TEXT("UserDefinedStructure"), TEXT("bUseUserDefinedStructure")); return UseUserDefinedStructure; } void FStructureEditorUtils::RecreateDefaultInstanceInEditorData(UUserDefinedStruct* Struct) { auto StructEditorData = Struct ? CastChecked<UUserDefinedStructEditorData>(Struct->EditorData) : nullptr; if (StructEditorData) { StructEditorData->RecreateDefaultInstance(); } } bool FStructureEditorUtils::Fill_MakeStructureDefaultValue(const UUserDefinedStruct* Struct, uint8* StructData) { bool bResult = true; if (Struct && StructData) { auto StructEditorData = CastChecked<UUserDefinedStructEditorData>(Struct->EditorData); const uint8* DefaultInstance = StructEditorData->GetDefaultInstance(); if (DefaultInstance) { Struct->CopyScriptStruct(StructData, DefaultInstance); } else { bResult = false; } } return bResult; } bool FStructureEditorUtils::Fill_MakeStructureDefaultValue(const UProperty* Property, uint8* PropertyData) { bool bResult = true; if (const UStructProperty* StructProperty = Cast<const UStructProperty>(Property)) { if (const UUserDefinedStruct* InnerStruct = Cast<const UUserDefinedStruct>(StructProperty->Struct)) { bResult &= Fill_MakeStructureDefaultValue(InnerStruct, PropertyData); } } else if (const UArrayProperty* ArrayProp = Cast<const UArrayProperty>(Property)) { StructProperty = Cast<const UStructProperty>(ArrayProp->Inner); const UUserDefinedStruct* InnerStruct = StructProperty ? Cast<const UUserDefinedStruct>(StructProperty->Struct) : NULL; if(InnerStruct) { FScriptArrayHelper ArrayHelper(ArrayProp, PropertyData); for (int32 Index = 0; Index < ArrayHelper.Num(); ++Index) { uint8* const ValuePtr = ArrayHelper.GetRawPtr(Index); bResult &= Fill_MakeStructureDefaultValue(InnerStruct, ValuePtr); } } } return bResult; } void FStructureEditorUtils::CompileStructure(UUserDefinedStruct* Struct) { if (Struct) { IKismetCompilerInterface& Compiler = FModuleManager::LoadModuleChecked<IKismetCompilerInterface>(KISMET_COMPILER_MODULENAME); FCompilerResultsLog Results; Compiler.CompileStructure(Struct, Results); } } void FStructureEditorUtils::OnStructureChanged(UUserDefinedStruct* Struct) { if (Struct) { Struct->Status = EUserDefinedStructureStatus::UDSS_Dirty; CompileStructure(Struct); Struct->MarkPackageDirty(); } } //TODO: Move to blueprint utils void FStructureEditorUtils::RemoveInvalidStructureMemberVariableFromBlueprint(UBlueprint* Blueprint) { if (Blueprint) { const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>(); const UScriptStruct* FallbackStruct = GetFallbackStruct(); FString DislpayList; TArray<FName> ZombieMemberNames; for (int32 VarIndex = 0; VarIndex < Blueprint->NewVariables.Num(); ++VarIndex) { const FBPVariableDescription& Var = Blueprint->NewVariables[VarIndex]; if (Var.VarType.PinCategory == K2Schema->PC_Struct) { const UScriptStruct* ScriptStruct = Cast<const UScriptStruct>(Var.VarType.PinSubCategoryObject.Get()); const bool bInvalidStruct = (NULL == ScriptStruct) || (FallbackStruct == ScriptStruct); if (bInvalidStruct) { DislpayList += Var.FriendlyName.IsEmpty() ? Var.VarName.ToString() : Var.FriendlyName; DislpayList += TEXT("\n"); ZombieMemberNames.Add(Var.VarName); } } } if (ZombieMemberNames.Num()) { auto Response = FMessageDialog::Open( EAppMsgType::OkCancel, FText::Format( LOCTEXT("RemoveInvalidStructureMemberVariable_Msg", "The following member variables in blueprint '{0}' have invalid type. Would you like to remove them? \n\n{1}"), FText::FromString(Blueprint->GetFullName()), FText::FromString(DislpayList) )); check((EAppReturnType::Ok == Response) || (EAppReturnType::Cancel == Response)); if (EAppReturnType::Ok == Response) { Blueprint->Modify(); for (auto NameIter = ZombieMemberNames.CreateConstIterator(); NameIter; ++NameIter) { const FName Name = *NameIter; Blueprint->NewVariables.RemoveAll(FFindByNameHelper<FBPVariableDescription>(Name)); //TODO: Add RemoveFirst to TArray FBlueprintEditorUtils::RemoveVariableNodes(Blueprint, Name); } } } } } TArray<FStructVariableDescription>& FStructureEditorUtils::GetVarDesc(UUserDefinedStruct* Struct) { check(Struct); return CastChecked<UUserDefinedStructEditorData>(Struct->EditorData)->VariablesDescriptions; } const TArray<FStructVariableDescription>& FStructureEditorUtils::GetVarDesc(const UUserDefinedStruct* Struct) { check(Struct); return CastChecked<const UUserDefinedStructEditorData>(Struct->EditorData)->VariablesDescriptions; } FString FStructureEditorUtils::GetTooltip(const UUserDefinedStruct* Struct) { const auto StructEditorData = Struct ? Cast<const UUserDefinedStructEditorData>(Struct->EditorData) : NULL; return StructEditorData ? StructEditorData->ToolTip : FString(); } bool FStructureEditorUtils::ChangeTooltip(UUserDefinedStruct* Struct, const FString& InTooltip) { auto StructEditorData = Struct ? Cast<UUserDefinedStructEditorData>(Struct->EditorData) : NULL; if (StructEditorData && (InTooltip != StructEditorData->ToolTip)) { const FScopedTransaction Transaction(LOCTEXT("ChangeTooltip", "Change UDS Tooltip")); StructEditorData->Modify(); StructEditorData->ToolTip = InTooltip; Struct->SetMetaData(FBlueprintMetadata::MD_Tooltip, *StructEditorData->ToolTip); return true; } return false; } FString FStructureEditorUtils::GetVariableTooltip(const UUserDefinedStruct* Struct, FGuid VarGuid) { const auto VarDesc = GetVarDescByGuid(Struct, VarGuid); return VarDesc ? VarDesc->ToolTip : FString(); } bool FStructureEditorUtils::ChangeVariableTooltip(UUserDefinedStruct* Struct, FGuid VarGuid, const FString& InTooltip) { auto VarDesc = GetVarDescByGuid(Struct, VarGuid); if (VarDesc && (InTooltip != VarDesc->ToolTip)) { const FScopedTransaction Transaction(LOCTEXT("ChangeVariableTooltip", "Change UDS Variable Tooltip")); ModifyStructData(Struct); VarDesc->ToolTip = InTooltip; auto Property = FindField<UProperty>(Struct, VarDesc->VarName); if (Property) { Property->SetMetaData(FBlueprintMetadata::MD_Tooltip, *VarDesc->ToolTip); } return true; } return false; } bool FStructureEditorUtils::ChangeEditableOnBPInstance(UUserDefinedStruct* Struct, FGuid VarGuid, bool bInIsEditable) { const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>(); auto VarDesc = GetVarDescByGuid(Struct, VarGuid); const bool bNewDontEditoOnInstance = !bInIsEditable; if (VarDesc && (bNewDontEditoOnInstance != VarDesc->bDontEditoOnInstance)) { const FScopedTransaction Transaction(LOCTEXT("ChangeVariableOnBPInstance", "Change variable editable on BP instance")); ModifyStructData(Struct); VarDesc->bDontEditoOnInstance = bNewDontEditoOnInstance; OnStructureChanged(Struct); return true; } return false; } bool FStructureEditorUtils::MoveVariable(UUserDefinedStruct* Struct, FGuid VarGuid, EMoveDirection MoveDirection) { if (Struct) { const bool bMoveUp = (EMoveDirection::MD_Up == MoveDirection); auto& DescArray = GetVarDesc(Struct); const int32 InitialIndex = bMoveUp ? 1 : 0; const int32 IndexLimit = DescArray.Num() - (bMoveUp ? 0 : 1); for (int32 Index = InitialIndex; Index < IndexLimit; ++Index) { if (DescArray[Index].VarGuid == VarGuid) { const FScopedTransaction Transaction(LOCTEXT("ReorderVariables", "Varaibles reordered")); ModifyStructData(Struct); DescArray.Swap(Index, Index + (bMoveUp ? -1 : 1)); OnStructureChanged(Struct); return true; } } } return false; } void FStructureEditorUtils::ModifyStructData(UUserDefinedStruct* Struct) { UUserDefinedStructEditorData* EditorData = Struct ? Cast<UUserDefinedStructEditorData>(Struct->EditorData) : NULL; ensure(EditorData); if (EditorData) { EditorData->Modify(); } } bool FStructureEditorUtils::CanEnableMultiLineText(const UUserDefinedStruct* Struct, FGuid VarGuid) { auto VarDesc = GetVarDescByGuid(Struct, VarGuid); if (VarDesc) { auto Property = FindField<UProperty>(Struct, VarDesc->VarName); if (Property) { // Can only set multi-line text on string and text properties return Property->IsA(UStrProperty::StaticClass()) || Property->IsA(UTextProperty::StaticClass()); } } return false; } bool FStructureEditorUtils::ChangeMultiLineTextEnabled(UUserDefinedStruct* Struct, FGuid VarGuid, bool bIsEnabled) { auto VarDesc = GetVarDescByGuid(Struct, VarGuid); if (CanEnableMultiLineText(Struct, VarGuid) && VarDesc->bEnableMultiLineText != bIsEnabled) { const FScopedTransaction Transaction(LOCTEXT("ChangeMultiLineTextEnabled", "Change Multi-line Text Enabled")); ModifyStructData(Struct); VarDesc->bEnableMultiLineText = bIsEnabled; auto Property = FindField<UProperty>(Struct, VarDesc->VarName); if (Property) { if (VarDesc->bEnableMultiLineText) { Property->SetMetaData("MultiLine", TEXT("true")); } else { Property->RemoveMetaData("MultiLine"); } } return true; } return false; } bool FStructureEditorUtils::IsMultiLineTextEnabled(const UUserDefinedStruct* Struct, FGuid VarGuid) { auto VarDesc = GetVarDescByGuid(Struct, VarGuid); if (CanEnableMultiLineText(Struct, VarGuid)) { return VarDesc->bEnableMultiLineText; } return false; } bool FStructureEditorUtils::CanEnable3dWidget(const UUserDefinedStruct* Struct, FGuid VarGuid) { const auto VarDesc = GetVarDescByGuid(Struct, VarGuid); const auto PropertyStruct = VarDesc ? Cast<const UStruct>(VarDesc->SubCategoryObject.Get()) : NULL; return FEdMode::CanCreateWidgetForStructure(PropertyStruct); } bool FStructureEditorUtils::Change3dWidgetEnabled(UUserDefinedStruct* Struct, FGuid VarGuid, bool bIsEnabled) { auto VarDesc = GetVarDescByGuid(Struct, VarGuid); const auto PropertyStruct = VarDesc ? Cast<const UStruct>(VarDesc->SubCategoryObject.Get()) : NULL; if (FEdMode::CanCreateWidgetForStructure(PropertyStruct) && (VarDesc->bEnable3dWidget != bIsEnabled)) { const FScopedTransaction Transaction(LOCTEXT("Change3dWidgetEnabled", "Change 3d Widget Enabled")); ModifyStructData(Struct); VarDesc->bEnable3dWidget = bIsEnabled; auto Property = FindField<UProperty>(Struct, VarDesc->VarName); if (Property) { if (VarDesc->bEnable3dWidget) { Property->SetMetaData(FEdMode::MD_MakeEditWidget, TEXT("true")); } else { Property->RemoveMetaData(FEdMode::MD_MakeEditWidget); } } return true; } return false; } bool FStructureEditorUtils::Is3dWidgetEnabled(const UUserDefinedStruct* Struct, FGuid VarGuid) { const auto VarDesc = GetVarDescByGuid(Struct, VarGuid); const auto PropertyStruct = VarDesc ? Cast<const UStruct>(VarDesc->SubCategoryObject.Get()) : NULL; return VarDesc && VarDesc->bEnable3dWidget && FEdMode::CanCreateWidgetForStructure(PropertyStruct); } FGuid FStructureEditorUtils::GetGuidForProperty(const UProperty* Property) { auto UDStruct = Property ? Cast<const UUserDefinedStruct>(Property->GetOwnerStruct()) : NULL; auto VarDesc = UDStruct ? GetVarDesc(UDStruct).FindByPredicate(FFindByNameHelper<FStructVariableDescription>(Property->GetFName())) : NULL; return VarDesc ? VarDesc->VarGuid : FGuid(); } UProperty* FStructureEditorUtils::GetPropertyByGuid(const UUserDefinedStruct* Struct, const FGuid VarGuid) { const auto VarDesc = GetVarDescByGuid(Struct, VarGuid); return VarDesc ? FindField<UProperty>(Struct, VarDesc->VarName) : NULL; } FGuid FStructureEditorUtils::GetGuidFromPropertyName(const FName Name) { return FMemberVariableNameHelper::GetGuidFromName(Name); } struct FReinstanceDataTableHelper { // TODO: shell we cache the dependency? static TArray<UDataTable*> GetTablesDependentOnStruct(UUserDefinedStruct* Struct) { TArray<UDataTable*> Result; if (Struct) { TArray<UObject*> DataTables; GetObjectsOfClass(UDataTable::StaticClass(), DataTables); for (auto DataTableObj : DataTables) { auto DataTable = Cast<UDataTable>(DataTableObj); if (DataTable && (Struct == DataTable->RowStruct)) { Result.Add(DataTable); } } } return Result; } }; void FStructureEditorUtils::BroadcastPreChange(UUserDefinedStruct* Struct) { FStructureEditorUtils::FStructEditorManager::Get().PreChange(Struct, EStructureEditorChangeInfo::Changed); auto DataTables = FReinstanceDataTableHelper::GetTablesDependentOnStruct(Struct); for (auto DataTable : DataTables) { DataTable->CleanBeforeStructChange(); } } void FStructureEditorUtils::BroadcastPostChange(UUserDefinedStruct* Struct) { auto DataTables = FReinstanceDataTableHelper::GetTablesDependentOnStruct(Struct); for (auto DataTable : DataTables) { DataTable->RestoreAfterStructChange(); } FStructureEditorUtils::FStructEditorManager::Get().PostChange(Struct, EStructureEditorChangeInfo::Changed); } #undef LOCTEXT_NAMESPACE
26,507
9,526
/* * A344279.cpp * * Created on: 14-May-2021 * * Author: Soumyadeep Dhar * * A344279: Numbers a(n)=m such that |m| is the smallest, k=n*m and r=(n^2+1)*m * for two quadratic equations of the form t^2+k*t+r = 0 and t^2+r*t+k^2 = 0 * have non-zero integer roots, where k is the coefficient of t and r is the * constant in first equation, which has non-zero roots p and q * (i.e., {k, r, p, q} โˆˆ โ„คโ‰ , k=p+q and r=p*q). Also r is the coefficient of t * and k^2 is the constant in second equation, which has non-zero roots u and v * (i.e., {r, k, u, v} โˆˆ โ„คโ‰ , r=u+v and k^2=u*v). * * Example: -1, -4, -1, -16, 9, -36, 5, -1, -81, -100, -121, -4, 9, -196, -225, * -256, 8, 5, -361, -400, -1, -484, -529, -576, -625, -676, -729, -784, * -841, -900, -961, -1024, -9, 9, -1225, -1296, -1369, -1444, -1521, * -1600, -1681, -1764, -1849, -1936, -2025, -2116, 5, -2304, -2401, -2500 * * A344279: https://oeis.org/A344279/b344279.txt * * Sequence Author: Soumyadeep Dhar, May 14, 2021 * */ #include <map> #include <tuple> #include <iomanip> #include "largeint.h" #include "processor.h" using LargeInteger = ns::dn::li::LargeInt; using LargeIntegerSequence = ns::dn::is::IntegerSequenceProcessor<ns::dn::is::A344279>; // Process input data to generate next elements of the sequence template <> unsigned int LargeIntegerSequence::generate() { int _count = 1; std::pair<unsigned int, std::string> _element; // keep result values std::map<long long int, std::tuple < long long int , long long int , long long int , long long int , long long int , long long int , long long int , long long int>> _results; for (long long int n = 1; n <= 225; n++) { // Check all numbers upto 100 for (long long int c = 1; c <= 250000; c++) { bool isFound = false; for (auto s : {1, -1}) { // Find 'a * b' as initial expected 'm' long long int m = s*c*(n*n + 1); // Find 'a * b' as initial expected 'k' long long int k = s*c*n; // Get k^2 value long long int kk = (k * k); // Find possible (a, b) as root of the equation // x^2 -kx + m (where a + b = k and a * b = m) long long int a = (k + sqrt(kk - (4 * m))) / 2; long long int b = k - a; // Ignore non integer roots if(m != (a * b)) continue; // For all possible roots of the equation // x^2 - mx + k^2 (where x + y = m and x * y = k^2) long long int y = (m + sqrt((m * m) - (4 * kk))) / 2; long long int x = m - y; // If valid roots found if (kk != (x * y)) continue; // Store result _results[n] = std::make_tuple(c*s, k, m, kk, a, b, x, y); // Print output results std::cout << " " << std::setw(9) << n; std::cout << " " << std::setw(9) << c*s; std::cout << " " << std::setw(9) << k; std::cout << " " << std::setw(9) << m; std::cout << " " << std::setw(9) << kk; std::cout << " " << std::setw(9) << a; std::cout << " " << std::setw(9) << b; std::cout << " " << std::setw(9) << x; std::cout << " " << std::setw(9) << y << std::endl; // Mark solution found isFound = true; break; } // No need to search further as result already found if(isFound) break; } } // Store shorted result data _count = 1; for (auto _x : _results) { _element.first = _count; _element.second = std::to_string(std::get<0>(_x.second)); // Write output data _ouWriter << _element; // Update element count _count++; } return 0; } int main() { // Initialize sequence LargeIntegerSequence seqA344279("../data/oeis/b000290.txt", "../data/oeis/b000290.txt", "../data/A344279.txt"); // Generate sequence seqA344279.generate(); return 0; }
4,017
1,677
//Palindromic Partitions #include <iostream> #include <cstdio> #include <vector> using namespace std; typedef long long int lli; const lli MOD = lli(1e9)+7, base = 31; lli n; string S; lli modpow(lli a, lli b) { if(!b) return 1; else if(b == 1) return a; else { lli res = modpow(a, b/2)%MOD; res *= res; res %= MOD; if(b%2) res *= a; return res%MOD; } } lli solve(lli L, lli R) { if(L > R) return 0; lli hasha = 0, hashb = 0; for(lli i = 0;i < n;i++) { if(L+i >= R-i) break; hasha *= base; hasha %= MOD; hasha += lli(S[L+i]-'a'); hasha %= MOD; hashb += lli(S[R-i]-'a')*modpow(base, i); hashb %= MOD; if(hasha == hashb) return solve(L+i+1, R-i-1)+2; } return 1; } int main(void) { lli t; scanf("%lld", &t); while(t--) { cin >> S; n = lli(S.size()); printf("%lld\n", solve(0, n-1)); } }
840
470
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetVerticalSync(true); // this uses depth information for occlusion // rather than always drawing things on top of each other ofEnableDepthTest(); // this sets the camera's distance from the object cam.setDistance(100); ofSetCircleResolution(64); bShowHelp = true; } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ cam.begin(); ofRotateX(ofRadToDeg(.5)); ofRotateY(ofRadToDeg(-.5)); ofBackground(0); ofSetColor(255,0,0); ofFill(); ofDrawBox(30); ofNoFill(); ofSetColor(0); ofDrawBox(30); ofPushMatrix(); ofTranslate(0,0,20); ofSetColor(0,0,255); ofFill(); ofDrawBox(5); ofNoFill(); ofSetColor(0); ofDrawBox(5); ofPopMatrix(); cam.end(); drawInteractionArea(); ofSetColor(255); string msg = string("Using mouse inputs to navigate (press 'c' to toggle): ") + (cam.getMouseInputEnabled() ? "YES" : "NO"); msg += string("\nShowing help (press 'h' to toggle): ")+ (bShowHelp ? "YES" : "NO"); if (bShowHelp) { msg += "\n\nLEFT MOUSE BUTTON DRAG:\nStart dragging INSIDE the yellow circle -> camera XY rotation .\nStart dragging OUTSIDE the yellow circle -> camera Z rotation (roll).\n\n"; msg += "LEFT MOUSE BUTTON DRAG + TRANSLATION KEY (" + ofToString(cam.getTranslationKey()) + ") PRESSED\n"; msg += "OR MIDDLE MOUSE BUTTON (if available):\n"; msg += "move over XY axes (truck and boom).\n\n"; msg += "RIGHT MOUSE BUTTON:\n"; msg += "move over Z axis (dolly)"; } msg += "\n\nfps: " + ofToString(ofGetFrameRate(), 2); ofDrawBitmapStringHighlight(msg, 10, 20); } //-------------------------------------------------------------- void ofApp::drawInteractionArea(){ ofRectangle vp = ofGetCurrentViewport(); float r = MIN(vp.width, vp.height) * 0.5f; float x = vp.width * 0.5f; float y = vp.height * 0.5f; ofPushStyle(); ofSetLineWidth(3); ofSetColor(255, 255, 0); ofNoFill(); glDepthMask(false); ofCircle(x, y, r); glDepthMask(true); ofPopStyle(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ switch(key) { case 'C': case 'c': if(cam.getMouseInputEnabled()) cam.disableMouseInput(); else cam.enableMouseInput(); break; case 'F': case 'f': ofToggleFullscreen(); break; case 'H': case 'h': bShowHelp ^=true; break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
3,433
1,191
#pragma once #include <algorithm> #include <complex> #include <iostream> #include <numeric> #include <string> #include <vector> #include "Abort.hpp" namespace Jet { namespace Utilities { /** * @brief Determines if an integral value is a power of 2. * @param value Number to check. * @return True if `value` is a power of 2. */ constexpr inline bool is_pow_2(size_t value) { return static_cast<bool>(value && !(value & (value - 1))); } /** * @brief Finds the log2 value of a known power of 2, otherwise finds the floor * of log2 of the operand. * * This works by counting the highest set bit in a size_t by examining the * number of leading zeros. This value can then be subtracted from the * number of bits in the size_t value to yield the log2 value. * * @param value Value to calculate log2 of. If 0, the result is undefined * @return size_t log2 result of value. If value is a non power-of-2, returns * the floor of the log2 operation. */ constexpr inline size_t fast_log2(size_t value) { return static_cast<size_t>(std::numeric_limits<size_t>::digits - __builtin_clzll((value)) - 1ULL); } /** * Streams a pair of elements to an output stream. * * @tparam T1 Type of the first element in the pair. * @tparam T2 Type of the second element in the pair. * @param os Output stream to be modified. * @param p Pair to be inserted. * @return Reference to the given output stream. */ template <class T1, class T2> inline std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &p) { return os << '{' << p.first << ',' << p.second << '}'; } /** * Streams a vector to an output stream. * * @tparam T Type of the elements in the vector. * @param os Output stream to be modified. * @param v Vector to be inserted. * @return Reference to the given output stream. */ template <class T> inline std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { os << '{'; for (size_t i = 0; i < v.size(); i++) { if (i != 0) { os << " "; } os << v[i]; } os << '}'; return os; } /** * Converts an ID into a unique string index of the form [a-zA-Z][0-9]*. * * @param id ID to be converted. * @return String index associated with the ID. */ inline std::string GenerateStringIndex(size_t id) { static const std::vector<std::string> alphabet = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; const size_t div_id = id / alphabet.size(); const std::string prefix = alphabet[id % alphabet.size()]; const std::string suffix = (div_id == 0) ? "" : std::to_string(div_id - 1); return prefix + suffix; } /** * Computes the order (i.e., number of rows and columns) of the given square * matrix. * * @tparam scalar_type_t Template parameter of std::complex. * @return Order of the matrix. */ template <class scalar_type_t> inline size_t Order(const std::vector<std::complex<scalar_type_t>> &mat) { // If sqrt() returns a value just under the true square root, increment n. size_t n = static_cast<size_t>(sqrt(mat.size())); n += n * n != mat.size(); return n; } /** * Returns the `n` x `n` complex-valued identity matrix. * * @tparam scalar_type_t Template parameter of std::complex. * @param n Order of the desired identity matrix. * @return Vector representing the desired matrix, encoded in row-major order. */ template <class scalar_type_t> inline std::vector<std::complex<scalar_type_t>> Eye(size_t n) { std::vector<std::complex<scalar_type_t>> eye(n * n, 0); for (size_t i = 0; i < n; i++) { eye[i * n + i] = 1; } return eye; } /** * Multiplies the two given square matrices. * * @tparam scalar_type_t Template parameter of std::complex. * @param m1 Matrix on the LHS of the multiplication. * @param m2 Matrix on the RHS of the multiplication. * @param n Order of the two matrices. * @return Matrix representing the product of `m1` and `m2`. */ template <typename scalar_type_t> inline std::vector<std::complex<scalar_type_t>> MultiplySquareMatrices(const std::vector<std::complex<scalar_type_t>> &m1, const std::vector<std::complex<scalar_type_t>> &m2, size_t n) { JET_ABORT_IF_NOT(m1.size() == n * n, "LHS matrix has the wrong order"); JET_ABORT_IF_NOT(m2.size() == n * n, "RHS matrix has the wrong order"); std::vector<std::complex<scalar_type_t>> product(n * n); for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < n; j++) { for (size_t k = 0; k < n; k++) { product[i * n + j] += m1[i * n + k] * m2[k * n + j]; } } } return product; } /** * Raises the given matrix to the specified exponent. * * @tparam scalar_type_t Template parameter of std::complex. * @param mat Matrix at the base of the power. * @param k Exponent of the power. * @return Matrix representing `mat` raised to the power of `k`. */ template <typename scalar_type_t> inline std::vector<std::complex<scalar_type_t>> Pow(const std::vector<std::complex<scalar_type_t>> &mat, size_t k) { if (k == 1) { return mat; } const auto n = Order(mat); if (k == 0) { return Eye<scalar_type_t>(n); } std::vector<std::complex<scalar_type_t>> power = mat; for (size_t i = 2; i <= k; i++) { power = MultiplySquareMatrices(power, mat, n); } return power; } /** * Adds the given matrices. * * @tparam scalar_type_t Template parameter of std::complex. * @param m1 Matrix on the LHS of the addition. * @param m2 Matrix on the RHS of the addition. * @return Matrix representing the sum of `m1` and `m2`. */ template <typename scalar_type_t> inline std::vector<std::complex<scalar_type_t>> operator+(const std::vector<std::complex<scalar_type_t>> &m1, const std::vector<std::complex<scalar_type_t>> &m2) { JET_ABORT_IF_NOT(m1.size() == m2.size(), "Matrices have different sizes"); std::vector<std::complex<scalar_type_t>> sum(m1.size()); for (size_t i = 0; i < m1.size(); i++) { sum[i] = m1[i] + m2[i]; } return sum; } /** * Subtracts the given matrices. * * @tparam scalar_type_t Template parameter of std::complex. * @param m1 Matrix on the LHS of the subtraction. * @param m2 Matrix on the RHS of the subtraction. * @return Matrix representing `m2` subtracted from `m1`. */ template <typename scalar_type_t> inline std::vector<std::complex<scalar_type_t>> operator-(const std::vector<std::complex<scalar_type_t>> &m1, const std::vector<std::complex<scalar_type_t>> &m2) { JET_ABORT_IF_NOT(m1.size() == m2.size(), "Matrices have different sizes"); std::vector<std::complex<scalar_type_t>> diff(m1.size()); for (size_t i = 0; i < m1.size(); i++) { diff[i] = m1[i] - m2[i]; } return diff; } /** * Returns the product of the given scalar and matrix. * * @tparam scalar_type_t Template parameter of std::complex. * @param mat Matrix to be scaled. * @param c Scalar to be applied to the matrix. * @return Matrix representing the scalar product of `c` and `mat`. */ template <typename scalar_type_t> inline std::vector<std::complex<scalar_type_t>> operator*(const std::vector<std::complex<scalar_type_t>> &mat, std::complex<scalar_type_t> c) { std::vector<std::complex<scalar_type_t>> product = mat; for (size_t i = 0; i < product.size(); i++) { product[i] *= c; } return product; } /** * Returns a diagonal matrix with the same dimensions of the given matrix where * each entry along the main diagonal is derived by applying std::exp() to the * corresponding entry in the given matrix. * * @tparam scalar_type_t Template parameter of std::complex. * @param mat Matrix to be converted into a diagonal matrix. * @return Matrix representing the diagonal exponentation of the given matrix. */ template <typename scalar_type_t> inline std::vector<std::complex<scalar_type_t>> DiagExp(const std::vector<std::complex<scalar_type_t>> &mat) { const auto n = Order(mat); std::vector<std::complex<scalar_type_t>> diag(mat.size(), 0); for (size_t i = 0; i < n; i++) { diag[i * n + i] = std::exp(mat[i * n + i]); } return diag; } /** * Returns a diagonal tensor with the given main diagonal. * * @tparam Tensor Type of the tensor. * @tparam T Type of the diagonal entries. * @param vec Entries to be copied to the main diagonal of the tensor. * @return Tensor with the given main diagonal. */ template <typename Tensor, typename T> inline Tensor DiagMatrix(const std::vector<T> &vec) { const size_t n = vec.size(); Tensor tens({n, n}); for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < n; j++) { tens.SetValue({i, j}, (i == j) ? vec[i] : 0.0); } } return tens; } /** * Reports whether the given element is in the provided vector. * * @tparam T Type of the elements in the vector. * @param e Element being searched for. * @param v Vector to be searched. * @return True if the element is in the vector. */ template <class T> inline bool InVector(const T &e, const std::vector<T> &v) { return std::find(v.cbegin(), v.cend(), e) != v.cend(); } /** * Computes the intersection of two small vectors. * * @tparam T Type of the elements in the vectors. * @param v1 Vector on the LHS of the intersection. * @param v2 Vector on the RHS of the intersection. * @return Vector containing the elements in both vectors. */ template <typename T> inline std::vector<T> VectorIntersection(const std::vector<T> &v1, const std::vector<T> &v2) { std::vector<T> result; for (const auto &value : v1) { if (InVector(value, v2)) { result.emplace_back(value); } } return result; } /** * Computes the union of two small vectors. * * @tparam T Type of the elements in the vectors. * @param v1 Vector on the LHS of the union. * @param v2 Vector on the RHS of the union. * @return Vector containing the elements in at least one vector. */ template <typename T> inline std::vector<T> VectorUnion(const std::vector<T> &v1, const std::vector<T> &v2) { std::vector<T> result = v1; for (const auto &value : v2) { if (!InVector(value, v1)) { result.emplace_back(value); } } return result; } /** * Computes the difference of two small vectors. * * @tparam T Type of the elements in the vectors. * @param v1 Vector on the LHS of the difference. * @param v2 Vector on the RHS of the difference. * @return Vector containing the elements only in the first vector. */ template <typename T> inline std::vector<T> VectorSubtraction(const std::vector<T> &v1, const std::vector<T> &v2) { std::vector<T> result; for (const auto &value : v1) { if (!InVector(value, v2)) { result.emplace_back(value); } } return result; } /** * Computes the disjunctive union of two small vectors. * * @tparam T Type of the elements in the vectors. * @param v1 Vector on the LHS of the disjunctive union. * @param v2 Vector on the RHS of the disjunctive union. * @return Vector containing the elements in exactly one of the vectors. */ template <typename T> inline std::vector<T> VectorDisjunctiveUnion(const std::vector<T> &v1, const std::vector<T> &v2) { return VectorSubtraction(VectorUnion(v1, v2), VectorIntersection(v1, v2)); } /** * Concatenates the strings in the given vector (using "" as the separator). * * @param v Vector to be concatenated. * @return String representing the contatentation of the vector contents. */ inline std::string JoinStringVector(const std::vector<std::string> &v) { return std::accumulate(v.begin(), v.end(), std::string("")); } /** * Concatenates the elements in the two given vectors. * * @tparam T Type of the elements in the vectors. * @param v1 Prefix of the concatenation. * @param v2 Suffix of the concatenation. * @return Vector representing the contatentation of `v1` and `v2`. */ template <typename T> inline std::vector<T> VectorConcatenation(const std::vector<T> &v1, const std::vector<T> &v2) { std::vector<T> concat = v1; concat.insert(concat.end(), v2.begin(), v2.end()); return concat; } /** * Returns the factorial of the given number. * * @warning This function is susceptible to overflow errors for large values of * `n`. * * @param n Number whose factorial is to be computed. * @return Factorial of the given number. */ inline size_t Factorial(size_t n) { size_t prod = 1; for (size_t i = 2; i <= n; i++) { prod *= i; } return prod; } /** * @brief Returns the size of a shape. * * @param shape Index dimensions. * @return Product of the index dimensions in the shape. */ inline size_t ShapeToSize(const std::vector<size_t> &shape) { size_t size = 1; for (const auto &dim : shape) { size *= dim; } return size; } /** * @brief Converts a linear index into a multi-dimensional index. * * The multi-dimensional index is written in row-major order. * * Example: To compute the multi-index (i, j) of an element in a 2x2 matrix * given a linear index of 2, `shape` would be {2, 2} and the result * would be `{1, 0}`. * \code{.cpp} * std::vector<size_t> multi_index = UnravelIndex(2, {2, 2}); // {1, 0} * \endcode * * @param index Linear index to be unraveled. * @param shape Size of each index dimension. * @return Multi-index associated with the linear index. */ inline std::vector<size_t> UnravelIndex(unsigned long long index, const std::vector<size_t> &shape) { const size_t size = ShapeToSize(shape); JET_ABORT_IF(size <= index, "Linear index does not fit in the shape."); std::vector<size_t> multi_index(shape.size()); for (int i = multi_index.size() - 1; i >= 0; i--) { multi_index[i] = index % shape[i]; index /= shape[i]; } return multi_index; } /** * @brief Converts a multi-dimensional index into a linear index. * * @note This function is the inverse of UnravelIndex(). * * @param index Multi-index to be raveled, expressed in row-major order. * @param shape Size of each index dimension. * @return Linear index associated with the multi-index. */ inline unsigned long long RavelIndex(const std::vector<size_t> &index, const std::vector<size_t> &shape) { JET_ABORT_IF_NOT(index.size() == shape.size(), "Number of index and shape dimensions must match."); size_t multiplier = 1; unsigned long long linear_index = 0; for (int i = index.size() - 1; i >= 0; i--) { JET_ABORT_IF(index[i] >= shape[i], "Index does not fit in the shape."); linear_index += index[i] * multiplier; multiplier *= shape[i]; } return linear_index; } /** * Splits `s` (at most once) on the given delimiter and stores the result in the * provided vector. If an instance of the delimiter is found, the contents of * `s` up to (and including) the first occurrence of the delimiter are erased. * * @param s String to be split. * @param delimiter Delimeter separating each part of the split string. * @param tokens Vector to store the result of the split. */ inline void SplitStringOnDelimiter(std::string &s, const std::string &delimiter, std::vector<std::string> &tokens) { const size_t pos = s.find(delimiter); if (pos == std::string::npos) { tokens.emplace_back(s); return; } const auto token = s.substr(0, pos); tokens.emplace_back(token); s.erase(0, pos + delimiter.length()); tokens.emplace_back(s); } /** * Splits `s` (at most once) on each of the given delimiters (in order). * * @warning All spaces are removed from `s` prior to performing the split. * * @param s String to be split. * @param delimiters Delimiters separating each part of the split string. * @return Vector containing the result of the split (excluding empty tokens). */ inline std::vector<std::string> SplitStringOnMultipleDelimiters(std::string s, const std::vector<std::string> &delimiters) { // Remove spaces. s.erase(std::remove_if(s.begin(), s.end(), isspace), s.end()); std::vector<std::string> tokens = {s}; for (std::size_t i = 0; i < delimiters.size(); i++) { tokens.pop_back(); SplitStringOnDelimiter(s, delimiters[i], tokens); } // Remove empty tokens. const auto empty = [](const std::string &token) { return token.empty(); }; tokens.erase(std::remove_if(tokens.begin(), tokens.end(), empty), tokens.end()); return tokens; } /** * Splits `s` on the given delimiter (as many times as possible) and stores the * result in the provided vector. * * @param s String to be split. * @param delimiter Delimeter separating each part of the split string. * @param tokens Vector to store the result of the split. */ inline void SplitStringOnDelimiterRecursively(const std::string &s, const std::string &delimiter, std::vector<std::string> &tokens) { const size_t pos = s.find(delimiter); if (pos == std::string::npos) { tokens.emplace_back(s); } else { tokens.emplace_back(s.begin(), s.begin() + pos); const auto remaining = s.substr(pos + delimiter.length()); SplitStringOnDelimiterRecursively(remaining, delimiter, tokens); } } /** * Replaces each occurrence of `from` with `to` in the given string. * * @param s String to be searched for occurrences of `from`. * @param from Substring to be replaced in `s`. * @param to Replacement string for `from`. */ inline void ReplaceAllInString(std::string &s, const std::string &from, const std::string &to) { JET_ABORT_IF(from.empty(), "Cannot replace occurrences of an empty string"); size_t pos = s.find(from, 0); while (pos != std::string::npos) { s.replace(pos, from.length(), to); // Skip over `to` in case part of it matches `from`. pos = s.find(from, pos + to.length()); } } /** * Returns the total amount of system memory as reported by /proc/meminfo. * * Adapted from * https://github.com/Russellislam08/RAMLogger/blob/master/readproc.h * * @return Total amount of system memory (in kB). * If an error occurs, -1 is returned. */ inline int GetTotalMemory() { FILE *meminfo = fopen("/proc/meminfo", "r"); if (meminfo == NULL) { return -1; } char line[256]; while (fgets(line, sizeof(line), meminfo)) { int memTotal; if (sscanf(line, "MemTotal: %d kB", &memTotal) == 1) { fclose(meminfo); return memTotal; } } // Getting here means we were not able to find what we were looking for fclose(meminfo); return -1; } /** * Returns the amount of available system memory as reported by /proc/meminfo. * * @see GetTotalMemory() * * @return Amount of available system memory (in kB). * If an error occurs, -1 is returned. */ inline int GetAvailableMemory() { /* Same function as above but it parses the meminfo file in order to obtain the current amount of physical memory available */ FILE *meminfo = fopen("/proc/meminfo", "r"); if (meminfo == NULL) { return -1; } char line[256]; while (fgets(line, sizeof(line), meminfo)) { int memAvail; if (sscanf(line, "MemAvailable: %d kB", &memAvail) == 1) { fclose(meminfo); return memAvail; } } fclose(meminfo); return -1; } /** * Use OpenMP when available to copy * * @param a vector to copy * @param b vector to copy to */ template <typename T> void FastCopy(const std::vector<T> &a, std::vector<T> &b) { #ifdef _OPENMP size_t max_right_dim = 1024; size_t size = a.size(); if (b.size() != size) b.resize(size); #pragma omp parallel for schedule(static, max_right_dim) for (std::size_t p = 0; p < size; ++p) { b[p] = a[p]; } #else b = a; #endif } /** * Determine if vector w contains v * * @param v * @param w * * @return true if every element of v is in w */ template <typename T> bool VectorInVector(const std::vector<T> &v, const std::vector<T> &w) { for (std::size_t i = 0; i < v.size(); ++i) { if (!InVector(v[i], w)) return false; } return true; } }; // namespace Utilities }; // namespace Jet
21,155
6,939
// redirection: FIXME! #include "Offline/MCDataProducts/inc/GenParticle.hh"
76
29
#include <bits/stdc++.h> #define ll long int using namespace std; int main() { string s; cin>>s; if(s[0]>='a' && s[0]<='z') { s[0]=toupper(s[0]); cout<<s<<endl; } else { cout<<s<<endl; } return 0; }
229
110
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is part of xlslib -- A multiplatform, C/C++ library * for dynamic generation of Excel(TM) files. * * Copyright 2004 Yeico S. A. de C. V. All Rights Reserved. * Copyright 2008-2013 David Hoerl All Rights Reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY David Hoerl ''AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL David Hoerl OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "xlslib/record.h" #include "xlslib/note.h" #include "xlslib/globalrec.h" #include "xlslib/datast.h" #include "xlslib/rectypes.h" using namespace xlslib_core; using namespace xlslib_strings; /* ********************************* * note_t class implementation ********************************* */ note_t::note_t(CGlobalRecords& gRecords, unsigned32_t rowval, unsigned32_t colval, const std::string& msg, const std::string& auth, xf_t* pxfval) : cell_t(gRecords, rowval, colval, pxfval) { gRecords.char2str16(msg, this->text); gRecords.char2str16(auth, this->author); } note_t::note_t(CGlobalRecords& gRecords, unsigned32_t rowval, unsigned32_t colval, const ustring& msg, const ustring& auth, xf_t* pxfval) : cell_t(gRecords, rowval, colval, pxfval) { gRecords.wide2str16(msg, this->text); gRecords.wide2str16(auth, this->author); } #ifndef __FRAMEWORK__ note_t::note_t(CGlobalRecords& gRecords, unsigned32_t rowval, unsigned32_t colval, const u16string& msg, const u16string& auth, xf_t* pxfval) : cell_t(gRecords, rowval, colval, pxfval), text(msg), author(auth) { } #endif note_t::~note_t() { } size_t note_t::GetSize(void) const { return 12; } CUnit* note_t::GetData(CDataStorage &datastore) const { return datastore.MakeCNote(*this); // NOTE: this pointer HAS to be deleted elsewhere. } /* ********************************* * CNote class implementation ********************************* * * BIFF ROW (208h) 16 00 00 00 00 03 00 2C 01 00 00 00 00 00 01 0F 00 * BIFF 6 (06h) 43 00 00 00 00 0F 00 8C 16 22 AA FD 90 F8 3F 00 00 * C0 00 00 FD 15 00 1E 01 00 1F 00 00 00 00 00 00 * D0 3F 04 41 13 00 1E 04 00 06 03 * BIFF 6 (06h) 39 00 00 01 00 0F 00 8C 16 22 AA FD 90 98 40 00 00 * 00 00 00 FE 11 00 44 00 00 00 C0 44 00 00 02 C0 * 05 44 00 00 02 C0 05 * BIFF RK (27Eh) 10 00 00 02 00 0F 00 00 00 40 40 * BIFF DBCELL (D7h) 6 7C 00 00 00 00 00 * BIFF MSODRAWING (ECh) 224 0F 00 02 F0 7E 01 00 00 10 00 08 F0 08 00 00 00 * 03 00 00 00 02 04 00 00 0F 00 03 F0 66 01 00 00 * 0F 00 04 F0 28 00 00 00 01 00 09 F0 10 00 00 00 * 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 * 02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00 * 0F 00 04 F0 90 00 00 00 A2 0C 0A F0 08 00 00 00 * 01 04 00 00 00 0A 00 00 D3 00 0B F0 4E 00 00 00 * 80 00 A8 92 41 0C 8B 00 02 00 00 00 BF 00 08 00 * 08 00 58 01 00 00 00 00 81 01 FF FF E1 00 83 01 * FF FF E1 00 85 01 F4 00 00 10 BF 01 10 00 10 00 * C3 01 F4 00 00 10 01 02 00 00 00 00 03 02 F4 00 * 00 10 3F 02 03 00 03 00 BF 03 02 00 02 00 00 00 * 10 F0 12 00 00 00 03 00 00 00 60 02 01 00 40 00 * 02 00 60 02 04 00 F3 00 00 00 11 F0 00 00 00 00 * BIFF OBJ (5Dh) 52 15 00 12 00 19 00 01 00 11 40 A8 92 41 0C 80 8D * 42 0C 00 00 00 00 0D 00 16 00 D8 AC 8C FF 20 14 * 4F 47 BA 90 F3 6F D0 9F 7B C0 00 00 10 00 00 00 * 00 00 00 00 * BIFF MSODRAWING (ECh) 8 00 00 0D F0 00 00 00 00 * BIFF TXO (1B6h) 18 12 02 00 00 00 00 00 00 00 00 1A 00 10 00 00 00 * 00 00 * BIFF CONTINUE (3Ch) 27 00 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F * 50 51 52 53 54 55 56 57 58 59 5A * BIFF CONTINUE (3Ch) 16 00 00 05 00 BF 00 0E 00 1A 00 00 00 00 00 00 00 * BIFF MSODRAWING (ECh) 150 0F 00 04 F0 96 00 00 00 A2 0C 0A F0 08 00 00 00 * 02 04 00 00 00 0A 00 00 E3 00 0B F0 54 00 00 00 * 80 00 28 C8 3F 04 85 00 01 00 00 00 8B 00 02 00 * 00 00 BF 00 08 00 0A 00 58 01 00 00 00 00 81 01 * FF FF E1 00 83 01 FF FF E1 00 85 01 F4 00 00 10 * BF 01 10 00 10 00 C3 01 F4 00 00 10 01 02 00 00 * 00 00 03 02 F4 00 00 10 3F 02 03 00 03 00 BF 03 * 00 00 02 00 00 00 10 F0 12 00 00 00 03 00 01 00 * 90 01 01 00 4D 00 02 00 20 03 02 00 33 00 00 00 * 11 F0 00 00 00 00 * BIFF OBJ (5Dh) 52 15 00 12 00 19 00 02 00 11 40 28 C8 3F 04 20 8A * 42 0C 00 00 00 00 0D 00 16 00 19 B5 48 49 52 4A * AF 49 9E AB 90 6C 27 12 73 34 00 00 8B 00 02 00 * 00 00 00 00 * BIFF MSODRAWING (ECh) 8 00 00 0D F0 00 00 00 00 * BIFF TXO (1B6h) 18 12 02 00 00 00 00 00 00 00 00 0A 00 10 00 00 00 * 00 00 * BIFF CONTINUE (3Ch) 11 00 30 31 32 33 34 35 36 37 38 39 * BIFF CONTINUE (3Ch) 16 00 00 05 00 46 00 0E 00 0A 00 72 00 00 00 00 00 * BIFF NOTE (1Ch) 16 00 00 00 00 00 00 01 00 04 00 00 75 73 65 72 00 * BIFF NOTE (1Ch) 16 00 00 01 00 00 00 02 00 04 00 00 75 73 65 72 00 * BIFF WINDOW2 (23Eh) 18 B6 00 00 00 00 00 40 00 00 00 00 00 00 00 72 00 * 00 00 * */ CNote::CNote(CDataStorage &datastore, const note_t& notedef) : CRecord(datastore) { unsigned16_t idx = 1; // OBJ reference SetRecordType(RECTYPE_NOTE); AddValue16((unsigned16_t)notedef.GetRow()); AddValue16((unsigned16_t)notedef.GetCol()); AddValue16(0); // grBit AddValue16(idx); AddUnicodeString(notedef.GetAuthor(), LEN2_NOFLAGS_PADDING_UNICODE); SetRecordLength(GetDataSize()-RECORD_HEADER_SIZE); } CNote::~CNote() { } // make an OBJ record: void CNote::mk_obj_Record(const note_t* notedef) { unsigned16_t idx = 1; SetRecordType(RECTYPE_OBJ); AddValue16((unsigned16_t)notedef->GetRow()); AddValue16((unsigned16_t)notedef->GetCol()); AddValue16(0); // grBit AddValue16(idx); SetRecordLength(GetDataSize()-RECORD_HEADER_SIZE); } // start void CNote::mk_obj_CMO_SubRecord(const note_t* notedef) { (void)notedef; // stop warning AddValue16(0x15); // ftCmo AddValue16(14+12-4); AddValue16(0x19); // ot = Comment AddValue16(1); // id = OBJ id = 1 AddValue16(0); // flags AddFixedDataArray(0, 14+12-10); // reserved SetRecordLength(GetDataSize()-RECORD_HEADER_SIZE); } // end void CNote::mk_obj_END_SubRecord(const note_t* notedef) { (void)notedef; // stop warning AddValue16(0x00); // ftEnd AddValue16(0); SetRecordLength(GetDataSize()-RECORD_HEADER_SIZE); } // note structure ??? void CNote::mk_obj_NTS_SubRecord(const note_t* notedef) { (void)notedef; // stop warning AddValue16(0x0D); // ftNts AddValue16(0); SetRecordLength(GetDataSize()-RECORD_HEADER_SIZE); }
7,659
4,491
#include "Geometry/MTDNumberingBuilder/plugins/CmsMTDBuilder.h" #include "DetectorDescription/Core/interface/DDFilteredView.h" #include "Geometry/MTDNumberingBuilder/interface/GeometricTimingDet.h" #include "Geometry/MTDNumberingBuilder/plugins/ExtractStringFromDDD.h" #include "DataFormats/DetId/interface/DetId.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "Geometry/MTDNumberingBuilder/plugins/CmsMTDSubStrctBuilder.h" #include "Geometry/MTDNumberingBuilder/plugins/CmsMTDEndcapBuilder.h" #include <bitset> CmsMTDBuilder::CmsMTDBuilder() {} void CmsMTDBuilder::buildComponent( DDFilteredView& fv, GeometricTimingDet* g, std::string s ) { CmsMTDSubStrctBuilder theCmsMTDSubStrctBuilder; CmsMTDEndcapBuilder theCmsMTDEndcapBuilder; GeometricTimingDet* subdet = new GeometricTimingDet( &fv, theCmsMTDStringToEnum.type( fv.logicalPart().name().fullname() ) ); switch( theCmsMTDStringToEnum.type( fv.logicalPart().name().fullname() ) ) { case GeometricTimingDet::ETL: theCmsMTDEndcapBuilder.build( fv, subdet, s ); break; case GeometricTimingDet::BTL: theCmsMTDSubStrctBuilder.build( fv, subdet, s ); break; default: throw cms::Exception("CmsMTDBuilder") << " ERROR - I was expecting a SubDet, I got a " << fv.logicalPart().name().fullname(); } g->addComponent( subdet ); } #include "DataFormats/ForwardDetId/interface/BTLDetId.h" #include "DataFormats/ForwardDetId/interface/ETLDetId.h" void CmsMTDBuilder::sortNS( DDFilteredView& fv, GeometricTimingDet* det ) { GeometricTimingDet::ConstGeometricTimingDetContainer & comp = det->components(); std::stable_sort( comp.begin(), comp.end(), subDetByType); for( uint32_t i = 0; i < comp.size(); i++ ) { const uint32_t side = det->component(i)->translation().z() > 0 ? 1 : 0; switch( comp[i]->type() ) { case GeometricTimingDet::BTL: det->component(i)->setGeographicalID(BTLDetId(0,0,0,0,0)); break; case GeometricTimingDet::ETL: det->component(i)->setGeographicalID(ETLDetId(side,0,0,0)); break; default: throw cms::Exception("CmsMTDBuilder") << " ERROR - I was expecting a SubDet, I got a " << comp[i]->name(); } } }
2,242
838
/* The MIT License Copyright (c) 2011 by Jorrit Tyberghein 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 <crystalspace.h> #include "edcommon/model.h" #include "edcommon/tools.h" #include "edcommon/uitools.h" #include "edcommon/listctrltools.h" #include "edcommon/customcontrol.h" #include "editor/iuidialog.h" #include <wx/wx.h> #include <wx/imaglist.h> #include <wx/listctrl.h> #include <wx/treectrl.h> #include <wx/listbox.h> #include <wx/choicebk.h> #include <wx/notebook.h> #include <wx/xrc/xmlres.h> namespace Ares { // -------------------------------------------------------------------------- Value* StandardValueIterator::NextChild (csString* name) { if (name && !names.IsEmpty ()) *name = names[idx]; idx++; return children[idx-1]; } // -------------------------------------------------------------------------- csString Value::Dump (bool verbose) { csString dump; switch (GetType ()) { case VALUE_STRING: dump.Format ("V(string,'%s'%s)", GetStringValue (), parent ? ",[PAR]": ""); break; case VALUE_STRINGARRAY: dump.Format ("V(string[],''%s)", parent ? ",[PAR]": ""); break; case VALUE_LONG: dump.Format ("V(long,'%ld'%s)", GetLongValue (), parent ? ",[PAR]": ""); break; case VALUE_BOOL: dump.Format ("V(long,'%d'%s)", GetBoolValue (), parent ? ",[PAR]": ""); break; case VALUE_FLOAT: dump.Format ("V(float,'%g'%s)", GetFloatValue (), parent ? ",[PAR]": ""); break; case VALUE_COLLECTION: dump.Format ("V(collection%s)", parent ? ",[PAR]": ""); break; case VALUE_COMPOSITE: dump.Format ("V(composite%s)", parent ? ",[PAR]": ""); break; case VALUE_NONE: dump.Format ("V(none%s)", parent ? ",[PAR]": ""); break; default: dump.Format ("V(?%s)", parent ? ",[PAR]": ""); break; } if (verbose) { if (GetType () == VALUE_COLLECTION || GetType () == VALUE_COMPOSITE) { csRef<ValueIterator> it = GetIterator (); while (it->HasNext ()) { csString name; Value* val = it->NextChild (&name); dump.AppendFmt ("\n %s", (const char*)val->Dump (false)); } } } return dump; } bool Value::IsChild (Value* value) { csRef<ValueIterator> it = GetIterator (); while (it->HasNext ()) { if (value == it->NextChild ()) return true; } return false; } // -------------------------------------------------------------------------- DialogResult AbstractCompositeValue::GetDialogValue () { DialogResult result; csRef<ValueIterator> it = GetIterator (); while (it->HasNext ()) { csString name; Value* value = it->NextChild (&name); result.Put (name, View::ValueToString (value)); } return result; } void CompositeValue::AddChildren (ValueType type, ...) { va_list args; va_start (args, type); AddChildren (type, args); va_end (args); } void CompositeValue::AddChildren (ValueType type, va_list args) { while (type != VALUE_NONE) { const char* name = va_arg (args, char*); switch (type) { case VALUE_STRING: { const char* value = va_arg (args, char*); AddChild (name, NEWREF(StringValue,new StringValue(value))); break; } case VALUE_LONG: { long value = va_arg (args, long); AddChild (name, NEWREF(LongValue,new LongValue(value))); break; } case VALUE_FLOAT: { float value = va_arg (args, double); AddChild (name, NEWREF(FloatValue,new FloatValue(value))); break; } case VALUE_BOOL: { bool value = va_arg (args, int); AddChild (name, NEWREF(BoolValue,new BoolValue(value))); break; } case VALUE_STRINGARRAY: { const csStringArray* value = va_arg (args, csStringArray*); AddChild (name, NEWREF(StringArrayValue,new StringArrayValue(*value))); break; } case VALUE_COLLECTION: case VALUE_COMPOSITE: { Value* value = va_arg (args, Value*); AddChild (name, value); break; } default: break; } type = (ValueType) va_arg (args, int); } } // -------------------------------------------------------------------------- CompositeValue* StandardCollectionValue::NewCompositeChild (ValueType type, ...) { va_list args; va_start (args, type); csRef<CompositeValue> composite = View::CreateComposite (type, args); va_end (args); children.Push (composite); composite->SetParent (this); return composite; } StringArrayValue* StandardCollectionValue::NewStringArrayChild (ValueType type, ...) { va_list args; va_start (args, type); csRef<StringArrayValue> stringarray = View::CreateStringArray (type, args); va_end (args); children.Push (stringarray); stringarray->SetParent (this); return stringarray; } void StandardCollectionValue::RemoveChild (Value* child) { children.Delete (child); FireValueChanged (); } // -------------------------------------------------------------------------- void FilteredCollectionValue::UpdateFilter () { filteredChildren.DeleteAll (); if (!collection) return; FilterSetup (); csRef<ValueIterator> it = collection->GetIterator (); while (it->HasNext ()) { Value* child = it->NextChild (); if (Filter (child)) filteredChildren.Push (child); } } // -------------------------------------------------------------------------- MirrorValue::MirrorValue (ValueType type) : type (type) { changeListener.AttachNew (new SelChangeListener (this)); mirroringValue = &nullValue; } MirrorValue::~MirrorValue () { SetMirrorValue (0); DeleteAll (); } void MirrorValue::SetupComposite (Value* compositeValue) { CS_ASSERT (compositeValue->GetType () == VALUE_COMPOSITE); DeleteAll (); csRef<ValueIterator> it = compositeValue->GetIterator (); while (it->HasNext ()) { csString name; Value* child = it->NextChild (&name); csRef<MirrorValue> mv; mv.AttachNew (new MirrorValue (child->GetType ())); AddChild (name, mv); } } void MirrorValue::SetMirrorValue (Value* value) { if (mirroringValue == value) return; if (mirroringValue && mirroringValue != &nullValue) { mirroringValue->RemoveValueChangeListener (changeListener); for (size_t i = 0 ; i < children.GetSize () ; i++) // @@@ (remove static_cast if children is again an array of MirrorValue (static_cast<MirrorValue*> (children[i]))->SetMirrorValue (0); } mirroringValue = value; if (mirroringValue) { mirroringValue->AddValueChangeListener (changeListener); for (size_t i = 0 ; i < children.GetSize () ; i++) // @@@ (remove static_cast if children is again an array of MirrorValue (static_cast<MirrorValue*> (children[i]))->SetMirrorValue (value->GetChild (i)); } else mirroringValue = &nullValue; } void MirrorValue::ValueChanged () { #if DO_DEBUG printf ("ValueChanged: %s\n", Dump ().GetData ()); #endif FireValueChanged (); } // -------------------------------------------------------------------------- class SelectedBoolValue : public BoolValue { private: long* selection; public: SelectedBoolValue (long* s) : selection (s) { } virtual ~SelectedBoolValue () { } // Make sure this class doesn't cause crashes if the parent list // selection value is removed. void Invalidate () { selection = 0; } virtual void SetBoolValue (bool fl) { } virtual bool GetBoolValue () { if (!selection) return false; return (*selection != -1); } }; ListSelectedValue::ListSelectedValue (wxListCtrl* listCtrl, Value* collectionValue, ValueType type) : wxEvtHandler (), MirrorValue (type), listCtrl (listCtrl), collectionValue (collectionValue) { listCtrl->Connect (wxEVT_COMMAND_LIST_ITEM_SELECTED, wxCommandEventHandler (ListSelectedValue :: OnSelectionChange), 0, this); listCtrl->Connect (wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxCommandEventHandler (ListSelectedValue :: OnSelectionChange), 0, this); selection = ListCtrlTools::GetFirstSelectedRow (listCtrl); UpdateToSelection (); } ListSelectedValue::~ListSelectedValue () { if (selectedStateValue) selectedStateValue->Invalidate (); listCtrl->Disconnect (wxEVT_COMMAND_LIST_ITEM_SELECTED, wxCommandEventHandler (ListSelectedValue :: OnSelectionChange), 0, this); listCtrl->Disconnect (wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxCommandEventHandler (ListSelectedValue :: OnSelectionChange), 0, this); } void ListSelectedValue::UpdateToSelection () { Value* value = 0; if (selection != -1) value = collectionValue->GetChild (size_t (selection)); if (value != GetMirrorValue ()) { SetMirrorValue (value); FireValueChanged (); } } void ListSelectedValue::OnSelectionChange (wxCommandEvent& event) { long idx = ListCtrlTools::GetFirstSelectedRow (listCtrl); selection = idx; #if DO_DEBUG printf ("ListSelectedValue::OnSelectionChange: %s\n", Dump ().GetData ()); #endif UpdateToSelection (); if (selectedStateValue) selectedStateValue->FireValueChanged (); } Value* ListSelectedValue::GetSelectedState () { if (!selectedStateValue) selectedStateValue.AttachNew (new SelectedBoolValue (&selection)); return selectedStateValue; } // -------------------------------------------------------------------------- TreeSelectedValue::TreeSelectedValue (wxTreeCtrl* treeCtrl, Value* collectionValue, ValueType type) : MirrorValue (type), treeCtrl (treeCtrl), collectionValue (collectionValue) { treeCtrl->Connect (wxEVT_COMMAND_TREE_SEL_CHANGED, wxCommandEventHandler (TreeSelectedValue :: OnSelectionChange), 0, this); selection = treeCtrl->GetSelection (); UpdateToSelection (); } TreeSelectedValue::~TreeSelectedValue () { treeCtrl->Disconnect (wxEVT_COMMAND_TREE_SEL_CHANGED, wxCommandEventHandler (TreeSelectedValue :: OnSelectionChange), 0, this); } /** * Find a tree item corresponding with a given value. */ static wxTreeItemId TreeFromValue (wxTreeCtrl* tree, wxTreeItemId parent, Value* collectionValue, Value* value) { wxTreeItemIdValue cookie; wxTreeItemId treeChild = tree->GetFirstChild (parent, cookie); csRef<ValueIterator> it = collectionValue->GetIterator (); while (it->HasNext ()) { Value* child = it->NextChild (); if (value == child) return treeChild; treeChild = TreeFromValue (tree, treeChild, child, value); if (treeChild.IsOk ()) return treeChild; treeChild = tree->GetNextChild (parent, cookie); } return wxTreeItemId(); } /** * Get a value corresponding with a given tree item. */ static Value* ValueFromTree (wxTreeCtrl* tree, wxTreeItemId item, Value* collectionValue) { wxTreeItemId parent = tree->GetItemParent (item); if (parent.IsOk ()) { Value* value = ValueFromTree (tree, parent, collectionValue); if (!value) return 0; // Can this happen? csString name = (const char*)tree->GetItemText (item).mb_str (wxConvUTF8); csRef<ValueIterator> it = value->GetIterator (); while (it->HasNext ()) { Value* child = it->NextChild (); if (name == child->GetStringValue ()) return child; } return 0; // Can this happen? } else { return collectionValue; } } void TreeSelectedValue::UpdateToSelection () { Value* value = 0; if (selection.IsOk ()) value = ValueFromTree (treeCtrl, selection, collectionValue); if (value != GetMirrorValue ()) { SetMirrorValue (value); FireValueChanged (); } } void TreeSelectedValue::OnSelectionChange (wxCommandEvent& event) { selection = treeCtrl->GetSelection (); #if DO_DEBUG printf ("TreeSelectedValue::OnSelectionChange: %s\n", Dump ().GetData ()); #endif UpdateToSelection (); } // -------------------------------------------------------------------------- bool AbstractNewAction::DoDialog (View* view, wxWindow* component, iUIDialog* dialog, bool update) { Value* origValue = 0; if (dialog) { dialog->Clear (); if (update) { origValue = view->GetSelectedValue (component); if (!origValue) update = false; else { csString d = origValue->Dump (true); printf ("%s\n", d.GetData ()); fflush (stdout); dialog->SetFieldContents (origValue->GetDialogValue ()); } } if (dialog->Show (0) == 0) return false; } size_t idx = csArrayItemNotFound; wxListCtrl* listCtrl = 0; //wxTreeCtrl* treeCtrl = 0; if (component->IsKindOf (CLASSINFO (wxListCtrl))) { listCtrl = wxStaticCast (component, wxListCtrl); idx = ListCtrlTools::GetFirstSelectedRow (listCtrl); } else if (component->IsKindOf (CLASSINFO (wxTreeCtrl))) { //treeCtrl = wxStaticCast (component, wxTreeCtrl); } DialogResult dialogResult; if (dialog) dialogResult = dialog->GetFieldContents (); if (update) { if (!collection->UpdateValue (idx, origValue, dialogResult)) return false; view->SetSelectedValue (component, origValue); } else { Value* value = collection->NewValue (idx, view->GetSelectedValue (component), dialogResult); if (!value) return false; view->SetSelectedValue (component, value); } return true; } bool NewChildAction::Do (View* view, wxWindow* component) { return DoDialog (view, component, 0); } NewChildDialogAction::NewChildDialogAction (Value* collection, iUIDialog* dialog) : AbstractNewAction (collection), dialog (dialog) { } NewChildDialogAction::~NewChildDialogAction () { } bool NewChildDialogAction::Do (View* view, wxWindow* component) { csRef<iUIDialog> dlg (scfQueryInterface<iUIDialog> (dialog)); return DoDialog (view, component, dlg); } EditChildDialogAction::EditChildDialogAction (Value* collection, iUIDialog* dialog) : AbstractNewAction (collection), dialog (dialog) { } EditChildDialogAction::~EditChildDialogAction () { } bool EditChildDialogAction::Do (View* view, wxWindow* component) { csRef<iUIDialog> dlg (scfQueryInterface<iUIDialog> (dialog)); return DoDialog (view, component, dlg, true); } bool EditChildDialogAction::IsActive (View* view, wxWindow* component) { return view->GetSelectedValue (component) != 0; } bool DeleteChildAction::Do (View* view, wxWindow* component) { Value* value = view->GetSelectedValue (component); if (!value) return false; // Nothing to do. return collection->DeleteValue (value); } bool DeleteChildAction::IsActive (View* view, wxWindow* component) { return view->GetSelectedValue (component) != 0; } // -------------------------------------------------------------------------- View::View (wxWindow* parent) : parent (parent), lastContextID (wxID_HIGHEST + 10000), eventHandler (this) { changeListener.AttachNew (new ViewChangeListener (this)); } void View::Reset () { DestroyBindings (); DestroyActionBindings (); lastContextID = wxID_HIGHEST + 10000; bindings.DeleteAll (); bindingsByComponent.DeleteAll (); bindingsByValue.DeleteAll (); disabledComponents.DeleteAll (); changeListener = 0; rmbContexts.DeleteAll (); buttonActions.DeleteAll (); listToHeading.DeleteAll (); } void View::DestroyBindings () { ComponentToBinding::GlobalIterator it = bindingsByComponent.GetIterator (); while (it.HasNext ()) { csPtrKey<wxWindow> component; Binding* binding = it.Next (component); binding->value->RemoveValueChangeListener (changeListener); if (binding->eventType == wxEVT_COMMAND_TEXT_UPDATED || binding->eventType == wxEVT_COMMAND_LIST_ITEM_SELECTED || binding->eventType == wxEVT_COMMAND_CHOICE_SELECTED || binding->eventType == wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED || binding->eventType == wxEVT_COMMAND_CHECKBOX_CLICKED) component->Disconnect (binding->eventType, wxCommandEventHandler (EventHandler :: OnComponentChanged), 0, &eventHandler); } } void View::RemoveBinding (wxWindow* component) { Binding* binding = bindingsByComponent.Get (component, 0); if (!binding) return; binding->value->RemoveValueChangeListener (changeListener); if (binding->eventType == wxEVT_COMMAND_TEXT_UPDATED || binding->eventType == wxEVT_COMMAND_LIST_ITEM_SELECTED || binding->eventType == wxEVT_COMMAND_CHOICE_SELECTED || binding->eventType == wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED || binding->eventType == wxEVT_COMMAND_CHECKBOX_CLICKED) component->Disconnect (binding->eventType, wxCommandEventHandler (EventHandler :: OnComponentChanged), 0, &eventHandler); bindingsByComponent.Delete (component, binding); bindingsByValue.Delete ((Value*)(binding->value), binding); bindings.Delete (binding); } void View::DestroyActionBindings () { while (rmbContexts.GetSize () > 0) { RmbContext lc = rmbContexts.Pop (); lc.component->Disconnect (wxEVT_CONTEXT_MENU, wxContextMenuEventHandler (EventHandler :: OnRMB), 0, &eventHandler); while (lc.actionDefs.GetSize () > 0) { ActionDef ad = lc.actionDefs.Pop (); lc.component->Disconnect (ad.id, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler (EventHandler :: OnActionExecuted), 0, &eventHandler); } } csHash<csRef<Action>,csPtrKey<wxButton> >::GlobalIterator it = buttonActions.GetIterator (); while (it.HasNext ()) { csPtrKey<wxButton> button; csRef<Action> action = it.Next (button); button->Disconnect (wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler (EventHandler :: OnActionExecuted), 0, &eventHandler); } buttonActions.DeleteAll (); } View::~View () { DestroyBindings (); DestroyActionBindings (); } wxWindow* View::FindComponentByName (wxWindow* container, const char* name) { wxWindowList list = container->GetChildren (); wxWindowList::iterator iter; for (iter = list.begin (); iter != list.end () ; ++iter) { wxWindow* child = *iter; csString childName = (const char*)child->GetName ().mb_str (wxConvUTF8); if (childName == name) return child; size_t i = childName.FindFirst ('_'); if (i != (size_t)-1) { childName = childName.Slice (0, i); if (childName == name) return child; } wxWindow* found = FindComponentByName (child, name); if (found) return found; } return 0; } bool View::BindEnabled (Value* value, wxWindow* component) { RegisterBinding (value, component, wxEVT_NULL, true); ValueChanged (value); return true; } bool View::BindEnabled (Value* value, const char* compName) { //wxString wxcompName = wxString::FromUTF8 (compName); //wxWindow* comp = parent->FindWindow (wxcompName); wxWindow* comp = FindComponentByName (parent, compName); if (!comp) { printf ("BindEnabled: Can't find component '%s'!\n", compName); return false; } return BindEnabled (value, comp); } bool View::Bind (Value* value, wxWindow* component) { if (component->IsKindOf (CLASSINFO (wxTextCtrl))) return Bind (value, wxStaticCast (component, wxTextCtrl)); if (component->IsKindOf (CLASSINFO (wxChoice))) return Bind (value, wxStaticCast (component, wxChoice)); if (component->IsKindOf (CLASSINFO (wxComboBox))) return Bind (value, wxStaticCast (component, wxComboBox)); if (component->IsKindOf (CLASSINFO (wxCheckBox))) return Bind (value, wxStaticCast (component, wxCheckBox)); if (component->IsKindOf (CLASSINFO (wxPanel))) return Bind (value, wxStaticCast (component, wxPanel)); if (component->IsKindOf (CLASSINFO (wxDialog))) return Bind (value, wxStaticCast (component, wxDialog)); if (component->IsKindOf (CLASSINFO (wxListCtrl))) return Bind (value, wxStaticCast (component, wxListCtrl)); if (component->IsKindOf (CLASSINFO (wxTreeCtrl))) return Bind (value, wxStaticCast (component, wxTreeCtrl)); if (component->IsKindOf (CLASSINFO (wxChoicebook))) return Bind (value, wxStaticCast (component, wxChoicebook)); CustomControl* customComp (dynamic_cast<CustomControl*> (component)); if (customComp) return Bind (value, customComp); csString compName = (const char*)component->GetName ().mb_str (wxConvUTF8); printf ("Bind: Unsupported type for component '%s'!\n", compName.GetData ()); return false; } bool View::Bind (Value* value, const char* compName) { //wxString wxcompName = wxString::FromUTF8 (compName); //wxWindow* comp = parent->FindWindow (wxcompName); wxWindow* comp = FindComponentByName (parent, compName); if (!comp) { printf ("Bind: Can't find component '%s'!\n", compName); return false; } return Bind (value, comp); } void View::RegisterBinding (Value* value, wxWindow* component, wxEventType eventType, bool changeEnabled) { Binding* b = new Binding (); b->value = value; b->component = component; b->eventType = eventType; b->changeEnabled = changeEnabled; if (!changeEnabled) bindingsByComponent.Put (component, b); bindingsByValue.Put (value, b); if (eventType != wxEVT_NULL) component->Connect (eventType, wxCommandEventHandler (EventHandler :: OnComponentChanged), 0, &eventHandler); value->AddValueChangeListener (changeListener); } bool View::Bind (Value* value, wxChoice* component) { switch (value->GetType ()) { case VALUE_STRING: case VALUE_LONG: case VALUE_BOOL: case VALUE_FLOAT: case VALUE_NONE: // Supported too in case the type is as of yet unknown. break; default: printf ("Unsupported value type for choice control!\n"); return false; } RegisterBinding (value, component, wxEVT_COMMAND_CHOICE_SELECTED); ValueChanged (value); return true; } bool View::Bind (Value* value, wxTextCtrl* component) { switch (value->GetType ()) { case VALUE_STRING: case VALUE_LONG: case VALUE_BOOL: case VALUE_FLOAT: case VALUE_NONE: // Supported too in case the type is as of yet unknown. break; default: printf ("Unsupported value type for text control!\n"); return false; } RegisterBinding (value, component, wxEVT_COMMAND_TEXT_UPDATED); ValueChanged (value); return true; } bool View::Bind (Value* value, wxComboBox* component) { switch (value->GetType ()) { case VALUE_STRING: case VALUE_LONG: case VALUE_BOOL: case VALUE_FLOAT: case VALUE_NONE: // Supported too in case the type is as of yet unknown. break; default: printf ("Unsupported value type for text control!\n"); return false; } RegisterBinding (value, component, wxEVT_COMMAND_TEXT_UPDATED); ValueChanged (value); return true; } bool View::Bind (Value* value, wxCheckBox* component) { switch (value->GetType ()) { case VALUE_STRING: case VALUE_LONG: case VALUE_BOOL: case VALUE_FLOAT: case VALUE_NONE: // Supported too in case the type is as of yet unknown. break; default: printf ("Unsupported value type for checkbox!\n"); return false; } RegisterBinding (value, component, wxEVT_COMMAND_CHECKBOX_CLICKED); ValueChanged (value); return true; } bool View::Bind (Value* value, CustomControl* component) { RegisterBinding (value, component, wxEVT_NULL); ValueChanged (value); return true; } bool View::Bind (Value* value, wxChoicebook* component) { switch (value->GetType ()) { case VALUE_STRING: case VALUE_LONG: case VALUE_NONE: // Supported too in case the type is as of yet unknown. break; default: printf ("Unsupported value type for text control!\n"); return false; } RegisterBinding (value, component, wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED); ValueChanged (value); return true; } bool View::BindContainer (Value* value, wxWindow* component) { // We also support VALUE_NONE here because that can be useful in situations where we don't // know the type yet (for example when the value is a ListSelectedValue and nothing has been // selected). if (value->GetType () != VALUE_COMPOSITE && value->GetType () != VALUE_NONE) { printf ("Unsupported value type for panels! Only VALUE_COMPOSITE is supported.\n"); return false; } csString compName = (const char*)component->GetName ().mb_str (wxConvUTF8); RegisterBinding (value, component, wxEVT_NULL); csRef<ValueIterator> it = value->GetIterator (); while (it->HasNext ()) { csString name; Value* child = it->NextChild (&name); wxWindow* childComp = FindComponentByName (component, name); if (!childComp) { printf ("Warning: no component found for child '%s'!\n", name.GetData ()); } else { compName = (const char*)childComp->GetName ().mb_str (wxConvUTF8); if (!Bind (child, childComp)) return false; } } ValueChanged (value); return true; } bool View::Bind (Value* value, wxDialog* component) { return BindContainer (value, component); } bool View::Bind (Value* value, wxPanel* component) { return BindContainer (value, component); } bool View::Bind (Value* value, wxListCtrl* component) { // We also support VALUE_NONE here because that can be useful in situations where we don't // know the type yet (for example when the value is a ListSelectedValue and nothing has been // selected). if (value->GetType () != VALUE_COLLECTION && value->GetType () != VALUE_NONE) { printf ("Unsupported value type for lists! Only VALUE_COLLECTION is supported.\n"); return false; } RegisterBinding (value, component, wxEVT_NULL); ValueChanged (value); return true; } bool View::Bind (Value* value, wxTreeCtrl* component) { // We also support VALUE_NONE here because that can be useful in situations where we don't // know the type yet (for example when the value is a ListSelectedValue and nothing has been // selected). if (value->GetType () != VALUE_COLLECTION && value->GetType () != VALUE_NONE) { printf ("Unsupported value type for trees! Only VALUE_COLLECTION is supported.\n"); return false; } RegisterBinding (value, component, wxEVT_NULL); ValueChanged (value); return true; } static bool ValueToBoolStatic (Value* value) { switch (value->GetType ()) { case VALUE_STRING: { const char* v = value->GetStringValue (); return v && *v == 't'; } case VALUE_LONG: return bool (value->GetLongValue ()); case VALUE_BOOL: return value->GetBoolValue (); case VALUE_FLOAT: return fabs (value->GetFloatValue ()) > .000001f; case VALUE_STRINGARRAY: return value->GetStringArrayValue () && !value->GetStringArrayValue ()->IsEmpty (); case VALUE_COLLECTION: case VALUE_COMPOSITE: { csRef<ValueIterator> it = value->GetIterator (); return it->HasNext (); } default: return false; } } bool View::ValueToBool (Value* value) { return ValueToBoolStatic (value); } csString View::ValueToString (Value* value) { csString val; switch (value->GetType ()) { case VALUE_STRING: return csString (value->GetStringValue ()); case VALUE_LONG: val.Format ("%ld", value->GetLongValue ()); return val; case VALUE_BOOL: return csString (value->GetBoolValue () ? "true" : "false"); case VALUE_FLOAT: val.Format ("%g", value->GetFloatValue ()); return val; case VALUE_STRINGARRAY: return csString("<stringarray>"); case VALUE_COLLECTION: return csString ("<collection>"); case VALUE_COMPOSITE: return csString ("<composite>"); default: return csString ("<?>"); } } void View::LongToValue (long l, Value* value) { csString str; switch (value->GetType ()) { case VALUE_STRING: str.Format ("%ld", l); value->SetStringValue (str); return; case VALUE_LONG: value->SetLongValue (l); return; case VALUE_BOOL: value->SetBoolValue (bool (l)); return; case VALUE_FLOAT: value->SetFloatValue (float (l)); return; case VALUE_STRINGARRAY: return; case VALUE_COLLECTION: return; case VALUE_COMPOSITE: return; default: return; } } void View::BoolToValue (bool in, Value* value) { switch (value->GetType ()) { case VALUE_STRING: value->SetStringValue (in ? "true" : "false"); return; case VALUE_LONG: value->SetLongValue (long (in)); return; case VALUE_BOOL: value->SetBoolValue (in); return; case VALUE_FLOAT: value->SetFloatValue (float (in)); return; case VALUE_STRINGARRAY: return; case VALUE_COLLECTION: return; case VALUE_COMPOSITE: return; default: return; } } void View::StringToValue (const char* str, Value* value) { switch (value->GetType ()) { case VALUE_STRING: value->SetStringValue (str); return; case VALUE_LONG: { long l; csScanStr (str, "%d", &l); value->SetLongValue (l); return; } case VALUE_BOOL: { bool l; csScanStr (str, "%b", &l); value->SetBoolValue (l); return; } case VALUE_FLOAT: { float l; csScanStr (str, "%f", &l); value->SetFloatValue (l); return; } case VALUE_STRINGARRAY: return; case VALUE_COLLECTION: return; case VALUE_COMPOSITE: return; default: return; } } Value* View::FindChild (Value* collection, const char* str) { csRef<ValueIterator> it = collection->GetIterator (); while (it->HasNext ()) { Value* child = it->NextChild (); if (ValueToString (child) == str) return child; } return 0; } csRef<CompositeValue> View::CreateComposite (ValueType type, va_list args) { csRef<CompositeValue> composite = NEWREF(CompositeValue,new CompositeValue()); composite->AddChildren (type, args); return composite; } csRef<CompositeValue> View::CreateComposite (ValueType type, ...) { va_list args; va_start (args, type); csRef<CompositeValue> value = CreateComposite (type, args); va_end (args); return value; } csRef<StringArrayValue> View::CreateStringArray (ValueType type, va_list args) { csRef<StringArrayValue> stringarray = NEWREF(StringArrayValue,new StringArrayValue()); csStringArray& array = stringarray->GetArray (); while (type != VALUE_NONE) { switch (type) { case VALUE_STRING: { const char* value = va_arg (args, char*); array.Push (value); break; } case VALUE_LONG: { long value = va_arg (args, long); csString fmt; fmt.Format ("%ld", value); array.Push (fmt); break; } case VALUE_BOOL: { bool value = va_arg (args, int); csString fmt; fmt.Format ("%d", int (value)); array.Push (fmt); break; } case VALUE_FLOAT: { float value = va_arg (args, double); csString fmt; fmt.Format ("%g", value); array.Push (fmt); break; } default: array.Push ("<?>"); break; } type = (ValueType) va_arg (args, int); } return stringarray; } csRef<StringArrayValue> View::CreateStringArray (ValueType type, ...) { va_list args; va_start (args, type); csRef<StringArrayValue> value = CreateStringArray (type, args); va_end (args); return value; } csStringArray View::ConstructListRow (const ListHeading& lh, Value* value) { csStringArray row; ValueType t = value->GetType (); if (t == VALUE_STRINGARRAY) { const csStringArray* array = value->GetStringArrayValue (); if (!array) return row; for (size_t i = 0 ; i < lh.heading.GetSize () ; i++) { csString el = array->Get (lh.indices[i]); row.Push (el); } } else if (t == VALUE_COMPOSITE) { for (size_t i = 0 ; i < lh.names.GetSize () ; i++) { Value* child = value->GetChildByName (lh.names[i]); if (child) row.Push (ValueToString (child)); else { printf ("Warning: child '%s' is missing!\n", (const char*)lh.names[i]); row.Push (""); } } } else { row.Push (ValueToString (value)); } return row; } size_t View::FindRmbContext (wxWindow* component) { for (size_t i = 0 ; i < rmbContexts.GetSize () ; i++) if (rmbContexts[i].component == component) return i; return csArrayItemNotFound; } void View::OnRMB (wxContextMenuEvent& event) { wxWindow* component = wxStaticCast (event.GetEventObject (), wxWindow); size_t idx = FindRmbContext (component); if (idx == csArrayItemNotFound) { // We also try the parent since when the list is empty we apparently get // a child of the list instead of the list itself. component = component->GetParent (); if (component == 0) return; idx = FindRmbContext (component); if (idx == csArrayItemNotFound) return; } if (component->IsKindOf (CLASSINFO (wxListCtrl))) { wxListCtrl* listCtrl = wxStaticCast (component, wxListCtrl); bool hasItem; if (!ListCtrlTools::CheckHitList (listCtrl, hasItem, event.GetPosition ())) return; } else if (component->IsKindOf (CLASSINFO (wxTreeCtrl))) { wxTreeCtrl* treeCtrl = wxStaticCast (component, wxTreeCtrl); if (!treeCtrl->IsShownOnScreen ()) return; int flags = 0; wxTreeItemId idx = treeCtrl->HitTest (treeCtrl->ScreenToClient (event.GetPosition ()), flags); if (!idx.IsOk()) { if (!treeCtrl->GetScreenRect ().Contains (event.GetPosition ())) return; } else treeCtrl->SelectItem (idx); } const RmbContext& lc = rmbContexts[idx]; wxMenu contextMenu; for (size_t j = 0 ; j < lc.actionDefs.GetSize () ; j++) { Action* action = lc.actionDefs[j].action; wxMenuItem* item = contextMenu.Append (lc.actionDefs[j].id, wxString::FromUTF8 (action->GetName ())); bool active = action->IsActive (this, component); item->Enable (active); } component->PopupMenu (&contextMenu); } void View::OnActionExecuted (wxCommandEvent& event) { int id = event.GetId (); // We have to scan all lists here to find the one that has the right id. for (size_t i = 0 ; i < rmbContexts.GetSize () ; i++) { const RmbContext& lc = rmbContexts[i]; for (size_t j = 0 ; j < lc.actionDefs.GetSize () ; j++) if (lc.actionDefs[j].id == id) { lc.actionDefs[j].action->Do (this, lc.component); return; } } // Scan all buttons if we didn't find a list. csHash<csRef<Action>,csPtrKey<wxButton> >::GlobalIterator it = buttonActions.GetIterator (); while (it.HasNext ()) { csPtrKey<wxButton> button; csRef<Action> action = it.Next (button); if (button == event.GetEventObject ()) { action->Do (this, button); return; } } } void View::OnComponentChanged (wxCommandEvent& event) { wxWindow* component = wxStaticCast (event.GetEventObject (), wxWindow); Binding* binding = bindingsByComponent.Get (component, 0); if (!binding) { printf ("OnComponentChanged: Something went wrong! Called without a value!\n"); return; } if (binding->processing) return; binding->processing = true; #if DO_DEBUG printf ("View::OnComponentChanged: %s\n", binding->value->Dump ().GetData ()); #endif if (component->IsKindOf (CLASSINFO (wxTextCtrl))) { wxTextCtrl* textCtrl = wxStaticCast (component, wxTextCtrl); csString text = (const char*)textCtrl->GetValue ().mb_str (wxConvUTF8); StringToValue (text, binding->value); } else if (component->IsKindOf (CLASSINFO (wxChoice))) { wxChoice* choiceCtrl = wxStaticCast (component, wxChoice); csString text = (const char*)choiceCtrl->GetStringSelection ().mb_str (wxConvUTF8); StringToValue (text, binding->value); } else if (component->IsKindOf (CLASSINFO (wxComboBox))) { wxComboBox* combo = wxStaticCast (component, wxComboBox); csString text = (const char*)combo->GetValue ().mb_str (wxConvUTF8); StringToValue (text, binding->value); } else if (component->IsKindOf (CLASSINFO (wxCheckBox))) { wxCheckBox* checkBox = wxStaticCast (component, wxCheckBox); BoolToValue (checkBox->GetValue (), binding->value); } else if (component->IsKindOf (CLASSINFO (wxChoicebook))) { wxChoicebook* choicebook = wxStaticCast (component, wxChoicebook); int pageSel = choicebook->GetSelection (); if (binding->value->GetType () == VALUE_LONG) LongToValue ((long)pageSel, binding->value); else { csString value; if (pageSel == wxNOT_FOUND) value = ""; else { wxString pageTxt = choicebook->GetPageText (pageSel); value = (const char*)pageTxt.mb_str (wxConvUTF8); } StringToValue (value, binding->value); } } else { printf ("OnComponentChanged: this type of component not yet supported!\n"); } binding->processing = false; } void View::BuildTree (wxTreeCtrl* treeCtrl, Value* value, wxTreeItemId& parent) { csRef<ValueIterator> it = value->GetIterator (); while (it->HasNext ()) { Value* child = it->NextChild (); wxTreeItemId itemId = treeCtrl->AppendItem (parent, wxString::FromUTF8 (child->GetStringValue ())); BuildTree (treeCtrl, child, itemId); } } void View::UpdateTree (wxTreeCtrl* treeCtrl, Value* value, wxTreeItemId& parent) { csRef<ValueIterator> it = value->GetIterator (); wxTreeItemIdValue cookie; wxTreeItemId itemId = treeCtrl->GetFirstChild (parent, cookie); bool addingnew = false; // Set to true as soon as we're adding new items ourselves. while (it->HasNext ()) { Value* child = it->NextChild (); wxString newLabel = wxString::FromUTF8 (child->GetStringValue ()); if ((!addingnew) && itemId.IsOk ()) { wxString currentLabel = treeCtrl->GetItemText (itemId); if (currentLabel != newLabel) { treeCtrl->SetItemText (itemId, newLabel); } UpdateTree (treeCtrl, child, itemId); itemId = treeCtrl->GetNextChild (parent, cookie); } else { itemId = treeCtrl->AppendItem (parent, newLabel); UpdateTree (treeCtrl, child, itemId); addingnew = true; } } if (!addingnew) { // Might have to remove stuff. csArray<wxTreeItemId> toRemove; while (itemId.IsOk ()) { toRemove.Push (itemId); itemId = treeCtrl->GetNextChild (parent, cookie); } for (size_t i = 0 ; i < toRemove.GetSize () ; i++) treeCtrl->Delete (toRemove[i]); } } bool View::IsValueBound (Value* value) const { ValueToBinding::ConstIterator it = bindingsByValue.GetIterator (value); return it.HasNext (); } bool View::CheckIfParentDisabled (wxWindow* window) { window = window->GetParent (); while (window) { if (window == parent) return false; if (disabledComponents.In (window)) return true; if (window->IsEnabled () == false) return true; window = window->GetParent (); } return false; } void View::EnableBoundComponents (wxWindow* comp, bool state) { if (state) disabledComponents.Delete (comp); else disabledComponents.Add (comp); bool parentDisabled = CheckIfParentDisabled (comp); if (parentDisabled) state = false; EnableBoundComponentsInt (comp, state); } void View::EnableBoundComponentsInt (wxWindow* comp, bool state) { if (comp->IsKindOf (CLASSINFO (wxPanel)) || comp->IsKindOf (CLASSINFO (wxDialog))) { if (disabledComponents.In (comp)) state = false; wxWindowList list = comp->GetChildren (); wxWindowList::iterator iter; for (iter = list.begin (); iter != list.end () ; ++iter) { wxWindow* child = *iter; EnableBoundComponentsInt (child, state); } } else { Binding* binding = bindingsByComponent.Get (comp, 0); if (binding) { if (!state) comp->Enable (state); else if (!disabledComponents.In (comp)) comp->Enable (state); } } } void View::ValueChanged (Value* value) { #if DO_DEBUG printf ("View::ValueChanged: %s\n", value->Dump ().GetData ()); #endif ValueToBinding::Iterator it = bindingsByValue.GetIterator (value); if (!it.HasNext ()) { printf ("ValueChanged: Something went wrong! Called without a valid binding!\n"); CS_ASSERT (false); return; } while (it.HasNext ()) { Binding* b = it.Next (); wxWindow* comp = b->component; if (b->changeEnabled) { // Modify disabled/enabled state instead of value. bool state = ValueToBool (value); EnableBoundComponents (comp, state); continue; } if (!b->processing) { CustomControl* customCtrl; if (comp->IsKindOf (CLASSINFO (wxTextCtrl))) { b->processing = true; wxTextCtrl* textCtrl = wxStaticCast (comp, wxTextCtrl); csString text = ValueToString (value); textCtrl->SetValue (wxString::FromUTF8 (text)); b->processing = false; } else if (comp->IsKindOf (CLASSINFO (wxChoice))) { b->processing = true; wxChoice* choiceCtrl = wxStaticCast (comp, wxChoice); csString text = ValueToString (value); choiceCtrl->SetStringSelection (wxString::FromUTF8 (text)); b->processing = false; } else if (comp->IsKindOf (CLASSINFO (wxComboBox))) { b->processing = true; wxComboBox* combo = wxStaticCast (comp, wxComboBox); csString text = ValueToString (value); combo->SetValue (wxString::FromUTF8 (text)); b->processing = false; } else if (comp->IsKindOf (CLASSINFO (wxCheckBox))) { b->processing = true; wxCheckBox* checkBox = wxStaticCast (comp, wxCheckBox); bool in = ValueToBool (value); checkBox->SetValue (in); b->processing = false; } else if ((customCtrl = dynamic_cast<CustomControl*> (comp))) { customCtrl->SyncValue (value); } else if (comp->IsKindOf (CLASSINFO (wxPanel)) || comp->IsKindOf (CLASSINFO (wxDialog))) { // If the value of a composite changes we update the children. csRef<ValueIterator> it = value->GetIterator (); while (it->HasNext ()) { Value* child = it->NextChild (); if (IsValueBound (child)) ValueChanged (child); } } else if (comp->IsKindOf (CLASSINFO (wxListCtrl))) { //csString compName = (const char*)comp->GetName ().mb_str (wxConvUTF8); //printf ("ValueChanged for component '%s'\n", compName.GetData ()); fflush (stdout); wxListCtrl* listCtrl = wxStaticCast (comp, wxListCtrl); long idx = ListCtrlTools::GetFirstSelectedRow (listCtrl); listCtrl->Freeze (); listCtrl->DeleteAllItems (); ListHeading lhdef; const ListHeading& lh = listToHeading.Get (listCtrl, lhdef); csRef<ValueIterator> it = value->GetIterator (); while (it->HasNext ()) { Value* child = it->NextChild (); ListCtrlTools::AddRow (listCtrl, ConstructListRow (lh, child)); } if (idx != -1) ListCtrlTools::SelectRow (listCtrl, idx, true); listCtrl->Thaw (); } else if (comp->IsKindOf (CLASSINFO (wxTreeCtrl))) { wxTreeCtrl* treeCtrl = wxStaticCast (comp, wxTreeCtrl); treeCtrl->Freeze (); wxTreeItemId rootId = treeCtrl->GetRootItem (); if (rootId.IsOk ()) { UpdateTree (treeCtrl, value, rootId); } else { treeCtrl->DeleteAllItems (); rootId = treeCtrl->AddRoot (wxString::FromUTF8 (value->GetStringValue ())); BuildTree (treeCtrl, value, rootId); } treeCtrl->Thaw (); } else if (comp->IsKindOf (CLASSINFO (wxChoicebook))) { wxChoicebook* choicebook = wxStaticCast (comp, wxChoicebook); if (value->GetType () == VALUE_LONG) choicebook->ChangeSelection (value->GetLongValue ()); else { csString text = ValueToString (value); wxString wxtext = wxString::FromUTF8 (text); for (size_t i = 0 ; i < choicebook->GetPageCount () ; i++) { wxString wxp = choicebook->GetPageText (i); if (wxp == wxtext) { choicebook->ChangeSelection (i); return; } } // If we come here we set to the first page. choicebook->SetSelection (0); } } else { printf ("ValueChanged: this type of component not yet supported!\n"); } } } } bool View::DefineHeading (const char* listName, const char* heading, const char* names) { wxString wxlistName = wxString::FromUTF8 (listName); wxWindow* comp = parent->FindWindow (wxlistName); if (!comp) { printf ("DefineHeading: Can't find component '%s'!\n", listName); return false; } if (!comp->IsKindOf (CLASSINFO (wxListCtrl))) { printf ("DefineHeading: Component '%s' is not a list control!\n", listName); return false; } wxListCtrl* listCtrl = wxStaticCast (comp, wxListCtrl); return DefineHeading (listCtrl, heading, names); } bool View::DefineHeading (wxListCtrl* listCtrl, const char* heading, const char* names) { ListHeading lh; lh.heading.SplitString (heading, ","); lh.names.SplitString (names, ","); for (size_t i = 0 ; i < lh.heading.GetSize () ; i++) ListCtrlTools::SetColumn (listCtrl, i, lh.heading[i], 100); listToHeading.Put (listCtrl, lh); return true; } bool View::DefineHeadingIndexed (const char* listName, const char* heading, ...) { wxString wxlistName = wxString::FromUTF8 (listName); wxWindow* comp = parent->FindWindow (wxlistName); if (!comp) { printf ("DefineHeading: Can't find component '%s'!\n", listName); return false; } if (!comp->IsKindOf (CLASSINFO (wxListCtrl))) { printf ("DefineHeading: Component '%s' is not a list control!\n", listName); return false; } wxListCtrl* listCtrl = wxStaticCast (comp, wxListCtrl); va_list args; va_start (args, heading); bool rc = DefineHeadingIndexed (listCtrl, heading, args); va_end (args); return rc; } bool View::DefineHeadingIndexed (wxListCtrl* listCtrl, const char* heading, ...) { va_list args; va_start (args, heading); bool rc = DefineHeadingIndexed (listCtrl, heading, args); va_end (args); return rc; } bool View::DefineHeadingIndexed (wxListCtrl* listCtrl, const char* heading, va_list args) { ListHeading lh; lh.heading.SplitString (heading, ","); for (size_t i = 0 ; i < lh.heading.GetSize () ; i++) { int index = va_arg (args, int); lh.indices.Push (index); ListCtrlTools::SetColumn (listCtrl, i, lh.heading[i], 100); } listToHeading.Put (listCtrl, lh); return true; } bool View::AddAction (const char* compName, Action* action) { wxString wxcompName = wxString::FromUTF8 (compName); wxWindow* comp = parent->FindWindow (wxcompName); if (!comp) { printf ("AddAction: Can't find component '%s'!\n", compName); return false; } return AddAction (comp, action); } bool View::AddAction (wxWindow* component, Action* action) { if (component->IsKindOf (CLASSINFO (wxButton))) return AddAction (wxStaticCast (component, wxButton), action); if (component->IsKindOf (CLASSINFO (wxListCtrl)) || component->IsKindOf (CLASSINFO (wxTreeCtrl))) return AddContextAction (component, action); printf ("AddAction: Unsupported type for component!\n"); return false; } bool View::AddContextAction (wxWindow* component, Action* action) { component->Connect (lastContextID, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler (EventHandler :: OnActionExecuted), 0, &eventHandler); size_t idx = FindRmbContext (component); if (idx == csArrayItemNotFound) { RmbContext lc; lc.component = component; idx = rmbContexts.Push (lc); component->Connect (wxEVT_CONTEXT_MENU, wxContextMenuEventHandler (EventHandler :: OnRMB), 0, &eventHandler); } RmbContext& lc = rmbContexts[idx]; ActionDef ad; ad.id = lastContextID; ad.action = action; lc.actionDefs.Push (ad); lastContextID++; return true; } bool View::AddAction (wxButton* button, Action* action) { button->Connect (wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler (EventHandler :: OnActionExecuted), 0, &eventHandler); buttonActions.Put (button, action); wxString wxlabel = wxString::FromUTF8 (action->GetName ()); button->SetLabel (wxlabel); return true; } bool View::SetSelectedValue (wxWindow* component, Value* value) { Binding* binding = bindingsByComponent.Get (component, 0); if (!binding) { printf ("SetSelectedValue: Component is not bound to a value!\n"); return false; } if (component->IsKindOf (CLASSINFO (wxListCtrl))) { wxListCtrl* listCtrl = wxStaticCast (component, wxListCtrl); csRef<ValueIterator> it = binding->value->GetIterator (); bool found = false; size_t idx = 0; while (it->HasNext ()) { Value* child = it->NextChild (); if (child == value) { found = true; break; } idx++; } if (found) { ListCtrlTools::SelectRow (listCtrl, idx, true); return true; } return false; } if (component->IsKindOf (CLASSINFO (wxTreeCtrl))) { wxTreeCtrl* treeCtrl = wxStaticCast (component, wxTreeCtrl); wxTreeItemId child = TreeFromValue (treeCtrl, treeCtrl->GetRootItem (), binding->value, value); if (child.IsOk ()) { treeCtrl->SelectItem (child); return true; } return false; } printf ("SetSelectedValue: Unsupported type for component!\n"); return false; } Value* View::GetValue (wxWindow* component) { Binding* binding = bindingsByComponent.Get (component, 0); if (!binding) return 0; return binding->value; } Value* View::GetSelectedValue (wxWindow* component) { Binding* binding = bindingsByComponent.Get (component, 0); if (!binding) { printf ("GetSelectedValue: Component is not bound to a value!\n"); return 0; } if (component->IsKindOf (CLASSINFO (wxListCtrl))) { wxListCtrl* listCtrl = wxStaticCast (component, wxListCtrl); long idx = ListCtrlTools::GetFirstSelectedRow (listCtrl); if (idx < 0) return 0; return binding->value->GetChild (size_t (idx)); } if (component->IsKindOf (CLASSINFO (wxTreeCtrl))) { wxTreeCtrl* treeCtrl = wxStaticCast (component, wxTreeCtrl); wxTreeItemId selection = treeCtrl->GetSelection (); if (selection.IsOk ()) return ValueFromTree (treeCtrl, selection, binding->value); else return 0; } printf ("GetSelectedValue: Unsupported type for component!\n"); return 0; } csArray<Value*> View::GetSelectedValues (wxWindow* component) { Binding* binding = bindingsByComponent.Get (component, 0); if (!binding) { printf ("GetSelectedValue: Component is not bound to a value!\n"); return 0; } csArray<Value*> values; if (component->IsKindOf (CLASSINFO (wxListCtrl))) { wxListCtrl* listCtrl = wxStaticCast (component, wxListCtrl); csArray<long> indices = ListCtrlTools::GetSelectedRowIndices (listCtrl); for (size_t i = 0 ; i < indices.GetSize () ; i++) values.Push (binding->value->GetChild (size_t (indices[i]))); return values; } if (component->IsKindOf (CLASSINFO (wxTreeCtrl))) { wxTreeCtrl* treeCtrl = wxStaticCast (component, wxTreeCtrl); wxTreeItemId selection = treeCtrl->GetSelection (); // @@@ Only support first selection for now. if (selection.IsOk ()) values.Push (ValueFromTree (treeCtrl, selection, binding->value)); return values; } printf ("GetSelectedValue: Unsupported type for component!\n"); return 0; } class SignalChangeListener : public ValueChangeListener { private: csRef<Value> source; csRef<Value> dest; bool dochildren; public: SignalChangeListener (Value* source, Value* dest, bool dochildren) : source (source), dest (dest), dochildren (dochildren) { } virtual ~SignalChangeListener () { } virtual void ValueChanged (Value* value) { // printf ("SIGNAL: from %s to %s\n", source->Dump ().GetData (), dest->Dump ().GetData ()); dest->FireValueChanged (); if (dochildren) { csRef<ValueIterator> it = dest->GetIterator (); while (it->HasNext ()) { Value* child = it->NextChild (); // printf (" FIRE: to %s\n", child->Dump ().GetData ()); child->FireValueChanged (); } } } }; void View::Signal (Value* source, Value* dest, bool dochildren) { csRef<SignalChangeListener> listener; listener.AttachNew (new SignalChangeListener (source, dest, dochildren)); source->AddValueChangeListener (listener); } class NotValue : public BoolValue { private: csRef<Value> value; public: NotValue (Value* value) : value (value) { } virtual ~NotValue () { } virtual void SetBoolValue (bool fl) { } virtual bool GetBoolValue () { return !ValueToBoolStatic (value); } }; csRef<Value> View::Not (Value* value) { csRef<Value> v; v.AttachNew (new NotValue (value)); csRef<StandardChangeListener> changeListener; changeListener.AttachNew (new StandardChangeListener (v)); value->AddValueChangeListener (changeListener); return v; } class AndValue : public BoolValue { private: csRef<Value> value1, value2; public: AndValue (Value* value1, Value* value2) : value1 (value1), value2 (value2) { } virtual ~AndValue () { } virtual void SetBoolValue (bool fl) { } virtual bool GetBoolValue () { return ValueToBoolStatic (value1) && ValueToBoolStatic (value2); } }; csRef<Value> View::And (Value* value1, Value* value2) { csRef<Value> v; v.AttachNew (new AndValue (value1, value2)); csRef<StandardChangeListener> changeListener; changeListener.AttachNew (new StandardChangeListener (v)); value1->AddValueChangeListener (changeListener); value2->AddValueChangeListener (changeListener); return v; } class OrValue : public BoolValue { private: csRef<Value> value1, value2; public: OrValue (Value* value1, Value* value2) : value1 (value1), value2 (value2) { } virtual ~OrValue () { } virtual void SetBoolValue (bool fl) { } virtual bool GetBoolValue () { return ValueToBoolStatic (value1) || ValueToBoolStatic (value2); } }; csRef<Value> View::Or (Value* value1, Value* value2) { csRef<Value> v; v.AttachNew (new OrValue (value1, value2)); csRef<StandardChangeListener> changeListener; changeListener.AttachNew (new StandardChangeListener (v)); value1->AddValueChangeListener (changeListener); value2->AddValueChangeListener (changeListener); return v; } // -------------------------------------------------------------------------- } // namespace Ares
54,434
17,986
/****************************************************************************** Plush Version 1.2 read_3ds.c 3DS Object Reader Copyright (c) 1996-2000, Justin Frankel ******************************************************************************/ #include "plush.h" typedef struct { pl_uInt16 id; void (*func)(pl_uChar *ptr, pl_uInt32 p); } _pl_3DSChunk; static pl_Obj *obj; static pl_Obj *bobj; static pl_Obj *lobj; static pl_sInt16 currentobj; static pl_Mat *_m; static pl_Float _pl3DSReadFloat(pl_uChar **ptr); static pl_uInt32 _pl3DSReadDWord(pl_uChar **ptr); static pl_uInt16 _pl3DSReadWord(pl_uChar **ptr); static void _pl3DSChunkReader(pl_uChar *ptr, int len); static void _pl3DSRGBFReader(pl_uChar *f, pl_uInt32 p); static void _pl3DSRGBBReader(pl_uChar *f, pl_uInt32 p); static int _pl3DSASCIIZReader(pl_uChar *ptr, pl_uInt32 p, char *as); static void _pl3DSObjBlockReader(pl_uChar *ptr, pl_uInt32 p); static void _pl3DSTriMeshReader(pl_uChar *f, pl_uInt32 p); static void _pl3DSVertListReader(pl_uChar *f, pl_uInt32 p); static void _pl3DSFaceListReader(pl_uChar *f, pl_uInt32 p); static void _pl3DSFaceMatReader(pl_uChar *f, pl_uInt32 p); static void MapListReader(pl_uChar *f, pl_uInt32 p); static pl_sInt16 _pl3DSFindChunk(pl_uInt16 id); static _pl_3DSChunk _pl3DSChunkNames[] = { {0x4D4D,NULL}, /* Main */ {0x3D3D,NULL}, /* Object Mesh */ {0x4000,_pl3DSObjBlockReader}, {0x4100,_pl3DSTriMeshReader}, {0x4110,_pl3DSVertListReader}, {0x4120,_pl3DSFaceListReader}, {0x4130,_pl3DSFaceMatReader}, {0x4140,MapListReader}, {0xAFFF,NULL}, /* Material */ {0xA010,NULL}, /* Ambient */ {0xA020,NULL}, /* Diff */ {0xA030,NULL}, /* Specular */ {0xA200,NULL}, /* Texture */ {0x0010,_pl3DSRGBFReader}, {0x0011,_pl3DSRGBBReader}, }; pl_Obj *plRead3DSObjFromFile(char *fn, pl_Mat *m) { FILE *f = fopen(fn, "rb"); if (!f) return 0; fseek(f, 0, 2); pl_uInt32 p = ftell(f); rewind(f); WDL_HeapBuf buf; buf.Resize(p); int s = fread(buf.Get(), 1, p, f); fclose(f); if(!s) return 0; return plRead3DSObj(buf.Get(), s, m); } pl_Obj *plRead3DSObjFromResource(HINSTANCE hInst, int resid, pl_Mat *m) { #ifdef _WIN32 HRSRC hResource = FindResource(hInst, MAKEINTRESOURCE(resid), "3DS"); if(!hResource) return NULL; DWORD imageSize = SizeofResource(hInst, hResource); if(imageSize < 6) return NULL; HGLOBAL res = LoadResource(hInst, hResource); const void* pResourceData = LockResource(res); if(!pResourceData) return NULL; unsigned char *data = (unsigned char *)pResourceData; pl_Obj *o = plRead3DSObj(data, imageSize, m); DeleteObject(res); return o; #else return 0; #endif } pl_Obj *plRead3DSObj(void *ptr, int size, pl_Mat *m) { _m = m; obj = bobj = lobj = 0; currentobj = 0; _pl3DSChunkReader((pl_uChar *)ptr, size); return bobj; } static pl_Float _pl3DSReadFloat(pl_uChar **ptr) { pl_uInt32 *i; pl_IEEEFloat32 c; i = (pl_uInt32 *) &c; *i = _pl3DSReadDWord(ptr); return ((pl_Float) c); } static pl_uInt32 _pl3DSReadDWord(pl_uChar **ptr) { pl_uInt32 r; pl_uChar *p = *ptr; r = *p++; r |= (*p++)<<8; r |= (*p++)<<16; r |= (*p++)<<24; *ptr += 4; return r; } static pl_uInt16 _pl3DSReadWord(pl_uChar **ptr) { pl_uInt16 r; pl_uChar *p = *ptr; r = *p++; r |= (*p++)<<8; *ptr += 2; return r; } static void _pl3DSRGBFReader(pl_uChar *f, pl_uInt32 p) { pl_Float c[3]; if(p < 3*4) return; c[0] = _pl3DSReadFloat(&f); c[1] = _pl3DSReadFloat(&f); c[2] = _pl3DSReadFloat(&f); } static void _pl3DSRGBBReader(pl_uChar *f, pl_uInt32 p) { unsigned char c[3]; if(p < 3) return; memcpy(c, f, sizeof(c)); } static int _pl3DSASCIIZReader(pl_uChar *ptr, pl_uInt32 p, char *as) { int l = 0; while (*ptr && p>0) { if(as) *as++ = *ptr; ptr++; l++; p--; } if(as) *as = 0; return l+1; } static void _pl3DSObjBlockReader(pl_uChar *ptr, pl_uInt32 p) { int l = _pl3DSASCIIZReader(ptr, p, 0); ptr += l; p -= l; _pl3DSChunkReader(ptr, p); } static void _pl3DSTriMeshReader(pl_uChar *ptr, pl_uInt32 p) { pl_uInt32 i; pl_Face *face; obj = new pl_Obj; _pl3DSChunkReader(ptr, p); i = obj->Faces.GetSize(); face = obj->Faces.Get(); while (i--) { pl_Vertex *vp=obj->Vertices.Get(); pl_Vertex *fVertices[3] = { vp+face->VertexIndices[0], vp+face->VertexIndices[1], vp+face->VertexIndices[2], }; face->MappingU[0][0] = fVertices[0]->xformedx; face->MappingV[0][0] = fVertices[0]->xformedy; face->MappingU[0][1] = fVertices[1]->xformedx; face->MappingV[0][1] = fVertices[1]->xformedy; face->MappingU[0][2] = fVertices[2]->xformedx; face->MappingV[0][2] = fVertices[2]->xformedy; face++; } obj->CalculateNormals(); if (currentobj == 0) { currentobj = 1; lobj = bobj = obj; } else { lobj->Children.Add(obj); lobj = obj; } } static void _pl3DSVertListReader(pl_uChar *f, pl_uInt32 p) { pl_uInt16 nv; pl_Vertex *v; int len = (int)p; nv = _pl3DSReadWord(&f); len -= 2; if(len <= 0) return; obj->Vertices.Resize(nv); v = obj->Vertices.Get(); while (nv--) { memset(v,0,sizeof(pl_Vertex)); v->x = _pl3DSReadFloat(&f); v->y = _pl3DSReadFloat(&f); v->z = _pl3DSReadFloat(&f); len -= 3*4; if(len < 0) return; v++; } } static void _pl3DSFaceListReader(pl_uChar *f, pl_uInt32 p) { pl_uInt16 nv; pl_uInt16 c[3]; pl_uInt16 flags; pl_Face *face; int len = (int)p; nv = _pl3DSReadWord(&f); len -= 2; if(len <= 0) return; obj->Faces.Resize(nv); face = obj->Faces.Get(); while (nv--) { memset(face,0,sizeof(pl_Face)); c[0] = _pl3DSReadWord(&f); c[1] = _pl3DSReadWord(&f); c[2] = _pl3DSReadWord(&f); flags = _pl3DSReadWord(&f); len -= 4*2; if(len < 0) return; face->VertexIndices[0] = (c[0]&0x0000FFFF); face->VertexIndices[1] = (c[1]&0x0000FFFF); face->VertexIndices[2] = (c[2]&0x0000FFFF); face->Material = _m; face++; } if(len) _pl3DSChunkReader(f, len); } static void _pl3DSFaceMatReader(pl_uChar *ptr, pl_uInt32 p) { pl_uInt16 n, nf; int l = _pl3DSASCIIZReader(ptr, p, 0); ptr += l; p -= l; n = _pl3DSReadWord(&ptr); while (n--) { nf = _pl3DSReadWord(&ptr); } } static void MapListReader(pl_uChar *f, pl_uInt32 p) { pl_uInt16 nv; pl_Float c[2]; pl_Vertex *v; int len = (int) p; nv = _pl3DSReadWord(&f); len -= 2; v = obj->Vertices.Get(); if (nv == obj->Vertices.GetSize()) while (nv--) { c[0] = _pl3DSReadFloat(&f); c[1] = _pl3DSReadFloat(&f); len -= 2*4; if (len < 0) return; v->xformedx = c[0]; v->xformedy = c[1]; v++; } } static pl_sInt16 _pl3DSFindChunk(pl_uInt16 id) { pl_sInt16 i; for (i = 0; i < sizeof(_pl3DSChunkNames)/sizeof(_pl3DSChunkNames[0]); i++) if (id == _pl3DSChunkNames[i].id) return i; return -1; } static void _pl3DSChunkReader(pl_uChar *ptr, int len) { pl_uInt32 hlen; pl_uInt16 hid; pl_sInt16 n; while (len > 0) { hid = _pl3DSReadWord(&ptr); len -= 2; if(len <= 0) return; hlen = _pl3DSReadDWord(&ptr); len -= 4; if(len <= 0) return; if (hlen == 0) return; hlen -= 6; n = _pl3DSFindChunk(hid); if (n < 0) { ptr += hlen; len -= hlen; } else { pl_uChar *p = ptr; if (_pl3DSChunkNames[n].func != NULL) _pl3DSChunkNames[n].func(p, hlen); else _pl3DSChunkReader(p, hlen); ptr += hlen; len -= hlen; } } }
7,930
3,661
// Copyright (c) 2018-present Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "information_schema.h" #include <boost/algorithm/string/join.hpp> #include "runtime_state.h" #include "meta_server_interact.hpp" #include "schema_factory.h" #include "network_socket.h" #include "scalar_fn_call.h" #include "parser.h" namespace baikaldb { int InformationSchema::init() { init_partition_split_info(); init_region_status(); init_columns(); init_statistics(); init_schemata(); init_tables(); init_virtual_index_influence_info(); init_routines(); init_key_column_usage(); init_referential_constraints(); return 0; } int64_t InformationSchema::construct_table(const std::string& table_name, FieldVec& fields) { auto& table = _tables[table_name];//_tables[table_name]ๅ–ๅ‡บ็š„ๆ˜ฏSchema_info table.set_table_id(--_max_table_id); table.set_table_name(table_name); table.set_database("information_schema"); table.set_database_id(_db_id); table.set_namespace_name("INTERNAL"); table.set_engine(pb::INFORMATION_SCHEMA); int id = 0; for (auto& pair : fields) { auto* field = table.add_fields(); field->set_field_name(pair.first); field->set_mysql_type(pair.second); field->set_field_id(++id); } SchemaFactory::get_instance()->update_table(table); return table.table_id(); } void InformationSchema::init_partition_split_info() { // ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"partition_key", pb::STRING}, {"table_name", pb::STRING}, {"split_info", pb::STRING}, {"split_rows", pb::STRING}, }; int64_t table_id = construct_table("PARTITION_SPLIT_INFO", fields); // ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) -> std::vector<SmartRecord> { std::vector<SmartRecord> records; if (state->client_conn() == nullptr) { return records; } std::string namespace_ = state->client_conn()->user_info->namespace_; std::string table_name; for (auto expr : conditions) { if (expr->node_type() != pb::FUNCTION_CALL) { continue; } int32_t fn_op = static_cast<ScalarFnCall*>(expr)->fn().fn_op(); if (fn_op != parser::FT_EQ) { continue; } if (!expr->children(0)->is_slot_ref()) { continue; } SlotRef* slot_ref = static_cast<SlotRef*>(expr->children(0)); int32_t field_id = slot_ref->field_id(); if (field_id != 2) { continue; } if (expr->children(1)->is_constant()) { table_name = expr->children(1)->get_value(nullptr).get_string(); } } if (table_name.empty()) { return records; } auto* factory = SchemaFactory::get_instance(); int64_t condition_table_id = 0; if (factory->get_table_id(namespace_ + "." + table_name, condition_table_id) != 0) { return records; } auto index_ptr = factory->get_index_info_ptr(condition_table_id); if (index_ptr == nullptr) { return records; } if (index_ptr->fields.size() < 2) { return records; } std::map<std::string, pb::RegionInfo> region_infos; factory->get_all_region_by_table_id(condition_table_id, &region_infos); std::string last_partition_key; std::vector<std::string> last_keys; std::vector<int64_t> last_region_ids; last_keys.reserve(3); last_region_ids.reserve(3); int64_t last_id = 0; std::string partition_key; auto type1 = index_ptr->fields[0].type; auto type2 = index_ptr->fields[1].type; records.reserve(10000); std::vector<std::vector<int64_t>> region_ids; region_ids.reserve(10000); pb::QueryRequest req; pb::QueryResponse res; req.set_op_type(pb::QUERY_REGION); for (auto& pair : region_infos) { TableKey start_key(pair.second.start_key()); int pos = 0; partition_key = start_key.decode_start_key_string(type1, pos); if (partition_key != last_partition_key) { if (last_keys.size() > 1) { for (auto id : last_region_ids) { req.add_region_ids(id); } region_ids.emplace_back(last_region_ids); auto record = factory->new_record(table_id); record->set_string(record->get_field_by_name("partition_key"), last_partition_key); record->set_string(record->get_field_by_name("table_name"), table_name); record->set_string(record->get_field_by_name("split_info"), boost::join(last_keys, ",")); //record->set_string(record->get_field_by_name("split_rows"), boost::join(rows, ",")); records.emplace_back(record); } last_partition_key = partition_key; last_keys.clear(); last_region_ids.clear(); last_region_ids.emplace_back(last_id); } last_keys.emplace_back(start_key.decode_start_key_string(type2, pos)); last_region_ids.emplace_back(pair.second.region_id()); last_id = pair.second.region_id(); } if (last_keys.size() > 1) { for (auto id : last_region_ids) { req.set_op_type(pb::QUERY_REGION); } region_ids.emplace_back(last_region_ids); auto record = factory->new_record(table_id); record->set_string(record->get_field_by_name("partition_key"), last_partition_key); record->set_string(record->get_field_by_name("table_name"), table_name); record->set_string(record->get_field_by_name("split_info"), boost::join(last_keys, ",")); //record->set_string(record->get_field_by_name("split_rows"), boost::join(rows, ",")); records.emplace_back(record); } MetaServerInteract::get_instance()->send_request("query", req, res); std::unordered_map<int64_t, std::string> region_lines; for (auto& info : res.region_infos()) { region_lines[info.region_id()] = std::to_string(info.num_table_lines()); } for (uint32_t i = 0; i < records.size(); i++) { std::vector<std::string> rows; rows.reserve(3); if (i < region_ids.size()) { for (auto& id : region_ids[i]) { rows.emplace_back(region_lines[id]); } } records[i]->set_string(records[i]->get_field_by_name("split_rows"), boost::join(rows, ",")); } return records; }; } void InformationSchema::init_region_status() { // ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"region_id", pb::INT64}, {"parent", pb::INT64}, {"table_id", pb::INT64}, {"main_table_id", pb::INT64}, {"table_name", pb::STRING}, {"start_key", pb:: STRING}, {"end_key", pb::STRING}, {"create_time", pb::STRING}, {"peers", pb::STRING}, {"leader", pb::STRING}, {"version", pb::INT64}, {"conf_version", pb::INT64}, {"num_table_lines", pb::INT64}, {"used_size", pb::INT64}, }; int64_t table_id = construct_table("REGION_STATUS", fields); // ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) -> std::vector<SmartRecord> { std::vector<SmartRecord> records; if (state->client_conn() == nullptr) { return records; } std::string namespace_ = state->client_conn()->user_info->namespace_; std::string table_name; for (auto expr : conditions) { if (expr->node_type() != pb::FUNCTION_CALL) { continue; } int32_t fn_op = static_cast<ScalarFnCall*>(expr)->fn().fn_op(); if (fn_op != parser::FT_EQ) { continue; } if (!expr->children(0)->is_slot_ref()) { continue; } SlotRef* slot_ref = static_cast<SlotRef*>(expr->children(0)); int32_t field_id = slot_ref->field_id(); if (field_id != 5) { continue; } if (expr->children(1)->is_constant()) { table_name = expr->children(1)->get_value(nullptr).get_string(); } } if (table_name.empty()) { return records; } auto* factory = SchemaFactory::get_instance(); int64_t condition_table_id = 0; if (factory->get_table_id(namespace_ + "." + table_name, condition_table_id) != 0) { return records; } auto index_ptr = factory->get_index_info_ptr(condition_table_id); if (index_ptr == nullptr) { return records; } std::map<std::string, pb::RegionInfo> region_infos; factory->get_all_region_by_table_id(condition_table_id, &region_infos); records.reserve(region_infos.size()); for (auto& pair : region_infos) { auto& region = pair.second; TableKey start_key(region.start_key()); TableKey end_key(region.end_key()); auto record = factory->new_record(table_id); record->set_int64(record->get_field_by_name("region_id"), region.region_id()); record->set_int64(record->get_field_by_name("parent"), region.parent()); record->set_int64(record->get_field_by_name("table_id"), region.table_id()); record->set_int64(record->get_field_by_name("main_table_id"), region.main_table_id()); record->set_string(record->get_field_by_name("table_name"), table_name); record->set_int64(record->get_field_by_name("version"), region.version()); record->set_int64(record->get_field_by_name("conf_version"), region.conf_version()); record->set_int64(record->get_field_by_name("num_table_lines"), region.num_table_lines()); record->set_int64(record->get_field_by_name("used_size"), region.used_size()); record->set_string(record->get_field_by_name("leader"), region.leader()); record->set_string(record->get_field_by_name("peers"), boost::join(region.peers(), ",")); time_t t = region.timestamp(); struct tm t_result; localtime_r(&t, &t_result); char s[100]; strftime(s, sizeof(s), "%F %T", &t_result); record->set_string(record->get_field_by_name("create_time"), s); record->set_string(record->get_field_by_name("start_key"), start_key.decode_start_key_string(*index_ptr)); record->set_string(record->get_field_by_name("end_key"), end_key.decode_start_key_string(*index_ptr)); records.emplace_back(record); } return records; }; } // MYSQLๅ…ผๅฎน่กจ void InformationSchema::init_columns() { // ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"TABLE_CATALOG", pb::STRING}, {"TABLE_SCHEMA", pb::STRING}, {"TABLE_NAME", pb::STRING}, {"COLUMN_NAME", pb::STRING}, {"ORDINAL_POSITION", pb::INT64}, {"COLUMN_DEFAULT", pb::STRING}, {"IS_NULLABLE", pb::STRING}, {"DATA_TYPE", pb::STRING}, {"CHARACTER_MAXIMUM_LENGTH", pb::INT64}, {"CHARACTER_OCTET_LENGTH", pb::INT64}, {"NUMERIC_PRECISION", pb::INT64}, {"NUMERIC_SCALE", pb::INT64}, {"DATETIME_PRECISION", pb::INT64}, {"CHARACTER_SET_NAME", pb::STRING}, {"COLLATION_NAME", pb::STRING}, {"COLUMN_TYPE", pb::STRING}, {"COLUMN_KEY", pb::STRING}, {"EXTRA", pb::STRING}, {"PRIVILEGES", pb::STRING}, {"COLUMN_COMMENT", pb::STRING}, }; int64_t table_id = construct_table("COLUMNS", fields); // ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) -> std::vector<SmartRecord> { std::vector<SmartRecord> records; if (state->client_conn() == nullptr) { return records; } std::string namespace_ = state->client_conn()->user_info->namespace_; std::string table_name; auto* factory = SchemaFactory::get_instance(); auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get()); records.reserve(tb_vec.size() * 10); for (auto& table_info : tb_vec) { int i = 0; std::vector<std::string> items; boost::split(items, table_info->name, boost::is_any_of(".")); std::string db = items[0]; std::multimap<int32_t, IndexInfo> field_index; for (auto& index_id : table_info->indices) { IndexInfo index_info = factory->get_index_info(index_id); for (auto& field : index_info.fields) { field_index.insert(std::make_pair(field.id, index_info)); } } for (auto& field : table_info->fields) { if (field.deleted) { continue; } auto record = factory->new_record(table_id); record->set_string(record->get_field_by_name("TABLE_CATALOG"), "def"); record->set_string(record->get_field_by_name("TABLE_SCHEMA"), db); record->set_string(record->get_field_by_name("TABLE_NAME"), table_info->short_name); record->set_string(record->get_field_by_name("COLUMN_NAME"), field.short_name); record->set_int64(record->get_field_by_name("ORDINAL_POSITION"), ++i); record->set_string(record->get_field_by_name("COLUMN_DEFAULT"), field.default_value); record->set_string(record->get_field_by_name("IS_NULLABLE"), field.can_null ? "YES" : "NO"); record->set_string(record->get_field_by_name("DATA_TYPE"), to_mysql_type_string(field.type)); switch (field.type) { case pb::STRING: record->set_int64(record->get_field_by_name("CHARACTER_MAXIMUM_LENGTH"), 1048576); record->set_int64(record->get_field_by_name("CHARACTER_OCTET_LENGTH"), 3145728); break; case pb::INT8: case pb::UINT8: record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 3); record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0); break; case pb::INT16: case pb::UINT16: record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 5); record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0); break; case pb::INT32: case pb::UINT32: record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 10); record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0); break; case pb::INT64: record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 19); record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0); break; case pb::UINT64: record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 20); record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 0); break; case pb::FLOAT: record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 38); record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 6); break; case pb::DOUBLE: record->set_int64(record->get_field_by_name("NUMERIC_SCALE"), 308); record->set_int64(record->get_field_by_name("NUMERIC_PRECISION"), 15); break; case pb::DATETIME: case pb::TIMESTAMP: case pb::DATE: record->set_int64(record->get_field_by_name("DATETIME_PRECISION"), 0); break; default: break; } record->set_string(record->get_field_by_name("CHARACTER_SET_NAME"), "utf8"); record->set_string(record->get_field_by_name("COLLATION_NAME"), "utf8_general_ci"); record->set_string(record->get_field_by_name("COLUMN_TYPE"), to_mysql_type_full_string(field.type)); std::vector<std::string> extra_vec; if (field_index.count(field.id) == 0) { record->set_string(record->get_field_by_name("COLUMN_KEY"), " "); } else { std::vector<std::string> index_types; index_types.reserve(4); auto range = field_index.equal_range(field.id); for (auto index_iter = range.first; index_iter != range.second; ++index_iter) { auto& index_info = index_iter->second; std::string index = pb::IndexType_Name(index_info.type); if (index_info.type == pb::I_FULLTEXT) { index += "(" + pb::SegmentType_Name(index_info.segment_type) + ")"; } index_types.push_back(index); extra_vec.push_back(pb::IndexState_Name(index_info.state)); } record->set_string(record->get_field_by_name("COLUMN_KEY"), boost::algorithm::join(index_types, "|")); } if (table_info->auto_inc_field_id == field.id) { extra_vec.push_back("auto_increment"); } else { //extra_vec.push_back(" "); } record->set_string(record->get_field_by_name("EXTRA"), boost::algorithm::join(extra_vec, "|")); record->set_string(record->get_field_by_name("PRIVILEGES"), "select,insert,update,references"); record->set_string(record->get_field_by_name("COLUMN_COMMENT"), field.comment); records.emplace_back(record); } } return records; }; } void InformationSchema::init_referential_constraints() { // ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"CONSTRAINT_CATALOG", pb::STRING}, {"CONSTRAINT_SCHEMA", pb::STRING}, {"CONSTRAINT_NAME", pb::STRING}, {"UNIQUE_CONSTRAINT_CATALOG", pb::STRING}, {"UNIQUE_CONSTRAINT_SCHEMA", pb::STRING}, {"UNIQUE_CONSTRAINT_NAME", pb::STRING}, {"MATCH_OPTION", pb::STRING}, {"UPDATE_RULE", pb::STRING}, {"DELETE_RULE", pb::STRING}, {"TABLE_NAME", pb::STRING}, {"REFERENCED_TABLE_NAME", pb::STRING} }; int64_t table_id = construct_table("REFERENTIAL_CONSTRAINTS", fields); // ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) -> std::vector<SmartRecord> { std::vector<SmartRecord> records; return records; }; } void InformationSchema::init_key_column_usage() { // ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"CONSTRAINT_CATALOG", pb::STRING}, {"CONSTRAINT_SCHEMA", pb::STRING}, {"CONSTRAINT_NAME", pb::STRING}, {"TABLE_CATALOG", pb::STRING}, {"TABLE_SCHEMA", pb::STRING}, {"TABLE_NAME", pb::STRING}, {"COLUMN_NAME", pb::STRING}, {"ORDINAL_POSITION", pb::INT64}, {"POSITION_IN_UNIQUE_CONSTRAINT", pb::INT64}, {"REFERENCED_TABLE_SCHEMA", pb::STRING}, {"REFERENCED_TABLE_NAME", pb::STRING}, {"REFERENCED_COLUMN_NAME", pb::STRING} }; int64_t table_id = construct_table("KEY_COLUMN_USAGE", fields); // ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) -> std::vector<SmartRecord> { std::vector<SmartRecord> records; if (state->client_conn() == nullptr) { return records; } std::string namespace_ = state->client_conn()->user_info->namespace_; std::string table_name; auto* factory = SchemaFactory::get_instance(); auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get()); records.reserve(tb_vec.size() * 10); for (auto& table_info : tb_vec) { int i = 0; std::vector<std::string> items; boost::split(items, table_info->name, boost::is_any_of(".")); std::string db = items[0]; std::multimap<int32_t, IndexInfo> field_index; for (auto& index_id : table_info->indices) { IndexInfo index_info = factory->get_index_info(index_id); auto index_type = index_info.type; if (index_type != pb::I_PRIMARY && index_type != pb::I_UNIQ) { continue; } int idx = 0; for (auto& field : index_info.fields) { idx ++; auto record = factory->new_record(table_id); record->set_string(record->get_field_by_name("CONSTRAINT_CATALOG"), "def"); record->set_string(record->get_field_by_name("CONSTRAINT_SCHEMA"), db); record->set_string(record->get_field_by_name("CONSTRAINT_NAME"), index_type == pb::I_PRIMARY ? "PRIMARY":"name_key"); record->set_string(record->get_field_by_name("TABLE_CATALOG"), "def"); record->set_string(record->get_field_by_name("TABLE_SCHEMA"), db); record->set_string(record->get_field_by_name("TABLE_NAME"), table_info->short_name); record->set_string(record->get_field_by_name("COLUMN_NAME"), field.short_name); record->set_int64(record->get_field_by_name("ORDINAL_POSITION"), idx); records.emplace_back(record); } } } return records; }; } void InformationSchema::init_statistics() { // ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"TABLE_CATALOG", pb::STRING}, {"TABLE_SCHEMA", pb::STRING}, {"TABLE_NAME", pb::STRING}, {"NON_UNIQUE", pb::STRING}, {"INDEX_SCHEMA", pb::STRING}, {"INDEX_NAME", pb::STRING}, {"SEQ_IN_INDEX", pb::INT64}, {"COLUMN_NAME", pb::STRING}, {"COLLATION", pb::STRING}, {"CARDINALITY", pb::INT64}, {"SUB_PART", pb::INT64}, {"PACKED", pb::STRING}, {"NULLABLE", pb::STRING}, {"INDEX_TYPE", pb::STRING}, {"COMMENT", pb::STRING}, {"INDEX_COMMENT", pb::STRING}, }; int64_t table_id = construct_table("STATISTICS", fields); // ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) -> std::vector<SmartRecord> { std::vector<SmartRecord> records; if (state->client_conn() == nullptr) { return records; } std::string namespace_ = state->client_conn()->user_info->namespace_; std::string table_name; auto* factory = SchemaFactory::get_instance(); auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get()); records.reserve(tb_vec.size() * 10); for (auto& table_info : tb_vec) { std::vector<std::string> items; boost::split(items, table_info->name, boost::is_any_of(".")); std::string db = items[0]; for (auto& index_id : table_info->indices) { auto index_ptr = factory->get_index_info_ptr(index_id); if (index_ptr == nullptr) { continue; } if (index_ptr->index_hint_status != pb::IHS_NORMAL) { continue; } int i = 0; for (auto& field : index_ptr->fields) { auto record = factory->new_record(table_id); record->set_string(record->get_field_by_name("TABLE_CATALOG"), "def"); record->set_string(record->get_field_by_name("TABLE_SCHEMA"), db); record->set_string(record->get_field_by_name("TABLE_NAME"), table_info->short_name); record->set_string(record->get_field_by_name("INDEX_SCHEMA"), db); std::string index_name = index_ptr->short_name; std::string index_type = "BTREE"; std::string non_unique = "0"; if (index_ptr->type == pb::I_PRIMARY) { index_name = "PRIMARY"; } else if (index_ptr->type == pb::I_KEY) { non_unique = "1"; } else if (index_ptr->type == pb::I_FULLTEXT) { non_unique = "1"; index_type = "FULLTEXT"; } record->set_string(record->get_field_by_name("INDEX_NAME"), index_name); record->set_string(record->get_field_by_name("COLUMN_NAME"), field.short_name); record->set_string(record->get_field_by_name("NON_UNIQUE"), non_unique); record->set_int64(record->get_field_by_name("SEQ_IN_INDEX"), i++); record->set_string(record->get_field_by_name("NULLABLE"), field.can_null ? "YES" : ""); record->set_string(record->get_field_by_name("COLLATION"), "A"); record->set_string(record->get_field_by_name("INDEX_TYPE"), index_type); record->set_string(record->get_field_by_name("INDEX_COMMENT"), index_ptr->comments); std::ostringstream comment; comment << "'{\"segment_type\":\""; comment << pb::SegmentType_Name(index_ptr->segment_type) << "\", "; comment << "\"storage_type\":\""; comment << pb::StorageType_Name(index_ptr->storage_type) << "\", "; comment << "\"is_global\":\"" << index_ptr->is_global << "\"}'"; record->set_string(record->get_field_by_name("COMMENT"), comment.str()); records.emplace_back(record); } } } return records; }; } void InformationSchema::init_schemata() { // ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"CATALOG_NAME", pb::STRING}, {"SCHEMA_NAME", pb::STRING}, {"DEFAULT_CHARACTER_SET_NAME", pb::STRING}, {"DEFAULT_COLLATION_NAME", pb::STRING}, {"SQL_PATH", pb::INT64}, }; int64_t table_id = construct_table("SCHEMATA", fields); // ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) -> std::vector<SmartRecord> { std::vector<SmartRecord> records; if (state->client_conn() == nullptr) { return records; } auto* factory = SchemaFactory::get_instance(); std::vector<std::string> db_vec = factory->get_db_list(state->client_conn()->user_info->all_database); records.reserve(db_vec.size()); for (auto& db : db_vec) { auto record = factory->new_record(table_id); record->set_string(record->get_field_by_name("CATALOG_NAME"), "def"); record->set_string(record->get_field_by_name("SCHEMA_NAME"), db); record->set_string(record->get_field_by_name("DEFAULT_CHARACTER_SET_NAME"), "utf8mb4"); record->set_string(record->get_field_by_name("DEFAULT_COLLATION_NAME"), "utf8mb4_bin"); records.emplace_back(record); } return records; }; } void InformationSchema::init_tables() { // ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"TABLE_CATALOG", pb::STRING}, {"TABLE_SCHEMA", pb::STRING}, {"TABLE_NAME", pb::STRING}, {"TABLE_TYPE", pb::STRING}, {"ENGINE", pb::STRING}, {"VERSION", pb::INT64}, {"ROW_FORMAT", pb::STRING}, {"TABLE_ROWS", pb::INT64}, {"AVG_ROW_LENGTH", pb::INT64}, {"DATA_LENGTH", pb::INT64}, {"MAX_DATA_LENGTH", pb::INT64}, {"INDEX_LENGTH", pb::INT64}, {"DATA_FREE", pb::INT64}, {"AUTO_INCREMENT", pb::INT64}, {"CREATE_TIME", pb::DATETIME}, {"UPDATE_TIME", pb::DATETIME}, {"CHECK_TIME", pb::DATETIME}, {"TABLE_COLLATION", pb::STRING}, {"CHECKSUM", pb::INT64}, {"CREATE_OPTIONS", pb::STRING}, {"TABLE_COMMENT", pb::STRING}, {"TABLE_ID", pb::INT64}, }; int64_t table_id = construct_table("TABLES", fields); // ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) -> std::vector<SmartRecord> { std::vector<SmartRecord> records; if (state->client_conn() == nullptr) { return records; } std::string namespace_ = state->client_conn()->user_info->namespace_; std::string table_name; auto* factory = SchemaFactory::get_instance(); auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get()); records.reserve(tb_vec.size()); for (auto& table_info : tb_vec) { std::vector<std::string> items; boost::split(items, table_info->name, boost::is_any_of(".")); std::string db = items[0]; auto record = factory->new_record(table_id); record->set_string(record->get_field_by_name("TABLE_CATALOG"), "def"); record->set_string(record->get_field_by_name("TABLE_SCHEMA"), db); record->set_string(record->get_field_by_name("TABLE_NAME"), table_info->short_name); record->set_string(record->get_field_by_name("TABLE_TYPE"), "BASE TABLE"); record->set_string(record->get_field_by_name("ENGINE"), "Innodb"); record->set_int64(record->get_field_by_name("VERSION"), table_info->version); record->set_string(record->get_field_by_name("ROW_FORMAT"), "Compact"); record->set_int64(record->get_field_by_name("TABLE_ROWS"), 0); record->set_int64(record->get_field_by_name("AVG_ROW_LENGTH"), table_info->byte_size_per_record); record->set_int64(record->get_field_by_name("DATA_LENGTH"), 0); record->set_int64(record->get_field_by_name("MAX_DATA_LENGTH"), 0); record->set_int64(record->get_field_by_name("INDEX_LENGTH"), 0); record->set_int64(record->get_field_by_name("DATA_FREE"), 0); record->set_int64(record->get_field_by_name("AUTO_INCREMENT"), 0); ExprValue ct(pb::TIMESTAMP); ct._u.uint32_val = table_info->timestamp; record->set_value(record->get_field_by_name("CREATE_TIME"), ct.cast_to(pb::DATETIME)); record->set_string(record->get_field_by_name("TABLE_COLLATION"), "utf8_bin"); record->set_string(record->get_field_by_name("CREATE_OPTIONS"), ""); record->set_string(record->get_field_by_name("TABLE_COMMENT"), ""); record->set_int64(record->get_field_by_name("TABLE_ID"), table_info->id); records.emplace_back(record); } return records; }; } void InformationSchema::init_virtual_index_influence_info() { //ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"database_name",pb::STRING}, {"table_name",pb::STRING}, {"virtual_index_name",pb::STRING}, {"sign",pb::STRING}, {"sample_sql",pb::STRING}, }; int64_t table_id = construct_table("VIRTUAL_INDEX_AFFECT_SQL", fields); //ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state,std::vector<ExprNode*>& conditions) -> std::vector <SmartRecord> { std::vector <SmartRecord> records; //ๆ›ดๆ–ฐ่กจไธญๆ•ฐๆฎๅ‰๏ผŒ่ฆไบคไบ’ไธ€ๆฌก๏ผŒไปŽTableMemๅ–ๅฝฑๅ“้ขๆ•ฐๆฎ pb::QueryRequest request; pb::QueryResponse response; //1ใ€่ฎพๅฎšๆŸฅ่ฏข่ฏทๆฑ‚็š„ๆ“ไฝœ็ฑปๅž‹ request.set_op_type(pb::QUERY_SHOW_VIRINDX_INFO_SQL); //2ใ€ๅ‘้€่ฏทๆฑ‚ MetaServerInteract::get_instance()->send_request("query", request, response); //3.ๅ–ๅ‡บresponseไธญ็š„ๅฝฑๅ“้ขไฟกๆฏ auto& virtual_index_info_sqls = response.virtual_index_influence_info();//virtual_index_info and affected_sqls if(state -> client_conn() == nullptr){ return records; } std::string namespace_ = state->client_conn()->user_info->namespace_; std::string table_name; auto* factory = SchemaFactory::get_instance(); auto tb_vec = factory->get_table_list(namespace_, state->client_conn()->user_info.get()); records.reserve(tb_vec.size()); for (auto& it1 : virtual_index_info_sqls) { std::string key = it1.virtual_index_info(); std::string infuenced_sql = it1.affected_sqls(); std::string sign = it1.affected_sign(); std::vector<std::string> items1; boost::split(items1, key, boost::is_any_of(",")); auto record = factory->new_record(table_id); record->set_string(record->get_field_by_name("database_name"), items1[0]); record->set_string(record->get_field_by_name("table_name"), items1[1]); record->set_string(record->get_field_by_name("virtual_index_name"),items1[2]); record->set_string(record->get_field_by_name("sign"), sign); record->set_string(record->get_field_by_name("sample_sql"), infuenced_sql); records.emplace_back(record); } return records; }; } void InformationSchema::init_routines() { // ๅฎšไน‰ๅญ—ๆฎตไฟกๆฏ FieldVec fields { {"SPECIFIC_NAME", pb::STRING}, {"ROUTINE_CATALOG", pb::STRING}, {"ROUTINE_SCHEMA", pb::STRING}, {"ROUTINE_NAME", pb::STRING}, {"ROUTINE_TYPE", pb::STRING}, {"DATA_TYPE", pb::STRING}, {"CHARACTER_MAXIMUM_LENGTH", pb::INT64}, {"CHARACTER_OCTET_LENGTH", pb::INT64}, {"NUMERIC_PRECISION", pb::UINT64}, {"NUMERIC_SCALE", pb::INT64}, {"DATETIME_PRECISION", pb::UINT64}, {"CHARACTER_SET_NAME", pb::STRING}, {"COLLATION_NAME", pb::STRING}, {"DTD_IDENTIFIER", pb::STRING}, {"ROUTINE_BODY", pb::STRING}, {"ROUTINE_DEFINITION" , pb::STRING}, {"EXTERNAL_NAME" , pb::STRING}, {"EXTERNAL_LANGUAGE" , pb::STRING}, {"PARAMETER_STYLE", pb::STRING}, {"IS_DETERMINISTIC", pb::STRING}, {"SQL_DATA_ACCESS", pb::STRING}, {"SQL_PATH", pb::STRING}, {"SECURITY_TYPE", pb::STRING}, {"CREATED", pb::STRING}, {"LAST_ALTERED", pb::DATETIME}, {"SQL_MODE", pb::DATETIME}, {"ROUTINE_COMMENT", pb::STRING}, {"DEFINER", pb::STRING}, {"CHARACTER_SET_CLIENT", pb::STRING}, {"COLLATION_CONNECTION", pb::STRING}, {"DATABASE_COLLATION", pb::STRING}, }; int64_t table_id = construct_table("ROUTINES", fields); // ๅฎšไน‰ๆ“ไฝœ _calls[table_id] = [table_id](RuntimeState* state, std::vector<ExprNode*>& conditions) -> std::vector<SmartRecord> { std::vector<SmartRecord> records; return records; }; } } // namespace baikaldb
38,338
11,778
/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2016 Imperial College London * Copyright 2013-2016 Andreas Schuh * * 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 "mirtk/Mapping.h" #include "mirtk/Config.h" // WINDOWS #include "mirtk/Math.h" #include "mirtk/Memory.h" #include "mirtk/Cfstream.h" #include "mirtk/BaseImage.h" #include "mirtk/VoxelFunction.h" #include "mirtk/PointSetUtils.h" #include "vtkSmartPointer.h" #include "vtkPointSet.h" #include "vtkPolyData.h" #include "vtkImageData.h" #include "mirtk/PiecewiseLinearMap.h" #include "mirtk/MeshlessHarmonicMap.h" #include "mirtk/MeshlessBiharmonicMap.h" namespace mirtk { // ============================================================================= // Factory method // ============================================================================= // ----------------------------------------------------------------------------- Mapping *Mapping::New(const char *fname) { UniquePtr<Mapping> map; const size_t max_name_len = 32; char map_type_name[max_name_len]; Cifstream is(fname); is.ReadAsChar(map_type_name, max_name_len); if (strncmp(map_type_name, MeshlessHarmonicMap::NameOfType(), max_name_len) == 0) { map.reset(new MeshlessHarmonicMap()); } else if (strncmp(map_type_name, MeshlessBiharmonicMap::NameOfType(), max_name_len) == 0) { map.reset(new MeshlessBiharmonicMap()); } else { // Note that a picewise linear map is stored using a VTK file format and // therefore the map file contains no "mirtk::PiecewiseLinearMap" header. map.reset(new PiecewiseLinearMap()); } map->Read(fname); return map.release(); } // ============================================================================= // Auxiliary functors // ============================================================================= namespace MappingUtils { // ----------------------------------------------------------------------------- /// Evaluate map at lattice points class EvaluateMap : public VoxelFunction { const Mapping *_Map; vtkImageData *_Domain; const BaseImage *_Output; const int _NumberOfVoxels; const int _l1, _l2; public: EvaluateMap(const Mapping *map, vtkImageData *domain, const BaseImage *output, int l1, int l2) : _Map(map), _Domain(domain), _Output(output), _NumberOfVoxels(output->NumberOfSpatialVoxels()), _l1(l1), _l2(l2) {} template <class T> void operator ()(int i, int j, int k, int, T *v) const { if (!_Domain || _Domain->GetScalarComponentAsFloat(i, j, k, 0) != .0) { double x = i, y = j, z = k; _Output->ImageToWorld(x, y, z); double *f = new double[_Map->NumberOfComponents()]; _Map->Evaluate(f, x, y, z); for (int l = _l1; l < _l2; ++l, v += _NumberOfVoxels) { *v = f[l]; } delete[] f; } else { for (int l = _l1; l < _l2; ++l, v += _NumberOfVoxels) { *v = numeric_limits<T>::quiet_NaN(); } } } }; } // namespace MappingUtils using namespace MappingUtils; // ============================================================================= // Construction/Destruction // ============================================================================= // ----------------------------------------------------------------------------- void Mapping::CopyAttributes(const Mapping &other) { _OutsideValue = other._OutsideValue; } // ----------------------------------------------------------------------------- Mapping::Mapping() : _OutsideValue(mirtk::nan) { } // ----------------------------------------------------------------------------- Mapping::Mapping(const Mapping &other) : Object(other) { CopyAttributes(other); } // ----------------------------------------------------------------------------- Mapping &Mapping::operator =(const Mapping &other) { if (this != &other) { Object::operator =(other); CopyAttributes(other); } return *this; } // ----------------------------------------------------------------------------- void Mapping::Initialize() { } // ----------------------------------------------------------------------------- Mapping::~Mapping() { } // ============================================================================= // Map domain // ============================================================================= // ----------------------------------------------------------------------------- ImageAttributes Mapping::Attributes(int nx, int ny, int nz) const { if (this->NumberOfArguments() >= 2) { if (ny <= 0) ny = nx; } else { ny = 0; } if (this->NumberOfArguments() >= 3) { if (nz <= 0) nz = nx; } else { nz = 0; } double x1, y1, z1, x2, y2, z2; this->BoundingBox(x1, y1, z1, x2, y2, z2); const double lx = x2 - x1; const double ly = y2 - y1; const double lz = z2 - z1; ImageAttributes lattice; lattice._xorigin = x1 + .5 * lx; lattice._yorigin = y1 + .5 * ly; lattice._zorigin = z1 + .5 * lz; lattice._x = nx; lattice._y = ny; lattice._z = nz; lattice._dx = (lattice._x == 0 ? .0 : lx / nx); lattice._dy = (lattice._y == 0 ? .0 : ly / ny); lattice._dz = (lattice._z == 0 ? .0 : lz / nz); if (lattice._x == 0) lattice._x = 1; if (lattice._y == 0) lattice._y = 1; if (lattice._z == 0) lattice._z = 1; return lattice; } // ----------------------------------------------------------------------------- ImageAttributes Mapping::Attributes(double dx, double dy, double dz) const { double x1, y1, z1, x2, y2, z2; this->BoundingBox(x1, y1, z1, x2, y2, z2); const double lx = x2 - x1; const double ly = y2 - y1; const double lz = z2 - z1; if (dx <= .0) { dx = sqrt(lx*lx + ly*ly + lz*lz) / 256; } if (this->NumberOfArguments() >= 2) { if (dy <= .0) dy = dx; } else { dy = 0; } if (this->NumberOfArguments() >= 3) { if (dz <= .0) dz = dx; } else { dz = 0; } ImageAttributes lattice; lattice._xorigin = x1 + .5 * lx; lattice._yorigin = y1 + .5 * ly; lattice._zorigin = z1 + .5 * lz; lattice._x = iceil(lx / dx); lattice._y = iceil(ly / dy); lattice._z = iceil(lz / dz); lattice._dx = (lattice._x == 0 ? .0 : dx); lattice._dy = (lattice._y == 0 ? .0 : dy); lattice._dz = (lattice._z == 0 ? .0 : dz); if (lattice._x == 0) lattice._x = 1; if (lattice._y == 0) lattice._y = 1; if (lattice._z == 0) lattice._z = 1; return lattice; } // ============================================================================= // Evaluation // ============================================================================= // ----------------------------------------------------------------------------- void Mapping::Evaluate(GenericImage<float> &f, int l, vtkSmartPointer<vtkPointSet> m) const { ImageAttributes lattice = f.Attributes(); lattice._dt = .0; if (l >= NumberOfComponents() || l + lattice._t > NumberOfComponents()) { cerr << this->NameOfType() << "::Evaluate: Component index out of range" << endl; exit(1); } vtkSmartPointer<vtkImageData> mask; if (m) { mask = NewVtkMask(lattice._x, lattice._y, lattice._z); ImageStencilToMask(ImageStencil(mask, WorldToImage(m, &f)), mask); } ParallelForEachVoxel(EvaluateMap(this, mask, &f, l, l + lattice._t), lattice, f); } // ----------------------------------------------------------------------------- void Mapping::Evaluate(GenericImage<double> &f, int l, vtkSmartPointer<vtkPointSet> m) const { ImageAttributes lattice = f.Attributes(); lattice._dt = .0; if (l >= NumberOfComponents() || l + lattice._t > NumberOfComponents()) { cerr << this->NameOfType() << "::Evaluate: Component index out of range" << endl; exit(1); } vtkSmartPointer<vtkImageData> mask; if (m) { mask = NewVtkMask(lattice._x, lattice._y, lattice._z); ImageStencilToMask(ImageStencil(mask, WorldToImage(m, &f)), mask); } ParallelForEachVoxel(EvaluateMap(this, mask, &f, l, l + lattice._t), lattice, f); } // ============================================================================= // I/O // ============================================================================= // ----------------------------------------------------------------------------- bool Mapping::Read(const char *fname) { Cifstream is(fname); const size_t max_name_len = 32; char map_type_name[max_name_len]; is.ReadAsChar(map_type_name, max_name_len); if (strncmp(map_type_name, this->NameOfClass(), max_name_len) != 0) { return false; } this->ReadMap(is); this->Initialize(); return true; } // ----------------------------------------------------------------------------- bool Mapping::Write(const char *fname) const { Cofstream os(fname); const size_t max_name_len = 32; char map_type_name[max_name_len] = {0}; #ifdef WINDOWS strncpy_s(map_type_name, max_name_len, this->NameOfClass(), max_name_len); #else strncpy(map_type_name, this->NameOfClass(), max_name_len); #endif os.WriteAsChar(map_type_name, max_name_len); this->WriteMap(os); return true; } // ----------------------------------------------------------------------------- void Mapping::ReadMap(Cifstream &) { cerr << this->NameOfClass() << "::ReadMap not implemented" << endl; exit(1); } // ----------------------------------------------------------------------------- void Mapping::WriteMap(Cofstream &) const { cerr << this->NameOfClass() << "::WriteMap not implemented" << endl; exit(1); } } // namespace mirtk
10,152
3,359
//---------------------------------------------------------------------------// // MIT License // // Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation> // Copyright (c) 2020-2021 Nikita Kaskov <nemo@nil.foundation> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //---------------------------------------------------------------------------// #ifndef FILECOIN_STORAGE_PROOFS_POST_ELECTION_VANILLA_HPP #define FILECOIN_STORAGE_PROOFS_POST_ELECTION_VANILLA_HPP #include <boost/log/trivial.hpp> #include <nil/crypto3/hash/sha2.hpp> #include <algorithm> #include <nil/filecoin/storage/proofs/core/merkle/proof.hpp> #include <nil/filecoin/storage/proofs/core/btree/map.hpp> #include <nil/filecoin/storage/proofs/core/parameter_cache.hpp> #include <nil/filecoin/storage/proofs/core/sector.hpp> namespace nil { namespace filecoin { namespace post { namespace election { struct SetupParams { /// Size of the sector in bytes. std::uint64_t sector_size; std::size_t challenge_count; std::size_t challenged_nodes; }; struct PublicParams : public parameter_set_metadata { virtual std::string identifier() const override { return "ElectionPoSt::PublicParams{{sector_size: " + sector_size + ", count: " + challenge_count + ", nodes: " + challenged_nodes + "}}"; } /// Size of the sector in bytes. std::uint64_t sector_size; std::size_t challenge_count; std::size_t challenged_nodes; }; template<typename Domain> struct PublicInputs { Domain randomness; sector_id_type sector_id; Domain prover_id; Domain comm_r; Fr partial_ticket; std::uint64_t sector_challenge_index; }; template<typename MerkleTreeType> struct PrivateInputs { MerkleTreeWrapper<typename MerkleTreeType::hash_type, MerkleTreeType::Store, MerkleTreeType::base_arity, MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity> tree; typename MerkleTreeType::hash_type::digest_type comm_c; typename MerkleTreeType::hash_type::digest_type comm_r_last; }; struct Candidate { sector_id_type sector_id; Fr partial_ticket; std::array<std::uint8_t, 32> ticket; std::uint64_t sector_challenge_index; }; template<typename BasicMerkleProof> struct Proof { std::vector<typename BasicMerkleProof::hash_type::digest_type> leafs() { std::vector<typename BasicMerkleProof::hash_type::digest_type> result; for (const auto &proof : inclusion_proofs) { result.emplace_back(proof.leaf()); } return result; } typename BasicMerkleProof::hash_type::digest_type comm_r_last() { return inclusion_proofs[0].root(); } std::vector<typename BasicMerkleProof::hash_type::digest_type> commitments() { std::vector<typename BasicMerkleProof::hash_type::digest_type> result; for (const auto &proof : inclusion_proofs) { result.emplace_back(proof.root()); } return result; } std::vector<std::vector< std::pair<std::vector<typename BasicMerkleProof::hash_type::digest_type>, std::size_t>>> paths() { std::vector<std::vector< std::pair<std::vector<typename BasicMerkleProof::hash_type::digest_type>, std::size_t>>> result; for (const auto &proof : inclusion_proofs) { result.emplace_back(proof.path()); } return result; } std::vector<merkletree::MerkleProof<typename BasicMerkleProof::hash, BasicMerkleProof::BaseArity, BasicMerkleProof::SubTreeArity, BasicMerkleProof::TopTreeArity>> inclusion_proofs; std::array<std::uint8_t, 32> ticket; typename BasicMerkleProof::hash_type::digest_type comm_c; }; template<typename MerkleTreeType> class ElectionPoSt : public proof_scheme< PublicParams, SetupParams, PublicInputs<typename MerkleTreeType::hash_type::digest_type>, PrivateInputs<MerkleTreeType>, Proof<typename MerkleTreeType::proof_type>, no_requirements> { typedef proof_scheme< PublicParams, SetupParams, PublicInputs<typename MerkleTreeType::hash_type::digest_type>, PrivateInputs<MerkleTreeType>, Proof<typename MerkleTreeType::proof_type>, no_requirements> policy_type; public: typedef typename policy_type::public_params_type public_params_type; typedef typename policy_type::setup_params setup_params_type; typedef typename policy_type::public_inputs public_inputs_type; typedef typename policy_type::private_inputs private_inputs_type; typedef typename policy_type::proof_type proof_type; typedef typename policy_type::requirements_type requirements_type; virtual public_params_type setup(const setup_params_type &p) override { return {p.sector_size, p.challenge_count, p.challenged_nodes}; } virtual proof_type prove(const public_params_type &params, const public_inputs_type &inputs, const private_inputs_type &pinputs) override { // 1. Inclusions proofs of all challenged leafs in all challenged ranges const auto tree = pinputs.tree; std::size_t tree_leafs = tree.leafs(); BOOST_LOG_TRIVIAL(trace) << std::format("Generating proof for tree of len {} with leafs {}", tree.len(), tree_leafs); const auto inclusion_proofs = (0..pub_params.challenge_count) .into_par_iter() .flat_map( | n | { // TODO: replace unwrap with proper error handling const auto challenged_leaf_start = generate_leaf_challenge( pub_params, pub_inputs.randomness, pub_inputs.sector_challenge_index, std::uint64_t(n)); (0..pub_params.challenged_nodes) .into_par_iter() .map(move | i | {tree.gen_cached_proof(std::uint(challenged_leaf_start) + i, None)}) }) .collect::<Result<Vec<_>>>(); // 2. correct generation of the ticket from the partial_ticket (add this to the candidate) const auto ticket = finalize_ticket(inputs.partial_ticket); return {inclusion_proofs, ticket, pinputs.comm_c}; } virtual bool verify(const public_params_type &pub_params, const public_inputs_type &pub_inputs, const proof_type &pr) override { // verify that H(Comm_c || Comm_r_last) == Comm_R // comm_r_last is the root of the proof const auto comm_r_last = pr.inclusion_proofs[0].root(); const auto comm_c = pr.comm_c; const auto comm_r = &pub_inputs.comm_r; if (AsRef ::<[u8]>::as_ref(&<typename MerkleTreeType::hash_type>::Function::hash2( &comm_c, &comm_r_last, )) != AsRef::<[u8]>::as_ref(comm_r)) { return false; } for (int n = 0; n < pub_params.challenge_count; n++) { const auto challenged_leaf_start = generate_leaf_challenge( pub_params, pub_inputs.randomness, pub_inputs.sector_challenge_index, n); for (int i = 0; i < pub_params.challenged_nodes; i++) { const auto merkle_proof = &proof.inclusion_proofs[n * pub_params.challenged_nodes + i]; // validate all comm_r_lasts match if (merkle_proof.root() != comm_r_last) { return false; } // validate the path length const auto expected_path_length = merkle_proof.expected_len(pub_params.sector_size / NODE_SIZE); if (expected_path_length != merkle_proof.path().size()) { return false; } if (!merkle_proof.validate(challenged_leaf_start + i)) { return false; } } } return true; } }; template<typename MerkleTreeType> std::vector<Candidate> generate_candidates( const PublicParams &pub_params, const std::vector<sector_id_type> &challenged_sectors, const btree::map<sector_id_type, MerkleTreeWrapper<typename MerkleTreeType::hash_type, typename MerkleTreeType::store_type, MerkleTreeType::BaseArity, MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>> &trees, const typename MerkleTreeType::hash_type::digest_type &prover_id, const typename MerkleTreeType::hash_type::digest_type &randomness) { challenged_sectors.par_iter() .enumerate() .map(| (sector_challenge_index, sector_id) | { auto tree; switch (trees.get(sector_id)) { case Some(tree): tree = tree; break; case None: tree = bail !(Error::MissingPrivateInput("tree", (*sector_id).into())); break; }; generate_candidate::<Tree>(pub_params, tree, prover_id, *sector_id, randomness, std::uint64_t(sector_challenge_index), ) }) .collect() } template<typename MerkleTreeType> Candidate generate_candidate( const PublicParams &pub_params, const MerkleTreeWrapper<typename MerkleTreeType::hash_type, typename MerkleTreeType::store_type, MerkleTreeType::BaseArity, MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity> &tree, const typename MerkleTreeType::hash_type::digest_type &prover_id, sector_id_type sector_id, const typename MerkleTreeType::hash_type::digest_type &randomness, std::uint64_t sector_challenge_index) { Fr randomness_fr = randomness.into(); Fr prover_id_fr = prover_id.into(); std::vector<MerkleTreeType::hash_type::digest_type> data = { randomness_fr.into(), prover_id_fr.into(), Fr::from(sector_id).into()}; for (int n = 0; n < pub_params.challenge_count; n++) { const auto challenge = generate_leaf_challenge(pub_params, randomness, sector_challenge_index, n); Fr val = tree.read_at(challenge as usize).into(); data.push_back(val.into()); } // pad for md std::size_t arity = PoseidonMDArity; while (data.size() % arity) { data.push(MerkleTreeType::hash_type::digest_type::default()); } Fr partial_ticket = PoseidonFunction::hash_md(&data).into(); // ticket = sha256(partial_ticket) std::array<std::uint8_t, 32> ticket = finalize_ticket(&partial_ticket); return {sector_challenge_index, sector_id, partial_ticket, ticket}; } template<typename FinalizationHash = crypto3::hashes::sha2<256>> std::array<std::uint8_t, 32> finalize_ticket(const Fr &partial_ticket) { const auto bytes = fr_into_bytes(partial_ticket); const auto ticket_hash = Sha256::digest(&bytes); std::array<std::uint8_t, 32> ticket; ticket.fill(0); ticket.copy_from_slice(&ticket_hash[..]); return ticket; } bool is_valid_sector_challenge_index(std::uint64_t challenge_count, std::uint64_t index) { return index < challenge_count; } template<typename Domain, typename FinalizationHash = crypto3::hashes::sha2<256>> sector_id_type generate_sector_challenge(const Domain &randomness, std::size_t n, const ordered_sector_set &sectors) { using namespace crypto3::hashes; accumulator_set<FinalizationHash> acc; hash<FinalizationHash>(randomness, acc); hash<FinalizationHash>(n, acc); const auto hash = accumulators::extract<FinalizationHash>(acc); const auto sector_challenge = LittleEndian::read_u64(&hash[..8]); std::uint sector_index = (std::uint64_t(sector_challenge % sectors.size())); const auto sector = *sectors.iter().nth(sector_index).context("invalid challenge generated"); return sector; } template<typename Domain> std::vector<sector_id_type> generate_sector_challenges(const Domain &randomness, std::uint64_t challenge_count, const ordered_sector_set &sectors) { std::vector<sector_id_type> result(challenge_count); for (int i = 0; i < challenge_count; i++) { result[i] = generate_sector_challenge(randomness, i, sectors); } return result; } /// Generate all challenged leaf ranges for a single sector, such that the range fits into the sector. template<typename Domain> std::vector<std::uint64_t> generate_leaf_challenges(const PublicParams &pub_params, const Domain &randomness, std::uint64_t sector_challenge_index, std::size_t challenge_count) { std::vector<std::uint64_t> challenges(challenge_count); for (int leaf_challenge_index = 0; leaf_challenge_index < challenge_count; leaf_challenge_index++) { challenges.emplace_back(generate_leaf_challenge(pub_params, randomness, sector_challenge_index, leaf_challenge_index)); } return challenges; } /// Generates challenge, such that the range fits into the sector. template<typename Domain, typename LeafHash = crypto3::hashes::sha2<256>> std::uint64_t generate_leaf_challenge(const PublicParams &pub_params, const Domain &randomness, std::uint64_t sector_challenge_index, std::uint64_t leaf_challenge_index) { BOOST_ASSERT_MSG(pub_params.sector_size > pub_params.challenged_nodes * NODE_SIZE, "sector size is too small"); auto hasher = Sha256(); hasher.input(AsRef::<[u8]>::as_ref(&randomness)); hasher.input(&sector_challenge_index.to_le_bytes()[..]); hasher.input(&leaf_challenge_index.to_le_bytes()[..]); const auto hash = hasher.result(); const auto leaf_challenge = LittleEndian::read_u64(&hash[..8]); std::uint64_t challenged_range_index = leaf_challenge % (pub_params.sector_size / (pub_params.challenged_nodes * NODE_SIZE)); return challenged_range_index * pub_params.challenged_nodes; } } // namespace election } // namespace post } // namespace filecoin } // namespace nil #endif
20,088
5,150
// // LoadedModel.cpp // martian-terrain // // Created by Sidharth Mishra on 5/20/18. // #include "LoadedModel.h" using namespace sidmishraw_model; using namespace std; LoadedModel::LoadedModel():ofNode() { } LoadedModel::LoadedModel(string modelName, bool optimize):ofNode() { this->model = ofxAssimpModelLoader(); this->model.loadModel(modelName); this->model.setScaleNormalization(false); } bool LoadedModel::loadModel(string modelName, bool optimize) { return this->model.loadModel(modelName); } void LoadedModel::update() { this->model.update(); } bool LoadedModel::hasAnimations() { return this->model.hasAnimations(); } void LoadedModel::playAllAnimations() { this->model.playAllAnimations(); } void LoadedModel::stopAllAnimations() { this->model.stopAllAnimations(); } void LoadedModel::resetAllAnimations() { this->model.resetAllAnimations(); } bool LoadedModel::hasMeshes() { return this->model.hasMeshes(); } unsigned int LoadedModel::getMeshCount() { return this->model.getMeshCount(); } void LoadedModel::clear() { this->model.clear(); } void LoadedModel::setScale(float x, float y, float z) { this->model.setScale(x, y, z); } void LoadedModel::setScale(ofVec3f scaleVector) { this->setScale(scaleVector.x, scaleVector.y, scaleVector.z); } void LoadedModel::setPosition(float x, float y, float z) { this->model.setPosition(x, y, z); } void LoadedModel::setPosition(ofVec3f posVector) { this->setPosition(posVector.x, posVector.y, posVector.z); } void LoadedModel::setRotation(int which, float angle, float rot_x, float rot_y, float rot_z) { this->model.setRotation(which, angle, rot_x, rot_y, rot_z); } void LoadedModel::setScaleNormalization(bool normalize) { this->model.setScaleNormalization(normalize); } void LoadedModel::setNormalizationFactor(float factor) { this->model.setNormalizationFactor(factor); } vector<string> LoadedModel::getMeshNames() { return this->model.getMeshNames(); } int LoadedModel::getNumMeshes() { return this->model.getNumMeshes(); } ofMesh LoadedModel::getMesh(string name) { return this->model.getMesh(name); } ofMesh LoadedModel::getMesh(int num) { return this->model.getMesh(num); } void LoadedModel::drawWireframe() { this->model.drawWireframe(); } void LoadedModel::drawFaces() { this->model.drawFaces(); } void LoadedModel::drawVertices() { this->model.drawVertices(); } void LoadedModel::enableTextures() { this->model.enableTextures(); } void LoadedModel::disableTextures() { this->model.disableTextures(); } void LoadedModel::enableNormals() { this->model.enableNormals(); } void LoadedModel::disableNormals() { this->model.disableNormals(); } void LoadedModel::enableMaterials() { this->model.enableMaterials(); } void LoadedModel::disableMaterials() { this->model.disableMaterials(); } void LoadedModel::enableColors() { this->model.enableColors(); } void LoadedModel::disableColors() { this->model.disableColors(); } void LoadedModel::draw(ofPolyRenderMode renderType) { this->model.draw(renderType); } ofPoint LoadedModel::getPosition() { return this->model.getPosition(); } ofPoint LoadedModel::getSceneCenter() { return this->model.getSceneCenter(); } float LoadedModel::getNormalizedScale() { return this->model.getNormalizedScale(); } ofVec3f LoadedModel::getScale() { return this->model.getScale(); } ofMatrix4x4 LoadedModel::getTransformMatrix() { return this->model.getModelMatrix(); } ofVec3f LoadedModel::getSceneMin(bool bScaled) { return this->model.getSceneMin(bScaled); } ofVec3f LoadedModel::getSceneMax(bool bScaled) { return this->model.getSceneMax(bScaled); } int LoadedModel::getNumRotations() { return this->model.getNumRotations(); } ofVec3f LoadedModel::getRotationAxis(int which) { return this->model.getRotationAxis(which); } float LoadedModel::getRotationAngle(int which) { return this->model.getRotationAngle(which); } void LoadedModel::calculateDimensions() { this->model.calculateDimensions(); }
4,027
1,414
// Licensed under the BSD license. See LICENSE.txt for more details. #include "gmock/gmock.h" #include "gtest/gtest.h" #include "runtime/buffer.h" using namespace ::testing; using namespace ::std; namespace physis { namespace runtime { TEST(BufferHost, EnsureCapacity) { BufferHost buf; size_t s = 100; buf.EnsureCapacity(s); EXPECT_EQ(buf.size(), s); } TEST(BufferHost, Copyout2D) { BufferHost buf; int s = 4*4; buf.EnsureCapacity(s*sizeof(int)); int *p = (int*)buf.Get(); for (int i = 0; i < s; ++i) { p[i] = i; } int q[4]; buf.Copyout(sizeof(int), 2, IndexArray(4,4), q, IndexArray(0,0), IndexArray(4,1)); for (int i = 0; i < 4; ++i) { EXPECT_EQ(q[i], i); } buf.Copyout(sizeof(int), 2, IndexArray(4,4), q, IndexArray(1,0), IndexArray(1,4)); for (int i = 0; i < 4; ++i) { EXPECT_EQ(q[i], i*4+1); } buf.Copyout(sizeof(int), 2, IndexArray(4,4), q, IndexArray(1,1), IndexArray(2,2)); int k = 0; for (int i = 1; i < 3; ++i) { for (int j = 1; j < 3; ++j) { EXPECT_EQ(j+i*4, q[k]); ++k; } } } TEST(BufferHost, Copyin2D) { BufferHost buf; int s = 4*4; buf.EnsureCapacity(s*sizeof(int)); int p[s]; int q[s]; for (int i = 0; i < s; ++i) { p[i] = 0; } buf.CopyinAll(p); for (int i = 0; i < s; ++i) { p[i] = i; } buf.Copyin(sizeof(int), 2, IndexArray(4,4), p, IndexArray(0,0), IndexArray(4,1)); buf.CopyoutAll(q); for (int i = 0; i < 4; ++i) { EXPECT_EQ(q[i], i); } buf.Copyin(sizeof(int), 2, IndexArray(4,4), p, IndexArray(1,0), IndexArray(1,4)); buf.CopyoutAll(q); for (int j = 0; j < 4; ++j) { for (int i = 1; i < 2; ++i) { EXPECT_EQ(q[i+j*4], i-1+j); } } buf.Copyin(sizeof(int), 2, IndexArray(4,4), p, IndexArray(1,1), IndexArray(2,2)); buf.CopyoutAll(q); for (int j = 1; j < 3; ++j) { for (int i = 1; i < 3; ++i) { EXPECT_EQ(q[i+j*4], i - 1 + 2 * (j-1)); } } } TEST(BufferHost, Copyout3D) { BufferHost buf; int rank = 3; IndexArray size(3, 4, 5); int ne = size.accumulate(rank); buf.EnsureCapacity(ne*sizeof(int)); int *p = (int*)buf.Get(); for (int i = 0; i < ne; ++i) { p[i] = i; } int q[ne]; buf.Copyout(sizeof(int), rank, size, q, IndexArray(0,0,0), IndexArray(3, 1 ,1)); for (int i = 0; i < 3; ++i) { EXPECT_EQ(q[i], i); } buf.Copyout(sizeof(int), rank, size, q, IndexArray(1,0,0), IndexArray(1, 4 ,1)); for (int i = 0; i < 4; ++i) { EXPECT_EQ(q[i], 1+i*3); } buf.Copyout(sizeof(int), rank, size, q, IndexArray(0,0,0), IndexArray(1, 4 ,5)); int k = 0; for (int i = 0; i < 5; ++i) { for (int j = 0; j < 4; ++j) { EXPECT_EQ(q[k], j*3+i*3*4); ++k; } } buf.Copyout(sizeof(int), rank, size, q, IndexArray(1,0,0), IndexArray(2, 4 ,5)); k = 0; for (int i = 0; i < 5; ++i) { for (int j = 0; j < 4; ++j) { for (int l = 1; l < 3; ++l) { EXPECT_EQ(q[k], l+j*3+i*3*4); ++k; } } } } TEST(BufferHost, Copyin3D) { BufferHost buf; int rank = 3; IndexArray size(3, 4, 5); int ne = size.accumulate(rank); buf.EnsureCapacity(ne*sizeof(int)); int p[ne]; int q[ne]; for (int i = 0; i < ne; ++i) { p[i] = 0; } buf.CopyinAll(p); for (int i = 0; i < ne; ++i) { p[i] = i; } buf.Copyin(sizeof(int), rank, size, p, IndexArray(0,0,0), IndexArray(3, 1 ,1)); buf.CopyoutAll(q); for (int i = 0; i < 3; ++i) { EXPECT_EQ(q[i], i); } buf.Copyin(sizeof(int), rank, size, p, IndexArray(1,0,0), IndexArray(1, 4 ,1)); buf.CopyoutAll(q); for (int i = 0; i < 4; ++i) { EXPECT_EQ(i, q[1+i*3]); } buf.Copyin(sizeof(int), rank, size, p, IndexArray(0,0,0), IndexArray(1, 4 ,5)); buf.CopyoutAll(q); int k = 0; for (int i = 0; i < 5; ++i) { for (int j = 0; j < 4; ++j) { EXPECT_EQ(k, q[j*3+i*3*4]); ++k; } } buf.Copyin(sizeof(int), rank, size, p, IndexArray(1,0,0), IndexArray(2, 4 ,5)); buf.CopyoutAll(q); k = 0; for (int i = 0; i < 5; ++i) { for (int j = 0; j < 4; ++j) { for (int l = 1; l < 3; ++l) { EXPECT_EQ(k, q[l+j*3+i*3*4]); ++k; } } } } } // namespace runtime } // namespace physis int main(int argc, char *argv[]) { ::testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); }
4,482
2,160
#include <stdio.h> #define N 30 int main(void) { char a[N]; int i,j,n; gets(a); for(i=0;i<N;i++) { n=0; if(a[i]!='\0') n++; } for(j=0;j<n;j++) { if(a[j]==a[n-j-1]) printf("true"); else printf("false"); }return 0; }
281
164
/* * ===================================================================================== * * Filename: * * Description: * * Version: 1.0 * Created: Thanks to github you know it * Revision: none * Compiler: g++ * * Author: Mahmut Erdem ร–ZGEN m.erdemozgen@gmail.com * * * ===================================================================================== */ #include <iostream> int main(int argc, const char *argv[]) { int num1; std::cout << "Enter an integer: "; std::cin >> num1; std::cout << num1 << " is " << ((num1 % 2 == 0) ? "even" : "odd") << std::endl; return 0; }
673
206
// [2021y-02m-05d] Idrisov Denis R. #include <mygtest/modern.hpp> #ifdef TEST_TOOLS_MATCH_OPTIMIZE_MASK #define dTEST_COMPONENT tools, match #define dTEST_METHOD optimize_mask #define dTEST_TAG tdd #include <tools/match/optimize_mask.hpp> namespace me = ::tools; //============================================================================== namespace { template<class ch, class s1, class s2> void optimization(const s1& src_mask, const s2& expect) { typedef std::basic_string<ch> str_type; str_type mask = src_mask; const size_t len = me::optimize_mask(mask); const str_type result(mask, 0, len); ASSERT_TRUE(result == expect) << "mask = '" << mask << "'\n" << "expected = '" << expect << "'\n" ; } #define optimize(mask, expect) \ optimization<char>(mask, expect); \ optimization<wchar_t>(L##mask, L##expect) } // namespace //============================================================================== #ifndef NDEBUG // nullptr (death) TEST_COMPONENT(000) { size_t len = 0; ASSERT_DEATH_DEBUG( char* mask = NULL; len = me::optimize_mask(mask) ); ASSERT_DEATH_DEBUG( wchar_t* mask = NULL; len = me::optimize_mask(mask) ); (void) len; } #endif // !NDEBUG TEST_COMPONENT(001) { std::string mask = "1**?a"; const size_t len = me::optimize_mask(mask); ASSERT_TRUE(len == 4); ASSERT_TRUE(mask.size() == 4); std::string re(mask, 0, len); ASSERT_TRUE(re == "1*?a"); ASSERT_TRUE(mask == "1*?a"); } TEST_COMPONENT(002) { // 0123456789012345678 char mask[] = "aaa****bbbb"; const std::string etalon = "aaa*bbbb"; const size_t len = me::optimize_mask(mask); const std::string result(mask, len); ASSERT_TRUE(len == etalon.length()); ASSERT_TRUE(etalon == result); } TEST_COMPONENT(003) { // 0123456789012345678 char mask[] = "aaa****bbbb***ccc"; const std::string etalon = "aaa*bbbb*ccc"; const size_t len = me::optimize_mask(mask); const std::string result(mask, len); ASSERT_TRUE(len == etalon.length()); ASSERT_TRUE(etalon == result); } TEST_COMPONENT(004) { char mask[] = "***"; const std::string etalon = "*"; const size_t len = me::optimize_mask(mask); const std::string result(mask, len); ASSERT_TRUE(len == etalon.length()); ASSERT_TRUE(etalon == result); } TEST_COMPONENT(005) { char mask[] = ""; const std::string etalon = ""; const size_t len = me::optimize_mask(mask); const std::string result(mask, len); ASSERT_TRUE(len == etalon.length()); ASSERT_TRUE(etalon == result); } TEST_COMPONENT(006) { char mask[] = "txt"; const std::string etalon = "txt"; const size_t len = me::optimize_mask(mask); const std::string result(mask, len); ASSERT_TRUE(len == etalon.length()); ASSERT_TRUE(etalon == result); } TEST_COMPONENT(007) { std::string mask = "1**?***a*?**"; const size_t len = me::optimize_mask(mask); ASSERT_TRUE(len == 8); std::string re(mask, 0, len); ASSERT_TRUE(re == "1*?*a*?*"); ASSERT_TRUE(mask == "1*?*a*?*"); } TEST_COMPONENT(008) { std::string val = "123???***??456"; const size_t len = me::optimize_mask(val); ASSERT_TRUE(val == "123???*??456"); ASSERT_TRUE(len == 12); } // --- stress TEST_COMPONENT(009) { optimize("*.*" , "*.*" ); optimize("" , "" ); optimize("**?test??.** /" , "*?test??.* /" ); optimize("*?m.?*" , "*?m.?*" ); optimize("*?m.?*/" , "*?m.?*/" ); optimize("*?m.?* /" , "*?m.?* /" ); optimize(" *?m.?* /" , " *?m.?* /" ); optimize("*?m.?" , "*?m.?" ); optimize("*?m.?/" , "*?m.?/" ); optimize("*?m.? /" , "*?m.? /" ); optimize(" *?m.? /" , " *?m.? /" ); optimize(" *?m.? " , " *?m.? " ); optimize("*?m.??" , "*?m.??" ); optimize(" *?m.?? " , " *?m.?? " ); optimize(" *?m.?? /" , " *?m.?? /" ); optimize("*?m.\?\?" , "*?m.\?\?" ); optimize("*?m.\?\? " , "*?m.\?\? " ); optimize("*?m.?*?" , "*?m.?*?" ); optimize(" *?m.?*? " , " *?m.?*? " ); optimize(" *?m.?*?/" , " *?m.?*?/" ); optimize(" *?m.?*? /" , " *?m.?*? /" ); optimize("*?m.?*?/ " , "*?m.?*?/ " ); optimize(" *?m.?*? / " , " *?m.?*? / " ); optimize(" *?m.?*?" , " *?m.?*?" ); optimize(" *?m.?*?/" , " *?m.?*?/" ); optimize(" *?m.?*? /" , " *?m.?*? /" ); optimize(" *?m.?*? / " , " *?m.?*? / " ); optimize(" *?m.?*? //" , " *?m.?*? //" ); optimize(" *?m.?*?/ " , " *?m.?*?/ " ); optimize(" *?m.?*? " , " *?m.?*? " ); optimize(" *?m.?*? /" , " *?m.?*? /" ); optimize(" *?m.?*? / " , " *?m.?*? / " ); optimize(" *?m.?*?/ " , " *?m.?*?/ " ); optimize(" ***?m.?***?/ " , " *?m.?*?/ " ); } #endif // !TEST_TOOLS_MATCH_OPTIMIZE_MASK
5,303
2,240
#pragma once #include "sl.h" #include "defines.hpp" #include "input.hpp" class controller { public: virtual input get_input() { return input(direction::horizontal, 0, rotation::none); } }; class player_controller : public controller { virtual input get_input() override { auto key_left = slGetKey(SL_KEY_LEFT); auto key_right = slGetKey(SL_KEY_RIGHT); auto key_down = slGetKey(SL_KEY_DOWN); auto rotate_left = slGetKey('Z'); auto rotate_right = slGetKey('X'); if (key_left) { return input(direction::horizontal, -1, rotation::none); } if (key_right) { return input(direction::horizontal, 1, rotation::none); } if (key_down) { return input(direction::vertical, -1, rotation::none); } if (rotate_left) { return input(direction::horizontal, 0, rotation::left); } if (rotate_right) { return input(direction::horizontal, 0, rotation::right); } return input(direction::horizontal, 0, rotation::none); } }; class ai_controller : public controller { virtual input get_input() override { return input(direction::horizontal, 0, rotation::none); } };
1,109
406
/*========================================================================= Program: Visualization Toolkit Module: vtkHiddenLineRemovalPass.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtk_glew.h" #include "vtkHiddenLineRemovalPass.h" #include "vtkActor.h" #include "vtkMapper.h" #include "vtkObjectFactory.h" #include "vtkOpenGLError.h" #include "vtkProp.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkRenderState.h" #include <string> // Define to print debug statements to the OpenGL CS stream (useful for e.g. // apitrace debugging): //#define ANNOTATE_STREAM namespace { void annotate(const std::string &str) { #ifdef ANNOTATE_STREAM vtkOpenGLStaticCheckErrorMacro("Error before glDebug.") glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER, GL_DEBUG_SEVERITY_NOTIFICATION, 0, str.size(), str.c_str()); vtkOpenGLClearErrorMacro(); #else // ANNOTATE_STREAM (void)str; #endif // ANNOTATE_STREAM } } vtkStandardNewMacro(vtkHiddenLineRemovalPass) //------------------------------------------------------------------------------ void vtkHiddenLineRemovalPass::PrintSelf(std::ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ void vtkHiddenLineRemovalPass::Render(const vtkRenderState *s) { this->NumberOfRenderedProps = 0; // Separate the wireframe props from the others: std::vector<vtkProp*> wireframeProps; std::vector<vtkProp*> otherProps; for (int i = 0; i < s->GetPropArrayCount(); ++i) { bool isWireframe = false; vtkProp *prop = s->GetPropArray()[i]; vtkActor *actor = vtkActor::SafeDownCast(prop); if (actor) { vtkProperty *property = actor->GetProperty(); if (property->GetRepresentation() == VTK_WIREFRAME) { isWireframe = true; } } if (isWireframe) { wireframeProps.push_back(actor); } else { otherProps.push_back(actor); } } vtkViewport *vp = s->GetRenderer(); // Render the non-wireframe geometry as normal: annotate("Rendering non-wireframe props."); this->NumberOfRenderedProps = this->RenderProps(otherProps, vp); vtkOpenGLStaticCheckErrorMacro("Error after non-wireframe geometry."); // Store the coincident topology parameters -- we want to force polygon // offset to keep the drawn lines sharp: int ctMode = vtkMapper::GetResolveCoincidentTopology(); double ctFactor, ctUnits; vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(ctFactor, ctUnits); vtkMapper::SetResolveCoincidentTopology(VTK_RESOLVE_POLYGON_OFFSET); vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(2.0, 2.0); // Draw the wireframe props as surfaces into the depth buffer only: annotate("Rendering wireframe prop surfaces."); this->SetRepresentation(wireframeProps, VTK_SURFACE); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); this->RenderProps(wireframeProps, vp); vtkOpenGLStaticCheckErrorMacro("Error after wireframe surface rendering."); // Now draw the wireframes as normal: annotate("Rendering wireframes."); this->SetRepresentation(wireframeProps, VTK_WIREFRAME); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); this->NumberOfRenderedProps = this->RenderProps(wireframeProps, vp); vtkOpenGLStaticCheckErrorMacro("Error after wireframe rendering."); // Restore the previous coincident topology parameters: vtkMapper::SetResolveCoincidentTopology(ctMode); vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(ctFactor, ctUnits); } //------------------------------------------------------------------------------ bool vtkHiddenLineRemovalPass::WireframePropsExist(vtkProp **propArray, int nProps) { for (int i = 0; i < nProps; ++i) { vtkActor *actor = vtkActor::SafeDownCast(propArray[i]); if (actor) { vtkProperty *property = actor->GetProperty(); if (property->GetRepresentation() == VTK_WIREFRAME) { return true; } } } return false; } //------------------------------------------------------------------------------ vtkHiddenLineRemovalPass::vtkHiddenLineRemovalPass() { } //------------------------------------------------------------------------------ vtkHiddenLineRemovalPass::~vtkHiddenLineRemovalPass() { } //------------------------------------------------------------------------------ void vtkHiddenLineRemovalPass::SetRepresentation(std::vector<vtkProp *> &props, int repr) { for (std::vector<vtkProp*>::iterator it = props.begin(), itEnd = props.end(); it != itEnd; ++it) { vtkActor *actor = vtkActor::SafeDownCast(*it); if (actor) { actor->GetProperty()->SetRepresentation(repr); } } } //------------------------------------------------------------------------------ int vtkHiddenLineRemovalPass::RenderProps(std::vector<vtkProp *> &props, vtkViewport *vp) { int propsRendered = 0; for (std::vector<vtkProp*>::iterator it = props.begin(), itEnd = props.end(); it != itEnd; ++it) { propsRendered += (*it)->RenderOpaqueGeometry(vp); } return propsRendered; }
5,937
1,807
#include <iostream> #include <string> #include <vector> using namespace std; int get_all_digits(vector<char> num_palabra){ string digitos = ""; for(int i=0; i<num_palabra.size(); i++){ if(isdigit(num_palabra[i])){ digitos += num_palabra[i]; } } return stoi(digitos); } int main() { string palabra = "11"; //cout << stol(palabra, nullptr, 36) << endl; vector<string> palabras = {"version-1.9", "asd", "version-2.0", "123.45","version-1.11", "version-1.10"}; //cout << palabras[2] << endl; int nPal = palabras.size(); cout << "Palabras sin ordenar: " << endl; for(int i=0; i < nPal; i++) { cout << palabras[i] << " "; } cout << endl << endl; int numP0, numP1,num_char_0 ,num_char_1 ; char char_0, char_1; // bubblesort for(int i=0; i < nPal; i++){ for(int j=0; j < nPal-i-1; j++){ //numP0 = stol(palabras[j], nullptr, 100); //numP1 = stol(palabras[j+1], nullptr, 100); string palabra_0 = palabras[j]; string palabra_1 = palabras[j+1]; int menor_palabra = min(palabra_0.size(), palabra_1.size()); for(int c=0; c<menor_palabra; c++){ // comparo char a char: char_0 = palabras[j][c]; char_1 = palabras[j+1][c]; //cout << menor_palabra << " " << stof(char_0[0]) << endl; //num_char_0 = stol(char_0, nullptr, 36); //num_char_1 = stol(char_1, nullptr, 36); // MUERTE bool ambos_numeros = isdigit(char_0) && isdigit(char_1); if(ambos_numeros){ string sub_palabra_0 = copy(palabras[j], c, palabras[j].size()); string sub_palabra_1 = copy(palabras[j+1], c, palabras[j+1].size()) int num_palabra_0 = get_all_digits(sub_palabra_0); int num_palabra_1 = get_all_digits(sub_palabra_1); if (num_palabra_0 > num_palabra_1){ palabras[j].swap(palabras[j+1]); break; } }else{ if(char_0 > char_1){ //cout << "char0 > char1: " << palabras[j] << " " << palabras[j+1] << endl; palabras[j].swap(palabras[j+1]); break; } if(char_0 < char_1) { //listo, ordenado break; } } } } } cout << "Palabras ordenadas:" << endl; for(int i=0; i < nPal; i++) { cout << palabras[i] << " "; } cout << endl; return 0; }
2,773
997
//[ HelloWorld //////////////////////////////////////////////////////////////////// // Copyright 2008 Eric Niebler. 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) #include <iostream> #include <boost/proto/core.hpp> #include <boost/proto/context.hpp> #include <boost/typeof/std/ostream.hpp> namespace proto = boost::proto; proto::terminal< std::ostream & >::type cout_ = {std::cout}; template< typename Expr > void evaluate( Expr const & expr ) { proto::default_context ctx; proto::eval(expr, ctx); } int main() { evaluate( cout_ << "hello" << ',' << " world" ); return 0; } //]
734
251
// NOLINT(namespace-envoy) #include <math.h> #include <string> #include "proxy_wasm_intrinsics.h" // Use global variables so the compiler cannot optimize the operations away. int32_t i32a = 0; int32_t i32b = 1; double f64a = 0.0; double f64b = 1.0; // Emscripten in some modes and versions would use functions from the asm2wasm module to implement // these operations: int32_t % /, double conversion to int32_t and remainder(). extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onStart(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) { logInfo(std::string("out ") + std::to_string(i32a / i32b) + " " + std::to_string(i32a % i32b) + " " + std::to_string((int32_t)remainder(f64a, f64b))); }
752
301
#pragma once #include "dag_block.hpp" #include "final_chain/final_chain.hpp" #include "transaction_manager/transaction.hpp" #include "transaction_manager/transaction_manager.hpp" #include "vdf_sortition.hpp" namespace taraxa { enum class BlockStatus { invalid, proposed, broadcasted, verified, unseen }; using BlockStatusTable = ExpirationCacheMap<blk_hash_t, BlockStatus>; // Thread safe class DagBlockManager { public: DagBlockManager(addr_t node_addr, vdf_sortition::VdfConfig const &vdf_config, optional<state_api::DPOSConfig> dpos_config, unsigned verify_threads, std::shared_ptr<DbStorage> db, std::shared_ptr<TransactionManager> trx_mgr, std::shared_ptr<FinalChain> final_chain, std::shared_ptr<PbftChain> pbft_chain, logger::Logger log_time_, uint32_t queue_limit = 0); ~DagBlockManager(); void insertBlock(DagBlock const &blk); // Only used in initial syncs when blocks are received with full list of transactions void insertBroadcastedBlockWithTransactions(DagBlock const &blk, std::vector<Transaction> const &transactions); void pushUnverifiedBlock(DagBlock const &block, bool critical); // add to unverified queue void pushUnverifiedBlock(DagBlock const &block, std::vector<Transaction> const &transactions, bool critical); // add to unverified queue DagBlock popVerifiedBlock(); // get one verified block and pop void pushVerifiedBlock(DagBlock const &blk); std::pair<size_t, size_t> getDagBlockQueueSize() const; level_t getMaxDagLevelInQueue() const; void start(); void stop(); bool isBlockKnown(blk_hash_t const &hash); std::shared_ptr<DagBlock> getDagBlock(blk_hash_t const &hash) const; void clearBlockStatausTable() { blk_status_.clear(); } bool pivotAndTipsValid(DagBlock const &blk); uint64_t getCurrentMaxProposalPeriod() const; uint64_t getLastProposalPeriod() const; void setLastProposalPeriod(uint64_t const period); std::pair<uint64_t, bool> getProposalPeriod(level_t level); std::shared_ptr<ProposalPeriodDagLevelsMap> newProposePeriodDagLevelsMap(level_t anchor_level); private: using uLock = boost::unique_lock<boost::shared_mutex>; using sharedLock = boost::shared_lock<boost::shared_mutex>; using upgradableLock = boost::upgrade_lock<boost::shared_mutex>; using upgradeLock = boost::upgrade_to_unique_lock<boost::shared_mutex>; void verifyBlock(); std::atomic<bool> stopped_ = true; size_t num_verifiers_ = 4; const uint32_t cache_max_size_ = 10000; const uint32_t cache_delete_step_ = 100; std::atomic<uint64_t> last_proposal_period_ = 0; uint64_t current_max_proposal_period_ = 0; std::shared_ptr<DbStorage> db_; std::shared_ptr<TransactionManager> trx_mgr_; std::shared_ptr<FinalChain> final_chain_; std::shared_ptr<PbftChain> pbft_chain_; logger::Logger log_time_; // seen blks BlockStatusTable blk_status_; ExpirationCacheMap<blk_hash_t, DagBlock> seen_blocks_; std::vector<std::thread> verifiers_; mutable boost::shared_mutex shared_mutex_for_unverified_qu_; mutable boost::shared_mutex shared_mutex_for_verified_qu_; boost::condition_variable_any cond_for_unverified_qu_; boost::condition_variable_any cond_for_verified_qu_; uint32_t queue_limit_; std::map<uint64_t, std::deque<std::pair<DagBlock, std::vector<Transaction> > > > unverified_qu_; std::map<uint64_t, std::deque<DagBlock> > verified_qu_; vdf_sortition::VdfConfig vdf_config_; optional<state_api::DPOSConfig> dpos_config_; LOG_OBJECTS_DEFINE }; } // namespace taraxa
3,611
1,234
#include "runicpch.h" #include "SceneManager.h" namespace Runic { Scope<SceneManager::SceneManagerData> SceneManager::s_Data = CreateScope<SceneManager::SceneManagerData>(); }
178
58
/*+-------------------------------------------------------------------------+ | MultiVehicle simulator (libmvsim) | | | | Copyright (C) 2014-2020 Jose Luis Blanco Claraco | | Copyright (C) 2017 Borys Tymchenko (Odessa Polytechnic University) | | Distributed under 3-clause BSD License | | See COPYING | +-------------------------------------------------------------------------+ */ #include <mrpt/opengl/COpenGLScene.h> #include <mvsim/VehicleDynamics/VehicleAckermann.h> #include <mvsim/World.h> #include <cmath> #include <rapidxml.hpp> #include "xml_utils.h" using namespace mvsim; using namespace std; // Ctor: DynamicsAckermann::DynamicsAckermann(World* parent) : VehicleBase(parent, 4 /*num wheels*/) { m_chassis_mass = 500.0; m_chassis_z_min = 0.20; m_chassis_z_max = 1.40; m_chassis_color = mrpt::img::TColor(0xe8, 0x30, 0x00); // Default shape: m_chassis_poly.clear(); m_chassis_poly.emplace_back(-0.8, -1.0); m_chassis_poly.emplace_back(-0.8, 1.0); m_chassis_poly.emplace_back(1.5, 0.9); m_chassis_poly.emplace_back(1.8, 0.8); m_chassis_poly.emplace_back(1.8, -0.8); m_chassis_poly.emplace_back(1.5, -0.9); updateMaxRadiusFromPoly(); m_fixture_chassis = nullptr; for (int i = 0; i < 4; i++) m_fixture_wheels[i] = nullptr; // Default values: // rear-left: m_wheels_info[WHEEL_RL].x = 0; m_wheels_info[WHEEL_RL].y = 0.9; // rear-right: m_wheels_info[WHEEL_RR].x = 0; m_wheels_info[WHEEL_RR].y = -0.9; // Front-left: m_wheels_info[WHEEL_FL].x = 1.3; m_wheels_info[WHEEL_FL].y = 0.9; // Front-right: m_wheels_info[WHEEL_FR].x = 1.3; m_wheels_info[WHEEL_FR].y = -0.9; } /** The derived-class part of load_params_from_xml() */ void DynamicsAckermann::dynamics_load_params_from_xml( const rapidxml::xml_node<char>* xml_node) { const std::map<std::string, std::string> varValues = {{"NAME", m_name}}; // <chassis ...> </chassis> if (const rapidxml::xml_node<char>* xml_chassis = xml_node->first_node("chassis"); xml_chassis) { // Attribs: TParameterDefinitions attribs; attribs["mass"] = TParamEntry("%lf", &this->m_chassis_mass); attribs["zmin"] = TParamEntry("%lf", &this->m_chassis_z_min); attribs["zmax"] = TParamEntry("%lf", &this->m_chassis_z_max); attribs["color"] = TParamEntry("%color", &this->m_chassis_color); parse_xmlnode_attribs( *xml_chassis, attribs, {}, "[DynamicsAckermann::dynamics_load_params_from_xml]"); // Shape node (optional, fallback to default shape if none found) if (const rapidxml::xml_node<char>* xml_shape = xml_chassis->first_node("shape"); xml_shape) mvsim::parse_xmlnode_shape( *xml_shape, m_chassis_poly, "[DynamicsAckermann::dynamics_load_params_from_xml]"); } //<rl_wheel pos="0 1" mass="6.0" width="0.30" diameter="0.62" /> //<rr_wheel pos="0 -1" mass="6.0" width="0.30" diameter="0.62" /> //<fl_wheel mass="6.0" width="0.30" diameter="0.62" /> //<fr_wheel mass="6.0" width="0.30" diameter="0.62" /> const char* w_names[4] = { "rl_wheel", // 0 "rr_wheel", // 1 "fl_wheel", // 2 "fr_wheel" // 3 }; // Load common params: for (size_t i = 0; i < 4; i++) { const rapidxml::xml_node<char>* xml_wheel = xml_node->first_node(w_names[i]); if (xml_wheel) m_wheels_info[i].loadFromXML(xml_wheel); } //<f_wheels_x>1.3</f_wheels_x> //<f_wheels_d>2.0</f_wheels_d> // Load front ackermann wheels and other params: { double front_x = 1.3; double front_d = 2.0; TParameterDefinitions ack_ps; // Front wheels: ack_ps["f_wheels_x"] = TParamEntry("%lf", &front_x); ack_ps["f_wheels_d"] = TParamEntry("%lf", &front_d); // other params: ack_ps["max_steer_ang_deg"] = TParamEntry("%lf_deg", &m_max_steer_ang); parse_xmlnode_children_as_param( *xml_node, ack_ps, varValues, "[DynamicsAckermann::dynamics_load_params_from_xml]"); // Front-left: m_wheels_info[WHEEL_FL].x = front_x; m_wheels_info[WHEEL_FL].y = 0.5 * front_d; // Front-right: m_wheels_info[WHEEL_FR].x = front_x; m_wheels_info[WHEEL_FR].y = -0.5 * front_d; } // Vehicle controller: // ------------------------------------------------- { const rapidxml::xml_node<char>* xml_control = xml_node->first_node("controller"); if (xml_control) { rapidxml::xml_attribute<char>* control_class = xml_control->first_attribute("class"); if (!control_class || !control_class->value()) throw runtime_error( "[DynamicsAckermann] Missing 'class' attribute in " "<controller> XML node"); const std::string sCtrlClass = std::string(control_class->value()); if (sCtrlClass == ControllerRawForces::class_name()) m_controller = ControllerBasePtr(new ControllerRawForces(*this)); else if (sCtrlClass == ControllerTwistFrontSteerPID::class_name()) m_controller = ControllerBasePtr(new ControllerTwistFrontSteerPID(*this)); else if (sCtrlClass == ControllerFrontSteerPID::class_name()) m_controller = ControllerBasePtr(new ControllerFrontSteerPID(*this)); else throw runtime_error(mrpt::format( "[DynamicsAckermann] Unknown 'class'='%s' in " "<controller> XML node", sCtrlClass.c_str())); m_controller->load_config(*xml_control); } } // Default controller: if (!m_controller) m_controller = ControllerBasePtr(new ControllerRawForces(*this)); } // See docs in base class: void DynamicsAckermann::invoke_motor_controllers( const TSimulContext& context, std::vector<double>& out_torque_per_wheel) { // Longitudinal forces at each wheel: out_torque_per_wheel.assign(4, 0.0); if (m_controller) { // Invoke controller: TControllerInput ci; ci.context = context; TControllerOutput co; m_controller->control_step(ci, co); // Take its output: out_torque_per_wheel[WHEEL_RL] = co.rl_torque; out_torque_per_wheel[WHEEL_RR] = co.rr_torque; out_torque_per_wheel[WHEEL_FL] = co.fl_torque; out_torque_per_wheel[WHEEL_FR] = co.fr_torque; // Kinematically-driven steering wheels: // Ackermann formulas for inner&outer weels turning angles wrt the // equivalent (central) one: computeFrontWheelAngles( co.steer_ang, m_wheels_info[WHEEL_FL].yaw, m_wheels_info[WHEEL_FR].yaw); } } void DynamicsAckermann::computeFrontWheelAngles( const double desired_equiv_steer_ang, double& out_fl_ang, double& out_fr_ang) const { // EQ1: cot(d)+0.5*w/l = cot(do) // EQ2: cot(di)=cot(do)-w/l const double w = m_wheels_info[WHEEL_FL].y - m_wheels_info[WHEEL_FR].y; const double l = m_wheels_info[WHEEL_FL].x - m_wheels_info[WHEEL_RL].x; ASSERT_(l > 0); const double w_l = w / l; const double delta = b2Clamp(std::abs(desired_equiv_steer_ang), 0.0, m_max_steer_ang); const bool delta_neg = (desired_equiv_steer_ang < 0); ASSERT_LT_(delta, 0.5 * M_PI - 0.01); const double cot_do = 1.0 / tan(delta) + 0.5 * w_l; const double cot_di = cot_do - w_l; // delta>0: do->right, di->left wheel // delta<0: do->left , di->right wheel (delta_neg ? out_fr_ang : out_fl_ang) = atan(1.0 / cot_di) * (delta_neg ? -1.0 : 1.0); (delta_neg ? out_fl_ang : out_fr_ang) = atan(1.0 / cot_do) * (delta_neg ? -1.0 : 1.0); } // See docs in base class: mrpt::math::TTwist2D DynamicsAckermann::getVelocityLocalOdoEstimate() const { mrpt::math::TTwist2D odo_vel; // Equations: // Velocities in local +X at each wheel i={0,1}: // v_i = vx - w_veh * wheel_{i,y} = w_i * R_i // Re-arranging: const double w0 = m_wheels_info[WHEEL_RL].getW(); const double w1 = m_wheels_info[WHEEL_RR].getW(); const double R0 = m_wheels_info[WHEEL_RL].diameter * 0.5; const double R1 = m_wheels_info[WHEEL_RR].diameter * 0.5; const double Ay = m_wheels_info[WHEEL_RL].y - m_wheels_info[WHEEL_RR].y; ASSERTMSG_( Ay != 0.0, "The two wheels of a differential vehicle CAN'T by at the same Y " "coordinate!"); const double w_veh = (w1 * R1 - w0 * R0) / Ay; const double vx_veh = w0 * R0 + w_veh * m_wheels_info[WHEEL_RL].y; odo_vel.vx = vx_veh; odo_vel.vy = 0.0; odo_vel.omega = w_veh; #if 0 // Debug { mrpt::math::TTwist2D gt_vel = this->getVelocityLocal(); printf("\n gt: vx=%7.03f, vy=%7.03f, w= %7.03fdeg\n", gt_vel.vx, gt_vel.vy, mrpt::RAD2DEG(gt_vel.omega)); printf("odo: vx=%7.03f, vy=%7.03f, w= %7.03fdeg\n", odo_vel.vx, odo_vel.vy, mrpt::RAD2DEG(odo_vel.omega)); } #endif return odo_vel; }
8,496
3,862
#pragma once #include "vke.hpp" #include "vkrenderer.hpp" #include "texture.hpp" #include "VulkanglTFModel.hpp" class pbrRenderer : public vke::vkRenderer { void generateBRDFLUT(); void generateCubemaps(); protected: virtual void configurePipelineLayout(); virtual void loadRessources(); virtual void freeRessources(); virtual void prepareDescriptors(); virtual void preparePipeline(); public: struct Pipelines { VkPipeline skybox; VkPipeline pbr; VkPipeline pbrAlphaBlend; } pipelines; VkDescriptorSet dsScene; struct Textures { vke::TextureCubeMap environmentCube; vke::Texture2D lutBrdf; vke::TextureCubeMap irradianceCube; vke::TextureCubeMap prefilteredCube; } textures; vkglTF::Model skybox; std::vector<vkglTF::Model> models; pbrRenderer (); virtual ~pbrRenderer(); virtual void destroy(); void renderPrimitive(vkglTF::Primitive &primitive, VkCommandBuffer commandBuffer); void prepareModels(); virtual void draw(VkCommandBuffer cmdBuff); };
1,126
359
//-------------------------------------------------------------------------------- // PlayerProjectiles.cpp //-------------------------------------------------------------------------------- // The class that manages the player projectiles //-------------------------------------------------------------------------------- #include "PlayerProjectiles.hpp" #include "GameScene.hpp" #include <algorithm> #include "collision.hpp" #include "text/mGBADebugging.hpp" #include "data/sprites/player-projectiles.hpp" constexpr u16 NoProjectile = -1; constexpr int PlayerProjectilePriority = 7; static const ProjectileType ProjectileTypes[] = { { CollisionShape::Circle, vec2<s16f7>(2, 2), buildSpriteAttrsFor(0, SpriteSize::s8x8_4bpp, PlayerProjectilePriority) } }; static SinglePaletteAllocator palette EWRAM_BSS(data::sprites::player_projectiles.png.palette); void PlayerProjectiles::init() { // Set everything to zero memset32(projectiles, 0, sizeof(projectiles)/sizeof(u32)); numProjectiles = 0; // Initialize the graphics pointers tilePtr = ObjectTilePointer(SpriteSize::s8x8_4bpp); tilePtr.setData(data::sprites::player_projectiles.png.tiles); palPtr = SinglePalettePointer(palette); } void PlayerProjectiles::update() { setProjectileSortMode(SortMode::Descending); numProjectiles = updateProjectiles(numProjectiles, projectiles); sortProjectiles(numProjectiles, projectiles); for (auto& enemy : gameScene().enemies) { auto epos = vec2<s16f7>(enemy.pos); for (u32 i = 0; i < numProjectiles; i++) { if (projectiles[i].type == NoProjectile) continue; const auto& ptype = ProjectileTypes[projectiles[i].type]; using CollisionFunction = bool(*)(vec2<s16f7>, s16f7, vec2<s16f7>, vec2<s16f7>); CollisionFunction collision; switch (enemy.shape) { case CollisionShape::Circle: collision = reinterpret_cast<CollisionFunction>(circleCircleCollision); break; case CollisionShape::Box: collision = reinterpret_cast<CollisionFunction>(circleBoxCollision); break; case CollisionShape::Bitmask: collision = reinterpret_cast<CollisionFunction>(circleBitmaskCollision); break; } if (collision(projectiles[i].pos, ptype.halfSize.x, epos, enemy.halfSize)) { if (enemy.damage()) { gameScene().explosions.addSmallExplosion(epos); gameScene().enemies.remove(&enemy); } projectiles[i].type = NoProjectile; break; } } } // std::remove_if returns the pointer to the last element after the removal // so I just subtract the original pointer from it to get the number of projectiles numProjectiles = std::remove_if(projectiles, projectiles+numProjectiles, [](const Projectile& proj) { return proj.type == NoProjectile; }) - projectiles; } void PlayerProjectiles::pushGraphics() { u32 attr2add = tilePtr.getTileId() + ATTR2_PALBANK(palPtr.getPalette()) + (graphics::oam.objCount << 16); pushProjectilesToOam(numProjectiles, projectiles, graphics::oam.shadowOAM + graphics::oam.objCount, ProjectileTypes, attr2add); graphics::oam.objCount += numProjectiles; ASSERT(graphics::oam.objCount <= MaxObjs); } GameScene& PlayerProjectiles::gameScene() { // Don't worry, I know what I'm doing #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Winvalid-offsetof" return *reinterpret_cast<GameScene*>( reinterpret_cast<std::byte*>(this) - offsetof(GameScene, playerProjectiles)); #pragma GCC diagnostic pop }
3,723
1,108
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_ON_DEMAND_OS_TRANSPORT_CLIENT_GRPC_HPP #define IROHA_ON_DEMAND_OS_TRANSPORT_CLIENT_GRPC_HPP #include "ordering/on_demand_os_transport.hpp" #include "network/impl/async_grpc_client.hpp" #include "ordering.grpc.pb.h" namespace iroha { namespace ordering { namespace transport { /** * gRPC client for on demand ordering service */ class OnDemandOsClientGrpc : public OdOsNotification { public: using TimepointType = std::chrono::system_clock::time_point; using TimeoutType = std::chrono::milliseconds; /** * Constructor is left public because testing required passing a mock * stub interface */ OnDemandOsClientGrpc( std::unique_ptr<proto::OnDemandOrdering::StubInterface> stub, std::shared_ptr<network::AsyncGrpcClient<google::protobuf::Empty>> async_call, std::function<TimepointType()> time_provider, std::chrono::milliseconds proposal_request_timeout); void onBatches(consensus::Round round, CollectionType batches) override; boost::optional<ProposalType> onRequestProposal( consensus::Round round) override; private: logger::Logger log_; std::unique_ptr<proto::OnDemandOrdering::StubInterface> stub_; std::shared_ptr<network::AsyncGrpcClient<google::protobuf::Empty>> async_call_; std::function<TimepointType()> time_provider_; std::chrono::milliseconds proposal_request_timeout_; }; class OnDemandOsClientGrpcFactory : public OdOsNotificationFactory { public: OnDemandOsClientGrpcFactory( std::shared_ptr<network::AsyncGrpcClient<google::protobuf::Empty>> async_call, std::function<OnDemandOsClientGrpc::TimepointType()> time_provider, OnDemandOsClientGrpc::TimeoutType proposal_request_timeout); /** * Create connection with insecure gRPC channel defined by * network::createClient method * @see network/impl/grpc_channel_builder.hpp * This factory method can be used in production code */ std::unique_ptr<OdOsNotification> create( const shared_model::interface::Peer &to) override; private: std::shared_ptr<network::AsyncGrpcClient<google::protobuf::Empty>> async_call_; std::function<OnDemandOsClientGrpc::TimepointType()> time_provider_; std::chrono::milliseconds proposal_request_timeout_; }; } // namespace transport } // namespace ordering } // namespace iroha #endif // IROHA_ON_DEMAND_OS_TRANSPORT_CLIENT_GRPC_HPP
2,817
828
#include "irods/rodsDef.h" #include "irods/rodsError.h" #include "irods/rodsErrorTable.h" struct ErrorStack; int addRErrorMsg(ErrorStack *myError, const int status, const char *msg) { if (!myError) { return USER__NULL_INPUT_ERR; } if (myError->len >= MAX_ERROR_MESSAGES) { return 0; } if (0 == myError->len % PTR_ARRAY_MALLOC_LEN) { const int newLen = myError->len + PTR_ARRAY_MALLOC_LEN; ErrorMessage** newErrMsg = (ErrorMessage**)malloc(newLen * sizeof(*newErrMsg)); memset(newErrMsg, 0, newLen * sizeof(*newErrMsg)); for (int i = 0; i < myError->len; i++ ) { newErrMsg[i] = myError->errMsg[i]; } if (myError->errMsg) { free(myError->errMsg); } myError->errMsg = newErrMsg; } myError->errMsg[myError->len] = (ErrorMessage*)malloc(sizeof(ErrorMessage)); snprintf(myError->errMsg[myError->len]->msg, ERR_MSG_LEN - 1, "%s", msg); myError->errMsg[myError->len]->status = status; myError->len++; return 0; } // addRErrorMsg int replErrorStack(ErrorStack *srcRError, ErrorStack *destRError) { if (!srcRError || !destRError || !srcRError->errMsg) { return USER__NULL_INPUT_ERR; } const int len = srcRError->len; for (int i = 0; i < len; i++) { const ErrorMessage* errMsg = srcRError->errMsg[i]; if (errMsg) { addRErrorMsg(destRError, errMsg->status, errMsg->msg); } } return 0; } // replErrorStack int freeRError(ErrorStack* myError) { if (!myError) { return USER__NULL_INPUT_ERR; } freeRErrorContent(myError); free(myError); return 0; } // freeRError int freeRErrorContent(ErrorStack *myError) { if (!myError || !myError->errMsg) { return USER__NULL_INPUT_ERR; } for (int i = 0; i < myError->len; i++) { free(myError->errMsg[i]); } free(myError->errMsg); memset(myError, 0, sizeof(ErrorStack)); return 0; } // freeRErrorContent int printErrorStack(ErrorStack* rError) { if (!rError || !rError->errMsg) { return USER__NULL_INPUT_ERR; } const int len = rError->len; for (int i = 0; i < len; i++ ) { ErrorMessage* errMsg = rError->errMsg[i]; if (errMsg) { if (STDOUT_STATUS != errMsg->status) { printf("Level %d: ", i); } printf("%s\n", errMsg->msg); } } return 0; } // printErrorStack #ifdef __cplusplus namespace irods { auto pop_error_message(ErrorStack& _stack) -> std::string { if (_stack.len < 1 || _stack.len >= MAX_ERROR_MESSAGES) { return {}; } if (!_stack.errMsg) { return {}; } const auto back_index = _stack.len - 1; if (!_stack.errMsg[back_index]) { return {}; } const std::string ret{_stack.errMsg[back_index]->msg}; std::free(_stack.errMsg[back_index]); _stack.len--; return ret; } // pop_error_message } // namespace irods #endif // #ifdef __cplusplus
3,127
1,131
// Copyright (C) 2008-2015 Conrad Sanderson // Copyright (C) 2008-2015 NICTA (www.nicta.com.au) // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! \addtogroup op_sum //! @{ template<typename T1> arma_hot inline void op_sum::apply(Mat<typename T1::elem_type>& out, const Op<T1,op_sum>& in) { arma_extra_debug_sigprint(); typedef typename T1::elem_type eT; const uword dim = in.aux_uword_a; arma_debug_check( (dim > 1), "sum(): parameter 'dim' must be 0 or 1" ); const Proxy<T1> P(in.m); if(P.is_alias(out) == false) { op_sum::apply_noalias(out, P, dim); } else { Mat<eT> tmp; op_sum::apply_noalias(tmp, P, dim); out.steal_mem(tmp); } } template<typename T1> arma_hot inline void op_sum::apply_noalias(Mat<typename T1::elem_type>& out, const Proxy<T1>& P, const uword dim) { arma_extra_debug_sigprint(); if(is_Mat<typename Proxy<T1>::stored_type>::value) { op_sum::apply_noalias_unwrap(out, P, dim); } else { op_sum::apply_noalias_proxy(out, P, dim); } } template<typename T1> arma_hot inline void op_sum::apply_noalias_unwrap(Mat<typename T1::elem_type>& out, const Proxy<T1>& P, const uword dim) { arma_extra_debug_sigprint(); typedef typename T1::elem_type eT; typedef typename Proxy<T1>::stored_type P_stored_type; const unwrap<P_stored_type> tmp(P.Q); const typename unwrap<P_stored_type>::stored_type& X = tmp.M; const uword X_n_rows = X.n_rows; const uword X_n_cols = X.n_cols; if(dim == 0) { out.set_size(1, X_n_cols); eT* out_mem = out.memptr(); for(uword col=0; col < X_n_cols; ++col) { out_mem[col] = arrayops::accumulate( X.colptr(col), X_n_rows ); } } else { out.zeros(X_n_rows, 1); eT* out_mem = out.memptr(); for(uword col=0; col < X_n_cols; ++col) { arrayops::inplace_plus( out_mem, X.colptr(col), X_n_rows ); } } } template<typename T1> arma_hot inline void op_sum::apply_noalias_proxy(Mat<typename T1::elem_type>& out, const Proxy<T1>& P, const uword dim) { arma_extra_debug_sigprint(); typedef typename T1::elem_type eT; const uword P_n_rows = P.get_n_rows(); const uword P_n_cols = P.get_n_cols(); if(dim == 0) { out.set_size(1, P_n_cols); eT* out_mem = out.memptr(); for(uword col=0; col < P_n_cols; ++col) { eT val1 = eT(0); eT val2 = eT(0); uword i,j; for(i=0, j=1; j < P_n_rows; i+=2, j+=2) { val1 += P.at(i,col); val2 += P.at(j,col); } if(i < P_n_rows) { val1 += P.at(i,col); } out_mem[col] = (val1 + val2); } } else { out.zeros(P_n_rows, 1); eT* out_mem = out.memptr(); for(uword col=0; col < P_n_cols; ++col) for(uword row=0; row < P_n_rows; ++row) { out_mem[row] += P.at(row,col); } } } //! @}
3,173
1,401
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/clb/v20180317/model/LbRsTargets.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Clb::V20180317::Model; using namespace std; LbRsTargets::LbRsTargets() : m_typeHasBeenSet(false), m_privateIpHasBeenSet(false), m_portHasBeenSet(false), m_vpcIdHasBeenSet(false), m_weightHasBeenSet(false) { } CoreInternalOutcome LbRsTargets::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Type") && !value["Type"].IsNull()) { if (!value["Type"].IsString()) { return CoreInternalOutcome(Core::Error("response `LbRsTargets.Type` IsString=false incorrectly").SetRequestId(requestId)); } m_type = string(value["Type"].GetString()); m_typeHasBeenSet = true; } if (value.HasMember("PrivateIp") && !value["PrivateIp"].IsNull()) { if (!value["PrivateIp"].IsString()) { return CoreInternalOutcome(Core::Error("response `LbRsTargets.PrivateIp` IsString=false incorrectly").SetRequestId(requestId)); } m_privateIp = string(value["PrivateIp"].GetString()); m_privateIpHasBeenSet = true; } if (value.HasMember("Port") && !value["Port"].IsNull()) { if (!value["Port"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `LbRsTargets.Port` IsInt64=false incorrectly").SetRequestId(requestId)); } m_port = value["Port"].GetInt64(); m_portHasBeenSet = true; } if (value.HasMember("VpcId") && !value["VpcId"].IsNull()) { if (!value["VpcId"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `LbRsTargets.VpcId` IsInt64=false incorrectly").SetRequestId(requestId)); } m_vpcId = value["VpcId"].GetInt64(); m_vpcIdHasBeenSet = true; } if (value.HasMember("Weight") && !value["Weight"].IsNull()) { if (!value["Weight"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `LbRsTargets.Weight` IsInt64=false incorrectly").SetRequestId(requestId)); } m_weight = value["Weight"].GetInt64(); m_weightHasBeenSet = true; } return CoreInternalOutcome(true); } void LbRsTargets::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_typeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Type"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_type.c_str(), allocator).Move(), allocator); } if (m_privateIpHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PrivateIp"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_privateIp.c_str(), allocator).Move(), allocator); } if (m_portHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Port"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_port, allocator); } if (m_vpcIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VpcId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_vpcId, allocator); } if (m_weightHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Weight"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_weight, allocator); } } string LbRsTargets::GetType() const { return m_type; } void LbRsTargets::SetType(const string& _type) { m_type = _type; m_typeHasBeenSet = true; } bool LbRsTargets::TypeHasBeenSet() const { return m_typeHasBeenSet; } string LbRsTargets::GetPrivateIp() const { return m_privateIp; } void LbRsTargets::SetPrivateIp(const string& _privateIp) { m_privateIp = _privateIp; m_privateIpHasBeenSet = true; } bool LbRsTargets::PrivateIpHasBeenSet() const { return m_privateIpHasBeenSet; } int64_t LbRsTargets::GetPort() const { return m_port; } void LbRsTargets::SetPort(const int64_t& _port) { m_port = _port; m_portHasBeenSet = true; } bool LbRsTargets::PortHasBeenSet() const { return m_portHasBeenSet; } int64_t LbRsTargets::GetVpcId() const { return m_vpcId; } void LbRsTargets::SetVpcId(const int64_t& _vpcId) { m_vpcId = _vpcId; m_vpcIdHasBeenSet = true; } bool LbRsTargets::VpcIdHasBeenSet() const { return m_vpcIdHasBeenSet; } int64_t LbRsTargets::GetWeight() const { return m_weight; } void LbRsTargets::SetWeight(const int64_t& _weight) { m_weight = _weight; m_weightHasBeenSet = true; } bool LbRsTargets::WeightHasBeenSet() const { return m_weightHasBeenSet; }
5,533
2,013
#include <bits/stdc++.h> using namespace std; class Graph{ int V; list<int> *adj; public: Graph(int V); void AddEdge(int v, int w); void BFS(int s); }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } void Graph::AddEdge(int v, int w) { adj[v].push_back(w); } void Graph::BFS(int s) { vector<int> dist; dist.resize(V, -1); bool *visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; list<int> queue; visited[s] = true; dist[s] = 0; queue.push_back(s); list<int>::iterator i; while(!queue.empty()){ s = queue.front(); //cout << s << " "; queue.pop_front(); for (i = adj[s].begin(); i != adj[s].end(); ++i){ if (!visited[*i] && dist[*i] == -1){ dist[*i] = dist[s] + 1; visited[*i] = true; queue.push_back(*i); } } } for(int i=0;i<dist.size();i++) if(dist[i]==-1) cout<<dist[i]<<" "; else if(dist[i]!=0) cout<<dist[i]*6<<" "; cout<<endl; } int main() { int q, n, m, s, x, y; cin >> q; while(q--){ cin >> n >> m; Graph g(n); while(m--){ cin >> x >> y; g.AddEdge(x-1, y-1); g.AddEdge(y-1, x-1); } cin >> s; g.BFS(s-1); } return 0; }
1,439
578
/************************************************************************* * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //-------------------------------------------------------------------------------- // CVE analysis // Contributor: Chunzheng Wang, <chunzheng.wang@cern.ch>, Shanghai //-------------------------------------------------------------------------------- #include <iostream> #include <cstdlib> #include <sys/time.h> #include <algorithm> // ROOT classes #include "TChain.h" #include "TTree.h" #include "TFile.h" #include "TList.h" #include "TH1F.h" #include "TH2F.h" #include "TH1D.h" #include "TH2D.h" #include "TProfile.h" #include "TProfile2D.h" #include "TMath.h" // Alice analysis base class #include "AliAnalysisTaskSE.h" // Alice analysis additional classes #include "AliAnalysisManager.h" #include "AliInputEventHandler.h" // Alice AOD classes #include "AliAODInputHandler.h" #include "AliAODHandler.h" #include "AliAODEvent.h" #include "AliAODVertex.h" #include "AliAODVZERO.h" // Alice classes #include "AliCentrality.h" #include "AliEventplane.h" #include "AliEventCuts.h" #include "AliAnalysisUtils.h" // Alice MC classes #include "AliMCEvent.h" #include "AliMCEventHandler.h" #include "AliAODMCParticle.h" // Alice "V" classes #include "AliVParticle.h" #include "AliVEvent.h" #include "AliVVertex.h" #include "AliVVZERO.h" // Alice PID classes #include "AliAODPid.h" #include "AliAODpidUtil.h" #include "AliPIDCombined.h" #include "AliPIDResponse.h" #include "AliMultSelection.h" #include "AliOADBContainer.h" #include "AliCentrality.h" #include "AliAnalysisTaskLambdaProtonCVE.h" using std::cout; using std::endl; ClassImp(AliAnalysisTaskLambdaProtonCVE); //--------------------------------------------------- AliAnalysisTaskLambdaProtonCVE::AliAnalysisTaskLambdaProtonCVE() : AliAnalysisTaskSE(), fDebug(0), fTrigger("kMB"), fPeriod("LHC10h"), fVzCut(10.0), fCentDiffCut(7.5), IsVZEROCalibOn(false), IsZDCCalibOn(false), IsTPCCalibOn(false), IsQAVZERO(false), IsQAZDC(false), IsQATPC(false), fPlanePtMin(0.2), fPlanePtMax(2.0), fEtaGapPos( 0.1), fEtaGapNeg(-0.1), fFilterBit(768), fNclsCut(70), fChi2Max(4.0), fChi2Min(0.1), fDcaCutz(3.2), fDcaCutxy(2.4), fPtMin(0.2), fPtMax(5.0), IsDoNUE(true), IsDoNUA(true), fNSigmaTPCCut(4), fNSigmaTOFCut(4), fV0PtMin(0.5), fV0CPAMin(0.995), fV0RapidityMax(0.5), fV0DecayLengthMin(3.), fV0DecayLengthMax(100.), fV0DCAToPrimVtxMax(1.5), fV0DcaBetweenDaughtersMax(1.), fDaughtersPtMax(20.), fDaughtersEtaMax(0.8), fDaughtersTPCNclsMin(70), fDaughtersDCAToPrimVtxMin(0.02), fV0PosProtonTPCNsigma(4.), fV0NegPionTPCNsigma(4.), fV0NegProtonTPCNsigma(4.), fV0PosPionTPCNsigma(4.), IsV0DaughterUseTOF(false), fV0PosProtonTOFNsigma(4.), fV0NegPionTOFNsigma(4.), fV0NegProtonTOFNsigma(4.), fV0PosPionTOFNsigma(4.), fLambdaMassCut(0.005), IsCheckPIDFlow(false), fMassMean(1.115683), fEtaCut(0.8), fDedxCut(10.0), fAOD(nullptr), //! aod Event fPIDResponse(nullptr), //! PID Handler fUtils(nullptr), //! Event Selection Options runNumList(0), fRunNum(-999), // runnumber fOldRunNum(-999), // old runnumber fRunNumBin(-999), // runnumer bin, 10:139510..., 11:170387..., 15HIR:246994... fVzBin(-999), // vertex z bin fCentBin(-999), // centrality bin: 0-10 fCent(-999), // value of centrality fPsi1ZNC(-999), fPsi1ZNA(-999), fPsi2V0C(-999), fPsi2V0A(-999), fPsi2TPCPos(-999), fPsi2TPCNeg(-999), SumQ2xTPCPos(0.), SumQ2yTPCPos(0.), fWgtMultTPCPos(0.), SumQ2xTPCNeg(0.), SumQ2yTPCNeg(0.), fWgtMultTPCNeg(0.), vecPosEPTrkID(0), vecNegEPTrkID(0), vecPosEPTrkPhi(0), vecNegEPTrkPhi(0), vecPosEPTrkNUAWgt(0), vecNegEPTrkNUAWgt(0), vecPDGCode(0), vecID(0), vecPhi(0), vecEta(0), vecPt(0), vecNUAWeight(0), vecNUEWeight(0), vecNUAWeightPID(0), vecNUEWeightPID(0), vecLambdaCode(0), vecLambdaPhi(0), vecLambdaPt(0), vecDaughterPosID(0), vecDaughterNegID(0), fSPDCutPU(nullptr), fV0CutPU(nullptr), fCenCutLowPU(nullptr), fCenCutHighPU(nullptr), fMultCutPU(nullptr), fListNUE(nullptr), hNUEweightPlus(nullptr), hNUEweightMinus(nullptr), fListNUA(nullptr), hNUAweightPlus(nullptr), hNUAweightMinus(nullptr), hCorrectNUAPos(nullptr), hCorrectNUANeg(nullptr), fListVZEROCalib(nullptr), hMultV0Read(nullptr), hMultV0(nullptr), contMult(nullptr), contQxncm(nullptr), contQyncm(nullptr), contQxnam(nullptr), contQynam(nullptr), fHCorrectV0ChWeghts(nullptr), fListZDCCalib(nullptr), tree(nullptr), fProfileForZNCGE(nullptr), fProfileForZNAGE(nullptr), fHn4DForZNCQxRC(nullptr), fHn4DForZNCQyRC(nullptr), fHn4DForZNCMtRC(nullptr), fHn4DForZNAQxRC(nullptr), fHn4DForZNAQyRC(nullptr), fHn4DForZNAMtRC(nullptr), fHn4DForZNCCountsRC(nullptr), fHn4DForZNACountsRC(nullptr), fProfile2DForCosC(nullptr), fProfile2DForSinC(nullptr), fProfile2DForCosA(nullptr), fProfile2DForSinA(nullptr), fOutputList(nullptr), fEvtCount(nullptr), fHistRunNumBin(nullptr), fHistPt(nullptr), fHistEta(nullptr), fHistNhits(nullptr), fHist2DPDedx(nullptr), fHistDcaXY(nullptr), fHistDcaZ(nullptr), fHistV0Pt(nullptr), fHistV0Eta(nullptr), fHistV0DcatoPrimVertex(nullptr), fHistV0CPA(nullptr), fHistV0DecayLength(nullptr), fHist2DPsi2TPCPosCent(nullptr), fHist2DPsi2TPCNegCent(nullptr), fHist2DPsi2V0CCent(nullptr), fHist2DPsi2V0ACent(nullptr), fHist2DPsi1ZNCCent(nullptr), fHist2DPsi1ZNACent(nullptr), fProfileTPCPsi2Correlation(nullptr), fProfileV0MPsi2Correlation(nullptr), fProfileZDCPsi1Correlation(nullptr), fProfileZDCPsi2Correlation(nullptr), fProfileV0CTPCPosPsi2Correlation(nullptr), fProfileV0ATPCPosPsi2Correlation(nullptr), fProfileV0CTPCNegPsi2Correlation(nullptr), fProfileV0ATPCNegPsi2Correlation(nullptr), fProfileDelta_Lambda_hPos(nullptr), fProfileDelta_Lambda_hNeg(nullptr), fProfileDelta_Lambda_Proton(nullptr), fProfileDelta_Lambda_AntiProton(nullptr), fProfileDelta_AntiLambda_hPos(nullptr), fProfileDelta_AntiLambda_hNeg(nullptr), fProfileDelta_AntiLambda_Proton(nullptr), fProfileDelta_AntiLambda_AntiProton(nullptr), fProfileGammaTPC_Lambda_hPos(nullptr), fProfileGammaTPC_Lambda_hNeg(nullptr), fProfileGammaTPC_Lambda_Proton(nullptr), fProfileGammaTPC_Lambda_AntiProton(nullptr), fProfileGammaTPC_AntiLambda_hPos(nullptr), fProfileGammaTPC_AntiLambda_hNeg(nullptr), fProfileGammaTPC_AntiLambda_Proton(nullptr), fProfileGammaTPC_AntiLambda_AntiProton(nullptr), fProfileGammaV0C_Lambda_hPos(nullptr), fProfileGammaV0C_Lambda_hNeg(nullptr), fProfileGammaV0C_Lambda_Proton(nullptr), fProfileGammaV0C_Lambda_AntiProton(nullptr), fProfileGammaV0C_AntiLambda_hPos(nullptr), fProfileGammaV0C_AntiLambda_hNeg(nullptr), fProfileGammaV0C_AntiLambda_Proton(nullptr), fProfileGammaV0C_AntiLambda_AntiProton(nullptr), fProfileGammaV0A_Lambda_hPos(nullptr), fProfileGammaV0A_Lambda_hNeg(nullptr), fProfileGammaV0A_Lambda_Proton(nullptr), fProfileGammaV0A_Lambda_AntiProton(nullptr), fProfileGammaV0A_AntiLambda_hPos(nullptr), fProfileGammaV0A_AntiLambda_hNeg(nullptr), fProfileGammaV0A_AntiLambda_Proton(nullptr), fProfileGammaV0A_AntiLambda_AntiProton(nullptr), fProfileGammaZNC_Lambda_hPos(nullptr), fProfileGammaZNC_Lambda_hNeg(nullptr), fProfileGammaZNC_Lambda_Proton(nullptr), fProfileGammaZNC_Lambda_AntiProton(nullptr), fProfileGammaZNC_AntiLambda_hPos(nullptr), fProfileGammaZNC_AntiLambda_hNeg(nullptr), fProfileGammaZNC_AntiLambda_Proton(nullptr), fProfileGammaZNC_AntiLambda_AntiProton(nullptr), fProfileGammaZNA_Lambda_hPos(nullptr), fProfileGammaZNA_Lambda_hNeg(nullptr), fProfileGammaZNA_Lambda_Proton(nullptr), fProfileGammaZNA_Lambda_AntiProton(nullptr), fProfileGammaZNA_AntiLambda_hPos(nullptr), fProfileGammaZNA_AntiLambda_hNeg(nullptr), fProfileGammaZNA_AntiLambda_Proton(nullptr), fProfileGammaZNA_AntiLambda_AntiProton(nullptr) { for (int i = 0; i < 3; i++) fVertex[i] = -999; for (int i = 0; i < 3; ++i) pV0XMeanRead[i] = nullptr; for (int i = 0; i < 3; ++i) pV0YMeanRead[i] = nullptr; for (int i = 0; i < 2; ++i) hQx2mV0[i] = nullptr; for (int i = 0; i < 2; ++i) hQy2mV0[i] = nullptr; for (int i = 0; i < 3; ++i) vtxQuant1[i] = -999; for (int i = 0; i < 3; ++i) vtxQuant2[i] = -999; for (int i = 0; i < 2; ++i) fHistCent[i] = nullptr; for (int i = 0; i < 2; ++i) fHistVz[i] = nullptr; for (int i = 0; i < 8; ++i) fHist2DCentQA[i] = nullptr; for (int i = 0; i < 2; ++i) fHist2DMultCentQA[i] = nullptr; for (int i = 0; i < 6; ++i) fHist2DMultMultQA[i] = nullptr; for (int i = 0; i < 2; ++i) fHistPhi[i] = nullptr; for (int i = 0; i < 2; i++) fHist2DEtaPhi[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0CQxCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0CQyCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0CQxVtx[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0CQyVtx[i] = nullptr; for (int i = 0; i < 2; ++i) fHist2DCalibPsi2V0CCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0AQxCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0AQyCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0AQxVtx[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0AQyVtx[i] = nullptr; for (int i = 0; i < 2; ++i) fHist2DCalibPsi2V0ACent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNCTowerMeanEnegry[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNCQxCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNCQyCent[i] = nullptr; for (int i = 0; i < 3; ++i) fHist2DCalibPsi1ZNCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNATowerMeanEnegry[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNAQxCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNAQyCent[i] = nullptr; for (int i = 0; i < 3; ++i) fHist2DCalibPsi1ZNACent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZDCQxAQxCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZDCQxAQyCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZDCQyAQxCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZDCQyAQyCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaPt[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaEta[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaPhi[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaDcaToPrimVertex[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaCPA[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaDecayLength[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaMass[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaPt[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaEta[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaPhi[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaDcaToPrimVertex[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaCPA[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaDecayLength[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaMass[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileLambdaMassVsPt[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileAntiLambdaMassVsPt[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPthPos[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPthNeg[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPtProton[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPtAntiProton[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPtLambda[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPtAntiLambda[i] = nullptr; } //--------------------------------------------------- AliAnalysisTaskLambdaProtonCVE::AliAnalysisTaskLambdaProtonCVE(const char *name) : AliAnalysisTaskSE(name), fDebug(0), fTrigger("kMB"), fPeriod("LHC10h"), fVzCut(10.0), fCentDiffCut(7.5), IsVZEROCalibOn(false), IsZDCCalibOn(false), IsTPCCalibOn(false), IsQAVZERO(false), IsQAZDC(false), IsQATPC(false), fPlanePtMin(0.2), fPlanePtMax(2.0), fEtaGapPos( 0.1), fEtaGapNeg(-0.1), fFilterBit(768), fNclsCut(70), fChi2Max(4.0), fChi2Min(0.1), fDcaCutz(3.2), fDcaCutxy(2.4), fPtMin(0.2), fPtMax(5.0), IsDoNUE(true), IsDoNUA(true), fNSigmaTPCCut(4), fNSigmaTOFCut(4), fV0PtMin(0.5), fV0CPAMin(0.995), fV0RapidityMax(0.5), fV0DecayLengthMin(3.), fV0DecayLengthMax(100.), fV0DCAToPrimVtxMax(1.5), fV0DcaBetweenDaughtersMax(1.), fDaughtersPtMax(20.), fDaughtersEtaMax(0.8), fDaughtersTPCNclsMin(70), fDaughtersDCAToPrimVtxMin(0.02), fV0PosProtonTPCNsigma(4.), fV0NegPionTPCNsigma(4.), fV0NegProtonTPCNsigma(4.), fV0PosPionTPCNsigma(4.), IsV0DaughterUseTOF(false), fV0PosProtonTOFNsigma(4.), fV0NegPionTOFNsigma(4.), fV0NegProtonTOFNsigma(4.), fV0PosPionTOFNsigma(4.), fLambdaMassCut(0.005), IsCheckPIDFlow(false), fMassMean(1.115683), fEtaCut(0.8), fDedxCut(10.0), fAOD(nullptr), //! aod Event fPIDResponse(nullptr), //! PID Handler fUtils(nullptr), //! Event Selection Options runNumList(0), fRunNum(-999), // runnumber fOldRunNum(-999), // old runnumber fRunNumBin(-999), // runnumer bin, 10:139510..., 11:170387..., 15HIR:246994... fVzBin(-999), // vertex z bin fCentBin(-999), // centrality bin: 0-10 fCent(-999), // value of centrality fPsi1ZNC(-999), fPsi1ZNA(-999), fPsi2V0C(-999), fPsi2V0A(-999), fPsi2TPCPos(-999), fPsi2TPCNeg(-999), SumQ2xTPCPos(0.), SumQ2yTPCPos(0.), fWgtMultTPCPos(0.), SumQ2xTPCNeg(0.), SumQ2yTPCNeg(0.), fWgtMultTPCNeg(0.), vecPosEPTrkID(0), vecNegEPTrkID(0), vecPosEPTrkPhi(0), vecNegEPTrkPhi(0), vecPosEPTrkNUAWgt(0), vecNegEPTrkNUAWgt(0), vecPDGCode(0), vecID(0), vecPhi(0), vecEta(0), vecPt(0), vecNUAWeight(0), vecNUEWeight(0), vecNUAWeightPID(0), vecNUEWeightPID(0), vecLambdaCode(0), vecLambdaPhi(0), vecLambdaPt(0), vecDaughterPosID(0), vecDaughterNegID(0), fSPDCutPU(nullptr), fV0CutPU(nullptr), fCenCutLowPU(nullptr), fCenCutHighPU(nullptr), fMultCutPU(nullptr), fListNUE(nullptr), hNUEweightPlus(nullptr), hNUEweightMinus(nullptr), fListNUA(nullptr), hNUAweightPlus(nullptr), hNUAweightMinus(nullptr), hCorrectNUAPos(nullptr), hCorrectNUANeg(nullptr), fListVZEROCalib(nullptr), hMultV0Read(nullptr), hMultV0(nullptr), contMult(nullptr), contQxncm(nullptr), contQyncm(nullptr), contQxnam(nullptr), contQynam(nullptr), fHCorrectV0ChWeghts(nullptr), fListZDCCalib(nullptr), tree(nullptr), fProfileForZNCGE(nullptr), fProfileForZNAGE(nullptr), fHn4DForZNCQxRC(nullptr), fHn4DForZNCQyRC(nullptr), fHn4DForZNCMtRC(nullptr), fHn4DForZNAQxRC(nullptr), fHn4DForZNAQyRC(nullptr), fHn4DForZNAMtRC(nullptr), fHn4DForZNCCountsRC(nullptr), fHn4DForZNACountsRC(nullptr), fProfile2DForCosC(nullptr), fProfile2DForSinC(nullptr), fProfile2DForCosA(nullptr), fProfile2DForSinA(nullptr), fOutputList(nullptr), fEvtCount(nullptr), fHistRunNumBin(nullptr), fHistPt(nullptr), fHistEta(nullptr), fHistNhits(nullptr), fHist2DPDedx(nullptr), fHistDcaXY(nullptr), fHistDcaZ(nullptr), fHistV0Pt(nullptr), fHistV0Eta(nullptr), fHistV0DcatoPrimVertex(nullptr), fHistV0CPA(nullptr), fHistV0DecayLength(nullptr), fHist2DPsi2TPCPosCent(nullptr), fHist2DPsi2TPCNegCent(nullptr), fHist2DPsi2V0CCent(nullptr), fHist2DPsi2V0ACent(nullptr), fHist2DPsi1ZNCCent(nullptr), fHist2DPsi1ZNACent(nullptr), fProfileTPCPsi2Correlation(nullptr), fProfileV0MPsi2Correlation(nullptr), fProfileZDCPsi1Correlation(nullptr), fProfileZDCPsi2Correlation(nullptr), fProfileV0CTPCPosPsi2Correlation(nullptr), fProfileV0ATPCPosPsi2Correlation(nullptr), fProfileV0CTPCNegPsi2Correlation(nullptr), fProfileV0ATPCNegPsi2Correlation(nullptr), fProfileDelta_Lambda_hPos(nullptr), fProfileDelta_Lambda_hNeg(nullptr), fProfileDelta_Lambda_Proton(nullptr), fProfileDelta_Lambda_AntiProton(nullptr), fProfileDelta_AntiLambda_hPos(nullptr), fProfileDelta_AntiLambda_hNeg(nullptr), fProfileDelta_AntiLambda_Proton(nullptr), fProfileDelta_AntiLambda_AntiProton(nullptr), fProfileGammaTPC_Lambda_hPos(nullptr), fProfileGammaTPC_Lambda_hNeg(nullptr), fProfileGammaTPC_Lambda_Proton(nullptr), fProfileGammaTPC_Lambda_AntiProton(nullptr), fProfileGammaTPC_AntiLambda_hPos(nullptr), fProfileGammaTPC_AntiLambda_hNeg(nullptr), fProfileGammaTPC_AntiLambda_Proton(nullptr), fProfileGammaTPC_AntiLambda_AntiProton(nullptr), fProfileGammaV0C_Lambda_hPos(nullptr), fProfileGammaV0C_Lambda_hNeg(nullptr), fProfileGammaV0C_Lambda_Proton(nullptr), fProfileGammaV0C_Lambda_AntiProton(nullptr), fProfileGammaV0C_AntiLambda_hPos(nullptr), fProfileGammaV0C_AntiLambda_hNeg(nullptr), fProfileGammaV0C_AntiLambda_Proton(nullptr), fProfileGammaV0C_AntiLambda_AntiProton(nullptr), fProfileGammaV0A_Lambda_hPos(nullptr), fProfileGammaV0A_Lambda_hNeg(nullptr), fProfileGammaV0A_Lambda_Proton(nullptr), fProfileGammaV0A_Lambda_AntiProton(nullptr), fProfileGammaV0A_AntiLambda_hPos(nullptr), fProfileGammaV0A_AntiLambda_hNeg(nullptr), fProfileGammaV0A_AntiLambda_Proton(nullptr), fProfileGammaV0A_AntiLambda_AntiProton(nullptr), fProfileGammaZNC_Lambda_hPos(nullptr), fProfileGammaZNC_Lambda_hNeg(nullptr), fProfileGammaZNC_Lambda_Proton(nullptr), fProfileGammaZNC_Lambda_AntiProton(nullptr), fProfileGammaZNC_AntiLambda_hPos(nullptr), fProfileGammaZNC_AntiLambda_hNeg(nullptr), fProfileGammaZNC_AntiLambda_Proton(nullptr), fProfileGammaZNC_AntiLambda_AntiProton(nullptr), fProfileGammaZNA_Lambda_hPos(nullptr), fProfileGammaZNA_Lambda_hNeg(nullptr), fProfileGammaZNA_Lambda_Proton(nullptr), fProfileGammaZNA_Lambda_AntiProton(nullptr), fProfileGammaZNA_AntiLambda_hPos(nullptr), fProfileGammaZNA_AntiLambda_hNeg(nullptr), fProfileGammaZNA_AntiLambda_Proton(nullptr), fProfileGammaZNA_AntiLambda_AntiProton(nullptr) { for (int i = 0; i < 3; i++) fVertex[i] = -999; for (int i = 0; i < 3; ++i) pV0XMeanRead[i] = nullptr; for (int i = 0; i < 3; ++i) pV0YMeanRead[i] = nullptr; for (int i = 0; i < 2; ++i) hQx2mV0[i] = nullptr; for (int i = 0; i < 2; ++i) hQy2mV0[i] = nullptr; for (int i = 0; i < 3; ++i) vtxQuant1[i] = -999; for (int i = 0; i < 3; ++i) vtxQuant2[i] = -999; for (int i = 0; i < 2; ++i) fHistCent[i] = nullptr; for (int i = 0; i < 2; ++i) fHistVz[i] = nullptr; for (int i = 0; i < 8; ++i) fHist2DCentQA[i] = nullptr; for (int i = 0; i < 2; ++i) fHist2DMultCentQA[i] = nullptr; for (int i = 0; i < 6; ++i) fHist2DMultMultQA[i] = nullptr; for (int i = 0; i < 2; ++i) fHistPhi[i] = nullptr; for (int i = 0; i < 2; i++) fHist2DEtaPhi[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0CQxCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0CQyCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0CQxVtx[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0CQyVtx[i] = nullptr; for (int i = 0; i < 2; ++i) fHist2DCalibPsi2V0CCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0AQxCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0AQyCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0AQxVtx[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileV0AQyVtx[i] = nullptr; for (int i = 0; i < 2; ++i) fHist2DCalibPsi2V0ACent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNCTowerMeanEnegry[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNCQxCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNCQyCent[i] = nullptr; for (int i = 0; i < 3; ++i) fHist2DCalibPsi1ZNCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNATowerMeanEnegry[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNAQxCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZNAQyCent[i] = nullptr; for (int i = 0; i < 3; ++i) fHist2DCalibPsi1ZNACent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZDCQxAQxCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZDCQxAQyCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZDCQyAQxCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileZDCQyAQyCCent[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaPt[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaEta[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaPhi[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaDcaToPrimVertex[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaCPA[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaDecayLength[i] = nullptr; for (int i = 0; i < 2; ++i) fHistLambdaMass[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaPt[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaEta[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaPhi[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaDcaToPrimVertex[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaCPA[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaDecayLength[i] = nullptr; for (int i = 0; i < 2; ++i) fHistAntiLambdaMass[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileLambdaMassVsPt[i] = nullptr; for (int i = 0; i < 2; ++i) fProfileAntiLambdaMassVsPt[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPthPos[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPthNeg[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPtProton[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPtAntiProton[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPtLambda[i] = nullptr; for (int i = 0; i < 5; ++i) fProfile2DRawFlowCentPtAntiLambda[i] = nullptr; DefineInput(0,TChain::Class()); DefineOutput(1,TList::Class()); } //------------------------------------------------ AliAnalysisTaskLambdaProtonCVE::~AliAnalysisTaskLambdaProtonCVE() { // Destructor // histograms are in the output list and deleted when the output if (fOutputList) delete fOutputList; } //--------------------------------------------------- void AliAnalysisTaskLambdaProtonCVE::Terminate(Option_t *) { // Terminate loop Printf("Terminate"); } //--------------------------------------------------- void AliAnalysisTaskLambdaProtonCVE::UserCreateOutputObjects() { fOutputList = new TList(); fOutputList -> SetName(GetName()); fOutputList -> SetOwner(kTRUE); //////////////////////// // Run Number Info //////////////////////// TString runNumList10h[90] = { "139510","139507","139505","139503","139465","139438","139437","139360","139329","139328","139314","139310", "139309","139173","139107","139105","139038","139037","139036","139029","139028","138872","138871","138870", "138837","138732","138730","138666","138662","138653","138652","138638","138624","138621","138583","138582", "138579","138578","138534","138469","138442","138439","138438","138396","138364","138275","138225","138201", "138197","138192","138190","137848","137844","137752","137751","137724","137722","137718","137704","137693", "137692","137691","137686","137685","137639","137638","137608","137595","137549","137546","137544","137541", "137539","137531","137530","137443","137441","137440","137439","137434","137432","137431","137430","137243", "137236","137235","137232","137231","137162","137161"}; TString runNumList15o[138] = { "246994","246991","246989","246984","246982","246948","246945","246928","246871","246870","246867","246865", "246864","246859","246858","246851","246847","246846","246845","246844","246810","246809","246808","246807", "246805","246804","246766","246765","246763","246760","246759","246758","246757","246751","246750","246434", "246431","246424","246392","246391","246276","246275","246272","246271","246225","246222","246217","246185", "246182","246181","246180","246178","246153","246152","246151","246148","246115","246113","246089","246087", "246053","246052","246049","246048","246042","246037","246036","246012","246003","246001","245963","245954", "245952","245949","245923","245833","245831","245829","245793","245785","245775","245766","245759","245752", "245731","245729","245705","245702","245692","245683","245554","245545","245544","245543","245542","245540", "245535","245507","245505","245504","245501","245497","245496","245454","245453","245450","245446","245441", "245411","245410","245409","245407","245401","245397","245396","245353","245349","245347","245346","245345", "245343","245259","245233","245232","245231","245152","245151","245146","245145","245068","245066","245064", "244983","244982","244980","244975","244918","244917"}; TString runNumList18q[125] = { "296623","296622","296621","296619","296618","296616","296615","296594","296553","296552","296551","296550", "296548","296547","296516","296512","296511","296510","296509","296472","296433","296424","296423","296420", "296419","296415","296414","296383","296381","296380","296379","296378","296377","296376","296375","296312", "296309","296304","296303","296280","296279","296273","296270","296269","296247","296246","296244","296243", "296242","296241","296240","296198","296197","296196","296195","296194","296192","296191","296143","296142", "296135","296134","296133","296132","296123","296074","296066","296065","296063","296062","296060","296016", "295942","295941","295937","295936","295913","295910","295909","295861","295860","295859","295856","295855", "295854","295853","295831","295829","295826","295825","295822","295819","295818","295816","295791","295788", "295786","295763","295762","295759","295758","295755","295754","295725","295723","295721","295719","295718", "295717","295714","295712","295676","295675","295673","295668","295667","295666","295615","295612","295611", "295610","295589","295588","295586","295585"}; TString runNumList18r[89] = { "297595","297590","297588","297558","297544","297542","297541","297540","297537","297512","297483","297479", "297452","297451","297450","297446","297442","297441","297415","297414","297413","297406","297405","297380", "297379","297372","297367","297366","297363","297336","297335","297333","297332","297317","297311","297310", "297278","297222","297221","297218","297196","297195","297193","297133","297132","297129","297128","297124", "297123","297119","297118","297117","297085","297035","297031","296966","296941","296938","296935","296934", "296932","296931","296930","296903","296900","296899","296894","296852","296851","296850","296848","296839", "296838","296836","296835","296799","296794","296793","296790","296787","296786","296785","296784","296781", "296752","296694","296693","296691","296690"}; runNumList = new std::map<int,int>; if (fPeriod.EqualTo("LHC10h")) for (int i = 0; i < 90; i++) runNumList->insert(std::pair<int,int>(runNumList10h[i].Atoi(),i)); else if (fPeriod.EqualTo("LHC15o")) for (int i = 0; i <138; i++) runNumList->insert(std::pair<int,int>(runNumList15o[i].Atoi(),i)); else if (fPeriod.EqualTo("LHC18q")) for (int i = 0; i <125; i++) runNumList->insert(std::pair<int,int>(runNumList18q[i].Atoi(),i)); else if (fPeriod.EqualTo("LHC18r")) for (int i = 0; i < 89; i++) runNumList->insert(std::pair<int,int>(runNumList18r[i].Atoi(),i)); else return; fHistRunNumBin = new TH1I("runNumBin","",(int)runNumList->size(),0,(int)runNumList->size()); std::map<int,int>::iterator iter; for (auto runNum : *runNumList) fHistRunNumBin->GetXaxis()->SetBinLabel(runNum.second, Form("%i",runNum.first)); fOutputList->Add(fHistRunNumBin); //////////////////////// // Pile up Function //////////////////////// // Dobrin 15o pass2 Pile-up function if (fPeriod.EqualTo("LHC15o")) { fSPDCutPU = new TF1("fSPDCutPU", "450. + 3.9*x", 0, 50000); Double_t parV0[8] = {33.4237, 0.953516, 0.0712137, 227.923, 8.9239, -0.00319679, 0.000306314, -7.6627e-07}; fV0CutPU = new TF1("fV0CutPU", "[0]+[1]*x - 6.*[2]*([3] + [4]*sqrt(x) + [5]*x + [6]*x*sqrt(x) + [7]*x*x)", 0, 100000); fV0CutPU->SetParameters(parV0); Double_t parV0CL0[6] = {0.0193587, 0.975914, 0.675714, 0.0292263, -0.000549509, 5.86421e-06}; fCenCutLowPU = new TF1("fCenCutLowPU", "[0]+[1]*x - 5.5*([2]+[3]*x+[4]*x*x+[5]*x*x*x)", 0, 100); fCenCutLowPU->SetParameters(parV0CL0); fCenCutHighPU = new TF1("fCenCutHighPU", "[0]+[1]*x + 5.5*([2]+[3]*x+[4]*x*x+[5]*x*x*x)", 0, 100); fCenCutHighPU->SetParameters(parV0CL0); Double_t parFB32[9] = {-812.822, 6.41796, 5421.83, -0.382601, 0.0299686, -26.6249, 321.388, -0.82615, 0.0167828}; fMultCutPU = new TF1("fMultCutPU", "[0]+[1]*x+[2]*exp([3]-[4]*x) - 6.*([5]+[6]*exp([7]-[8]*x))", 0, 100); fMultCutPU->SetParameters(parFB32); } // Rihan 18q/r Pile-up function if (fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")) { fSPDCutPU = new TF1("fSPDCutPU", "400. + 4.*x", 0, 10000); Double_t parV0[8] = {43.8011, 0.822574, 8.49794e-02, 1.34217e+02, 7.09023e+00, 4.99720e-02, -4.99051e-04, 1.55864e-06}; fV0CutPU = new TF1("fV0CutPU", "[0]+[1]*x - 6.*[2]*([3] + [4]*sqrt(x) + [5]*x + [6]*x*sqrt(x) + [7]*x*x)", 0, 100000); fV0CutPU->SetParameters(parV0); Double_t parV0CL0[6] = {0.320462, 0.961793, 1.02278, 0.0330054, -0.000719631, 6.90312e-06}; fCenCutLowPU = new TF1("fCenCutLowPU", "[0]+[1]*x - 6.5*([2]+[3]*x+[4]*x*x+[5]*x*x*x)", 0, 100); fCenCutLowPU->SetParameters(parV0CL0); fCenCutHighPU = new TF1("fCenCutHighPU", "[0]+[1]*x + 5.5*([2]+[3]*x+[4]*x*x+[5]*x*x*x)", 0, 100); fCenCutHighPU->SetParameters(parV0CL0); Double_t parFB32[8] = {2093.36, -66.425, 0.728932, -0.0027611, 1.01801e+02, -5.23083e+00, -1.03792e+00, 5.70399e-03}; fMultCutPU = new TF1("fMultCutPU", "[0]+[1]*x+[2]*x*x+[3]*x*x*x - 6.*([4]+[5]*sqrt(x)+[6]*x+[7]*x*x)", 0, 90); fMultCutPU->SetParameters(parFB32); } //////////////////////// // NUE //////////////////////// // Load Calibration Files // The global read-in lists and hists are loaded here. // They do not need to be loaded run by run. if (IsDoNUE) { if (!fListNUE) { std::cout<<("NUE list not found")<<std::endl; return; } if (fPeriod.EqualTo("LHC15o") || fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")) { hNUEweightPlus = (TH1D*)fListNUE->FindObject("trkEfficiencyChrgPos"); hNUEweightMinus = (TH1D*)fListNUE->FindObject("trkEfficiencyChrgNeg"); } } //////////////////////// // NUA //////////////////////// if (IsDoNUA) { if (!fListNUA) { std::cout<<("NUA list not found")<<std::endl; return; } if (fPeriod.EqualTo("LHC10h")) { hNUAweightPlus = (TH2D*)fListNUA->FindObject("hNUAweightPlus"); hNUAweightMinus = (TH2D*)fListNUA->FindObject("hNUAweightMinus"); } if (fPeriod.EqualTo("LHC15o") || fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")) { hCorrectNUAPos = new TH3F(); hCorrectNUANeg = new TH3F(); } } //////////////////////// // VZERO //////////////////////// if (IsVZEROCalibOn) { if (!fListVZEROCalib) { std::cout<<("VZERO calibration list not found")<<std::endl; return; } if (fPeriod.EqualTo("LHC10h")) { // Read GE Hists (x_y) : (iCh_runnumBin) hMultV0Read = (TH2D*)fListVZEROCalib->FindObject("hMultV0"); // Read Qx/y Mean Hists (x_y_z) : (runnumBin_centBin_vzBin) pV0XMeanRead[1] = (TProfile3D*)fListVZEROCalib->FindObject("pV0CCosMean"); pV0YMeanRead[1] = (TProfile3D*)fListVZEROCalib->FindObject("pV0CSinMean"); pV0XMeanRead[2] = (TProfile3D*)fListVZEROCalib->FindObject("pV0ACosMean"); pV0YMeanRead[2] = (TProfile3D*)fListVZEROCalib->FindObject("pV0ASinMean"); } if (fPeriod.EqualTo("LHC15o") || fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")) { // V0C Qx Mean // V0C Qy Mean // V0A Qx Mean // V0A Qy Mean contQxncm = (AliOADBContainer*)fListVZEROCalib->FindObject(Form("fqxc%im",2)); contQyncm = (AliOADBContainer*)fListVZEROCalib->FindObject(Form("fqyc%im",2)); contQxnam = (AliOADBContainer*)fListVZEROCalib->FindObject(Form("fqxa%im",2)); contQynam = (AliOADBContainer*)fListVZEROCalib->FindObject(Form("fqya%im",2)); for (int i = 0; i < 2; i++) { hQx2mV0[i] = new TH1D(); hQy2mV0[i] = new TH1D(); } } //15 V0 Mult if (fPeriod.EqualTo("LHC15o")) { contMult = (AliOADBContainer*)fListVZEROCalib->FindObject("hMultV0BefCorPfpx"); hMultV0 = new TH1D(); } if (fPeriod.EqualTo("LHC18q")) { fHCorrectV0ChWeghts = new TH2F(); } } //////////////////////// // ZDC //////////////////////// if (IsZDCCalibOn) { if (fPeriod.EqualTo("LHC10h") && !fListZDCCalib) { std::cout<<("ZDC calibration list not found")<<std::endl; return; } tree = new TTree(); fProfileForZNCGE = new TProfile(); fProfileForZNAGE = new TProfile(); fHn4DForZNCQxRC = new THnSparseF(); fHn4DForZNCQyRC = new THnSparseF(); fHn4DForZNCMtRC = new THnSparseF(); fHn4DForZNAQxRC = new THnSparseF(); fHn4DForZNAQyRC = new THnSparseF(); fHn4DForZNAMtRC = new THnSparseF(); fHn4DForZNCCountsRC = new THnSparseI(); fHn4DForZNACountsRC = new THnSparseI(); fProfile2DForCosC = new TProfile2D(); fProfile2DForSinC = new TProfile2D(); fProfile2DForCosA = new TProfile2D(); fProfile2DForSinA = new TProfile2D(); } //------------------ // QA //------------------ // event-wise fEvtCount = new TH1D("EvtCount", "Event Count", 25, 1, 26); fEvtCount->GetXaxis()->SetBinLabel(1,"All"); fEvtCount->GetXaxis()->SetBinLabel(2,"Read in"); fEvtCount->GetXaxis()->SetBinLabel(3,"Event"); fEvtCount->GetXaxis()->SetBinLabel(4,"Run Number"); fEvtCount->GetXaxis()->SetBinLabel(5,"Vertex"); fEvtCount->GetXaxis()->SetBinLabel(6,"Centrality"); fEvtCount->GetXaxis()->SetBinLabel(7,"Pile up"); fEvtCount->GetXaxis()->SetBinLabel(8,"Get VZERO Plane"); fEvtCount->GetXaxis()->SetBinLabel(9,"Get ZDC Plane"); fEvtCount->GetXaxis()->SetBinLabel(10,"Reset Vector"); fEvtCount->GetXaxis()->SetBinLabel(11,"Loop Track"); fEvtCount->GetXaxis()->SetBinLabel(12,"Get TPC Plane"); fEvtCount->GetXaxis()->SetBinLabel(13,"Resolution"); fEvtCount->GetXaxis()->SetBinLabel(14,"Loop V0"); fEvtCount->GetXaxis()->SetBinLabel(15,"Pair Lambda"); fEvtCount->GetXaxis()->SetBinLabel(20,"Manager"); fEvtCount->GetXaxis()->SetBinLabel(21,"Handler"); fEvtCount->GetXaxis()->SetBinLabel(22,"fAOD"); fEvtCount->GetXaxis()->SetBinLabel(23,"fPID"); fEvtCount->GetXaxis()->SetBinLabel(24,"fUtils"); fEvtCount->GetXaxis()->SetBinLabel(25,"fMultSel"); fOutputList->Add(fEvtCount); //////////// //QA Plots// //////////// // Event-wise QA fHistCent[0] = new TH1D("fHistCentBfCut", " Dist. of Centrality Before Cut ", 100, 0., 100.); fHistCent[1] = new TH1D("fHistCentAfCut", " Dist. of Centrality After Cut ", 100, 0., 100.); fOutputList->Add(fHistCent[0]); fOutputList->Add(fHistCent[1]); fHistVz[0] = new TH1D("fHistVzBfCut", "Dist of Centrality Before Cut", 200, -50., 50.); fHistVz[1] = new TH1D("fHistVzAfCut", "Dist of Centrality After Cut", 200, -50., 50.); fOutputList->Add(fHistVz[0]); fOutputList->Add(fHistVz[1]); fHist2DCentQA[0] = new TH2D("fHist2DCentQA_V0M_SPD1_BfCut", ";centV0M;centSPD1", 100, 0, 100, 100, 0, 100); fHist2DCentQA[1] = new TH2D("fHist2DCentQA_V0M_SPD1_AfCut", ";centV0M;centSPD1", 100, 0, 100, 100, 0, 100); fOutputList->Add(fHist2DCentQA[0]); fOutputList->Add(fHist2DCentQA[1]); fHist2DCentQA[2] = new TH2D("fHist2DCentQA_V0M_TRK_BfCut", ";centV0M;centTRK", 100, 0, 100, 100, 0, 100); fHist2DCentQA[3] = new TH2D("fHist2DCentQA_V0M_TRK_AfCut", ";centV0M;centTRK", 100, 0, 100, 100, 0, 100); fOutputList->Add(fHist2DCentQA[2]); fOutputList->Add(fHist2DCentQA[3]); fHist2DCentQA[4] = new TH2D("fHist2DCentQA_V0M_SPD0_BfCut", ";centV0M;centSPD0", 100, 0, 100, 100, 0, 100); fHist2DCentQA[5] = new TH2D("fHist2DCentQA_V0M_SPD0_AfCut", ";centV0M;centSPD0", 100, 0, 100, 100, 0, 100); fOutputList->Add(fHist2DCentQA[4]); fOutputList->Add(fHist2DCentQA[5]); fHist2DCentQA[6] = new TH2D("fHist2DCentQA_SPD1_SPD0_BfCut", ";centSPD1;centSPD0", 100, 0, 100, 100, 0, 100); fHist2DCentQA[7] = new TH2D("fHist2DCentQA_SPD1_SPD0_AfCut", ";centSPD1;centSPD0", 100, 0, 100, 100, 0, 100); fOutputList->Add(fHist2DCentQA[6]); fOutputList->Add(fHist2DCentQA[7]); fHist2DMultCentQA[0] = new TH2D("fHist2DMultCentQA_BfCut", ";centV0M;multFB32", 100, 0, 100, 20, 0, 5000); fHist2DMultCentQA[1] = new TH2D("fHist2DMultCentQA_AfCut", ";centV0M;multFB32", 100, 0, 100, 20, 0, 5000); fOutputList->Add(fHist2DMultCentQA[0]); fOutputList->Add(fHist2DMultCentQA[1]); // if (fMultComp.EqualTo("pileupByEDSTPC128") || fMultComp.EqualTo("pileupByGlobalTPC1")) { // hMultMultQA[0] = new TH2D("hMultMultQAmTPCmESDPileupBefCut", "befCut;multTPC;multESD", 50, 0, 5000, 160, 0, 16000); // hMultMultQA[1] = new TH2D("hMultMultQAmClobalmTPCEFPileupBefCut", "befCut;multGlobal;multTPCFE", 50, 0, 5000, 50, 0, 5000); // hMultMultQA[2] = new TH2D("hMultMultQAmFB32mTrkTOFBefCut", "befCut;multTrkTOF;nTrk", 201, 0, 20000, 201, 0, 20000); // hMultMultQA[3] = new TH2D("hMultMultQAmTPCmESDPileupAftCut", "aftCut;multTPC;multESD", 50, 0, 5000, 160, 0, 16000); // hMultMultQA[4] = new TH2D("hMultMultQAmClobalmTPCEFPileupAftCut", "aftCut;multGlobal;multTPCFE", 50, 0, 5000, 50, 0, 5000); // hMultMultQA[5] = new TH2D("hMultMultQAmFB32mTrkTOFAftCut", "aftCut;multTrkTOF;nTrk", 201, 0, 20000, 201, 0, 20000); // fOutputList->Add(hMultMultQA[0]); // fOutputList->Add(hMultMultQA[1]); // fOutputList->Add(hMultMultQA[2]); // fOutputList->Add(hMultMultQA[3]); // fOutputList->Add(hMultMultQA[4]); // fOutputList->Add(hMultMultQA[5]); // } // track-wise QA fHistPt = new TH1D("fHistPt", "", 200, 0., 20.); fHistEta = new TH1D("fHistEta", "", 200, -10., 10.); fHistNhits = new TH1D("fHistNhits", "", 200, 0., 200.); fHist2DPDedx = new TH2D("fHist2DPDedx", "", 400, -10., 10., 400, 0, 1000); fHistDcaXY = new TH1D("fHistDcaXY", "", 100, 0., 10.); fHistDcaZ = new TH1D("fHistDcaZ", "", 100, 0., 10.); fHistPhi[0] = new TH1D("fHistPhi", "", 100, 0, TMath::TwoPi()); fHistPhi[1] = new TH1D("fHistPhi_afterNUA", "", 100, 0, TMath::TwoPi()); fHist2DEtaPhi[0] = new TH2D("fHistEtaPhi", "", 16,-0.8,0.8, 100, 0, TMath::TwoPi()); fHist2DEtaPhi[1] = new TH2D("fHistEtaPhi_afterfNUA", "", 16,-0.8,0.8, 100, 0, TMath::TwoPi()); fOutputList->Add(fHistPt); fOutputList->Add(fHistEta); fOutputList->Add(fHistNhits); fOutputList->Add(fHist2DPDedx); fOutputList->Add(fHistDcaXY); fOutputList->Add(fHistDcaZ); for (int i = 0; i < 2; i++) fOutputList->Add(fHistPhi[i]); for (int i = 0; i < 2; i++) fOutputList->Add(fHist2DEtaPhi[i]); //Plane QA char chCalibStep[5]; for (int i = 0; i < 2; i++) { if (i==0) sprintf(chCalibStep,"GE"); if (i==1) sprintf(chCalibStep,"RC"); if (IsQAVZERO) { fProfileV0CQxCent[i] = new TProfile(Form("fProfileV0CQxCent%s",chCalibStep), "", 100, 0, 100); fProfileV0CQyCent[i] = new TProfile(Form("fProfileV0CQyCent%s",chCalibStep), "", 100, 0, 100); fProfileV0CQxVtx[i] = new TProfile(Form("fProfileV0CQxVtx%s",chCalibStep), "", 20, -10, 10); fProfileV0CQyVtx[i] = new TProfile(Form("fProfileV0CQyVtx%s",chCalibStep), "", 20, -10, 10); fHist2DCalibPsi2V0CCent[i] = new TH2D(Form("fHist2DCalibPsi2V0CCent%s",chCalibStep), "", 20, 0, 100, 100, 0, TMath::TwoPi()); fOutputList->Add(fProfileV0CQxCent[i]); fOutputList->Add(fProfileV0CQyCent[i]); fOutputList->Add(fProfileV0CQxVtx[i]); fOutputList->Add(fProfileV0CQyVtx[i]); fOutputList->Add(fHist2DCalibPsi2V0CCent[i]); fProfileV0AQxCent[i] = new TProfile(Form("fProfileV0AQxCent%s",chCalibStep), "", 100, 0, 100); fProfileV0AQyCent[i] = new TProfile(Form("fProfileV0AQyCent%s",chCalibStep), "", 100, 0, 100); fProfileV0AQxVtx[i] = new TProfile(Form("fProfileV0AQxVtx%s",chCalibStep), "", 20, -10, 10); fProfileV0AQyVtx[i] = new TProfile(Form("fProfileV0AQyVtx%s",chCalibStep), "", 20, -10, 10); fHist2DCalibPsi2V0ACent[i] = new TH2D(Form("fHist2DCalibPsi2V0ACent%s",chCalibStep), "", 20, 0, 100, 100, 0, TMath::TwoPi()); fOutputList->Add(fProfileV0AQxCent[i]); fOutputList->Add(fProfileV0AQyCent[i]); fOutputList->Add(fProfileV0AQxVtx[i]); fOutputList->Add(fProfileV0AQyVtx[i]); fOutputList->Add(fHist2DCalibPsi2V0ACent[i]); } if (IsQAZDC) { fProfileZNCQxCent[i] = new TProfile(Form("fProfileZNCQxCent%s",chCalibStep), "", 100, 0, 100); fProfileZNCQyCent[i] = new TProfile(Form("fProfileZNCQyCent%s",chCalibStep), "", 100, 0, 100); fHist2DCalibPsi1ZNCCent[i] = new TH2D(Form("fHist2DCalibPsi1ZNCCent%s",chCalibStep), "", 20, 0, 100, 100, 0, TMath::TwoPi()); fOutputList->Add(fProfileZNCQxCent[i]); fOutputList->Add(fProfileZNCQyCent[i]); fOutputList->Add(fHist2DCalibPsi1ZNCCent[i]); fProfileZNAQxCent[i] = new TProfile(Form("fProfileZNAQxCent%s",chCalibStep), "", 100, 0, 100); fProfileZNAQyCent[i] = new TProfile(Form("fProfileZNAQyCent%s",chCalibStep), "", 100, 0, 100); fHist2DCalibPsi1ZNACent[i] = new TH2D(Form("fHist2DCalibPsi1ZNACent%s",chCalibStep), "", 20, 0, 100, 100, 0, TMath::TwoPi()); fOutputList->Add(fProfileZNAQxCent[i]); fOutputList->Add(fProfileZNAQyCent[i]); fOutputList->Add(fHist2DCalibPsi1ZNACent[i]); fProfileZDCQxAQxCCent[i] = new TProfile(Form("fProfileZDCQxAQxCCent%s",chCalibStep), "", 100, 0, 100); fProfileZDCQxAQyCCent[i] = new TProfile(Form("fProfileZDCQxAQyCCent%s",chCalibStep), "", 100, 0, 100); fProfileZDCQyAQxCCent[i] = new TProfile(Form("fProfileZDCQyAQxCCent%s",chCalibStep), "", 100, 0, 100); fProfileZDCQyAQyCCent[i] = new TProfile(Form("fProfileZDCQyAQyCCent%s",chCalibStep), "", 100, 0, 100); fOutputList->Add(fProfileZDCQxAQxCCent[i]); fOutputList->Add(fProfileZDCQxAQyCCent[i]); fOutputList->Add(fProfileZDCQyAQxCCent[i]); fOutputList->Add(fProfileZDCQyAQyCCent[i]); } } if (IsQAZDC) { fHist2DCalibPsi1ZNCCent[2] = new TH2D("fHist2DCalibPsi1ZNCCentSF", "", 20, 0, 100, 100, 0, TMath::TwoPi()); fHist2DCalibPsi1ZNACent[2] = new TH2D("fHist2DCalibPsi1ZNACentSF", "", 20, 0, 100, 100, 0, TMath::TwoPi()); fOutputList->Add(fHist2DCalibPsi1ZNCCent[2]); fOutputList->Add(fHist2DCalibPsi1ZNACent[2]); fProfileZNCTowerMeanEnegry[0] = new TProfile("fProfileZNCTowerMeanEnegryRW","",5,0,5); fProfileZNCTowerMeanEnegry[1] = new TProfile("fProfileZNCTowerMeanEnegryGE","",5,0,5); fProfileZNATowerMeanEnegry[0] = new TProfile("fProfileZNATowerMeanEnegryRW","",5,0,5); fProfileZNATowerMeanEnegry[1] = new TProfile("fProfileZNATowerMeanEnegryGE","",5,0,5); fOutputList->Add(fProfileZNCTowerMeanEnegry[0]); fOutputList->Add(fProfileZNCTowerMeanEnegry[1]); fOutputList->Add(fProfileZNATowerMeanEnegry[0]); fOutputList->Add(fProfileZNATowerMeanEnegry[1]); } //V0s QA fHistV0Pt = new TH1D("hV0Pt","", 200, 0., 20.); fHistV0Eta = new TH1D("hV0Eta","", 200, -10., 10.); fHistV0DcatoPrimVertex = new TH1D("hV0DcaToPrimVertex","",200, 0., 20.); fHistV0CPA = new TH1D("hV0CPA","", 1000, 0.9, 1.); fHistV0DecayLength = new TH1D("hV0DecayLength","",500,0,500.); fOutputList->Add(fHistV0Pt); fOutputList->Add(fHistV0Eta); fOutputList->Add(fHistV0DcatoPrimVertex); fOutputList->Add(fHistV0CPA); fOutputList->Add(fHistV0DecayLength); //Lambda QA char chCut[5]; for (int i=0; i<2; i++) { ///// Case 0 = before cut, case 1 = afterCut. if (i==0) sprintf(chCut,"Bf"); if (i==1) sprintf(chCut,"Af"); /// Lambdas: fHistLambdaPt[i] = new TH1D(Form("hLambdaPt_%sMassCut",chCut),"", 200, 0., 20.); fHistLambdaEta[i] = new TH1D(Form("hLambdaEta_%sMassCut",chCut),"",200, -10., 10.); fHistLambdaPhi[i] = new TH1D(Form("hLambdaPhi_%sMassCut",chCut),"", 360, 0., TMath::TwoPi()); fHistLambdaDcaToPrimVertex[i] = new TH1D(Form("hLambdaDcaToPrimVertex_%sMassCut",chCut),"",200, 0., 20.); fHistLambdaCPA[i] = new TH1D(Form("hLambdaCPA_%sMassCut",chCut),"",200, 0.9, 1.); fHistLambdaDecayLength[i] = new TH1D(Form("hLambdaDecayLength_%sMassCut",chCut),"", 250, 0., 500.); fHistLambdaMass[i] = new TH1D(Form("hLambdaMass_%sMassCut",chCut),"",1000,1.,1.25); // Current bin size = 0.00025 fProfileLambdaMassVsPt[i] = new TProfile(Form("pLambdaMassVsPt_%sMassCut",chCut),"",200,0,20); fOutputList->Add(fHistLambdaPt[i]); fOutputList->Add(fHistLambdaEta[i]); fOutputList->Add(fHistLambdaPhi[i]); fOutputList->Add(fHistLambdaDcaToPrimVertex[i]); fOutputList->Add(fHistLambdaCPA[i]); fOutputList->Add(fHistLambdaDecayLength[i]); fOutputList->Add(fHistLambdaMass[i]); fOutputList->Add(fProfileLambdaMassVsPt[i]); // AntiLambdas fHistAntiLambdaPt[i] = new TH1D(Form("hAntiLambdaPt_%sMassCut",chCut),"", 200, 0., 20.); fHistAntiLambdaEta[i] = new TH1D(Form("hAntiLambdaEta_%sMassCut",chCut),"",200, -10., 10.); fHistAntiLambdaPhi[i] = new TH1D(Form("hAntiLambdaPhi_%sMassCut",chCut),"", 360, 0, TMath::TwoPi()); fHistAntiLambdaDcaToPrimVertex[i] = new TH1D(Form("hAntiLambdaDcaToPrimVertex_%sMassCut",chCut),"",200, 0., 20.); fHistAntiLambdaCPA[i] = new TH1D(Form("hAntiLambdaCPA_%sMassCut",chCut),"",200, 0.9, 1.); fHistAntiLambdaDecayLength[i] = new TH1D(Form("hAntiLambdaDecayLength_%sMassCut",chCut),"", 250, 0., 500.); fHistAntiLambdaMass[i] = new TH1D(Form("hAntiLambdaMass_%sMassCut",chCut),"",1000,1.,1.25); // Current bin size = 0.00025 fProfileAntiLambdaMassVsPt[i] = new TProfile(Form("pAntiLambdaMassVsPt_%sMassCut",chCut),"",200,0,20); fOutputList->Add(fHistAntiLambdaPt[i]); fOutputList->Add(fHistAntiLambdaEta[i]); fOutputList->Add(fHistAntiLambdaPhi[i]); fOutputList->Add(fHistAntiLambdaDcaToPrimVertex[i]); fOutputList->Add(fHistAntiLambdaCPA[i]); fOutputList->Add(fHistAntiLambdaDecayLength[i]); fOutputList->Add(fHistAntiLambdaMass[i]); fOutputList->Add(fProfileAntiLambdaMassVsPt[i]); } //Flow QA char chPlaneType[5]; for (int i = 0; i < 5; i++) { if (i==0) sprintf(chPlaneType,"TPC"); if (i==1) sprintf(chPlaneType,"V0C"); if (i==2) sprintf(chPlaneType,"V0A"); if (i==3) sprintf(chPlaneType,"ZNC"); if (i==4) sprintf(chPlaneType,"ZNA"); fProfile2DRawFlowCentPthPos[i] = new TProfile2D(Form("fProfile2DRawFlowCentPthPos_%s",chPlaneType),"",10,0,100,25,0,5); fProfile2DRawFlowCentPthNeg[i] = new TProfile2D(Form("fProfile2DRawFlowCentPthNeg_%s",chPlaneType),"",10,0,100,25,0,5); fProfile2DRawFlowCentPtProton[i] = new TProfile2D(Form("fProfile2DRawFlowCentPtProton_%s",chPlaneType),"",10,0,100,25,0,5); fProfile2DRawFlowCentPtAntiProton[i] = new TProfile2D(Form("fProfile2DRawFlowCentPtAntiProton_%s",chPlaneType),"",10,0,100,25,0,5); fProfile2DRawFlowCentPtLambda[i] = new TProfile2D(Form("fProfile2DRawFlowCentPtLambda_%s",chPlaneType),"",10,0,100,25,0,5); fProfile2DRawFlowCentPtAntiLambda[i] = new TProfile2D(Form("fProfile2DRawFlowCentPtAntiLambda_%s",chPlaneType),"",10,0,100,25,0,5); fOutputList->Add(fProfile2DRawFlowCentPthPos[i]); fOutputList->Add(fProfile2DRawFlowCentPthNeg[i]); fOutputList->Add(fProfile2DRawFlowCentPtProton[i]); fOutputList->Add(fProfile2DRawFlowCentPtAntiProton[i]); fOutputList->Add(fProfile2DRawFlowCentPtLambda[i]); fOutputList->Add(fProfile2DRawFlowCentPtAntiLambda[i]); } //////////////////////// // Results //////////////////////// // Plane we used fHist2DPsi2TPCPosCent = new TH2D("fHist2DPsi2TPCPosCent","",20,0,100,100,0,TMath::TwoPi()); fHist2DPsi2TPCNegCent = new TH2D("fHist2DPsi2TPCNegCent","",20,0,100,100,0,TMath::TwoPi()); fHist2DPsi2V0CCent = new TH2D("fHist2DPsi2V0CCent","",20,0,100,100,0,TMath::TwoPi()); fHist2DPsi2V0ACent = new TH2D("fHist2DPsi2V0ACent","",20,0,100,100,0,TMath::TwoPi()); fHist2DPsi1ZNCCent = new TH2D("fHist2DPsi1ZNCCent","",20,0,100,100,0,TMath::TwoPi()); fHist2DPsi1ZNACent = new TH2D("fHist2DPsi1ZNACent","",20,0,100,100,0,TMath::TwoPi()); fOutputList->Add(fHist2DPsi2TPCPosCent); fOutputList->Add(fHist2DPsi2TPCNegCent); fOutputList->Add(fHist2DPsi2V0CCent); fOutputList->Add(fHist2DPsi2V0ACent); fOutputList->Add(fHist2DPsi1ZNCCent); fOutputList->Add(fHist2DPsi1ZNACent); //Resolution ///SideC-SideA Event Plane Correlations for Resolution Estimation fProfileTPCPsi2Correlation = new TProfile("fProfileTPCPsi2Correlation","TPCPos-TPCNeg Psi2 Res. vs Cent; Cent; Resolution",100,0,100.); fProfileV0MPsi2Correlation = new TProfile("fProfileV0MPsi2Correlation","V0C-V0A Psi2 Res. vs Cent; Cent; Resolution",100,0,100.); fProfileZDCPsi1Correlation = new TProfile("fProfileZDCPsi1Correlation","ZNC-ZNA Psi1 Res. vs Cent; Cent; Resolution",100,0,100.); fProfileZDCPsi2Correlation = new TProfile("fProfileZDCPsi2Correlation","ZNC-ZNA Psi2 Res. vs Cent; Cent; Resolution",100,0,100.); fOutputList->Add(fProfileTPCPsi2Correlation); fOutputList->Add(fProfileV0MPsi2Correlation); fOutputList->Add(fProfileZDCPsi1Correlation); fOutputList->Add(fProfileZDCPsi2Correlation); ///V0X-TPC Event Plane Correlations for Resolution: fProfileV0CTPCPosPsi2Correlation = new TProfile("fProfileV0CTPCPosPsi2Correlation","V0C-TPCPos Psi2; Cent; Resolution",100,0,100.); fProfileV0ATPCPosPsi2Correlation = new TProfile("fProfileV0ATPCPosPsi2Correlation","V0A-TPCPos Psi2; Cent; Resolution",100,0,100.); fProfileV0CTPCNegPsi2Correlation = new TProfile("fProfileV0CTPCNegPsi2Correlation","V0C-TPCNeg Psi2; Cent; Resolution",100,0,100.); fProfileV0ATPCNegPsi2Correlation = new TProfile("fProfileV0ATPCNegPsi2Correlation","V0A-TPCNeg Psi2; Cent; Resolution",100,0,100.); fOutputList->Add(fProfileV0CTPCPosPsi2Correlation); fOutputList->Add(fProfileV0ATPCPosPsi2Correlation); fOutputList->Add(fProfileV0CTPCNegPsi2Correlation); fOutputList->Add(fProfileV0ATPCNegPsi2Correlation); ///Lambda-X correlators ///Delta Correlators: ///Lambda - X fProfileDelta_Lambda_hPos = new TProfile("fProfileDelta_Lambda_hPos", "", 20, 0., 100.); fProfileDelta_Lambda_hNeg = new TProfile("fProfileDelta_Lambda_hNeg", "", 20, 0., 100.); fProfileDelta_Lambda_Proton = new TProfile("fProfileDelta_Lambda_Proton", "", 20, 0., 100.); fProfileDelta_Lambda_AntiProton = new TProfile("fProfileDelta_Lambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileDelta_Lambda_hPos); fOutputList->Add(fProfileDelta_Lambda_hNeg); fOutputList->Add(fProfileDelta_Lambda_Proton); fOutputList->Add(fProfileDelta_Lambda_AntiProton); ///AntiLambda - X fProfileDelta_AntiLambda_hPos = new TProfile("fProfileDelta_AntiLambda_hPos", "", 20, 0., 100.); fProfileDelta_AntiLambda_hNeg = new TProfile("fProfileDelta_AntiLambda_hNeg", "", 20, 0., 100.); fProfileDelta_AntiLambda_Proton = new TProfile("fProfileDelta_AntiLambda_Proton", "", 20, 0., 100.); fProfileDelta_AntiLambda_AntiProton = new TProfile("fProfileDelta_AntiLambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileDelta_AntiLambda_hPos); fOutputList->Add(fProfileDelta_AntiLambda_hNeg); fOutputList->Add(fProfileDelta_AntiLambda_Proton); fOutputList->Add(fProfileDelta_AntiLambda_AntiProton); ///Gamma Correlators: //TPC Plane ///Lambda - X fProfileGammaTPC_Lambda_hPos = new TProfile("fProfileGammaTPC_Lambda_hPos", "", 20, 0., 100.); fProfileGammaTPC_Lambda_hNeg = new TProfile("fProfileGammaTPC_Lambda_hNeg", "", 20, 0., 100.); fProfileGammaTPC_Lambda_Proton = new TProfile("fProfileGammaTPC_Lambda_Proton", "", 20, 0., 100.); fProfileGammaTPC_Lambda_AntiProton = new TProfile("fProfileGammaTPC_Lambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaTPC_Lambda_hPos); fOutputList->Add(fProfileGammaTPC_Lambda_hNeg); fOutputList->Add(fProfileGammaTPC_Lambda_Proton); fOutputList->Add(fProfileGammaTPC_Lambda_AntiProton); ///AntiLambda - X fProfileGammaTPC_AntiLambda_hPos = new TProfile("fProfileGammaTPC_AntiLambda_hPos", "", 20, 0., 100.); fProfileGammaTPC_AntiLambda_hNeg = new TProfile("fProfileGammaTPC_AntiLambda_hNeg", "", 20, 0., 100.); fProfileGammaTPC_AntiLambda_Proton = new TProfile("fProfileGammaTPC_AntiLambda_Proton", "", 20, 0., 100.); fProfileGammaTPC_AntiLambda_AntiProton = new TProfile("fProfileGammaTPC_AntiLambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaTPC_AntiLambda_hPos); fOutputList->Add(fProfileGammaTPC_AntiLambda_hNeg); fOutputList->Add(fProfileGammaTPC_AntiLambda_Proton); fOutputList->Add(fProfileGammaTPC_AntiLambda_AntiProton); //V0C Plane ///Lambda - X fProfileGammaV0C_Lambda_hPos = new TProfile("fProfileGammaV0C_Lambda_hPos", "", 20, 0., 100.); fProfileGammaV0C_Lambda_hNeg = new TProfile("fProfileGammaV0C_Lambda_hNeg", "", 20, 0., 100.); fProfileGammaV0C_Lambda_Proton = new TProfile("fProfileGammaV0C_Lambda_Proton", "", 20, 0., 100.); fProfileGammaV0C_Lambda_AntiProton = new TProfile("fProfileGammaV0C_Lambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaV0C_Lambda_hPos); fOutputList->Add(fProfileGammaV0C_Lambda_hNeg); fOutputList->Add(fProfileGammaV0C_Lambda_Proton); fOutputList->Add(fProfileGammaV0C_Lambda_AntiProton); ///AntiLambda - X fProfileGammaV0C_AntiLambda_hPos = new TProfile("fProfileGammaV0C_AntiLambda_hPos", "", 20, 0., 100.); fProfileGammaV0C_AntiLambda_hNeg = new TProfile("fProfileGammaV0C_AntiLambda_hNeg", "", 20, 0., 100.); fProfileGammaV0C_AntiLambda_Proton = new TProfile("fProfileGammaV0C_AntiLambda_Proton", "", 20, 0., 100.); fProfileGammaV0C_AntiLambda_AntiProton = new TProfile("fProfileGammaV0C_AntiLambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaV0C_AntiLambda_hPos); fOutputList->Add(fProfileGammaV0C_AntiLambda_hNeg); fOutputList->Add(fProfileGammaV0C_AntiLambda_Proton); fOutputList->Add(fProfileGammaV0C_AntiLambda_AntiProton); //V0A Plane ///Lambda - X fProfileGammaV0A_Lambda_hPos = new TProfile("fProfileGammaV0A_Lambda_hPos", "", 20, 0., 100.); fProfileGammaV0A_Lambda_hNeg = new TProfile("fProfileGammaV0A_Lambda_hNeg", "", 20, 0., 100.); fProfileGammaV0A_Lambda_Proton = new TProfile("fProfileGammaV0A_Lambda_Proton", "", 20, 0., 100.); fProfileGammaV0A_Lambda_AntiProton = new TProfile("fProfileGammaV0A_Lambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaV0A_Lambda_hPos); fOutputList->Add(fProfileGammaV0A_Lambda_hNeg); fOutputList->Add(fProfileGammaV0A_Lambda_Proton); fOutputList->Add(fProfileGammaV0A_Lambda_AntiProton); ///AntiLambda - X fProfileGammaV0A_AntiLambda_hPos = new TProfile("fProfileGammaV0A_AntiLambda_hPos", "", 20, 0., 100.); fProfileGammaV0A_AntiLambda_hNeg = new TProfile("fProfileGammaV0A_AntiLambda_hNeg", "", 20, 0., 100.); fProfileGammaV0A_AntiLambda_Proton = new TProfile("fProfileGammaV0A_AntiLambda_Proton", "", 20, 0., 100.); fProfileGammaV0A_AntiLambda_AntiProton = new TProfile("fProfileGammaV0A_AntiLambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaV0A_AntiLambda_hPos); fOutputList->Add(fProfileGammaV0A_AntiLambda_hNeg); fOutputList->Add(fProfileGammaV0A_AntiLambda_Proton); fOutputList->Add(fProfileGammaV0A_AntiLambda_AntiProton); //ZNC Plane ///Lambda - X fProfileGammaZNC_Lambda_hPos = new TProfile("fProfileGammaZNC_Lambda_hPos", "", 20, 0., 100.); fProfileGammaZNC_Lambda_hNeg = new TProfile("fProfileGammaZNC_Lambda_hNeg", "", 20, 0., 100.); fProfileGammaZNC_Lambda_Proton = new TProfile("fProfileGammaZNC_Lambda_Proton", "", 20, 0., 100.); fProfileGammaZNC_Lambda_AntiProton = new TProfile("fProfileGammaZNC_Lambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaZNC_Lambda_hPos); fOutputList->Add(fProfileGammaZNC_Lambda_hNeg); fOutputList->Add(fProfileGammaZNC_Lambda_Proton); fOutputList->Add(fProfileGammaZNC_Lambda_AntiProton); ///AntiLambda - X fProfileGammaZNC_AntiLambda_hPos = new TProfile("fProfileGammaZNC_AntiLambda_hPos", "", 20, 0., 100.); fProfileGammaZNC_AntiLambda_hNeg = new TProfile("fProfileGammaZNC_AntiLambda_hNeg", "", 20, 0., 100.); fProfileGammaZNC_AntiLambda_Proton = new TProfile("fProfileGammaZNC_AntiLambda_Proton", "", 20, 0., 100.); fProfileGammaZNC_AntiLambda_AntiProton = new TProfile("fProfileGammaZNC_AntiLambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaZNC_AntiLambda_hPos); fOutputList->Add(fProfileGammaZNC_AntiLambda_hNeg); fOutputList->Add(fProfileGammaZNC_AntiLambda_Proton); fOutputList->Add(fProfileGammaZNC_AntiLambda_AntiProton); //ZNA Plane ///Lambda - X fProfileGammaZNA_Lambda_hPos = new TProfile("fProfileGammaZNA_Lambda_hPos", "", 20, 0., 100.); fProfileGammaZNA_Lambda_hNeg = new TProfile("fProfileGammaZNA_Lambda_hNeg", "", 20, 0., 100.); fProfileGammaZNA_Lambda_Proton = new TProfile("fProfileGammaZNA_Lambda_Proton", "", 20, 0., 100.); fProfileGammaZNA_Lambda_AntiProton = new TProfile("fProfileGammaZNA_Lambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaZNA_Lambda_hPos); fOutputList->Add(fProfileGammaZNA_Lambda_hNeg); fOutputList->Add(fProfileGammaZNA_Lambda_Proton); fOutputList->Add(fProfileGammaZNA_Lambda_AntiProton); ///AntiLambda - X fProfileGammaZNA_AntiLambda_hPos = new TProfile("fProfileGammaZNA_AntiLambda_hPos", "", 20, 0., 100.); fProfileGammaZNA_AntiLambda_hNeg = new TProfile("fProfileGammaZNA_AntiLambda_hNeg", "", 20, 0., 100.); fProfileGammaZNA_AntiLambda_Proton = new TProfile("fProfileGammaZNA_AntiLambda_Proton", "", 20, 0., 100.); fProfileGammaZNA_AntiLambda_AntiProton = new TProfile("fProfileGammaZNA_AntiLambda_AntiProton", "", 20, 0., 100.); fOutputList->Add(fProfileGammaZNA_AntiLambda_hPos); fOutputList->Add(fProfileGammaZNA_AntiLambda_hNeg); fOutputList->Add(fProfileGammaZNA_AntiLambda_Proton); fOutputList->Add(fProfileGammaZNA_AntiLambda_AntiProton); PostData(1,fOutputList); if (fDebug) Printf("UserCreateOutputObjects() Post Data Success!"); } //------------------------------------------------ void AliAnalysisTaskLambdaProtonCVE::UserExec(Option_t *) { if (fDebug) Printf("===============================We are in UserExec!================================"); fEvtCount->Fill(1); //---------------------------- // Handle //---------------------------- AliAnalysisManager* manager = AliAnalysisManager::GetAnalysisManager(); if (!manager) { AliError(Form("%s: Could not get Analysis Manager", GetName())); } else fEvtCount->Fill(20); AliAODInputHandler* handler = (AliAODInputHandler*)manager->GetInputEventHandler(); if (!handler) { AliError(Form("%s: Could not get Input Handler", GetName())); } else fEvtCount->Fill(21); fAOD = dynamic_cast <AliAODEvent*> (InputEvent()); if (!fAOD) { AliError(Form("%s: Could not get AOD event", GetName())); } else fEvtCount->Fill(22); fPIDResponse = handler->GetPIDResponse(); if (!fPIDResponse) { AliError(Form("%s: Could not get PIDResponse", GetName())); } else fEvtCount->Fill(23); fUtils = new AliAnalysisUtils(); if (!fUtils) { AliError(Form("%s: Could not get AliAnalysisUtils", GetName())); } else fEvtCount->Fill(24); if (fPeriod.EqualTo("LHC15o") || fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")) { AliMultSelection* fMultSel = (AliMultSelection*)InputEvent()->FindListObject("MultSelection"); if (!fMultSel) { AliError(Form("%s: Could not get AliMultSelection", GetName())); } else fEvtCount->Fill(25); if (!manager || !handler || !fAOD || !fPIDResponse || !fUtils || !fMultSel) return; } if (!manager || !handler || !fAOD || !fPIDResponse || !fUtils) return; fEvtCount->Fill(2); if (fDebug) Printf("Handles done!"); //---------------------------- // Trigger //---------------------------- UInt_t mask = handler->IsEventSelected(); bool isTrigselected = false; if (fTrigger.EqualTo("kMB")) isTrigselected = mask & AliVEvent::kMB; else if (fTrigger.EqualTo("kINT7")) isTrigselected = mask & AliVEvent::kINT7; else if (fTrigger.EqualTo("kINT7+kCentral+kSemiCentral")) isTrigselected = mask & (AliVEvent::kINT7 + AliVEvent::kCentral + AliVEvent::kSemiCentral); if (isTrigselected == false) return; fEvtCount->Fill(3); if (fDebug) Printf("trigger done!"); //---------------------------- // Run Number //---------------------------- fRunNum = fAOD->GetRunNumber(); if (fRunNum != fOldRunNum) { // Load the run dependent calibration hist if (!GetCalibHistForThisRun()) return; fRunNumBin = runNumList->at(fRunNum); fOldRunNum = fRunNum; if (fRunNumBin < 0) return; } fHistRunNumBin->Fill(fRunNumBin); fEvtCount->Fill(4); if (fDebug) Printf("run nummbr done!"); //---------------------------- // Vertex //---------------------------- AliAODVertex* fVtx = fAOD->GetPrimaryVertex(); fVtx -> GetXYZ(fVertex); AliAODVertex* vtSPD = fAOD->GetPrimaryVertexSPD(); double vx = fVertex[0]; double vy = fVertex[1]; double vz = fVertex[2]; if (fabs(fVertex[0])<1e-6 || fabs(fVertex[1])<1e-6 || fabs(fVertex[2])<1e-6) return; double dz = vz - fAOD->GetPrimaryVertexSPD()->GetZ(); if (fabs(vz) > fVzCut) return; if (!fVtx || fVtx->GetNContributors() < 2 || vtSPD->GetNContributors()<1) return; fHistVz[0]->Fill(vz); // https://twiki.cern.ch/twiki/bin/viewauth/ALICE/AliDPGtoolsEventProp // fEventCuts.SetCentralityEstimators("V0M","CL1"); // if (!fEventCuts->AcceptEvent(fAOD) ) return; if (fPeriod.EqualTo("LHC10h")) if (fabs(dz)>0.5) return; if (fPeriod.EqualTo("LHC15o")) { double covTrc[6],covSPD[6]; fVtx->GetCovarianceMatrix(covTrc); fAOD->GetPrimaryVertexSPD()->GetCovarianceMatrix(covSPD); double errTot = TMath::Sqrt(covTrc[5]+covSPD[5]); double errTrc = TMath::Sqrt(covTrc[5]); double nsigTot = TMath::Abs(dz)/errTot, nsigTrc = TMath::Abs(dz)/errTrc; if (fabs(dz)>0.2 || nsigTot>10 || nsigTrc>20) return; } fHistVz[1]->Fill(vz); for (int i = 0; i < 20; ++i) { if (vz > -10+i*1 && vz < -10+(i+1)*1) {fVzBin = i; break;} } if (fVzBin<-990) return; fEvtCount->Fill(5); if (fDebug) Printf("vertex done!"); //---------------------------- // Centrality //---------------------------- double centV0M = -1, centTRK = -1, centSPD0 = -1, centSPD1 = -1, centV0A = -1; if (fPeriod.EqualTo("LHC10h")) { centV0M = fAOD->GetCentrality()->GetCentralityPercentile("V0M"); centTRK = fAOD->GetCentrality()->GetCentralityPercentile("TRK"); centSPD0 = fAOD->GetCentrality()->GetCentralityPercentile("CL0"); centSPD1 = fAOD->GetCentrality()->GetCentralityPercentile("CL1"); centV0A = fAOD->GetCentrality()->GetCentralityPercentile("V0A"); } else if (fPeriod.EqualTo("LHC15o") || fPeriod.EqualTo("LHC18q")) { AliMultSelection* fMultSel = (AliMultSelection*)InputEvent()->FindListObject("MultSelection"); centV0M = fMultSel->GetMultiplicityPercentile("V0M"); centTRK = fMultSel->GetMultiplicityPercentile("TRK"); centSPD0 = fMultSel->GetMultiplicityPercentile("CL0"); centSPD1 = fMultSel->GetMultiplicityPercentile("CL1"); } //we use centV0M as the default centrality fCent = centV0M; fHist2DCentQA[0]->Fill(centV0M,centSPD1); fHist2DCentQA[2]->Fill(centV0M,centTRK); fHist2DCentQA[4]->Fill(centV0M,centSPD0); fHist2DCentQA[6]->Fill(centSPD1,centSPD0); if (fabs(fCent-centSPD1)>fCentDiffCut) return; fHist2DCentQA[1]->Fill(centV0M,centSPD1); fHist2DCentQA[3]->Fill(centV0M,centTRK); fHist2DCentQA[5]->Fill(centV0M,centSPD0); fHist2DCentQA[7]->Fill(centSPD1,centSPD0); if (fCent < 0 || fCent >= 80) return; // cent bin fCentBin = (int)fCent/10; fHistCent[0]->Fill(fCent); fEvtCount->Fill(6); if (fDebug) Printf("centrality done!"); //---------------------------- // Pile up //---------------------------- if (fPeriod.EqualTo("LHC10h")) if (!RemovalForRun1()) return; if (fPeriod.EqualTo("LHC15o") || fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")) { // hMultCentQA[0]->Fill(fCent, fAOD->GetNumberOfTracks()); // raw Trk Multi Vs Cent(V0M) // if (PileUpMultiVertex(fAOD)) return; // if (!RejectEvtMultComp(fAOD)) return; // hMultCentQA[1]->Fill(fCent, fAOD->GetNumberOfTracks()); // Mult_Cent QA // if (!AODPileupCheck (fAOD)) return; if (!RejectEvtTFFit()) return; // 15o_pass2 } fHistCent[1]->Fill(fCent); fEvtCount->Fill(7); if (fDebug) Printf("pile-up done!"); //---------------------------- // VZERO Plane //---------------------------- if (!GetVZEROPlane()) return; fEvtCount->Fill(8); if (fDebug) Printf("Get VZERO Plane done!"); //---------------------------- // ZDC Plane //---------------------------- if (!GetZDCPlane()) return; fEvtCount->Fill(9); if (fDebug) Printf("Get ZDC Plane done!"); //---------------------------- // Loop Tracks / Fill Vectors //---------------------------- //Reset vectors ResetVectors(); fEvtCount->Fill(10); if (!LoopTracks()) return; fEvtCount->Fill(11); if (fDebug) Printf("Loop Tracks done!"); //---------------------------- // TPC Plane //---------------------------- if (!GetTPCPlane()) return; fEvtCount->Fill(12); if (fDebug) Printf("Get TPC Plane done!"); //---------------------------- // Fill Resolution //---------------------------- fHist2DPsi2TPCPosCent -> Fill(fCent, fPsi2TPCPos); fHist2DPsi2TPCNegCent -> Fill(fCent, fPsi2TPCNeg); fHist2DPsi2V0CCent -> Fill(centSPD1, fPsi2V0C); fHist2DPsi2V0ACent -> Fill(centSPD1, fPsi2V0A); fHist2DPsi1ZNCCent -> Fill(fCent, fPsi1ZNC); fHist2DPsi1ZNACent -> Fill(fCent, fPsi1ZNA); fProfileTPCPsi2Correlation -> Fill(fCent, TMath::Cos(2*(fPsi2TPCNeg - fPsi2TPCPos))); fProfileV0MPsi2Correlation -> Fill(fCent, TMath::Cos(2*(fPsi2V0C - fPsi2V0A))); fProfileZDCPsi1Correlation -> Fill(fCent, TMath::Cos(1*(fPsi1ZNC - fPsi1ZNA))); fProfileZDCPsi2Correlation -> Fill(fCent, TMath::Cos(2*(fPsi1ZNC - fPsi1ZNA))); fProfileV0CTPCPosPsi2Correlation -> Fill(fCent, TMath::Cos(2*(fPsi2V0C - fPsi2TPCPos))); fProfileV0ATPCPosPsi2Correlation -> Fill(fCent, TMath::Cos(2*(fPsi2V0A - fPsi2TPCPos))); fProfileV0CTPCNegPsi2Correlation -> Fill(fCent, TMath::Cos(2*(fPsi2V0C - fPsi2TPCNeg))); fProfileV0ATPCNegPsi2Correlation -> Fill(fCent, TMath::Cos(2*(fPsi2V0A - fPsi2TPCNeg))); fEvtCount->Fill(13); //---------------------------- // Get Lambda Vector //---------------------------- if (!LoopV0s()) return; fEvtCount->Fill(14); if (fDebug) Printf("Get Lambda Vector done!"); //---------------------------- // Pair //---------------------------- if (!PairLambda()) return; fEvtCount->Fill(15); if (fDebug) Printf("Pair done!"); //------------------ // Post output data. //------------------ if (fDebug) Printf("analysis done!"); PostData(1,fOutputList); } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::GetVZEROPlane() { double multV0Ch[64] = {0}; double V0XMean[3] = {0}; double V0YMean[3] = {0}; // [0]: M; [1]: C; [2]: A; double qxGE[3] = {0}, qyGE[3] = {0}; double qxRC[3] = {0}, qyRC[3] = {0}; double multRingGE[3] = {0}; double psi2GE[3] = {0}; double psi2RC[3] = {0}; //Load the GE and RC histograms if (fPeriod.EqualTo("LHC10h") ) { for (int iCh = 0; iCh < 64; ++iCh) multV0Ch[iCh] = hMultV0Read->GetBinContent(iCh+1, fRunNumBin+1); for (int i = 1; i < 3; ++i) { // [0]: M; [1]: C; [2]: A; V0XMean[i] = pV0XMeanRead[i]->GetBinContent(fRunNumBin+1, fCentBin+1, fVzBin+1); V0YMean[i] = pV0YMeanRead[i]->GetBinContent(fRunNumBin+1, fCentBin+1, fVzBin+1); } } if (fPeriod.EqualTo("LHC15o")) for (int iCh = 0; iCh < 64; ++iCh) multV0Ch[iCh] = hMultV0->GetBinContent(iCh+1); if (fPeriod.EqualTo("LHC15o") || fPeriod.EqualTo("LHC18q")) { AliMultSelection* fMultSelection = (AliMultSelection*) InputEvent()->FindListObject("MultSelection"); double centrCL1 = fMultSelection->GetMultiplicityPercentile("CL1"); int iCentSPD = (int)centrCL1; if (iCentSPD >= 90) return false; V0XMean[0] = -999.; V0YMean[0] = -999.; for (int i = 0; i < 2; ++i) { // [1]: C; [2]: A; V0XMean[i+1] = hQx2mV0[i]->GetBinContent(iCentSPD+1); V0YMean[i+1] = hQy2mV0[i]->GetBinContent(iCentSPD+1); } } //Loop Over VZERO Channels //Gain Equalization for (int iCh = 0; iCh < 64; ++iCh) { double phi = TMath::Pi()/8. + TMath::Pi()/4.*(iCh%8); double multCh = 0.; // double multCh = fAOD->GetVZEROEqMultiplicity(iCh); if (fPeriod.EqualTo("LHC10h")) multCh= fAOD->GetVZEROEqMultiplicity(iCh); else if (fPeriod.EqualTo("LHC15o") || fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")) { AliAODVZERO* aodV0 = fAOD->GetVZEROData(); multCh = aodV0->GetMultiplicity(iCh); } if (iCh<32) { // C double multChGEC = -1; if (fPeriod.EqualTo("LHC10h") || fPeriod.EqualTo("LHC15o")) { if (iCh < 8) multChGEC = multCh/multV0Ch[iCh] * multV0Ch[0]; else if (iCh >= 8 && iCh < 16) multChGEC = multCh/multV0Ch[iCh] * multV0Ch[8]; else if (iCh >= 16 && iCh < 24) multChGEC = multCh/multV0Ch[iCh] * multV0Ch[16]; else if (iCh >= 24 && iCh < 32) multChGEC = multCh/multV0Ch[iCh] * multV0Ch[24]; } if (fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")){ int ibinV0 = fHCorrectV0ChWeghts->FindBin(fVertex[2],iCh); double V0chGE = (double)fHCorrectV0ChWeghts->GetBinContent(ibinV0); multChGEC = multCh*V0chGE; } if (multChGEC<0) continue; //for V0C GE qxGE[1] += multChGEC*TMath::Cos(2*phi); qyGE[1] += multChGEC*TMath::Sin(2*phi); multRingGE[1] += multChGEC; } else if (iCh>=32 && iCh<64) { // A double multChGEA = -1; if (fPeriod.EqualTo("LHC10h") || fPeriod.EqualTo("LHC15o")) { if (iCh >= 32 && iCh < 40) multChGEA = multCh/multV0Ch[iCh] * multV0Ch[32]; else if (iCh >= 40 && iCh < 48) multChGEA = multCh/multV0Ch[iCh] * multV0Ch[40]; else if (iCh >= 48 && iCh < 56) multChGEA = multCh/multV0Ch[iCh] * multV0Ch[48]; else if (iCh >= 56 && iCh < 64) multChGEA = multCh/multV0Ch[iCh] * multV0Ch[56]; } if (fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")){ int ibinV0 = fHCorrectV0ChWeghts->FindBin(fVertex[2],iCh); double V0chGE = (double)fHCorrectV0ChWeghts->GetBinContent(ibinV0); multChGEA = multCh*V0chGE; } if (multChGEA<0) continue; //for V0A GE qxGE[2] += multChGEA*TMath::Cos(2*phi); qyGE[2] += multChGEA*TMath::Sin(2*phi); multRingGE[2] += multChGEA; } } if (multRingGE[1] < 1.e-6 || multRingGE[2] < 1.e-6) return false; //VZERO GE Plane for (int i = 1; i < 3; i++) { psi2GE[i] = GetEventPlane(qxGE[i], qyGE[i], 2.); if (TMath::IsNaN(psi2GE[i])) return false; } //VZERO Recenter for (int i = 1; i < 3; ++i) { double qxMean = V0XMean[i]; double qyMean = V0YMean[i]; if (TMath::IsNaN(qxMean) || TMath::IsNaN(qyMean)) continue; if (qyMean < -900 || qxMean < -900) continue; // For 10 h, we've stored the qx/y of V0M, and they cannot been found in A.Dorbin's calib file for 15o period! qxRC[i] = qxGE[i] - qxMean; qyRC[i] = qyGE[i] - qyMean; psi2RC[i] = GetEventPlane(qxRC[i], qyRC[i], 2.); if (TMath::IsNaN(psi2RC[i])) return false; } // VZERO QA if (IsQAVZERO) { double centSPD = -999.; if (fPeriod.EqualTo("LHC15o")||fPeriod.EqualTo("LHC18q")||fPeriod.EqualTo("LHC18r")) { AliMultSelection* fMultSelection = (AliMultSelection*) InputEvent()->FindListObject("MultSelection"); centSPD = fMultSelection->GetMultiplicityPercentile("CL1"); } else if (fPeriod.EqualTo("LHC10h") ) { centSPD = fAOD->GetCentrality()->GetCentralityPercentile("CL1"); } //V0C fProfileV0CQxCent[0]->Fill(centSPD, qxGE[1]); fProfileV0CQyCent[0]->Fill(centSPD, qyGE[1]); fProfileV0CQxVtx[0] ->Fill(fVertex[2], qxGE[1]); fProfileV0CQyVtx[0] ->Fill(fVertex[2], qyGE[1]); fHist2DCalibPsi2V0CCent[0]->Fill(centSPD, psi2GE[1]); fProfileV0CQxCent[1]->Fill(centSPD, qxRC[1]); fProfileV0CQyCent[1]->Fill(centSPD, qyRC[1]); fProfileV0CQxVtx[1]->Fill(fVertex[2], qxRC[1]); fProfileV0CQyVtx[1]->Fill(fVertex[2], qyRC[1]); fHist2DCalibPsi2V0CCent[1]->Fill(centSPD, psi2GE[1]); //V0A fProfileV0AQxCent[0]->Fill(centSPD, qxGE[2]); fProfileV0AQyCent[0]->Fill(centSPD, qyGE[2]); fProfileV0AQxVtx[0]->Fill(fVertex[2], qxGE[2]); fProfileV0AQyVtx[0]->Fill(fVertex[2], qyGE[2]); fHist2DCalibPsi2V0ACent[0]->Fill(centSPD, psi2GE[2]); fProfileV0AQxCent[1]->Fill(centSPD, qxRC[2]); fProfileV0AQyCent[1]->Fill(centSPD, qyRC[2]); fProfileV0AQxVtx[1]->Fill(fVertex[2], qxRC[2]); fProfileV0AQyVtx[1]->Fill(fVertex[2], qyRC[2]); fHist2DCalibPsi2V0ACent[1]->Fill(centSPD, psi2RC[2]); } fPsi2V0C = psi2RC[1]; fPsi2V0A = psi2RC[2]; return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::GetZDCPlane() { if(!fPeriod.EqualTo("LHC10h")) return true; //now we only have ZDC Calibration Files of LHC10h AliAODZDC* fZDC = fAOD -> GetZDCData(); if (!fZDC) return false; const double x[4] = {-1.75, 1.75, -1.75, 1.75}; const double y[4] = {-1.75, -1.75, 1.75, 1.75}; const double* towerEnegryZNC = fZDC->GetZNCTowerEnergy(); const double* towerEnegryZNA = fZDC->GetZNATowerEnergy(); float towerEnegryZNCGE[5] = {0}; float towerEnegryZNAGE[5] = {0}; if(IsZDCCalibOn) { for (int iTower = 0; iTower < 5; ++iTower) { fProfileZNCTowerMeanEnegry[0]->Fill(iTower+0.5, towerEnegryZNC[iTower]); fProfileZNATowerMeanEnegry[0]->Fill(iTower+0.5, towerEnegryZNA[iTower]); } } //Loop Over ZDC Towers //Gain Equalization for (int iTower = 0; iTower < 5; ++iTower) { towerEnegryZNCGE[iTower] = towerEnegryZNC[iTower] / (fProfileForZNCGE->GetBinContent(iTower + 1)) * (fProfileForZNCGE->GetBinContent(2));//here to select the ref Tower towerEnegryZNAGE[iTower] = towerEnegryZNA[iTower] / (fProfileForZNAGE->GetBinContent(iTower + 1)) * (fProfileForZNAGE->GetBinContent(2)); } if(IsZDCCalibOn) { for (int iTower = 0; iTower < 5; ++iTower) { fProfileZNCTowerMeanEnegry[1]->Fill(iTower+0.5, towerEnegryZNCGE[iTower]); fProfileZNATowerMeanEnegry[1]->Fill(iTower+0.5, towerEnegryZNAGE[iTower]); } } float QxC = 0, QyC = 0, MC = 0; float QxA = 0, QyA = 0, MA = 0; for (int iTower = 0; iTower < 4; ++iTower) { QxC += towerEnegryZNCGE[iTower + 1] * x[iTower]; QyC += towerEnegryZNCGE[iTower + 1] * y[iTower]; MC += towerEnegryZNCGE[iTower + 1]; QxA += towerEnegryZNAGE[iTower + 1] * x[iTower]; QyA += towerEnegryZNAGE[iTower + 1] * y[iTower]; MA += towerEnegryZNAGE[iTower + 1]; } if (fabs(MC) < 1.e-6 || fabs(MA) < 1.e-6) return false; QxC /= MC; QyC /= MC; QxA /= MA; QyA /= MA; double psiCGE = GetEventPlane(QxC,QyC,1); double psiAGE = GetEventPlane(-QxA,QyA,1); if (TMath::IsNaN(psiCGE) || TMath::IsNaN(psiAGE)) return false; if (IsQAZDC) { //ZNC fProfileZNCQxCent[0] -> Fill(fCent, QxC); fProfileZNCQyCent[0] -> Fill(fCent, QyC); fHist2DCalibPsi1ZNCCent[0] -> Fill(fCent, psiCGE); //ZNA fProfileZNAQxCent[0] -> Fill(fCent,-QxA); fProfileZNAQyCent[0] -> Fill(fCent, QyA); fHist2DCalibPsi1ZNACent[0] -> Fill(fCent, psiAGE); //ZNC-ZNA fProfileZDCQxAQxCCent[0] -> Fill(fCent,-QxA*QxC); fProfileZDCQxAQyCCent[0] -> Fill(fCent,-QxA*QyC); fProfileZDCQyAQxCCent[0] -> Fill(fCent, QyA*QxC); fProfileZDCQyAQyCCent[0] -> Fill(fCent, QyA*QyC); } //ZDC Recenter double fillPosition[4] = {fCent,-999.,-999.,-999.}; int vtxBin[3] = {-999,-999,-999}; for (int i = 0; i < 3; i++) { if (fVertex[i] <= vtxQuant1[i]) vtxBin[i]=1; else if (fVertex[i] > vtxQuant1[i] && fVertex[i] <= vtxQuant2[i]) vtxBin[i]=2; else if (fVertex[i] > vtxQuant2[i]) vtxBin[i]=3; } fillPosition[1] = vtxBin[0] - 0.5; fillPosition[2] = vtxBin[1] - 0.5; fillPosition[3] = vtxBin[2] - 0.5; float QxCMean = fHn4DForZNCQxRC -> GetBinContent(fHn4DForZNCQxRC->GetBin(fillPosition)); float QyCMean = fHn4DForZNCQyRC -> GetBinContent(fHn4DForZNCQyRC->GetBin(fillPosition)); float MCMean = fHn4DForZNCMtRC -> GetBinContent(fHn4DForZNCMtRC->GetBin(fillPosition)); float QxAMean = fHn4DForZNAQxRC -> GetBinContent(fHn4DForZNAQxRC->GetBin(fillPosition)); float QyAMean = fHn4DForZNAQyRC -> GetBinContent(fHn4DForZNAQyRC->GetBin(fillPosition)); float MAMean = fHn4DForZNAMtRC -> GetBinContent(fHn4DForZNAMtRC->GetBin(fillPosition)); int entriesC = fHn4DForZNCCountsRC -> GetBinContent(fHn4DForZNCCountsRC->GetBin(fillPosition)); int entriesA = fHn4DForZNACountsRC -> GetBinContent(fHn4DForZNACountsRC->GetBin(fillPosition)); if (fabs(entriesC) < 2 || fabs(entriesA) < 2) return false; QxCMean /= entriesC; QyCMean /= entriesC; QxAMean /= entriesA; QyAMean /= entriesA; QxC -= QxCMean; QyC -= QyCMean; QxA -= QxAMean; QyA -= QyAMean; double psiCRC = GetEventPlane(QxC,QyC,1); double psiARC = GetEventPlane(-QxA,QyA,1); if (TMath::IsNaN(psiCRC) || TMath::IsNaN(psiARC)) return false; if (IsQAZDC) { //ZNC fProfileZNCQxCent[1] -> Fill(fCent, QxC); fProfileZNCQyCent[1] -> Fill(fCent, QyC); fHist2DCalibPsi1ZNCCent[1] -> Fill(fCent, psiCRC); //ZNA fProfileZNAQxCent[1] -> Fill(fCent,-QxA); fProfileZNAQyCent[1] -> Fill(fCent, QyA); fHist2DCalibPsi1ZNACent[1] -> Fill(fCent, psiARC); //ZNC-ZNA fProfileZDCQxAQxCCent[1] -> Fill(fCent,-QxA*QxC); fProfileZDCQxAQyCCent[1] -> Fill(fCent,-QxA*QyC); fProfileZDCQyAQxCCent[1] -> Fill(fCent, QyA*QxC); fProfileZDCQyAQyCCent[1] -> Fill(fCent, QyA*QyC); } //ZDC Shift double psiCSF = psiCRC; double psiASF = psiARC; for (int i = 1; i <= 20; i++) { double shiftCosC = fProfile2DForCosC->GetBinContent(fProfile2DForCosC->GetXaxis()->FindBin(fCent),i); double shiftSinC = fProfile2DForSinC->GetBinContent(fProfile2DForSinC->GetXaxis()->FindBin(fCent),i); double shiftCosA = fProfile2DForCosA->GetBinContent(fProfile2DForCosA->GetXaxis()->FindBin(fCent),i); double shiftSinA = fProfile2DForSinA->GetBinContent(fProfile2DForSinA->GetXaxis()->FindBin(fCent),i); psiCSF += (2./i) * (-shiftSinC * TMath::Cos(i*psiCSF) + shiftCosC * TMath::Sin(i*psiCSF)); psiASF += (2./i) * (-shiftSinA * TMath::Cos(i*psiASF) + shiftCosA * TMath::Sin(i*psiASF)); } if (TMath::IsNaN(psiCSF) || TMath::IsNaN(psiASF)) return false; if (IsQAZDC) { fHist2DCalibPsi1ZNCCent[2] -> Fill(fCent, psiCSF); fHist2DCalibPsi1ZNACent[2] -> Fill(fCent, psiASF); } fPsi1ZNC = psiCSF; fPsi1ZNA = psiASF; return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::LoopTracks() { int nTrks = fAOD->GetNumberOfTracks(); if (nTrks < 4) return false; for (int iTrk = 0; iTrk < nTrks; ++iTrk) { AliAODTrack* track = (AliAODTrack*)fAOD->GetTrack(iTrk); if (!track) { AliError(Form("%s: Could not get Track", GetName())); continue; } if (!track->TestFilterBit(fFilterBit)) continue; if (!AcceptAODTrack(track)) continue; //------------------ // NUE & NUA //------------------ double phi = track->Phi(); double pt = track->Pt(); double eta = track->Eta(); int charge = track->Charge(); int id = track->GetID(); fHistPhi[0]->Fill(phi); fHist2DEtaPhi[0]->Fill(eta,phi); double weight=1; if (IsDoNUE) { double wEffi = GetNUECor(charge, pt); if (wEffi<0) continue; else weight *= wEffi; } if (IsDoNUA) { double wAcc = GetNUACor(charge, phi, eta, fVertex[2]); if (wAcc<0) continue; else weight *= wAcc; fHistPhi[1]->Fill(phi, wAcc); fHist2DEtaPhi[1]->Fill(eta,phi,wAcc); } if (pt > fPlanePtMin && pt < fPlanePtMax) { ///TODO Use Pt as weight for Better resolution? if (eta >= fEtaGapPos) { SumQ2xTPCPos += weight * TMath::Cos(2 * phi); SumQ2yTPCPos += weight * TMath::Sin(2 * phi); fWgtMultTPCPos += weight; vecPosEPTrkID.push_back(id); vecPosEPTrkPhi.push_back(phi); vecPosEPTrkNUAWgt.push_back(weight); } else if (eta <= fEtaGapNeg) { SumQ2xTPCNeg += weight * TMath::Cos(2 * phi); SumQ2yTPCNeg += weight * TMath::Sin(2 * phi); fWgtMultTPCNeg += weight; vecNegEPTrkID.push_back(id); vecNegEPTrkPhi.push_back(phi); vecNegEPTrkNUAWgt.push_back(weight); } } bool isItProttrk = CheckPIDofParticle(track,3); // 3=proton int code = 0; if (charge > 0) { code = 999; if (isItProttrk) code = 2212; } else { /// charge < 0 code = -999; if (isItProttrk) code = -2212; } vecPDGCode.push_back(code); vecPhi.push_back(phi); vecEta.push_back(eta); vecPt.push_back(pt); vecID.push_back(id); } return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::GetTPCPlane() { double psi2TPCPos = GetEventPlane(SumQ2xTPCPos,SumQ2yTPCPos,2); double psi2TPCNeg = GetEventPlane(SumQ2xTPCNeg,SumQ2yTPCNeg,2); if (TMath::IsNaN(psi2TPCPos) || TMath::IsNaN(psi2TPCNeg)) return false; fPsi2TPCPos = psi2TPCPos; fPsi2TPCNeg = psi2TPCNeg; return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::LoopV0s() { int nV0s = fAOD->GetNumberOfV0s(); for (int iV0 = 0; iV0 < nV0s; iV0++) { AliAODv0 *v0 = fAOD->GetV0(iV0); if (!v0) { AliError(Form("%s: Could not get v0s", GetName())); continue; } //Basic kinematic variable double pt = v0->Pt(); double eta = v0->PseudoRapV0(); double dcaToPV = v0->DcaV0ToPrimVertex();//DCA to Primary Vertex double CPA = v0->CosPointingAngle(fVertex);//cosine pointing angle double dl = v0->DecayLengthV0(fVertex); fHistV0Pt -> Fill(pt); fHistV0Eta -> Fill(eta); fHistV0DcatoPrimVertex -> Fill(dcaToPV); fHistV0CPA -> Fill(CPA); fHistV0DecayLength -> Fill(dl); //V0 cut if (!IsGoodV0(v0)) continue; //V0 daughters cut AliAODTrack *nTrack = dynamic_cast<AliAODTrack*>(v0->GetDaughter(1)); AliAODTrack *pTrack = dynamic_cast<AliAODTrack*>(v0->GetDaughter(0)); if (!(IsGoodDaughterTrack(nTrack)) || !(IsGoodDaughterTrack(pTrack))) continue; float nDcaPV = v0->DcaNegToPrimVertex(); float pDcaPV = v0->DcaPosToPrimVertex(); if ( nDcaPV<fDaughtersDCAToPrimVtxMin || pDcaPV<fDaughtersDCAToPrimVtxMin) continue; int code = GetLambdaCode(pTrack,nTrack); if (TMath::Abs(code) != 3122) continue; TVector2 Vt(v0->MomV0X(), v0->MomV0Y()); double phi = Vt.Phi() > 0 ? Vt.Phi() : Vt.Phi() + TMath::TwoPi(); int id_posDaughter = v0->GetPosID(); int id_negDaughter = v0->GetNegID(); if (code == 3122) { double massLambda = v0->MassLambda(); fHistLambdaPt[0] -> Fill(pt); fHistLambdaEta[0] -> Fill(eta); fHistLambdaPhi[0] -> Fill(phi); fHistLambdaDcaToPrimVertex[0] -> Fill(dcaToPV); fHistLambdaCPA[0] -> Fill(CPA); fHistLambdaDecayLength[0] -> Fill(dl); fHistLambdaMass[0] -> Fill(massLambda); fProfileLambdaMassVsPt[0] -> Fill(pt, massLambda); if (TMath::Abs(massLambda - fMassMean) < fLambdaMassCut) { //if a particle has been used as daughter particle before(It happends), we have to refuse a new one. if (find(vecDaughterPosID.begin(), vecDaughterPosID.end(), id_posDaughter) != vecDaughterPosID.end()) continue; if (find(vecDaughterNegID.begin(), vecDaughterNegID.end(), id_negDaughter) != vecDaughterNegID.end()) continue; fHistLambdaPt[1] -> Fill(pt); fHistLambdaEta[1] -> Fill(eta); fHistLambdaPhi[1] -> Fill(phi); fHistLambdaDcaToPrimVertex[1] -> Fill(dcaToPV); fHistLambdaCPA[1] -> Fill(CPA); fHistLambdaDecayLength[1] -> Fill(dl); fHistLambdaMass[1] -> Fill(massLambda); fProfileLambdaMassVsPt[1] -> Fill(pt, massLambda); vecLambdaCode.push_back(code); vecLambdaPhi.push_back(phi); vecLambdaPt.push_back(pt); vecDaughterPosID.push_back(id_posDaughter); vecDaughterNegID.push_back(id_negDaughter); } } if (code == -3122) { double massAntiLambda = v0->MassAntiLambda(); fHistAntiLambdaPt[0] -> Fill(pt); fHistAntiLambdaEta[0] -> Fill(eta); fHistAntiLambdaPhi[0] -> Fill(phi); fHistAntiLambdaDcaToPrimVertex[0] -> Fill(dcaToPV); fHistAntiLambdaCPA[0] -> Fill(CPA); fHistAntiLambdaDecayLength[0] -> Fill(dl); fHistAntiLambdaMass[0] -> Fill(massAntiLambda); fProfileAntiLambdaMassVsPt[0] -> Fill(pt, massAntiLambda); if (TMath::Abs(massAntiLambda - fMassMean) < fLambdaMassCut) { if (find(vecDaughterPosID.begin(), vecDaughterPosID.end(), id_posDaughter) != vecDaughterPosID.end()) continue; if (find(vecDaughterNegID.begin(), vecDaughterNegID.end(), id_negDaughter) != vecDaughterNegID.end()) continue; fHistAntiLambdaPt[1] -> Fill(pt); fHistAntiLambdaEta[1] -> Fill(eta); fHistAntiLambdaPhi[1] -> Fill(phi); fHistAntiLambdaDcaToPrimVertex[1] -> Fill(dcaToPV); fHistAntiLambdaCPA[1] -> Fill(CPA); fHistAntiLambdaDecayLength[1] -> Fill(dl); fHistAntiLambdaMass[1] -> Fill(massAntiLambda); fProfileAntiLambdaMassVsPt[1] -> Fill(pt, massAntiLambda); vecLambdaCode.push_back(code); vecLambdaPhi.push_back(phi); vecLambdaPt.push_back(pt); vecDaughterPosID.push_back(id_posDaughter); vecDaughterNegID.push_back(id_negDaughter); } } }//loop V0 end return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::PairLambda() { //Lambda - X for (std::vector<double>::size_type jLambda = 0; jLambda < vecLambdaPhi.size(); jLambda++) { int code_lambda = vecLambdaCode[jLambda]; double phi_lambda = vecLambdaPhi[jLambda]; double pt_lambda = vecLambdaPt[jLambda]; int id_posDaughter = vecDaughterPosID[jLambda]; int id_negDaughter = vecDaughterNegID[jLambda]; //Remove AutoCorrelation: ///Get the Total sum of Pos TPC Qx,Qy locally, then Remove AutoCorr if needed. double fPosTPCQxTemp = 0., fPosTPCQyTemp = 0.; double fNegTPCQxTemp = 0., fNegTPCQyTemp = 0.; double fPosTPCMult = 0., fNegTPCMult = 0.; double qxPosTPC = 0., qyPosTPC = 0.; double qxNegTPC = 0., qyNegTPC = 0.; // use EP from opposite eta than the charged track! One way to remove AutoCorrelation. fNegTPCQxTemp = SumQ2xTPCNeg; fNegTPCQyTemp = SumQ2yTPCNeg; fNegTPCMult = fWgtMultTPCNeg; fPosTPCQxTemp = SumQ2xTPCPos; fPosTPCQyTemp = SumQ2yTPCPos; fPosTPCMult = fWgtMultTPCPos; //for NegEP std::vector<int>::iterator iterPosDaughterNegTPC = find(vecNegEPTrkID.begin(), vecNegEPTrkID.end(), id_posDaughter); std::vector<int>::iterator iterNegDaughterNegTPC = find(vecNegEPTrkID.begin(), vecNegEPTrkID.end(), id_negDaughter); //for PosEP std::vector<int>::iterator iterPosDaughterPosTPC = find(vecPosEPTrkID.begin(), vecPosEPTrkID.end(), id_posDaughter); std::vector<int>::iterator iterNegDaughterPosTPC = find(vecPosEPTrkID.begin(), vecPosEPTrkID.end(), id_negDaughter); if (iterPosDaughterNegTPC != vecNegEPTrkID.end()) { int iDaughter = distance(vecNegEPTrkID.begin(), iterPosDaughterNegTPC); qxNegTPC += vecNegEPTrkNUAWgt[iDaughter] * TMath::Cos(2 * vecNegEPTrkPhi[iDaughter]); qyNegTPC += vecNegEPTrkNUAWgt[iDaughter] * TMath::Sin(2 * vecNegEPTrkPhi[iDaughter]); fNegTPCMult -= vecNegEPTrkNUAWgt[iDaughter]; } if (iterNegDaughterNegTPC != vecNegEPTrkID.end()) { int iDaughter = distance(vecNegEPTrkID.begin(), iterNegDaughterNegTPC); qxNegTPC += vecNegEPTrkNUAWgt[iDaughter] * TMath::Cos(2 * vecNegEPTrkPhi[iDaughter]); qyNegTPC += vecNegEPTrkNUAWgt[iDaughter] * TMath::Sin(2 * vecNegEPTrkPhi[iDaughter]); fNegTPCMult -= vecNegEPTrkNUAWgt[iDaughter]; } if (iterPosDaughterPosTPC != vecPosEPTrkID.end()) { int iDaughter = distance(vecPosEPTrkID.begin(), iterPosDaughterPosTPC); qxPosTPC += vecPosEPTrkNUAWgt[iDaughter] * TMath::Cos(2 * vecPosEPTrkPhi[iDaughter]); qyPosTPC += vecPosEPTrkNUAWgt[iDaughter] * TMath::Sin(2 * vecPosEPTrkPhi[iDaughter]); fPosTPCMult -= vecPosEPTrkNUAWgt[iDaughter]; } if (iterNegDaughterPosTPC != vecPosEPTrkID.end()) { int iDaughter = distance(vecPosEPTrkID.begin(), iterNegDaughterPosTPC); qxPosTPC += vecPosEPTrkNUAWgt[iDaughter] * TMath::Cos(2 * vecPosEPTrkPhi[iDaughter]); qyPosTPC += vecPosEPTrkNUAWgt[iDaughter] * TMath::Sin(2 * vecPosEPTrkPhi[iDaughter]); fPosTPCMult -= vecPosEPTrkNUAWgt[iDaughter]; } fPosTPCQxTemp -= qxPosTPC; /// qx=0,qy=0 if Lambda daughters are on the opposite eta of the EP used.. fPosTPCQyTemp -= qyPosTPC; fNegTPCQxTemp -= qxNegTPC; /// qx=0,qy=0 if Lambda daughters are on the opposite eta of the EP used.. fNegTPCQyTemp -= qyNegTPC; if (fPosTPCMult > 0. && fNegTPCMult > 0.) { fPosTPCQxTemp = fPosTPCQxTemp/fPosTPCMult; fPosTPCQyTemp = fPosTPCQyTemp/fPosTPCMult; fNegTPCQxTemp = fNegTPCQxTemp/fNegTPCMult; fNegTPCQyTemp = fNegTPCQyTemp/fNegTPCMult; } else continue; double fPsi2PosTPCNoAuto = GetEventPlane(fPosTPCQxTemp,fPosTPCQyTemp,2.); //AutoCorrelation Removed Pos EP. double fPsi2NegTPCNoAuto = GetEventPlane(fNegTPCQxTemp,fNegTPCQyTemp,2.); //AutoCorrelation Removed Neg EP. if (TMath::IsNaN(fPsi2PosTPCNoAuto) || TMath::IsNaN(fPsi2NegTPCNoAuto)) continue; //Check the PID Flow if (IsCheckPIDFlow) { if (code_lambda == 3122) { fProfile2DRawFlowCentPtLambda[0]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi2PosTPCNoAuto))); fProfile2DRawFlowCentPtLambda[1]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi2V0C))); fProfile2DRawFlowCentPtLambda[2]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi2V0A))); fProfile2DRawFlowCentPtLambda[3]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi1ZNC))); fProfile2DRawFlowCentPtLambda[4]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi1ZNA))); } if (code_lambda == -3122) { fProfile2DRawFlowCentPtAntiLambda[0]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi2PosTPCNoAuto))); fProfile2DRawFlowCentPtAntiLambda[1]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi2V0C))); fProfile2DRawFlowCentPtAntiLambda[2]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi2V0A))); fProfile2DRawFlowCentPtAntiLambda[3]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi1ZNC))); fProfile2DRawFlowCentPtAntiLambda[4]->Fill(fCent, pt_lambda, TMath::Cos(2 * (phi_lambda - fPsi1ZNA))); } }// check PID flow over. for (std::vector<double>::size_type iTrk = 0; iTrk < vecPhi.size(); iTrk++) { int code = vecPDGCode[iTrk]; int id = vecID[iTrk]; double pt = vecPt[iTrk]; double eta = vecEta[iTrk]; double phi = vecPhi[iTrk]; if (id == id_posDaughter || id == id_negDaughter) continue; double fPsiNTPCNoAuto = -999; if (eta > 0.) fPsiNTPCNoAuto = fPsi2NegTPCNoAuto; else fPsiNTPCNoAuto = fPsi2PosTPCNoAuto; double delta = TMath::Cos(phi_lambda - phi); double gammaTPC = TMath::Cos(phi_lambda + phi - 2 *fPsiNTPCNoAuto); double gammaV0C = TMath::Cos(phi_lambda + phi - 2 *fPsi2V0C); double gammaV0A = TMath::Cos(phi_lambda + phi - 2 *fPsi2V0A); double gammaZNC = TMath::Cos(phi_lambda + phi - 2 *fPsi1ZNC); double gammaZNA = TMath::Cos(phi_lambda + phi - 2 *fPsi1ZNA); if (code > 0 && code_lambda == 3122) { fProfileDelta_Lambda_hPos -> Fill(fCent, delta); fProfileGammaTPC_Lambda_hPos -> Fill(fCent, gammaTPC); fProfileGammaV0C_Lambda_hPos -> Fill(fCent, gammaV0C); fProfileGammaV0A_Lambda_hPos -> Fill(fCent, gammaV0A); fProfileGammaZNC_Lambda_hPos -> Fill(fCent, gammaZNC); fProfileGammaZNA_Lambda_hPos -> Fill(fCent, gammaZNA); } if (code < 0 && code_lambda == 3122) { fProfileDelta_Lambda_hNeg -> Fill(fCent, delta); fProfileGammaTPC_Lambda_hNeg -> Fill(fCent, gammaTPC); fProfileGammaV0C_Lambda_hNeg -> Fill(fCent, gammaV0C); fProfileGammaV0A_Lambda_hNeg -> Fill(fCent, gammaV0A); fProfileGammaZNC_Lambda_hNeg -> Fill(fCent, gammaZNC); fProfileGammaZNA_Lambda_hNeg -> Fill(fCent, gammaZNA); } if (code > 0 && code_lambda == -3122) { fProfileDelta_AntiLambda_hPos -> Fill(fCent, delta); fProfileGammaTPC_AntiLambda_hPos -> Fill(fCent, gammaTPC); fProfileGammaV0C_AntiLambda_hPos -> Fill(fCent, gammaV0C); fProfileGammaV0A_AntiLambda_hPos -> Fill(fCent, gammaV0A); fProfileGammaZNC_AntiLambda_hPos -> Fill(fCent, gammaZNC); fProfileGammaZNA_AntiLambda_hPos -> Fill(fCent, gammaZNA); } if (code < 0 && code_lambda == -3122) { fProfileDelta_AntiLambda_hNeg -> Fill(fCent, delta); fProfileGammaTPC_AntiLambda_hNeg -> Fill(fCent, gammaTPC); fProfileGammaV0C_AntiLambda_hNeg -> Fill(fCent, gammaV0C); fProfileGammaV0A_AntiLambda_hNeg -> Fill(fCent, gammaV0A); fProfileGammaZNC_AntiLambda_hNeg -> Fill(fCent, gammaZNC); fProfileGammaZNA_AntiLambda_hNeg -> Fill(fCent, gammaZNA); } if (code == 2212 && code_lambda == 3122) { fProfileDelta_Lambda_Proton -> Fill(fCent, delta); fProfileGammaTPC_Lambda_Proton -> Fill(fCent, gammaTPC); fProfileGammaV0C_Lambda_Proton -> Fill(fCent, gammaV0C); fProfileGammaV0A_Lambda_Proton -> Fill(fCent, gammaV0A); fProfileGammaZNC_Lambda_Proton -> Fill(fCent, gammaZNC); fProfileGammaZNA_Lambda_Proton -> Fill(fCent, gammaZNA); } if (code == -2212 && code_lambda == 3122) { fProfileDelta_Lambda_AntiProton -> Fill(fCent, delta); fProfileGammaTPC_Lambda_AntiProton -> Fill(fCent, gammaTPC); fProfileGammaV0C_Lambda_AntiProton -> Fill(fCent, gammaV0C); fProfileGammaV0A_Lambda_AntiProton -> Fill(fCent, gammaV0A); fProfileGammaZNC_Lambda_AntiProton -> Fill(fCent, gammaZNC); fProfileGammaZNA_Lambda_AntiProton -> Fill(fCent, gammaZNA); } if (code == 2212 && code_lambda == -3122) { fProfileDelta_AntiLambda_Proton -> Fill(fCent, delta); fProfileGammaTPC_AntiLambda_Proton -> Fill(fCent, gammaTPC); fProfileGammaV0C_AntiLambda_Proton -> Fill(fCent, gammaV0C); fProfileGammaV0A_AntiLambda_Proton -> Fill(fCent, gammaV0A); fProfileGammaZNC_AntiLambda_Proton -> Fill(fCent, gammaZNC); fProfileGammaZNA_AntiLambda_Proton -> Fill(fCent, gammaZNA); } if (code == -2212 && code_lambda == -3122) { fProfileDelta_AntiLambda_AntiProton -> Fill(fCent, delta); fProfileGammaTPC_AntiLambda_AntiProton -> Fill(fCent, gammaTPC); fProfileGammaV0C_AntiLambda_AntiProton -> Fill(fCent, gammaV0C); fProfileGammaV0A_AntiLambda_AntiProton -> Fill(fCent, gammaV0A); fProfileGammaZNC_AntiLambda_AntiProton -> Fill(fCent, gammaZNC); fProfileGammaZNA_AntiLambda_AntiProton -> Fill(fCent, gammaZNA); } }// (Anti)Lambda-X pair done }/// loop over charge particle array if (IsCheckPIDFlow) { for (std::vector<double>::size_type iTrk = 0; iTrk < vecPhi.size(); iTrk++) { int code = vecPDGCode[iTrk]; double pt = vecPt[iTrk]; double eta = vecEta[iTrk]; double phi = vecPhi[iTrk]; if (code > 0) { if (eta > 0) fProfile2DRawFlowCentPthPos[0]->Fill(fCent, pt, TMath::Cos(2 * (phi-fPsi2TPCNeg))); else fProfile2DRawFlowCentPthPos[0]->Fill(fCent, pt, TMath::Cos(2 * (phi-fPsi2TPCPos))); fProfile2DRawFlowCentPthPos[1]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi2V0C))); fProfile2DRawFlowCentPthPos[2]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi2V0A))); fProfile2DRawFlowCentPthPos[3]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi1ZNC))); fProfile2DRawFlowCentPthPos[4]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi1ZNA))); } if (code < 0) { if (eta > 0) fProfile2DRawFlowCentPthNeg[0]->Fill(fCent, pt, TMath::Cos(2 * (phi-fPsi2TPCNeg))); else fProfile2DRawFlowCentPthNeg[0]->Fill(fCent, pt, TMath::Cos(2 * (phi-fPsi2TPCPos))); fProfile2DRawFlowCentPthNeg[1]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi2V0C))); fProfile2DRawFlowCentPthNeg[2]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi2V0A))); fProfile2DRawFlowCentPthNeg[3]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi1ZNC))); fProfile2DRawFlowCentPthNeg[4]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi1ZNA))); } if (code == 2212) { if (eta > 0) fProfile2DRawFlowCentPtProton[0]->Fill(fCent, pt, TMath::Cos(2 * (phi-fPsi2TPCNeg))); else fProfile2DRawFlowCentPtProton[0]->Fill(fCent, pt, TMath::Cos(2 * (phi-fPsi2TPCPos))); fProfile2DRawFlowCentPtProton[1]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi2V0C))); fProfile2DRawFlowCentPtProton[2]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi2V0A))); fProfile2DRawFlowCentPtProton[3]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi1ZNC))); fProfile2DRawFlowCentPtProton[4]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi1ZNA))); } if (code == -2212) { if (eta > 0) fProfile2DRawFlowCentPtAntiProton[0]->Fill(fCent, pt, TMath::Cos(2 * (phi-fPsi2TPCNeg))); else fProfile2DRawFlowCentPtAntiProton[0]->Fill(fCent, pt, TMath::Cos(2 * (phi-fPsi2TPCPos))); fProfile2DRawFlowCentPtAntiProton[1]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi2V0C))); fProfile2DRawFlowCentPtAntiProton[2]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi2V0A))); fProfile2DRawFlowCentPtAntiProton[3]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi1ZNC))); fProfile2DRawFlowCentPtAntiProton[4]->Fill(fCent, pt, TMath::Cos(2 * (phi - fPsi1ZNA))); } } }////--------- PID Flow hist are Filled ---------- return true; } //--------------------------------------------------- void AliAnalysisTaskLambdaProtonCVE::ResetVectors() { SumQ2xTPCPos = 0.; SumQ2yTPCPos = 0.; fWgtMultTPCPos = 0.; SumQ2xTPCNeg = 0.; SumQ2yTPCNeg = 0.; fWgtMultTPCNeg = 0.; std::vector<int>().swap(vecPosEPTrkID); std::vector<int>().swap(vecNegEPTrkID); std::vector<double>().swap(vecPosEPTrkPhi); std::vector<double>().swap(vecNegEPTrkPhi); std::vector<double>().swap(vecPosEPTrkNUAWgt); std::vector<double>().swap(vecNegEPTrkNUAWgt); std::vector<int>().swap(vecPDGCode); std::vector<int>().swap(vecID); std::vector<double>().swap(vecPhi); std::vector<double>().swap(vecEta); std::vector<double>().swap(vecPt); std::vector<double>().swap(vecNUAWeight); std::vector<double>().swap(vecNUEWeight); std::vector<double>().swap(vecNUAWeightPID); std::vector<double>().swap(vecNUEWeightPID); std::vector<int>().swap(vecLambdaCode); std::vector<double>().swap(vecLambdaPhi); std::vector<double>().swap(vecLambdaPt); std::vector<int>().swap(vecDaughterPosID); std::vector<int>().swap(vecDaughterNegID); } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::GetCalibHistForThisRun() { if (fPeriod.EqualTo("LHC10h")) { // 10h VZERO Calibration Histograms is Global // 10h ZDC Calibration Histograms if (IsZDCCalibOn) { tree -> Reset(); fProfileForZNCGE ->Reset(); fProfileForZNAGE ->Reset(); fHn4DForZNCQxRC ->Reset(); fHn4DForZNCQyRC ->Reset(); fHn4DForZNCMtRC ->Reset(); fHn4DForZNAQxRC ->Reset(); fHn4DForZNAQyRC ->Reset(); fHn4DForZNAMtRC ->Reset(); fHn4DForZNCCountsRC ->Reset(); fHn4DForZNACountsRC ->Reset(); fProfile2DForCosC ->Reset(); fProfile2DForSinC ->Reset(); fProfile2DForCosA ->Reset(); fProfile2DForSinA ->Reset(); float vtxQuant1Tmp[3]; float vtxQuant2Tmp[3]; tree = (TTree*)fListZDCCalib->FindObject(Form("run%d",fRunNum)); tree->SetBranchAddress("VtxQuant1",vtxQuant1Tmp); tree->SetBranchAddress("VtxQuant2",vtxQuant2Tmp); tree->GetEntry(0); for (int i = 0; i < 3; i++) { vtxQuant1[i] = vtxQuant1Tmp[i]; vtxQuant2[i] = vtxQuant2Tmp[i]; } fProfileForZNCGE = (TProfile*)fListZDCCalib -> FindObject(Form("ZNCTowerEnegryMean_run%d",fRunNum)); fProfileForZNAGE = (TProfile*)fListZDCCalib -> FindObject(Form("ZNATowerEnegryMean_run%d",fRunNum)); fHn4DForZNCQxRC = (THnSparseF*)fListZDCCalib -> FindObject(Form("Hn4DQxZNCCentVxVyVz_run%d",fRunNum)); fHn4DForZNCQyRC = (THnSparseF*)fListZDCCalib -> FindObject(Form("Hn4DQyZNCCentVxVyVz_run%d",fRunNum)); fHn4DForZNCMtRC = (THnSparseF*)fListZDCCalib -> FindObject(Form("Hn4DMtZNCCentVxVyVz_run%d",fRunNum)); fHn4DForZNAQxRC = (THnSparseF*)fListZDCCalib -> FindObject(Form("Hn4DQxZNACentVxVyVz_run%d",fRunNum)); fHn4DForZNAQyRC = (THnSparseF*)fListZDCCalib -> FindObject(Form("Hn4DQyZNACentVxVyVz_run%d",fRunNum)); fHn4DForZNAMtRC = (THnSparseF*)fListZDCCalib -> FindObject(Form("Hn4DMtZNACentVxVyVz_run%d",fRunNum)); fHn4DForZNCCountsRC = (THnSparseI*)fListZDCCalib -> FindObject(Form("Hn4DCountsZNCCentVxVyVz_run%d",fRunNum)); fHn4DForZNACountsRC = (THnSparseI*)fListZDCCalib -> FindObject(Form("Hn4DCountsZNACentVxVyVz_run%d",fRunNum)); fProfile2DForCosC = (TProfile2D*)fListZDCCalib -> FindObject(Form("Profile2DShiftCosC_run%d",fRunNum)); fProfile2DForSinC = (TProfile2D*)fListZDCCalib -> FindObject(Form("Profile2DShiftSinC_run%d",fRunNum)); fProfile2DForCosA = (TProfile2D*)fListZDCCalib -> FindObject(Form("Profile2DShiftCosA_run%d",fRunNum)); fProfile2DForSinA = (TProfile2D*)fListZDCCalib -> FindObject(Form("Profile2DShiftSinA_run%d",fRunNum)); if (!fProfileForZNCGE) return false; if (!fProfileForZNAGE) return false; if (!fHn4DForZNCQxRC) return false; if (!fHn4DForZNCQyRC) return false; if (!fHn4DForZNCMtRC) return false; if (!fHn4DForZNAQxRC) return false; if (!fHn4DForZNAQyRC) return false; if (!fHn4DForZNAMtRC) return false; if (!fHn4DForZNCCountsRC) return false; if (!fHn4DForZNACountsRC) return false; if (!fProfile2DForCosC) return false; if (!fProfile2DForSinC) return false; if (!fProfile2DForCosA) return false; if (!fProfile2DForSinA) return false; } } if (fPeriod.EqualTo("LHC15o")) { // 15o VZERO Calibration Histograms if (IsVZEROCalibOn) { hMultV0 -> Reset(); for (int i = 0; i < 2; i++) { hQx2mV0[i] -> Reset(); hQx2mV0[i] -> Reset(); } hMultV0 = ((TH1D*) contMult ->GetObject(fRunNum)); hQx2mV0[0] = ((TH1D*) contQxncm->GetObject(fRunNum)); hQy2mV0[0] = ((TH1D*) contQyncm->GetObject(fRunNum)); hQx2mV0[1] = ((TH1D*) contQxnam->GetObject(fRunNum)); hQy2mV0[1] = ((TH1D*) contQynam->GetObject(fRunNum)); if (!hMultV0) return false; if (!hQx2mV0[0]) return false; if (!hQy2mV0[0]) return false; if (!hQx2mV0[1]) return false; if (!hQy2mV0[1]) return false; } //15o NUA if (IsDoNUA) { hCorrectNUAPos -> Reset(); hCorrectNUANeg -> Reset(); hCorrectNUAPos = (TH3F*) fListNUA->FindObject(Form("fHist_NUA_VzPhiEta_Charge_Pos_Cent0_Run%d",fRunNum)); hCorrectNUANeg = (TH3F*) fListNUA->FindObject(Form("fHist_NUA_VzPhiEta_Charge_Neg_Cent0_Run%d",fRunNum)); if (!hCorrectNUAPos) return false; if (!hCorrectNUANeg) return false; } } if (fPeriod.EqualTo("LHC18q")) { if (IsVZEROCalibOn) { for (int i = 0; i < 2; i++) { hQx2mV0[i] -> Reset(); hQx2mV0[i] -> Reset(); } hQx2mV0[0] = ((TH1D*) contQxncm->GetObject(fRunNum)); hQy2mV0[0] = ((TH1D*) contQyncm->GetObject(fRunNum)); hQx2mV0[1] = ((TH1D*) contQxnam->GetObject(fRunNum)); hQy2mV0[1] = ((TH1D*) contQynam->GetObject(fRunNum)); for (int i = 0; i < 2; i++) { if (!hQx2mV0[i]) return false; if (!hQy2mV0[i]) return false; } fHCorrectV0ChWeghts -> Reset(); fHCorrectV0ChWeghts = (TH2F *) fListVZEROCalib->FindObject(Form("hWgtV0ChannelsvsVzRun%d",fRunNum)); if (!fHCorrectV0ChWeghts) return false; } //18q NUA if (IsDoNUA) { hCorrectNUAPos -> Reset(); hCorrectNUANeg -> Reset(); hCorrectNUAPos = (TH3F*) fListNUA->FindObject(Form("fHist_NUA_VzPhiEta_kPID%dPos_Run%d",0,fRunNum)); hCorrectNUANeg = (TH3F*) fListNUA->FindObject(Form("fHist_NUA_VzPhiEta_kPID%dNeg_Run%d",0,fRunNum)); if (!hCorrectNUAPos) return false; if (!hCorrectNUANeg) return false; } } return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::RemovalForRun1() { // pileup fUtils->SetUseOutOfBunchPileUp(true); fUtils->SetUseMVPlpSelection(true); // fUtils->SetMinPlpContribMV(5); bool isPileup = fUtils->IsPileUpEvent(fAOD); // bool isPileup = fUtils->IsPileUpMV(fAOD); // pp, p-Pb if (isPileup) return false; return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::RejectEvtMultComp() // 15o_pass1, old pile-up { // TPC cluster cut Int_t multEsd = ((AliAODHeader*)fAOD->GetHeader())->GetNumberOfESDTracks(); // multESD const Int_t nTrk = fAOD->GetNumberOfTracks(); Int_t multTPC=0; // FB128 + Common Track Cuts Int_t multTPCFE=0; // FB1 + Common Track Cuts + chi2 > 0.2 Int_t multGlobal=0; // FB16 + Common Track Cuts + Dca Cuts for (Int_t it1 = 0; it1 < nTrk; it1++) { AliAODTrack* aodTrk = (AliAODTrack*)fAOD->GetTrack(it1); if (!aodTrk) continue; if (aodTrk->TestFilterBit(128)) multTPC++; double Eta = aodTrk->Eta(); double Pt = aodTrk->Pt(); double Phi = aodTrk->Phi(); double charge = aodTrk->Charge(); if (Pt<0.2 || Pt>5.0 || TMath::Abs(Eta)>0.8 || aodTrk->GetTPCNcls()<fNclsCut || aodTrk->GetTPCsignal()<10.0) continue; if (aodTrk->TestFilterBit(1) && aodTrk->Chi2perNDF()>0.2) multTPCFE++; if (!aodTrk->TestFilterBit(16) || aodTrk->Chi2perNDF()<0.1) continue; Double_t dca[2] = {-99., -99.}; Double_t cov[3] = {-99., -99., -99.}; Double_t magField = fAOD->GetMagneticField(); if (magField!=0) { if (aodTrk->PropagateToDCA(fAOD->GetPrimaryVertex(), magField, 100., dca, cov) && TMath::Abs(dca[0]) < 0.3 && TMath::Abs(dca[1]) < 0.3) multGlobal++; } } fHist2DMultMultQA[0]->Fill(multTPC,multEsd); fHist2DMultMultQA[1]->Fill(multGlobal,multTPCFE); //TODO TString fMultComp = "pileupByGlobalTPC1"; if (fMultComp.EqualTo("pileupByEDSTPC128")) { // Rihan if ((Double_t)(multEsd*(1/3.45) - 90.) < (Double_t)multTPC) { fHist2DMultMultQA[3]->Fill(multTPC,multEsd); return true; } else return false; } if (fMultComp.EqualTo("pileupByGlobalTPC1")){ // A.Dobrin if (multTPCFE-1.78*multGlobal<62.87 && multTPCFE-1.48*multGlobal>-36.73) { fHist2DMultMultQA[4]->Fill(multGlobal,multTPCFE); return true; } else return false; } return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::RejectEvtTFFit() { Float_t centV0M = -999; Float_t centCL1 = -999; Float_t centCL0 = -999; AliMultSelection* fMultSelection = (AliMultSelection*) InputEvent()->FindListObject("MultSelection"); if (!fMultSelection) { printf("\n\n **WARNING** ::UserExec() AliMultSelection object not found.\n\n"); exit(1); } centV0M = (Float_t) fCent; centCL1 = fMultSelection->GetMultiplicityPercentile("CL1"); centCL0 = fMultSelection->GetMultiplicityPercentile("CL0"); Int_t nITSClsLy0 = fAOD->GetNumberOfITSClusters(0); Int_t nITSClsLy1 = fAOD->GetNumberOfITSClusters(1); Int_t nITSCls = nITSClsLy0 + nITSClsLy1; AliAODTracklets* aodTrkl = (AliAODTracklets*)fAOD->GetTracklets(); Int_t nITSTrkls = aodTrkl->GetNumberOfTracklets(); const Int_t nTracks = fAOD->GetNumberOfTracks(); Int_t multTrk = 0; for (Int_t it = 0; it < nTracks; it++) { AliAODTrack* aodTrk = (AliAODTrack*)fAOD->GetTrack(it); if (!aodTrk) { delete aodTrk; continue; } if (aodTrk->TestFilterBit(32)) { if ((TMath::Abs(aodTrk->Eta()) < 0.8) && (aodTrk->GetTPCNcls() >= 70) && (aodTrk->Pt() >= 0.2)) multTrk++; } } fHist2DMultCentQA[0]->Fill(centV0M, multTrk); // Mult(FB32) Vs Cent(V0M) AliAODVZERO* aodV0 = fAOD->GetVZEROData(); Float_t multV0a = aodV0->GetMTotV0A(); Float_t multV0c = aodV0->GetMTotV0C(); Float_t multV0Tot = multV0a + multV0c; UShort_t multV0aOn = aodV0->GetTriggerChargeA(); UShort_t multV0cOn = aodV0->GetTriggerChargeC(); UShort_t multV0On = multV0aOn + multV0cOn; // // // Int_t tpcClsTot = fAOD->GetNumberOfTPCClusters(); // Float_t nclsDif = Float_t(tpcClsTot) - (53182.6 + 113.326*multV0Tot - 0.000831275*multV0Tot*multV0Tot); // pile-up cuts if (centCL0 < fCenCutLowPU->Eval(centV0M)) return false; if (centCL0 > fCenCutHighPU->Eval(centV0M)) return false; if (Float_t(nITSCls) > fSPDCutPU->Eval(nITSTrkls)) return false; if (multV0On < fV0CutPU->Eval(multV0Tot)) return false; if (Float_t(multTrk) < fMultCutPU->Eval(centV0M)) return false; if (((AliAODHeader*)fAOD->GetHeader())->GetRefMultiplicityComb08() < 0) return false; if (fAOD->IsIncompleteDAQ()) return false; fHist2DMultCentQA[1]->Fill(centV0M, multTrk); // Mult(FB32) Vs Cent(V0M) return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::RejectEvtTPCITSfb32TOF () { //TOD+FB32 pile-up removal // https://twiki.cern.ch/twiki/bin/viewauth/ALICE/AliDPGtoolsEventProp Int_t multTrk=0; Int_t multTrkTOF=0; int nTrk = fAOD->GetNumberOfTracks(); for (Int_t it2 = 0; it2 < nTrk; it2++) { AliAODTrack* aodTrk = (AliAODTrack*)fAOD->GetTrack(it2); if (!aodTrk) continue; if (aodTrk->TestFilterBit(32)) { multTrk++; if ( TMath::Abs(aodTrk->GetTOFsignalDz()) <= 10 && aodTrk->GetTOFsignal() >= 12000 && aodTrk->GetTOFsignal() <= 25000) multTrkTOF++; else return false; } } fHist2DMultMultQA[2]->Fill(multTrkTOF, nTrk); return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::AODPileupCheck () { Int_t isPileup = fAOD->IsPileupFromSPD(3); if (isPileup !=0 && fPeriod.EqualTo("LHC16t")) return false; // LHC16t : pPb if (fAOD->IsIncompleteDAQ()) return false; if (((AliAODHeader*)fAOD->GetHeader())->GetRefMultiplicityComb08() < 0) return false; if (fPeriod.EqualTo("LHC15o")) { AliMultSelection* fMultSel = (AliMultSelection*)InputEvent()->FindListObject("MultSelection"); if (!fMultSel->GetThisEventIsNotPileup()) return false; if (!fMultSel->GetThisEventIsNotPileupMV()) return false; if (!fMultSel->GetThisEventIsNotPileupInMultBins()) return false; if (!fMultSel->GetThisEventHasNoInconsistentVertices()) return false; if (!fMultSel->GetThisEventPassesTrackletVsCluster()) return false; if (!fMultSel->GetThisEventIsNotIncompleteDAQ()) return false; if (!fMultSel->GetThisEventHasGoodVertex2016()) return false; } return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::PileUpMultiVertex() { // check for multi-vertexer pile-up const int kMinPlpContrib = 5; const double kMaxPlpChi2 = 5.0; const double kMinWDist = 15; const AliVVertex* vtPrm = 0; const AliVVertex* vtPlp = 0; int nPlp = 0; if (!(nPlp=fAOD->GetNumberOfPileupVerticesTracks())) return false; vtPrm = fAOD->GetPrimaryVertex(); if (vtPrm == fAOD->GetPrimaryVertexSPD()) return true; // there are pile-up vertices but no primary //int bcPrim = vtPrm->GetBC(); for (int ipl=0;ipl<nPlp;ipl++) { vtPlp = (const AliVVertex*)fAOD->GetPileupVertexTracks(ipl); if (vtPlp->GetNContributors() < kMinPlpContrib) continue; if (vtPlp->GetChi2perNDF() > kMaxPlpChi2) continue; //int bcPlp = vtPlp->GetBC(); //if (bcPlp!=AliVTrack::kTOFBCNA && TMath::Abs(bcPlp-bcPrim)>2) // return kTRUE; // pile-up from other BC double wDst = GetWDist(vtPrm,vtPlp); if (wDst<kMinWDist) continue; return true; // pile-up: well separated vertices } return false; } //--------------------------------------------------- double AliAnalysisTaskLambdaProtonCVE::GetWDist(const AliVVertex* v0, const AliVVertex* v1) { // calculate sqrt of weighted distance to other vertex if (!v0 || !v1) { printf("One of vertices is not valid\n"); return 0; } static TMatrixDSym vVb(3); double dist = -1; double dx = v0->GetX()-v1->GetX(); double dy = v0->GetY()-v1->GetY(); double dz = v0->GetZ()-v1->GetZ(); double cov0[6],cov1[6]; v0->GetCovarianceMatrix(cov0); v1->GetCovarianceMatrix(cov1); vVb(0,0) = cov0[0]+cov1[0]; vVb(1,1) = cov0[2]+cov1[2]; vVb(2,2) = cov0[5]+cov1[5]; vVb(1,0) = vVb(0,1) = cov0[1]+cov1[1]; vVb(0,2) = vVb(1,2) = vVb(2,0) = vVb(2,1) = 0.; vVb.InvertFast(); if (!vVb.IsValid()) {printf("Singular Matrix\n"); return dist;} dist = vVb(0,0)*dx*dx + vVb(1,1)*dy*dy + vVb(2,2)*dz*dz + 2*vVb(0,1)*dx*dy + 2*vVb(0,2)*dx*dz + 2*vVb(1,2)*dy*dz; return dist>0 ? TMath::Sqrt(dist) : -1; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::AcceptAODTrack(AliAODTrack *track) { //------------------ // track cut //------------------ double pt = track->Pt(); double eta = track->Eta(); int nhits = track->GetTPCNcls(); double dedx = track->GetTPCsignal(); double chi2 = track->Chi2perNDF(); int charge = track->Charge(); if ( pt < fPtMin || pt > fPtMax || fabs(eta) > fEtaCut || fabs(nhits) < fNclsCut || chi2 < fChi2Min || chi2 > fChi2Max || dedx < fDedxCut) return false; if (fFilterBit != 768){ if (fPeriod.EqualTo("LHC10h")) { //------------------ // dca cut //------------------ double mag = fAOD->GetMagneticField(); double dcaxy = 999.; double dcaz = 999.; double r[3]; double dca[2]; double cov[3]; double vx = fVertex[0]; double vy = fVertex[1]; double vz = fVertex[2]; bool proptodca = track->PropagateToDCA(fAOD->GetPrimaryVertex(), mag, 100., dca, cov); if (track->GetXYZ(r)) { dcaxy = r[0]; dcaz = r[1]; } else { double dcax = r[0] - vx; double dcay = r[1] - vy; dcaz = r[2] - vz; dcaxy = sqrt(dcax*dcax + dcay*dcay); } if (fabs(dcaxy)>fDcaCutxy) return false; if (fabs(dcaz)>fDcaCutz) return false; fHistDcaXY->Fill(dcaxy); fHistDcaZ->Fill(dcaz); } } fHistPt->Fill(pt); fHistEta->Fill(eta); fHistNhits->Fill(nhits); fHist2DPDedx->Fill(track->P()*charge, dedx); return true; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::CheckPIDofParticle(AliAODTrack* ftrack, int pidToCheck) { if (pidToCheck==0) return kTRUE; //// Charge Particles do not need PID check bool bPIDokay = kFALSE; if (!fPIDResponse) { Printf("\n Could Not access PIDResponse Task, please Add the Task...\n return with kFALSE pid\n"); return kFALSE; } /// Rihan todo: To set the low pT cuts for nSigmaTPC from AddTaskMacro! /// Although someone barely needs to change it given the purity.. float nSigTPC = 0, nSigTOF = 0, nSigRMS = 0; bool trkPtPID = ftrack->Pt(); int trkChargePID = ftrack->Charge(); ///Pion => if (pidToCheck==1) { nSigTPC = fPIDResponse->NumberOfSigmasTPC(ftrack, AliPID::kPion);//Some warning show here (***TDatabasePDG::AddParicle: particle with PDGcode = 3124 already defind),I don't understand what happended. --chunzheng nSigTOF = fPIDResponse->NumberOfSigmasTOF(ftrack, AliPID::kPion); nSigRMS = TMath::Sqrt(nSigTPC*nSigTPC + nSigTOF*nSigTOF); if (trkPtPID<=0.5 && TMath::Abs(nSigTPC)<=fNSigmaTPCCut) bPIDokay = kTRUE; // Using TPCTOF RMS cut for higher pt: else if (trkPtPID>0.5 && TMath::Abs(nSigRMS)<=fNSigmaTOFCut) bPIDokay = kTRUE; return bPIDokay; } ///Kaon => else if (pidToCheck==2) { nSigTPC = fPIDResponse->NumberOfSigmasTPC(ftrack, AliPID::kKaon); nSigTOF = fPIDResponse->NumberOfSigmasTOF(ftrack, AliPID::kKaon); nSigRMS = TMath::Sqrt(nSigTPC*nSigTPC + nSigTOF*nSigTOF); if (trkPtPID<=0.45 && TMath::Abs(nSigTPC)<=fNSigmaTPCCut) bPIDokay = kTRUE; else if (trkPtPID>0.45 && TMath::Abs(nSigRMS)<=fNSigmaTOFCut) bPIDokay = kTRUE; return bPIDokay; } ///proton => else if (pidToCheck==3) {/// nSigTPC = fPIDResponse->NumberOfSigmasTPC(ftrack, AliPID::kProton); nSigTOF = fPIDResponse->NumberOfSigmasTOF(ftrack, AliPID::kProton); nSigRMS = TMath::Sqrt(nSigTPC*nSigTPC + nSigTOF*nSigTOF); if (trkPtPID<=0.6 && TMath::Abs(nSigTPC)<=fNSigmaTPCCut) { bPIDokay = kTRUE; if (trkChargePID>0 && trkPtPID<0.4) bPIDokay = kFALSE; } else if (trkPtPID>0.6 && TMath::Abs(nSigRMS)<=fNSigmaTOFCut) { bPIDokay = kTRUE; } return bPIDokay; } else{ Printf("\n -Ve number not allowed! Choose among: 0,1,2,3 (Charge Pion, Kaon, Proton)\n return with kFALSE \n"); return kFALSE; } return kFALSE; } //--------------------------------------------------- double AliAnalysisTaskLambdaProtonCVE::GetNUECor(int charge, double pt) { double weightNUE = 1; if (fPeriod.EqualTo("LHC10h")) { if (charge>0) { hNUEweightPlus = (TH1D*)fListNUE->FindObject(Form("effVsPt_cent%iPlus",fCentBin)); if (!hNUEweightPlus) return -1; int ptBin = hNUEweightPlus->GetXaxis()->FindBin(pt); if (hNUEweightPlus->GetBinContent(ptBin)>0) { weightNUE = 1./ hNUEweightPlus->GetBinContent(ptBin); } else return -1; } if (charge<0) { hNUEweightMinus = (TH1D*)fListNUE->FindObject(Form("effVsPt_cent%iMinus",fCentBin)); if (!hNUEweightMinus) return -1; int ptBin = hNUEweightMinus->GetXaxis()->FindBin(pt); if (hNUEweightMinus->GetBinContent(ptBin)>0) { weightNUE = 1./ hNUEweightMinus->GetBinContent(ptBin); } else return -1; } } else if (fPeriod.EqualTo("LHC15o")) { if (charge>0) { //hNUEweightPlus = (TH1D*)fListNUE->FindObject("trkEfficiencyChrgPos"); if (!hNUEweightPlus) return -1; int ptBin = hNUEweightPlus->GetXaxis()->FindBin(pt); if (hNUEweightPlus->GetBinContent(ptBin)>0) { weightNUE = 1./ hNUEweightPlus->GetBinContent(ptBin); } else return -1; } if (charge<0) { //hNUEweightMinus = (TH1D*)fListNUE->FindObject("trkEfficiencyChrgNeg"); if (!hNUEweightMinus) return -1; int ptBin = hNUEweightMinus->GetXaxis()->FindBin(pt); if (hNUEweightMinus->GetBinContent(ptBin)>0) { weightNUE = 1./ hNUEweightMinus->GetBinContent(ptBin); } else return -1; } } return weightNUE; } //--------------------------------------------------- double AliAnalysisTaskLambdaProtonCVE::GetNUACor(int charge, double phi, double eta, double vz) { double weightNUA = 1; if (fVzBin<0 || fCentBin<0 || fRunNum<0) return -1; if (fPeriod.EqualTo("LHC10h")) { hNUAweightPlus = (TH2D*)fListNUA->FindObject(Form("weightdPhidEta_run%i_cent0_vz%i_plus",fRunNum, fVzBin)); hNUAweightMinus = (TH2D*)fListNUA->FindObject(Form("weightdPhidEta_run%i_cent0_vz%i_minus",fRunNum, fVzBin)); if (!hNUAweightPlus || !hNUAweightMinus) return -1; if (charge>0) { int phiBin = hNUAweightPlus->GetXaxis()->FindBin(phi); int etaBin = hNUAweightPlus->GetYaxis()->FindBin(eta); if (hNUAweightPlus->GetBinContent(phiBin, etaBin)>0) weightNUA = hNUAweightPlus->GetBinContent(phiBin, etaBin); return weightNUA; } else if (charge<0) { int phiBin = hNUAweightMinus->GetXaxis()->FindBin(phi); int etaBin = hNUAweightMinus->GetYaxis()->FindBin(eta); if (hNUAweightMinus->GetBinContent(phiBin, etaBin)>0) weightNUA = hNUAweightMinus->GetBinContent(phiBin, etaBin); return weightNUA; } } if (fPeriod.EqualTo("LHC15o")|| fPeriod.EqualTo("LHC18q") || fPeriod.EqualTo("LHC18r")) { // Rihan and Protty 's NUA Results if (charge>0) { if (!hCorrectNUAPos) return -1; int iBinNUA = hCorrectNUAPos->FindBin(vz,phi,eta); if (hCorrectNUAPos->GetBinContent(iBinNUA)>0) weightNUA = (double)hCorrectNUAPos->GetBinContent(iBinNUA); return weightNUA; } else if (charge<0) { if (!hCorrectNUANeg) return -1; int iBinNUA = hCorrectNUANeg->FindBin(vz,phi,eta); if (hCorrectNUANeg->GetBinContent(iBinNUA)>0) weightNUA = (double)hCorrectNUANeg->GetBinContent(iBinNUA); return weightNUA; } // In Rihan and Protty 's NUA results, the phi distribution is independent on centrality and particle charge } return weightNUA; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::IsGoodV0(AliAODv0 *aodV0) { // Offline reconstructed V0 only if (aodV0->GetOnFlyStatus()) return false; // Get daughters and check them AliAODTrack *myTrackNegTest = dynamic_cast<AliAODTrack*>(aodV0->GetDaughter(1)); AliAODTrack *myTrackPosTest = dynamic_cast<AliAODTrack*>(aodV0->GetDaughter(0)); if (!myTrackPosTest || !myTrackNegTest) { Printf("strange analysis::UserExec:: Error:Could not retreive one of the daughter track\n"); return false; } // Unlike signs of daughters if (myTrackNegTest->Charge() == myTrackPosTest->Charge()) return false; // Cosinus of pointing angle double dCPA = aodV0->CosPointingAngle(fVertex); // cut on Cosinus of pointing angle if (dCPA < fV0CPAMin) return false; // DCA of V0 double dV0Dca = aodV0->DcaV0ToPrimVertex(); if (TMath::Abs(dV0Dca) > fV0DCAToPrimVtxMax) return false; // V0 path length before decay double dDecayLength = aodV0->DecayLengthV0(fVertex); if (dDecayLength > fV0DecayLengthMax) return false; if (dDecayLength < fV0DecayLengthMin) return false; // DCA between daughters double dDCA = aodV0->DcaV0Daughters(); if (dDCA > fV0DcaBetweenDaughtersMax) return false; double dPt = aodV0->Pt(); if (dPt < fV0PtMin ) return false; double dRapidity = aodV0->RapLambda(); if (TMath::Abs(dRapidity) > fV0RapidityMax) return false; return kTRUE; } //--------------------------------------------------- bool AliAnalysisTaskLambdaProtonCVE::IsGoodDaughterTrack(const AliAODTrack *track) { // TPC refit if (!track->IsOn(AliAODTrack::kTPCrefit)) return false; // No kinks if (int(track->GetProdVertex()->GetType()) == AliAODVertex::kKink) return false; // Maximum value of transverse momentum double dPt = track->Pt(); if (dPt > fDaughtersPtMax) return false; // Maximum value of pseudorapidity double dEta = track->Eta(); if (TMath::Abs(dEta) > fDaughtersEtaMax) return false; // Minimum number of clusters float nCrossedRowsTPC = track->GetTPCClusterInfo(2,1); if (nCrossedRowsTPC < fDaughtersTPCNclsMin) return false; // Findable clusters > 0 int findable = track->GetTPCNclsF(); if (findable <= 0) return false; // [number of crossed rows]>0.8 [number of findable clusters]. if (nCrossedRowsTPC/findable < 0.8) return false; return true; } //--------------------------------------------------- int AliAnalysisTaskLambdaProtonCVE::GetLambdaCode(const AliAODTrack *pTrack, const AliAODTrack *nTrack) { bool IsLambda = kFALSE; bool IsAntiLambda = kFALSE; int code = 0; //ฮ›-->(p+)+(ฯ€-) float nSigTPCPosProton = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(pTrack, AliPID::kProton));//TPC p+ float nSigTPCNegPion = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(nTrack, AliPID::kPion));//TPC ฯ€- //(ฮ›-)-->(p-)+(ฯ€+) float nSigTPCPosPion = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(pTrack, AliPID::kPion));//TPC ฯ€+ float nSigTPCNegProton = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(nTrack, AliPID::kProton));//TPC p- IsLambda = (nSigTPCPosProton < fV0PosProtonTPCNsigma) && (nSigTPCNegPion < fV0NegPionTPCNsigma); IsAntiLambda = (nSigTPCNegProton < fV0NegProtonTPCNsigma) && (nSigTPCPosPion < fV0PosPionTPCNsigma); if (IsV0DaughterUseTOF) { float nSigTOFPosProton = TMath::Abs(fPIDResponse->NumberOfSigmasTOF(pTrack, AliPID::kProton));//TOF p+ float nSigTOFNegPion = TMath::Abs(fPIDResponse->NumberOfSigmasTOF(nTrack, AliPID::kPion));//TOF ฯ€- float nSigTOFPosPion = TMath::Abs(fPIDResponse->NumberOfSigmasTOF(pTrack, AliPID::kPion));//TOF ฯ€+ float nSigTOFNegProton = TMath::Abs(fPIDResponse->NumberOfSigmasTOF(nTrack, AliPID::kProton));//TOF p- IsLambda *= (nSigTOFPosProton < fV0PosProtonTOFNsigma && nSigTOFNegPion < fV0NegPionTOFNsigma); IsAntiLambda *= (nSigTOFNegProton < fV0NegProtonTOFNsigma && nSigTOFPosPion < fV0PosPionTOFNsigma); } if (IsLambda) code = 3122; if (IsAntiLambda) code = -3122; if (IsLambda && IsAntiLambda) code = 0; return code; } //--------------------------------------------------- double AliAnalysisTaskLambdaProtonCVE::GetEventPlane(double qx, double qy, double harmonic) { double psi = (1./harmonic)*TMath::ATan2(qy,qx); if (psi < 0) return psi += TMath::TwoPi()/harmonic; else return psi; } //---------------------------------------------------
128,393
58,758
#ifndef airsimcore_ufrudder_hpp #define airsimcore_ufrudder_hpp #include "UniForce.hpp" #include "UFRudderParams.hpp" namespace msr { namespace airlib { class UFRudder : public UniForce { public: UFRudder(const Vector3r& position, const Vector3r& normal, UFRudderParams::UniForceDirection turning_direction, UFRudderParams * params, const Environment* environment, uint id = -1) : params_(params) { initialize(position, normal, turning_direction, environment, id); setType(UniForceType::Rudder); setWrench2Zero(); setObjType(UpdatableObject::typeUpdObj::rudder); //params_->calculateMaxThrust(); } UFRudderParams * getCurrentParams() const { return params_; } void reportState(StateReporter& reporter) override { reporter.writeValue("Dir", static_cast<int>(getTurningDirection())); reporter.writeValue("Ctrl-in", getOutput().control_signal_input); reporter.writeValue("Ctrl-fl", getOutput().control_signal_filtered); reporter.writeValue("speed", getOutput().speed); reporter.writeValue("thrust", getOutput().thrust); reporter.writeValue("torque", getOutput().torque_scaler); } uint getActID() const override { return params_->getActID(); } void setControlSignal(real_T control_signal) override { real_T ctrl = Utils::clip(control_signal, -1.0f, 1.0f); UniForce::setControlSignal(ctrl); } protected: void setWrench(Wrench& wrench) override { Vector3r normal = getNormal(); wrench.force = normal *( getOutput().thrust + getOutput().resistance )* getAirDensityRatio(); wrench.torque = Vector3r(0,0,0); } private: void setOutput(Output& output, const FirstOrderFilter<real_T>& control_signal_filter) override { output.control_signal_input = control_signal_filter.getInput(); output.control_signal_filtered = control_signal_filter.getOutput(); auto ctrl_signal = output.control_signal_filtered - 0.5f; output.angle = ctrl_signal * params_->getMaxAngle() ; //resistance drag Vector3r unit_z(0, 1, 0); //NED frame Quaternionr angle_plane(AngleAxisr( output.angle, unit_z)); Vector3r force2plane = VectorMath::rotateVector(Vector3r(getAirSpeed().x(), 0, getAirSpeed().z()), angle_plane, true); const float velocity_input = std::abs(force2plane.z()) * force2plane.z(); output.resistance = velocity_input * params_->getResistance(); //airflow correction const float velocity_forward = getAirSpeed().x() * getAirSpeed().x(); output.thrust = velocity_forward * ctrl_signal * params_->getMaxThrust() ; output.torque_scaler = 0.0f; output.turning_direction = getTurningDirection(); output.vel_input = force2plane; } UniForceParams& getParams() const override { return (UniForceParams &)params_; } real_T getCtrlSigFltTC() const override { return params_->control_signal_filter_tc; } private: UFRudderParams * params_; }; } } #endif
2,990
1,190
#include <iostream> #include <vector> using namespace std; int main() { int n, k; cin >> n >> k; vector <int> data; for (int i = 0; i < n; i++) { int input; cin >> input; data.push_back(input); } int kth_value = data.at(k - 1), count = 0; for (int i = 0; i < data.size(); i++) { if (data.at(i) >= kth_value && data.at(i) > 0) count ++; } cout << count << endl; return 0; }
463
184
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "stdafx.h" #include "EditorCommon.h" #include <AzToolsFramework/Slice/SliceUtilities.h> #include <AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h> #include <LyShine/Bus/UiSystemBus.h> //------------------------------------------------------------------------------- #define UICANVASEDITOR_EXTRA_VERTICAL_PADDING_IN_PIXELS (8) //------------------------------------------------------------------------------- PropertiesContainer::PropertiesContainer(PropertiesWidget* propertiesWidget, EditorWindow* editorWindow) : QScrollArea(propertiesWidget) , m_propertiesWidget(propertiesWidget) , m_editorWindow(editorWindow) , m_containerWidget(new QWidget(this)) , m_rowLayout(new QVBoxLayout(m_containerWidget)) , m_selectedEntityDisplayNameWidget(nullptr) , m_selectionHasChanged(false) , m_isCanvasSelected(false) { // Hide the border. setStyleSheet("QScrollArea { border: 0px hidden transparent; }"); m_rowLayout->setContentsMargins(0, 0, 0, 0); m_rowLayout->setSpacing(0); setWidgetResizable(true); setFocusPolicy(Qt::ClickFocus); setWidget(m_containerWidget); // Get the serialize context. EBUS_EVENT_RESULT(m_serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); AZ_Assert(m_serializeContext, "We should have a valid context!"); } void PropertiesContainer::BuildSharedComponentList(ComponentTypeMap& sharedComponentsByType, const AzToolsFramework::EntityIdList& entitiesShown) { // For single selection of a slice-instanced entity, gather the direct slice ancestor // so we can visualize per-component differences. m_compareToEntity.reset(); if (1 == entitiesShown.size()) { AZ::SliceComponent::SliceInstanceAddress address; EBUS_EVENT_ID_RESULT(address, entitiesShown[0], AzFramework::EntityIdContextQueryBus, GetOwningSlice); if (address.IsValid()) { AZ::SliceComponent::EntityAncestorList ancestors; address.GetReference()->GetInstanceEntityAncestry(entitiesShown[0], ancestors, 1); if (!ancestors.empty()) { m_compareToEntity = AzToolsFramework::SliceUtilities::CloneSliceEntityForComparison(*ancestors[0].m_entity, *address.GetInstance(), *m_serializeContext); } } } // Create a SharedComponentInfo for each component // that selected entities have in common. // See comments on SharedComponentInfo for more details for (AZ::EntityId entityId : entitiesShown) { AZ::Entity* entity = nullptr; EBUS_EVENT_RESULT(entity, AZ::ComponentApplicationBus, FindEntity, entityId); AZ_Assert(entity, "Entity was selected but no such entity exists?"); if (!entity) { continue; } // Track how many of each component-type we've seen on this entity AZStd::unordered_map<AZ::Uuid, size_t> entityComponentCounts; for (AZ::Component* component : entity->GetComponents()) { const AZ::Uuid& componentType = azrtti_typeid(component); const AZ::SerializeContext::ClassData* classData = m_serializeContext->FindClassData(componentType); // Skip components without edit data if (!classData || !classData->m_editData) { continue; } // Skip components that are set to invisible. if (const AZ::Edit::ElementData* editorDataElement = classData->m_editData->FindElementData(AZ::Edit::ClassElements::EditorData)) { if (AZ::Edit::Attribute* visibilityAttribute = editorDataElement->FindAttribute(AZ::Edit::Attributes::Visibility)) { AzToolsFramework::PropertyAttributeReader reader(component, visibilityAttribute); AZ::u32 visibilityValue; if (reader.Read<AZ::u32>(visibilityValue)) { if (visibilityValue == AZ_CRC("PropertyVisibility_Hide", 0x32ab90f7)) { continue; } } } } // The sharedComponentList is created based on the first entity. if (entityId == *entitiesShown.begin()) { // Add new SharedComponentInfo SharedComponentInfo sharedComponent; sharedComponent.m_classData = classData; sharedComponentsByType[componentType].push_back(sharedComponent); } // Skip components that don't correspond to a type from the first entity. if (sharedComponentsByType.find(componentType) == sharedComponentsByType.end()) { continue; } // Update entityComponentCounts (may be multiple components of this type) auto entityComponentCountsIt = entityComponentCounts.find(componentType); size_t componentIndex = (entityComponentCountsIt == entityComponentCounts.end()) ? 0 : entityComponentCountsIt->second; entityComponentCounts[componentType] = componentIndex + 1; // Skip component if the first entity didn't have this many. if (componentIndex >= sharedComponentsByType[componentType].size()) { continue; } // Component accepted! Add it as an instance SharedComponentInfo& sharedComponent = sharedComponentsByType[componentType][componentIndex]; sharedComponent.m_instances.push_back(component); // If specified, locate the corresponding component in the comparison entity to // visualize differences. if (m_compareToEntity && !sharedComponent.m_compareInstance) { size_t compareComponentIndex = 0; for (AZ::Component* compareComponent : m_compareToEntity.get()->GetComponents()) { const AZ::Uuid& compareComponentType = azrtti_typeid(compareComponent); if (componentType == compareComponentType) { if (componentIndex == compareComponentIndex) { sharedComponent.m_compareInstance = compareComponent; break; } compareComponentIndex++; } } } } } // Cull any SharedComponentInfo that doesn't fit all our requirements ComponentTypeMap::iterator sharedComponentsByTypeIterator = sharedComponentsByType.begin(); while (sharedComponentsByTypeIterator != sharedComponentsByType.end()) { AZStd::vector<SharedComponentInfo>& sharedComponents = sharedComponentsByTypeIterator->second; // Remove component if it doesn't exist on every entity AZStd::vector<SharedComponentInfo>::iterator sharedComponentIterator = sharedComponents.begin(); while (sharedComponentIterator != sharedComponents.end()) { if (sharedComponentIterator->m_instances.size() != entitiesShown.size() || sharedComponentIterator->m_instances.empty()) { sharedComponentIterator = sharedComponents.erase(sharedComponentIterator); } else { ++sharedComponentIterator; } } // Remove entry if all its components were culled if (sharedComponents.size() == 0) { sharedComponentsByTypeIterator = sharedComponentsByType.erase(sharedComponentsByTypeIterator); } else { ++sharedComponentsByTypeIterator; } } } void PropertiesContainer::BuildSharedComponentUI(ComponentTypeMap& sharedComponentsByType, const AzToolsFramework::EntityIdList& entitiesShown) { (void)entitiesShown; // At this point in time: // - Each SharedComponentInfo should contain one component instance // from each selected entity. // - Any pre-existing m_componentEditor entries should be // cleared of component instances. // Add each component instance to its corresponding editor // We add them in the order that the component factories were registered in, this provides // a consistent order of components. It doesn't appear to be the case that components always // stay in the order they were added to the entity in, some of our slices do not have the // UiElementComponent first for example. const AZStd::vector<AZ::Uuid>* componentTypes; EBUS_EVENT_RESULT(componentTypes, UiSystemBus, GetComponentTypesForMenuOrdering); // There could be components that were not registered for component ordering. We don't // want to hide them. So add them at the end of the list AZStd::vector<AZ::Uuid> componentOrdering; componentOrdering = *componentTypes; for (auto sharedComponentMapEntry : sharedComponentsByType) { if (AZStd::find(componentOrdering.begin(), componentOrdering.end(), sharedComponentMapEntry.first) == componentOrdering.end()) { componentOrdering.push_back(sharedComponentMapEntry.first); } } for (auto& componentType : componentOrdering) { if (sharedComponentsByType.count(componentType) <= 0) { continue; // there are no components of this type in the sharedComponentsByType map } const auto& sharedComponents = sharedComponentsByType[componentType]; for (size_t sharedComponentIndex = 0; sharedComponentIndex < sharedComponents.size(); ++sharedComponentIndex) { const SharedComponentInfo& sharedComponent = sharedComponents[sharedComponentIndex]; AZ_Assert(sharedComponent.m_instances.size() == entitiesShown.size() && !sharedComponent.m_instances.empty(), "sharedComponentsByType should only contain valid entries at this point"); // Create an editor if necessary AZStd::vector<AzToolsFramework::ReflectedPropertyEditor*>& componentEditors = m_componentEditorsByType[componentType]; bool createdEditor = false; if (sharedComponentIndex >= componentEditors.size()) { componentEditors.push_back(CreatePropertyEditor()); createdEditor = true; } AzToolsFramework::ReflectedPropertyEditor& componentEditor = *componentEditors[sharedComponentIndex]; // Add instances to componentEditor for (AZ::Component* componentInstance : sharedComponent.m_instances) { // Note that in the case of a GenericComponentWrapper, // we give the editor the GenericComponentWrapper // rather than the underlying type. void* classPtr = componentInstance; const AZ::Uuid& classType = azrtti_typeid(componentInstance); // non-first instances are aggregated under the first instance void* aggregateInstance = nullptr; if (componentInstance != sharedComponent.m_instances.front()) { aggregateInstance = sharedComponent.m_instances.front(); } void* compareInstance = sharedComponent.m_compareInstance; componentEditor.AddInstance(classPtr, classType, aggregateInstance, compareInstance); } // Refresh editor componentEditor.InvalidateAll(); componentEditor.show(); } } } AzToolsFramework::ReflectedPropertyEditor* PropertiesContainer::CreatePropertyEditor() { AzToolsFramework::ReflectedPropertyEditor* editor = new AzToolsFramework::ReflectedPropertyEditor(nullptr); m_rowLayout->addWidget(editor); editor->hide(); const int propertyLabelWidth = 150; editor->Setup(m_serializeContext, m_propertiesWidget, true, propertyLabelWidth); editor->SetSavedStateKey(AZ_CRC("UiCanvasEditor_PropertyEditor", 0xc402ebcc)); editor->SetLabelAutoResizeMinimumWidth(propertyLabelWidth); editor->SetAutoResizeLabels(true); QObject::connect(editor, &AzToolsFramework::ReflectedPropertyEditor::OnExpansionContractionDone, this, &PropertiesContainer::SetHeightOfContentRect); return editor; } void PropertiesContainer::Update() { size_t selectedEntitiesAmount = m_selectedEntities.size(); QString displayName; if (selectedEntitiesAmount == 0) { displayName = "No Canvas Loaded"; } else if (selectedEntitiesAmount == 1) { // Either only one element selected, or none (still is 1 because it selects the canvas instead) // If the canvas was selected if (m_isCanvasSelected) { displayName = "Canvas"; } // Else one element was selected else { // Set the name in the properties pane to the name of the element AZ::EntityId selectedElement = m_selectedEntities.front(); AZStd::string selectedEntityName; EBUS_EVENT_ID_RESULT(selectedEntityName, selectedElement, UiElementBus, GetName); displayName = selectedEntityName.c_str(); } } else // more than one entity selected { displayName = ToString(selectedEntitiesAmount) + " elements selected"; } // Update the selected element display name if (m_selectedEntityDisplayNameWidget != nullptr) { m_selectedEntityDisplayNameWidget->setText(displayName); } // Clear content. { for (int j = m_rowLayout->count(); j > 0; --j) { AzToolsFramework::ReflectedPropertyEditor* editor = static_cast<AzToolsFramework::ReflectedPropertyEditor*>(m_rowLayout->itemAt(j - 1)->widget()); editor->hide(); editor->ClearInstances(); } m_compareToEntity.reset(); } if (m_selectedEntities.empty()) { return; // nothing to do } ComponentTypeMap sharedComponentList; BuildSharedComponentList(sharedComponentList, m_selectedEntities); BuildSharedComponentUI(sharedComponentList, m_selectedEntities); SetHeightOfContentRect(); } void PropertiesContainer::SetHeightOfContentRect() { int sumContentsRect = 0; for (auto& componentEditorsPair : m_componentEditorsByType) { for (AzToolsFramework::ReflectedPropertyEditor* editor : componentEditorsPair.second) { if (editor) { // We DON'T want to scroll thru individual editors. // We ONLY want to scroll thru the ENTIRE layout of editors. // We achieve this by setting each editor's minimum height // to its full layout and setting the container's height // (this class) to the full span of all its sub-editors. int minimumHeight = editor->GetContentHeight() + UICANVASEDITOR_EXTRA_VERTICAL_PADDING_IN_PIXELS; editor->setMinimumHeight(minimumHeight); sumContentsRect += minimumHeight; } } } // Set the container's maximum height. m_containerWidget->setMaximumHeight(sumContentsRect); } void PropertiesContainer::Refresh(AzToolsFramework::PropertyModificationRefreshLevel refreshLevel, const AZ::Uuid* componentType) { if (m_selectionHasChanged) { Update(); m_selectionHasChanged = false; } else { for (auto& componentEditorsPair : m_componentEditorsByType) { if (!componentType || (*componentType == componentEditorsPair.first)) { for (AzToolsFramework::ReflectedPropertyEditor* editor : componentEditorsPair.second) { if (editor) { editor->QueueInvalidation(refreshLevel); } } } } // If the selection has not changed, but a refresh was prompted then the name of the currently selected entity might // have changed. size_t selectedEntitiesAmount = m_selectedEntities.size(); // Check if only one entity is selected and that it is an element if (selectedEntitiesAmount == 1 && !m_isCanvasSelected) { // Set the name in the properties pane to the name of the element AZ::EntityId selectedElement = m_selectedEntities.front(); AZStd::string selectedEntityName; EBUS_EVENT_ID_RESULT(selectedEntityName, selectedElement, UiElementBus, GetName); // Update the selected element display name if (m_selectedEntityDisplayNameWidget != nullptr) { m_selectedEntityDisplayNameWidget->setText(selectedEntityName.c_str()); } } } } void PropertiesContainer::SelectionChanged(HierarchyItemRawPtrList* items) { m_selectedEntities.clear(); if (items) { for (auto i : *items) { m_selectedEntities.push_back(i->GetEntityId()); } } m_isCanvasSelected = false; if (m_selectedEntities.empty()) { // Add the canvas AZ::EntityId canvasId = m_editorWindow->GetCanvas(); if (canvasId.IsValid()) { m_selectedEntities.push_back(canvasId); m_isCanvasSelected = true; } } m_selectionHasChanged = true; } void PropertiesContainer::SelectedEntityPointersChanged() { m_selectionHasChanged = true; Refresh(); } void PropertiesContainer::RequestPropertyContextMenu(AzToolsFramework::InstanceDataNode* node, const QPoint& globalPos) { AZ::Component* componentToRemove = nullptr; { while (node) { if ((node->GetClassMetadata()) && (node->GetClassMetadata()->m_azRtti)) { if (node->GetClassMetadata()->m_azRtti->IsTypeOf(AZ::Component::RTTI_Type())) { AZ::Component* component = static_cast<AZ::Component*>(node->FirstInstance()); // Only break if the component we got was a component on an entity, not just a member variable component if (component->GetEntity() != nullptr) { componentToRemove = component; break; } } } node = node->GetParent(); } } HierarchyMenu contextMenu(m_editorWindow->GetHierarchy(), HierarchyMenu::Show::kRemoveComponents | HierarchyMenu::Show::kPushToSlice, false, componentToRemove); if (!contextMenu.isEmpty()) { contextMenu.exec(globalPos); } } void PropertiesContainer::SetSelectedEntityDisplayNameWidget(QLabel* selectedEntityDisplayNameWidget) { m_selectedEntityDisplayNameWidget = selectedEntityDisplayNameWidget; } #include <PropertiesContainer.moc>
19,743
5,018
#include "Game/UI/LobbyFilterManager.hpp" #include <iostream> namespace cge { LobbyFilterManager::~LobbyFilterManager(void) { if(m_container->getGui()) { m_container->getGui()->removeMousePreviewListener(this); } } LobbyFilterManager::LobbyFilterManager(agui::Gui* gui, GuiFactory* factory, LanguageManager* language, GuiColorManager* color, GuiFontManager* font ) : m_sizingContainer(false),m_canModifyFilters(false) { gui->addMousePreviewListener(this); agui::Font* f = font->getFont(0.9f); if(Platf::isRetina()) { f = font->getFont(2.1f); } m_viewAllButton = factory->createWhiteButton(); m_viewAllButton->setText(language->getElement("filter.all")); m_viewAllButton->setFont(f); m_viewAllButton->setFontColor(color->getColor("filter.all")); m_viewAllButton->resizeToContents(); m_viewAllButton->setToggleButton(true); m_viewAllButton->setAutoUntoggle(false); m_viewAllButton->addActionListener(this); m_viewAllButton->setToggleState(true); m_passTwoButton = factory->createWhiteButton(); m_passTwoButton->setText(language->getElement("filter.pass")); m_passTwoButton->setFont(f); m_passTwoButton->setFontColor(color->getColor("filter.pass")); m_passTwoButton->resizeToContents(); m_passTwoButton->setToggleButton(true); m_passTwoButton->addActionListener(this); m_regularButton = factory->createWhiteButton(); m_regularButton->setText(language->getElement("filter.regular")); m_regularButton->setFont(f); m_regularButton->setFontColor(color->getColor("filter.regular")); m_regularButton->resizeToContents(); m_regularButton->setToggleButton(true); m_regularButton->addActionListener(this); m_individualButton = factory->createWhiteButton(); m_individualButton->setText(language->getElement("filter.individual")); m_individualButton->setFont(f); m_individualButton->setFontColor(color->getColor("filter.individual")); m_individualButton->resizeToContents(); m_individualButton->setToggleButton(true); m_individualButton->addActionListener(this); m_cutThroatButton = factory->createWhiteButton(); m_cutThroatButton->setText(language->getElement("filter.cutthroat")); m_cutThroatButton->setFont(f); m_cutThroatButton->setFontColor(color->getColor("filter.cutthroat")); m_cutThroatButton->resizeToContents(); m_cutThroatButton->setToggleButton(true); m_cutThroatButton->addActionListener(this); m_regularBidButton = factory->createWhiteButton(); m_regularBidButton->setText(language->getElement("filter.regularbid")); m_regularBidButton->setFont(f); m_regularBidButton->setFontColor(color->getColor("filter.bid")); m_regularBidButton->resizeToContents(); m_regularBidButton->setToggleButton(true); m_regularBidButton->addActionListener(this); m_regularBidButton->setToggleState(true); m_mirrorBidButton = factory->createWhiteButton(); m_mirrorBidButton->setText(language->getElement("filter.mirrorbid")); m_mirrorBidButton->setFont(f); m_mirrorBidButton->setFontColor(color->getColor("filter.bid")); m_mirrorBidButton->resizeToContents(); m_mirrorBidButton->setToggleButton(true); m_mirrorBidButton->addActionListener(this); m_mirrorBidButton->setToggleState(true); m_suicideBidButton = factory->createWhiteButton(); m_suicideBidButton->setText(language->getElement("filter.suicidebid")); m_suicideBidButton->setFont(f); m_suicideBidButton->setFontColor(color->getColor("filter.bid")); m_suicideBidButton->resizeToContents(); m_suicideBidButton->setToggleButton(true); m_suicideBidButton->addActionListener(this); m_suicideBidButton->setToggleState(true); m_socialButton = factory->createWhiteButton(); m_socialButton->setText(language->getElement("filter.social")); m_socialButton->setFont(f); m_socialButton->setFontColor(color->getColor("filter.rated")); m_socialButton->resizeToContents(); m_socialButton->setToggleButton(true); m_socialButton->addActionListener(this); m_socialButton->setToggleState(true); m_ratedButton = factory->createWhiteButton(); m_ratedButton->setText(language->getElement("filter.rated")); m_ratedButton->setFont(f); m_ratedButton->setFontColor(color->getColor("filter.rated")); m_ratedButton->resizeToContents(); m_ratedButton->setToggleButton(true); m_ratedButton->addActionListener(this); m_ratedButton->setToggleState(true); /* m_scoreButton = factory->createWhiteButton(); m_scoreButton->setText(language->getElement("filter.score")); m_scoreButton->setFont(f); m_scoreButton->setFontColor(color->getColor("filter.score")); m_scoreButton->resizeToContents(); m_scoreButton->setToggleButton(true); m_scoreButton->addActionListener(this); m_scoreButton->setToggleState(true); m_timeButton = factory->createWhiteButton(); m_timeButton->setText(language->getElement("filter.time")); m_timeButton->setFont(f); m_timeButton->setFontColor(color->getColor("filter.score")); m_timeButton->resizeToContents(); m_timeButton->setToggleButton(true); m_timeButton->addActionListener(this); m_timeButton->setToggleState(true); m_handButton = factory->createWhiteButton(); m_handButton->setText(language->getElement("filter.hand")); m_handButton->setFont(f); m_handButton->setFontColor(color->getColor("filter.score")); m_handButton->resizeToContents(); m_handButton->setToggleButton(true); m_handButton->addActionListener(this); m_handButton->setToggleState(true); */ agui::Color checkColor = agui::Color(agui::Color(44,50,62)); m_hideEmptyCheckbox = factory->createCheckBox(); m_hideEmptyCheckbox->setText(language->getElement("filter.empty")); m_hideEmptyCheckbox->setFontColor(checkColor); m_hideEmptyCheckbox->setFont(f); m_hideEmptyCheckbox->resizeToContents(); m_hideEmptyCheckbox->addActionListener(this); m_hideFullCheckbox = factory->createCheckBox(); m_hideFullCheckbox->setText(language->getElement("filter.full")); m_hideFullCheckbox->setFontColor(checkColor); m_hideFullCheckbox->setFont(f); m_hideFullCheckbox->resizeToContents(); m_hideFullCheckbox->addActionListener(this); m_muteLobbyCheckbox = factory->createCheckBox(); m_muteLobbyCheckbox->setText(language->getElement("mute.lobby.chat")); m_muteLobbyCheckbox->setFontColor(checkColor); m_muteLobbyCheckbox->setFont(f); m_muteLobbyCheckbox->resizeToContents(); m_muteLobbyCheckbox->addActionListener(this); m_flow = factory->createFlowLayout(); m_typeFlow = factory->createFlowLayout(); m_bidFlow = factory->createFlowLayout(); // m_endRuleFlow = factory->createFlowLayout(); m_ratedFlow = factory->createFlowLayout(); m_hideFlow = factory->createFlowLayout(); m_muteFlow = factory->createFlowLayout(); m_container = factory->createToolContainer(); m_container->setMargins(3,2,3,2); m_flow->setMaxOnRow(1); m_container->add(m_flow); m_flow->add(m_typeFlow); m_flow->add(m_bidFlow); // m_flow->add(m_endRuleFlow); m_flow->add(m_ratedFlow); m_flow->add(m_hideFlow); m_flow->add(m_muteFlow); m_typeFlow->add(m_viewAllButton); m_typeFlow->add(m_regularButton); m_typeFlow->add(m_passTwoButton); m_typeFlow->add(m_individualButton); m_typeFlow->add(m_cutThroatButton); m_bidFlow->add(m_regularBidButton); m_bidFlow->add(m_mirrorBidButton); m_bidFlow->add(m_suicideBidButton); //m_endRuleFlow->add(m_scoreButton); //m_endRuleFlow->add(m_timeButton); //m_endRuleFlow->add(m_handButton); m_ratedFlow->add(m_socialButton); m_ratedFlow->add(m_ratedButton); //hide rated flow //m_ratedFlow->setVisibility(false); m_hideFlow->add(m_hideFullCheckbox); m_hideFlow->add(m_hideEmptyCheckbox); m_muteFlow->add(m_muteLobbyCheckbox); m_flow->setVerticalSpacing(1); m_typeFlow->setHorizontalSpacing(2); m_typeFlow->setHorizontallyCentered(true); m_hideFlow->setHorizontallyCentered(true); m_bidFlow->setHorizontalSpacing(2); m_bidFlow->setHorizontallyCentered(true); m_muteFlow->setHorizontallyCentered(true); // m_endRuleFlow->setHorizontalSpacing(2); // m_endRuleFlow->setHorizontallyCentered(true); m_ratedFlow->setHorizontalSpacing(2); m_ratedFlow->setHorizontallyCentered(true); m_hideFlow->setHorizontalSpacing(2); m_hideFlow->setVerticalSpacing(0); m_typeFlow->setVerticalSpacing(0); m_muteFlow->setVerticalSpacing(0); m_container->setSize(1,getHeight()); handleFilterLogic(m_viewAllButton); } ToolContainer* LobbyFilterManager::getWidget() { return m_container; } void LobbyFilterManager::actionPerformed(const agui::ActionEvent& evt ) { if(evt.getSource() == m_muteLobbyCheckbox) { DISPATCH_SCENE_EVENT (*it)->setBoolSetting("mute.lobby.chat.on",m_muteLobbyCheckbox->checked()); } else if(evt.getSource() == m_viewAllButton || evt.getSource() == m_passTwoButton || evt.getSource() == m_regularButton || evt.getSource() == m_individualButton || evt.getSource() == m_cutThroatButton || evt.getSource() == m_regularBidButton || evt.getSource() == m_mirrorBidButton || evt.getSource() == m_suicideBidButton || evt.getSource() == m_socialButton || evt.getSource() == m_ratedButton //|| // evt.getSource() == m_scoreButton || //evt.getSource() == m_timeButton || //evt.getSource() == m_handButton ) { handleFilterLogic(evt.getSource()); } if(evt.getSource() == m_hideEmptyCheckbox || evt.getSource() == m_hideFullCheckbox) { reapplyTableFilters(); } } void LobbyFilterManager::mouseMoveCB( agui::MouseEvent& evt ) { } void LobbyFilterManager::valueChanged( agui::Slider* source,int val ) { } void LobbyFilterManager::handleFilterLogic( agui::Widget* src ) { if(src != m_viewAllButton) { m_viewAllButton->setToggleState(false); } if(src == m_viewAllButton) { m_passTwoButton->setToggleState(true); m_regularButton->setToggleState(true); m_individualButton->setToggleState(true); m_cutThroatButton->setToggleState(true); //m_scoreButton->setToggleState(true); //m_timeButton->setToggleState(true); //m_handButton->setToggleState(true); m_ratedButton->setToggleState(true); m_socialButton->setToggleState(true); m_regularBidButton->setToggleState(true); m_mirrorBidButton->setToggleState(true); m_suicideBidButton->setToggleState(true); } if(!m_passTwoButton->isToggled() && !m_regularButton->isToggled() && !m_individualButton->isToggled() && !m_cutThroatButton->isToggled()) { if(src == m_passTwoButton) { m_passTwoButton->setToggleState(true); } else if(src == m_regularButton) { m_regularButton->setToggleState(true); } else if(src == m_individualButton) { m_individualButton->setToggleState(true); } else if(src == m_cutThroatButton) { m_cutThroatButton->setToggleState(true); } } if(src != m_viewAllButton && m_passTwoButton->isToggled() && m_regularButton->isToggled() && m_individualButton->isToggled() && m_cutThroatButton->isToggled() && /* m_scoreButton->isToggled() && m_timeButton->isToggled() && m_handButton->isToggled() && */ m_ratedButton->isToggled() && m_socialButton->isToggled() && m_regularBidButton->isToggled() && m_mirrorBidButton->isToggled() && m_suicideBidButton->isToggled()) { m_viewAllButton->setToggleState(true); } if(!m_regularBidButton->isToggled() && !m_mirrorBidButton->isToggled() && !m_suicideBidButton->isToggled()) { m_regularBidButton->setToggleState(true); } if(!m_socialButton->isToggled() && !m_ratedButton->isToggled()) { m_socialButton->setToggleState(true); } bool suicideState = (m_viewAllButton->isToggled() || m_regularButton->isToggled() || m_passTwoButton->isToggled()); m_suicideBidButton->setVisibility(suicideState); bool mirrorState = !(!m_viewAllButton->isToggled() && !m_regularButton->isToggled() && !m_individualButton->isToggled() && !m_cutThroatButton->isToggled() && m_passTwoButton->isToggled()); m_mirrorBidButton->setVisibility(mirrorState); /* if(!m_scoreButton->isToggled() && !m_timeButton->isToggled() && !m_handButton->isToggled()) { m_scoreButton->setToggleState(true); } */ reapplyTableFilters(); } void LobbyFilterManager::reapplyTableFilters() { std::vector<TableFilterEnum> filters; if(m_viewAllButton->isToggled()) filters.push_back(ALL_TABLES_TFILTER); if(m_passTwoButton->isToggled()) filters.push_back(PASS_TWO_TFILTER); if(m_regularButton->isToggled()) filters.push_back(REGULAR_TFILTER); if(m_individualButton->isToggled()) filters.push_back(INDIVIDUAL_TFILTER); if(m_cutThroatButton->isToggled()) filters.push_back(CUT_THROAT_TFILTER); if(m_hideEmptyCheckbox->checked()) filters.push_back(HIDE_EMPTY_TFILTER); if(m_hideFullCheckbox->checked()) filters.push_back(HIDE_FULL_TFILTER); if(m_regularBidButton->isToggled()) filters.push_back(NORMAL_BID_TFILTER); if(m_mirrorBidButton->isToggled()) filters.push_back(MIRROR_BID_TFILTER); if(m_suicideBidButton->isToggled()) filters.push_back(SUICIDE_BID_TFILTER); if(m_socialButton->isToggled()) filters.push_back(SOCIAL_TABLE_TFILTER); if(m_ratedButton->isToggled()) filters.push_back(RATED_TABLE_TFILTER); //if(m_scoreButton->isToggled()) // filters.push_back(SCORE_TFILTER); //if(m_timeButton->isToggled()) // filters.push_back(TIME_TFILTER); //if(m_handButton->isToggled()) // filters.push_back(HAND_TFILTER); DISPATCH_LOBBY_EVENT { (*it)->applyTableFilter(filters); } if(m_canModifyFilters) { DISPATCH_LOBBY_EVENT { (*it)->setTableFilters(filters); } } } int LobbyFilterManager::getHeight() const { return m_flow->getContentsHeight() + m_container->getMargin(agui::SIDE_TOP) + m_container->getMargin(agui::SIDE_BOTTOM); } void LobbyFilterManager::resize() { m_typeFlow->setSize(m_container->getInnerWidth(), m_typeFlow->getContentsHeight()); m_bidFlow->setSize(m_container->getInnerWidth(), m_bidFlow->getContentsHeight()); // m_endRuleFlow->setSize(m_container->getInnerWidth(), // m_endRuleFlow->getContentsHeight()); m_ratedFlow->setSize(m_container->getInnerWidth(), m_ratedFlow->getContentsHeight()); m_hideFlow->setSize(m_container->getInnerWidth(), m_hideFlow->getContentsHeight()); m_muteFlow->setSize(m_container->getInnerWidth(), m_muteFlow->getContentsHeight()); } void LobbyFilterManager::loadSettings( ClientShared* shared ) { loadTableFilters(shared->getSettingsManager()->getTableFilters()); m_muteLobbyCheckbox->setChecked(shared->getSettingsManager()->getBoolSetting("mute.lobby.chat.on")); } void LobbyFilterManager::loadTableFilters( const std::vector<TableFilterEnum> filters ) { m_viewAllButton->setToggleState(false); m_cutThroatButton->setToggleState(false); m_hideFullCheckbox->setChecked(false); m_hideEmptyCheckbox->setChecked(false); m_individualButton->setToggleState(false); m_mirrorBidButton->setToggleState(false); m_regularBidButton->setToggleState(true); m_passTwoButton->setToggleState(false); m_regularButton->setToggleState(false); m_suicideBidButton->setToggleState(false); m_ratedButton->setToggleState(false); m_socialButton->setToggleState(false); // m_scoreButton->setToggleState(false); // m_timeButton->setToggleState(false); // m_handButton->setToggleState(false); m_canModifyFilters = true; for(size_t i = 0; i < filters.size(); ++i) { if(i == filters.size() - 1) { dealWithFilter(filters[i],true); } else { dealWithFilter(filters[i],false); } } } void LobbyFilterManager::dealWithFilter( TableFilterEnum t, bool logic ) { switch(t) { case ALL_TABLES_TFILTER: m_viewAllButton->setToggleState(true); if(logic) handleFilterLogic(m_viewAllButton); break; case CUT_THROAT_TFILTER: m_cutThroatButton->setToggleState(true); if(logic) handleFilterLogic(m_cutThroatButton); break; case HIDE_FULL_TFILTER: m_hideFullCheckbox->setChecked(true); if(logic) handleFilterLogic(m_hideFullCheckbox); break; case HIDE_EMPTY_TFILTER: m_hideEmptyCheckbox->setChecked(true); if(logic) handleFilterLogic(m_hideEmptyCheckbox); break; case INDIVIDUAL_TFILTER: m_individualButton->setToggleState(true); if(logic) handleFilterLogic(m_individualButton); break; case MIRROR_BID_TFILTER: m_mirrorBidButton->setToggleState(true); if(logic) handleFilterLogic(m_mirrorBidButton); break; case NORMAL_BID_TFILTER: m_regularBidButton->setToggleState(true); if(logic) handleFilterLogic(m_regularBidButton); break; case PASS_TWO_TFILTER: m_passTwoButton->setToggleState(true); if(logic) handleFilterLogic(m_passTwoButton); break; case REGULAR_TFILTER: m_regularButton->setToggleState(true); if(logic) handleFilterLogic(m_regularButton); break; case SUICIDE_BID_TFILTER: m_suicideBidButton->setToggleState(true); if(logic) handleFilterLogic(m_suicideBidButton); break; case RATED_TABLE_TFILTER: m_ratedButton->setToggleState(true); if(logic) handleFilterLogic(m_ratedButton); break; case SOCIAL_TABLE_TFILTER: m_socialButton->setToggleState(true); if(logic) handleFilterLogic(m_socialButton); break; /* case SCORE_TFILTER: m_scoreButton->setToggleState(true); if(logic) handleFilterLogic(m_scoreButton); break; case TIME_TFILTER: m_timeButton->setToggleState(true); if(logic) handleFilterLogic(m_timeButton); break; case HAND_TFILTER: m_handButton->setToggleState(true); if(logic) handleFilterLogic(m_handButton); break; */ default: break; } } }
17,710
7,217
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "audio-stream.h" #include <lib/simple-codec/simple-codec-helper.h> #include <lib/zx/clock.h> #include <math.h> #include <string.h> #include <numeric> #include <optional> #include <utility> #include <ddk/debug.h> #include <ddk/metadata.h> #include <ddk/platform-defs.h> #include <fbl/auto_call.h> #include "src/media/audio/drivers/aml-g12-tdm/aml_tdm-bind.h" namespace audio { namespace aml_g12 { AmlG12TdmStream::AmlG12TdmStream(zx_device_t* parent, bool is_input, ddk::PDev pdev, const ddk::GpioProtocolClient enable_gpio) : SimpleAudioStream(parent, is_input), pdev_(std::move(pdev)), enable_gpio_(std::move(enable_gpio)) {} void AmlG12TdmStream::InitDaiFormats() { frame_rate_ = AmlTdmConfigDevice::kSupportedFrameRates[0]; for (size_t i = 0; i < metadata_.codecs.number_of_codecs; ++i) { // Only the PCM signed sample format is supported. dai_formats_[i].sample_format = SampleFormat::PCM_SIGNED; dai_formats_[i].frame_rate = frame_rate_; dai_formats_[i].bits_per_sample = metadata_.dai.bits_per_sample; dai_formats_[i].bits_per_slot = metadata_.dai.bits_per_slot; dai_formats_[i].number_of_channels = metadata_.dai.number_of_channels; dai_formats_[i].channels_to_use_bitmask = metadata_.codecs.channels_to_use_bitmask[i]; switch (metadata_.dai.type) { case metadata::DaiType::I2s: dai_formats_[i].frame_format = FrameFormat::I2S; break; case metadata::DaiType::StereoLeftJustified: dai_formats_[i].frame_format = FrameFormat::STEREO_LEFT; break; case metadata::DaiType::Tdm1: dai_formats_[i].frame_format = FrameFormat::TDM1; break; default: ZX_ASSERT(0); // Not supported. } } channels_to_use_ = std::numeric_limits<uint64_t>::max(); // Enable all. } zx_status_t AmlG12TdmStream::InitPDev() { size_t actual = 0; zx_status_t status = device_get_metadata(parent(), DEVICE_METADATA_PRIVATE, &metadata_, sizeof(metadata::AmlConfig), &actual); if (status != ZX_OK || sizeof(metadata::AmlConfig) != actual) { zxlogf(ERROR, "%s device_get_metadata failed %d", __FILE__, status); return status; } status = AmlTdmConfigDevice::Normalize(metadata_); if (status != ZX_OK) { return status; } InitDaiFormats(); if (!pdev_.is_valid()) { zxlogf(ERROR, "%s could not get pdev", __FILE__); return ZX_ERR_NO_RESOURCES; } status = pdev_.GetBti(0, &bti_); if (status != ZX_OK) { zxlogf(ERROR, "%s could not obtain bti - %d", __func__, status); return status; } ZX_ASSERT(metadata_.codecs.number_of_codecs <= 8); for (size_t i = 0; i < metadata_.codecs.number_of_codecs; ++i) { codecs_.push_back(SimpleCodecClient()); char fragment_name[32] = {}; snprintf(fragment_name, 32, "codec-%02lu", i + 1); status = codecs_[i].SetProtocol(ddk::CodecProtocolClient(parent(), fragment_name)); if (status != ZX_OK) { zxlogf(ERROR, "%s could set protocol - %s - %d", __func__, fragment_name, status); return status; } } std::optional<ddk::MmioBuffer> mmio; status = pdev_.MapMmio(0, &mmio); if (status != ZX_OK) { zxlogf(ERROR, "%s could not get mmio %d", __func__, status); return status; } aml_audio_ = std::make_unique<AmlTdmConfigDevice>(metadata_, *std::move(mmio)); if (aml_audio_ == nullptr) { zxlogf(ERROR, "%s failed to create TDM device with config", __func__); return ZX_ERR_NO_MEMORY; } // Initial setup of one page of buffer, just to be safe. status = InitBuffer(PAGE_SIZE); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to init buffer %d", __FILE__, status); return status; } status = aml_audio_->SetBuffer(pinned_ring_buffer_.region(0).phys_addr, pinned_ring_buffer_.region(0).size); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to set buffer %d", __FILE__, status); return status; } status = aml_audio_->InitHW(metadata_, channels_to_use_, frame_rate_); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to init tdm hardware %d\n", __FILE__, status); return status; } for (size_t i = 0; i < metadata_.codecs.number_of_codecs; ++i) { auto info = codecs_[i].GetInfo(); if (info.is_error()) { zxlogf(ERROR, "%s could get codec info %d", __func__, status); return info.error_value(); } // Reset and initialize codec after we have configured I2S. status = codecs_[i].Reset(); if (status != ZX_OK) { zxlogf(ERROR, "%s could not reset codec %d", __func__, status); return status; } auto supported_formats = codecs_[i].GetDaiFormats(); if (supported_formats.is_error()) { zxlogf(ERROR, "%s supported formats error %d", __func__, status); return supported_formats.error_value(); } if (!IsDaiFormatSupported(dai_formats_[i], supported_formats.value())) { zxlogf(ERROR, "%s codec does not support DAI format\n", __FILE__); return ZX_ERR_NOT_SUPPORTED; } status = codecs_[i].SetDaiFormat(dai_formats_[i]); if (status != ZX_OK) { zxlogf(ERROR, "%s could not set DAI format %d", __func__, status); return status; } codecs_[i].Start(); if (status != ZX_OK) { zxlogf(ERROR, "%s could not start codec %d", __func__, status); return status; } } zxlogf(INFO, "audio: %s initialized", metadata_.is_input ? "input" : "output"); return ZX_OK; } void AmlG12TdmStream::UpdateCodecsGainStateFromCurrent() { UpdateCodecsGainState({.gain = cur_gain_state_.cur_gain, .muted = cur_gain_state_.cur_mute, .agc_enabled = cur_gain_state_.cur_agc}); } void AmlG12TdmStream::UpdateCodecsGainState(GainState state) { for (size_t i = 0; i < metadata_.codecs.number_of_codecs; ++i) { auto state2 = state; state2.gain += metadata_.codecs.delta_gains[i]; if (override_mute_) { state2.muted = true; } codecs_[i].SetGainState(state2); } } zx_status_t AmlG12TdmStream::InitCodecsGain() { if (metadata_.codecs.number_of_codecs) { // Set our gain capabilities. float min_gain = std::numeric_limits<float>::lowest(); float max_gain = std::numeric_limits<float>::max(); float gain_step = std::numeric_limits<float>::lowest(); bool can_all_mute = true; bool can_all_agc = true; for (size_t i = 0; i < metadata_.codecs.number_of_codecs; ++i) { auto format = codecs_[i].GetGainFormat(); if (format.is_error()) { zxlogf(ERROR, "%s Could not get gain format %d", __FILE__, format.error_value()); return format.error_value(); } min_gain = std::max(min_gain, format->min_gain); max_gain = std::min(max_gain, format->max_gain); gain_step = std::max(gain_step, format->gain_step); can_all_mute = (can_all_mute && format->can_mute); can_all_agc = (can_all_agc && format->can_agc); } // Use first codec as reference initial gain. auto state = codecs_[0].GetGainState(); if (state.is_error()) { zxlogf(ERROR, "%s Could not get gain state %d", __FILE__, state.error_value()); return state.error_value(); } cur_gain_state_.cur_gain = state->gain; cur_gain_state_.cur_mute = false; cur_gain_state_.cur_agc = false; UpdateCodecsGainState(state.value()); cur_gain_state_.min_gain = min_gain; cur_gain_state_.max_gain = max_gain; cur_gain_state_.gain_step = gain_step; cur_gain_state_.can_mute = can_all_mute; cur_gain_state_.can_agc = can_all_agc; } else { cur_gain_state_.cur_gain = 0.f; cur_gain_state_.cur_mute = false; cur_gain_state_.cur_agc = false; cur_gain_state_.min_gain = 0.f; cur_gain_state_.max_gain = 0.f; cur_gain_state_.gain_step = .0f; cur_gain_state_.can_mute = false; cur_gain_state_.can_agc = false; } return ZX_OK; } zx_status_t AmlG12TdmStream::Init() { zx_status_t status; status = InitPDev(); if (status != ZX_OK) { return status; } status = AddFormats(); if (status != ZX_OK) { return status; } status = InitCodecsGain(); if (status != ZX_OK) { return status; } const char* in_out = "out"; if (metadata_.is_input) { in_out = "in"; } strncpy(mfr_name_, metadata_.manufacturer, sizeof(mfr_name_)); strncpy(prod_name_, metadata_.product_name, sizeof(prod_name_)); unique_id_ = metadata_.unique_id; const char* tdm_type = nullptr; switch (metadata_.dai.type) { case metadata::DaiType::I2s: tdm_type = "i2s"; break; case metadata::DaiType::StereoLeftJustified: tdm_type = "ljt"; break; case metadata::DaiType::Tdm1: tdm_type = "tdm1"; break; } snprintf(device_name_, sizeof(device_name_), "%s-audio-%s-%s", prod_name_, tdm_type, in_out); // TODO(mpuryear): change this to the domain of the clock received from the board driver clock_domain_ = 0; return ZX_OK; } // Timer handler for sending out position notifications void AmlG12TdmStream::ProcessRingNotification() { ScopedToken t(domain_token()); if (us_per_notification_) { notify_timer_.PostDelayed(dispatcher(), zx::usec(us_per_notification_)); } else { notify_timer_.Cancel(); return; } audio_proto::RingBufPositionNotify resp = {}; resp.hdr.cmd = AUDIO_RB_POSITION_NOTIFY; resp.monotonic_time = zx::clock::get_monotonic().get(); resp.ring_buffer_pos = aml_audio_->GetRingPosition(); NotifyPosition(resp); } zx_status_t AmlG12TdmStream::ChangeFormat(const audio_proto::StreamSetFmtReq& req) { fifo_depth_ = aml_audio_->fifo_depth(); for (size_t i = 0; i < metadata_.codecs.number_of_external_delays; ++i) { if (metadata_.codecs.external_delays[i].frequency == req.frames_per_second) { external_delay_nsec_ = metadata_.codecs.external_delays[i].nsecs; break; } } if (req.frames_per_second != frame_rate_ || req.channels_to_use_bitmask != channels_to_use_) { for (size_t i = 0; i < metadata_.codecs.number_of_codecs; ++i) { // Put codecs in safe state for rate change auto status = codecs_[i].Stop(); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to stop the codec", __FILE__); return status; } } frame_rate_ = req.frames_per_second; for (size_t i = 0; i < metadata_.codecs.number_of_codecs; ++i) { dai_formats_[i].frame_rate = frame_rate_; } channels_to_use_ = req.channels_to_use_bitmask; auto status = aml_audio_->InitHW(metadata_, channels_to_use_, frame_rate_); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to reinitialize the HW", __FILE__); return status; } for (size_t i = 0; i < metadata_.codecs.number_of_codecs; ++i) { status = codecs_[i].SetDaiFormat(dai_formats_[i]); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to set the DAI format", __FILE__); return status; } // Restart codec status = codecs_[i].Start(); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to restart the codec", __FILE__); return status; } } } return ZX_OK; } void AmlG12TdmStream::ShutdownHook() { for (size_t i = 0; i < metadata_.codecs.number_of_codecs; ++i) { // safe the codec so it won't throw clock errors when tdm bus shuts down codecs_[i].Stop(); } if (enable_gpio_.is_valid()) { enable_gpio_.Write(0); } aml_audio_->Shutdown(); pinned_ring_buffer_.Unpin(); } zx_status_t AmlG12TdmStream::SetGain(const audio_proto::SetGainReq& req) { // Modify parts of the gain state we have received in the request. if (req.flags & AUDIO_SGF_MUTE_VALID) { cur_gain_state_.cur_mute = req.flags & AUDIO_SGF_MUTE; } if (req.flags & AUDIO_SGF_AGC_VALID) { cur_gain_state_.cur_agc = req.flags & AUDIO_SGF_AGC; }; cur_gain_state_.cur_gain = req.gain; UpdateCodecsGainStateFromCurrent(); return ZX_OK; } zx_status_t AmlG12TdmStream::GetBuffer(const audio_proto::RingBufGetBufferReq& req, uint32_t* out_num_rb_frames, zx::vmo* out_buffer) { size_t ring_buffer_size = fbl::round_up<size_t, size_t>(req.min_ring_buffer_frames * frame_size_, std::lcm(frame_size_, aml_audio_->GetBufferAlignment())); size_t out_frames = ring_buffer_size / frame_size_; if (out_frames > std::numeric_limits<uint32_t>::max()) { return ZX_ERR_INVALID_ARGS; } size_t vmo_size = fbl::round_up<size_t, size_t>(ring_buffer_size, PAGE_SIZE); auto status = InitBuffer(vmo_size); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to init buffer %d", __FILE__, status); return status; } constexpr uint32_t rights = ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_MAP | ZX_RIGHT_TRANSFER; status = ring_buffer_vmo_.duplicate(rights, out_buffer); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to duplicate VMO %d", __FILE__, status); return status; } status = aml_audio_->SetBuffer(pinned_ring_buffer_.region(0).phys_addr, ring_buffer_size); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to set buffer %d", __FILE__, status); return status; } // This is safe because of the overflow check we made above. *out_num_rb_frames = static_cast<uint32_t>(out_frames); return ZX_OK; } zx_status_t AmlG12TdmStream::Start(uint64_t* out_start_time) { *out_start_time = aml_audio_->Start(); uint32_t notifs = LoadNotificationsPerRing(); if (notifs) { us_per_notification_ = static_cast<uint32_t>(1000 * pinned_ring_buffer_.region(0).size / (frame_size_ * frame_rate_ / 1000 * notifs)); notify_timer_.PostDelayed(dispatcher(), zx::usec(us_per_notification_)); } else { us_per_notification_ = 0; } override_mute_ = false; UpdateCodecsGainStateFromCurrent(); return ZX_OK; } zx_status_t AmlG12TdmStream::Stop() { override_mute_ = true; UpdateCodecsGainStateFromCurrent(); notify_timer_.Cancel(); us_per_notification_ = 0; aml_audio_->Stop(); return ZX_OK; } zx_status_t AmlG12TdmStream::AddFormats() { fbl::AllocChecker ac; supported_formats_.reserve(1, &ac); if (!ac.check()) { zxlogf(ERROR, "Out of memory, can not create supported formats list"); return ZX_ERR_NO_MEMORY; } // Add the range for basic audio support. audio_stream_format_range_t range; range.min_channels = metadata_.ring_buffer.number_of_channels; range.max_channels = metadata_.ring_buffer.number_of_channels; ZX_ASSERT(metadata_.ring_buffer.bytes_per_sample == 2); range.sample_formats = AUDIO_SAMPLE_FORMAT_16BIT; ZX_ASSERT(sizeof(AmlTdmConfigDevice::kSupportedFrameRates) / sizeof(uint32_t) == 2); ZX_ASSERT(AmlTdmConfigDevice::kSupportedFrameRates[0] == 48'000); ZX_ASSERT(AmlTdmConfigDevice::kSupportedFrameRates[1] == 96'000); range.min_frames_per_second = AmlTdmConfigDevice::kSupportedFrameRates[0]; range.max_frames_per_second = AmlTdmConfigDevice::kSupportedFrameRates[1]; range.flags = ASF_RANGE_FLAG_FPS_48000_FAMILY; supported_formats_.push_back(range); return ZX_OK; } zx_status_t AmlG12TdmStream::InitBuffer(size_t size) { // Make sure the DMA is stopped before releasing quarantine. aml_audio_->Stop(); // Make sure that all reads/writes have gone through. #if defined(__aarch64__) asm __volatile__("dsb sy"); #endif auto status = bti_.release_quarantine(); if (status != ZX_OK) { zxlogf(ERROR, "%s could not release quarantine bti - %d", __func__, status); return status; } pinned_ring_buffer_.Unpin(); status = zx_vmo_create_contiguous(bti_.get(), size, 0, ring_buffer_vmo_.reset_and_get_address()); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to allocate ring buffer vmo - %d", __func__, status); return status; } status = pinned_ring_buffer_.Pin(ring_buffer_vmo_, bti_, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE); if (status != ZX_OK) { zxlogf(ERROR, "%s failed to pin ring buffer vmo - %d", __func__, status); return status; } if (pinned_ring_buffer_.region_count() != 1) { if (!AllowNonContiguousRingBuffer()) { zxlogf(ERROR, "%s buffer is not contiguous", __func__); return ZX_ERR_NO_MEMORY; } } return ZX_OK; } static zx_status_t audio_bind(void* ctx, zx_device_t* device) { size_t actual = 0; metadata::AmlConfig metadata = {}; auto status = device_get_metadata(device, DEVICE_METADATA_PRIVATE, &metadata, sizeof(metadata::AmlConfig), &actual); if (status != ZX_OK || sizeof(metadata::AmlConfig) != actual) { zxlogf(ERROR, "%s device_get_metadata failed %d", __FILE__, status); return status; } if (metadata.is_input) { auto stream = audio::SimpleAudioStream::Create<audio::aml_g12::AmlG12TdmStream>( device, true, ddk::PDev::FromFragment(device), ddk::GpioProtocolClient(device, "gpio-enable")); if (stream == nullptr) { zxlogf(ERROR, "%s Could not create aml-g12-tdm driver", __FILE__); return ZX_ERR_NO_MEMORY; } __UNUSED auto dummy = fbl::ExportToRawPtr(&stream); } else { auto stream = audio::SimpleAudioStream::Create<audio::aml_g12::AmlG12TdmStream>( device, false, ddk::PDev::FromFragment(device), ddk::GpioProtocolClient(device, "gpio-enable")); if (stream == nullptr) { zxlogf(ERROR, "%s Could not create aml-g12-tdm driver", __FILE__); return ZX_ERR_NO_MEMORY; } __UNUSED auto dummy = fbl::ExportToRawPtr(&stream); } return ZX_OK; } static constexpr zx_driver_ops_t driver_ops = []() { zx_driver_ops_t ops = {}; ops.version = DRIVER_OPS_VERSION; ops.bind = audio_bind; return ops; }(); } // namespace aml_g12 } // namespace audio // clang-format off ZIRCON_DRIVER(aml_tdm, audio::aml_g12::driver_ops, "aml-tdm", "0.1");
18,052
6,935
#include "socket.h" #include "common/log.hpp" #include "common/string.hpp" #include "common/hash.hpp" #include "worker.h" #include "network/moon_connection.hpp" #include "network/custom_connection.hpp" #include "network/ws_connection.hpp" using namespace moon; socket::socket(router * r, worker* w, asio::io_context & ioctx) : router_(r) , worker_(w) , ioc_(ioctx) , timer_(ioctx) { response_ = message::create(); timeout(); } uint32_t socket::listen(const std::string & ip, uint16_t port, uint32_t owner, uint8_t type) { try { auto ctx = std::make_shared<socket::acceptor_context>(type, owner, ioc_); asio::ip::tcp::resolver resolver(ioc_); asio::ip::tcp::resolver::query query(ip, std::to_string(port)); auto iter = resolver.resolve(query); asio::ip::tcp::endpoint endpoint = *iter; ctx->acceptor.open(endpoint.protocol()); #if TARGET_PLATFORM != PLATFORM_WINDOWS ctx->acceptor.set_option(asio::ip::tcp::acceptor::reuse_address(true)); #endif ctx->acceptor.bind(endpoint); ctx->acceptor.listen(std::numeric_limits<int>::max()); auto id = uuid(); ctx->fd = id; acceptors_.emplace(id, ctx); return id; } catch (asio::system_error& e) { CONSOLE_ERROR(router_->logger(), "%s:%d %s(%d)", ip.data(), port, e.what(), e.code().value()); return 0; } } void socket::accept(int fd, int32_t sessionid, uint32_t owner) { MOON_CHECK(owner > 0, "socket::accept : invalid serviceid"); auto iter = acceptors_.find(fd); if (iter == acceptors_.end()) { return; } auto& ctx = iter->second; if (!ctx->acceptor.is_open()) { return; } worker* w = router_->get_worker(router_->worker_id(owner)); auto c = w->socket().make_connection(owner, ctx->type); ctx->acceptor.async_accept(c->socket(), [this, ctx, c, w, sessionid, owner](const asio::error_code& e) { if (!e) { c->fd(w->socket().uuid()); w->socket().add_connection(c, true); if (sessionid == 0) { accept(ctx->fd, sessionid, owner); } else { response(ctx->fd, ctx->owner, std::to_string(c->fd()), std::string_view{}, sessionid, PTYPE_TEXT); } } else { if (sessionid != 0) { response(ctx->fd, ctx->owner, moon::format("socket::accept error %s(%d)", e.message().data(), e.value()), "error"sv, sessionid, PTYPE_ERROR); } else { if (e != asio::error::operation_aborted) { CONSOLE_WARN(router_->logger(), "socket::accept error %s(%d)", e.message().data(), e.value()); } close(ctx->fd); } } }); } int socket::connect(const std::string& host, uint16_t port, uint32_t serviceid, uint32_t owner, uint8_t type, int32_t sessionid, int32_t timeout) { try { asio::ip::tcp::resolver resolver(ioc_); asio::ip::tcp::resolver::query query(host, std::to_string(port)); asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); worker* w = router_->get_worker(router_->worker_id(owner)); auto c = w->socket().make_connection(owner, type); if (0 == sessionid) { asio::connect(c->socket(), endpoint_iterator); c->fd(w->socket().uuid()); w->socket().add_connection(c, false); return c->fd(); } else { if (timeout > 0) { std::shared_ptr<asio::steady_timer> connect_timer = std::make_shared<asio::steady_timer>(ioc_); connect_timer->expires_from_now(std::chrono::milliseconds(timeout)); connect_timer->async_wait([this, c, serviceid, sessionid, host, port, connect_timer](const asio::error_code & e) { if (e) { CONSOLE_ERROR(router_->logger(), "connect %s:%d timer error %s", host.data(), port, e.message().data()); return; } if (c->fd() == 0) { c->close(); response(0, serviceid, std::string_view{}, moon::format("connect %s:%d timeout", host.data(), port), sessionid, PTYPE_ERROR); } }); } asio::async_connect(c->socket(), endpoint_iterator, [this, c, w, host, port, serviceid, sessionid](const asio::error_code& e, asio::ip::tcp::resolver::iterator) { if (!e) { c->fd(w->socket().uuid()); w->socket().add_connection(c, false); response(0, serviceid, std::to_string(c->fd()), std::string_view{}, sessionid, PTYPE_TEXT); } else { if (c->socket().is_open()) { response(0, serviceid, std::string_view{}, moon::format("connect %s:%d failed: %s(%d)", host.data(), port, e.message().data(), e.value()), sessionid, PTYPE_ERROR); } } }); } } catch (asio::system_error& e) { if (sessionid == 0) { CONSOLE_WARN(router_->logger(), "connect %s:%d failed: %s(%d)", host.data(), port, e.code().message().data(), e.code().value()); } else { asio::post(ioc_, [this, host, port, serviceid, sessionid, e]() { response(0,serviceid, std::string_view{} , moon::format("connect %s:%d failed: %s(%d)", host.data(), port, e.code().message().data(), e.code().value()) , sessionid, PTYPE_ERROR); }); } } return 0; } void socket::read(uint32_t fd, uint32_t owner, size_t n, read_delim delim, int32_t sessionid) { do { if (auto iter = connections_.find(fd); iter != connections_.end()) { if (iter->second->read(moon::read_request{ delim, n, sessionid })) { return; } } } while (0); ioc_.post([this, owner, sessionid]() { response(0, owner, "read an invalid socket", "closed", sessionid, PTYPE_ERROR); }); } bool socket::write(uint32_t fd, const buffer_ptr_t & data) { auto iter = connections_.find(fd); if (iter == connections_.end()) { return false; } return iter->second->send(data); } bool socket::write_with_flag(uint32_t fd, const buffer_ptr_t & data, int flag) { auto iter = connections_.find(fd); if (iter == connections_.end()) { return false; } MOON_ASSERT(flag > 0 && flag < static_cast<int>(buffer_flag::buffer_flag_max), "socket::write_with_flag flag invalid") data->set_flag(static_cast<buffer_flag>(flag)); return iter->second->send(data); } bool socket::write_message(uint32_t fd, message * m) { return write(fd, *m); } bool socket::close(uint32_t fd,bool remove) { if (auto iter = connections_.find(fd); iter != connections_.end()) { iter->second->close(); if (remove) { connections_.erase(iter); unlock_fd(fd); } return true; } if (auto iter = acceptors_.find(fd); iter != acceptors_.end()) { if (iter->second->acceptor.is_open()) { iter->second->acceptor.cancel(); iter->second->acceptor.close(); } if (remove) { acceptors_.erase(iter); unlock_fd(fd); } return true; } return false; } bool socket::settimeout(uint32_t fd, int v) { if (auto iter = connections_.find(fd); iter != connections_.end()) { iter->second->settimeout(v); return true; } return false; } bool socket::setnodelay(uint32_t fd) { if (auto iter = connections_.find(fd); iter != connections_.end()) { iter->second->set_no_delay(); return true; } return false; } bool socket::set_enable_frame(uint32_t fd, std::string flag) { moon::lower(flag); moon::frame_enable_flag v = frame_enable_flag::none; switch (moon::chash_string(flag)) { case "none"_csh: { v = moon::frame_enable_flag::none; break; } case "r"_csh: { v = moon::frame_enable_flag::receive; break; } case "w"_csh: { v = moon::frame_enable_flag::send; break; } case "wr"_csh: case "rw"_csh: { v = moon::frame_enable_flag::both; break; } default: CONSOLE_WARN(router_->logger(), "tcp::set_enable_frame Unsupported enable frame flag %s.Support: 'r' 'w' 'wr' 'rw'.", flag.data()); return false; } if (auto iter = connections_.find(fd); iter != connections_.end()) { auto c = std::dynamic_pointer_cast<moon_connection>(iter->second); if (c) { c->set_frame_flag(v); return true; } } return false; } uint32_t socket::uuid() { uint32_t res = 0; do { res = uuid_.fetch_add(1); res %= max_socket_num; ++res; res |= (worker_->id() << 16); } while (!try_lock_fd(res)); return res; } connection_ptr_t socket::make_connection(uint32_t serviceid, uint8_t type) { connection_ptr_t connection; switch (type) { case PTYPE_SOCKET: { connection = std::make_shared<moon_connection>(serviceid, type, this, ioc_); break; } case PTYPE_TEXT: { connection = std::make_shared<custom_connection>(serviceid, type, this, ioc_); break; } case PTYPE_SOCKET_WS: { connection = std::make_shared<ws_connection>(serviceid, type, this, ioc_); break; } default: break; } connection->logger(router_->logger()); return connection; } void socket::response(uint32_t sender, uint32_t receiver, string_view_t data, string_view_t header, int32_t sessionid, uint8_t type) { if (0 == sessionid) return; response_->set_sender(sender); response_->set_receiver(0); response_->get_buffer()->clear(); response_->get_buffer()->write_back(data.data(), 0, data.size()); response_->set_header(header); response_->set_sessionid(sessionid); response_->set_type(type); handle_message(receiver, response_); } bool socket::try_lock_fd(uint32_t fd) { std::unique_lock lck(lock_); return fd_watcher_.emplace(fd).second; } void socket::unlock_fd(uint32_t fd) { std::unique_lock lck(lock_); size_t count = fd_watcher_.erase(fd); MOON_CHECK(count == 1, "socket fd erase failed!"); } void socket::add_connection(const connection_ptr_t & c, bool accepted) { asio::dispatch(ioc_, [c, accepted, this]() mutable { connections_.emplace(c->fd(), c); c->start(accepted); }); } service * socket::find_service(uint32_t serviceid) { return worker_->find_service(serviceid);; } void socket::timeout() { timer_.expires_from_now(std::chrono::seconds(10)); timer_.async_wait([this](const asio::error_code & e) { if (e) { return; } auto now = base_connection::now(); for (auto& connection : connections_) { connection.second->timeout(now); } timeout(); }); }
11,688
3,822
#pragma once #include "device_properties.hpp" #include <pqrs/json.hpp> namespace krbn { namespace connected_devices { namespace details { class descriptions { public: descriptions(void) : descriptions("", "") { } descriptions(const std::string& manufacturer, const std::string& product) : manufacturer_(manufacturer), product_(product) { } descriptions(const device_properties& device_properties) : descriptions(device_properties.get_manufacturer().value_or(""), device_properties.get_product().value_or("")) { } static descriptions make_from_json(const nlohmann::json& json) { return descriptions(pqrs::json::find<std::string>(json, "manufacturer").value_or(""), pqrs::json::find<std::string>(json, "product").value_or("")); } nlohmann::json to_json(void) const { return nlohmann::json({ {"manufacturer", manufacturer_}, {"product", product_}, }); } const std::string& get_manufacturer(void) const { return manufacturer_; } const std::string& get_product(void) const { return product_; } bool operator==(const descriptions& other) const { return manufacturer_ == other.manufacturer_ && product_ == other.product_; } bool operator!=(const descriptions& other) const { return !(*this == other); } private: std::string manufacturer_; std::string product_; }; inline void to_json(nlohmann::json& json, const descriptions& descriptions) { json = descriptions.to_json(); } } // namespace details } // namespace connected_devices } // namespace krbn
1,710
501
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/DynArray.hpp> namespace RED4ext { namespace anim { struct AnimNode_BlendSpace_InternalsBlendSpacePoint { static constexpr const char* NAME = "animAnimNode_BlendSpace_InternalsBlendSpacePoint"; static constexpr const char* ALIAS = NAME; CName animationName; // 00 bool useFixedCoordinates; // 08 uint8_t unk09[0x10 - 0x9]; // 9 DynArray<float> fixedCoordinates; // 10 bool useStaticPose; // 20 uint8_t unk21[0x24 - 0x21]; // 21 float staticPoseTime; // 24 float staticPoseProgress; // 28 uint8_t unk2C[0x30 - 0x2C]; // 2C }; RED4EXT_ASSERT_SIZE(AnimNode_BlendSpace_InternalsBlendSpacePoint, 0x30); } // namespace anim } // namespace RED4ext
887
349
#include <math.h> #include <stdio.h> #include <cstring> #include <iostream> using namespace std; #define N 66000 unsigned int prime[N / 64]; #define gP(n) (prime[n>>6]&(1<<((n>>1)&31))) void sieve() { memset(prime, -1, sizeof(prime)); unsigned int i, i2, sqrtN = (unsigned int)sqrt((double)N) + 1; for(i = 3; i<sqrtN; i+=2) if(gP(i)) { i2 = i + i; for(unsigned int j = i*i; j<N; j+= i2) prime[j>>6] &= ~(1<<((j>>1)&31)); } } bool isPrime(int n) { return n==2 || ((n&1) && gP(n)); } int powmod(int b, int p, int m) { if (!p) return 1; if (p==1) return b%m; long long int h = powmod(b, p>>1, m); return ((p&1) ? h*((b*h)%m) : h*h)%m; } bool fermat(int n, int a) { return powmod(a, n, n) == a; } bool isC[65001]; bool isCarmichael(int n) { if (isPrime(n)) return false; for(int i=2; i<n; i++) if (!fermat(n, i)) return false; return true; } int main(){ sieve(); /* int cnt=0; for (int i=0; cnt<120 && i<65000; i++) if (isCarmichael(i)) printf("#%d: %d\n", ++cnt, i); */ int n; while(cin>>n && n) printf(isCarmichael(n) ? "The number %d is a Carmichael number.\n" : "%d is normal.\n", n); } // high probablity: sum of digits is zero /* #include <stdio.h> #include <iostream> using namespace std; bool isC[65001]; int main(){ int n; isC[561]=isC[1105]=isC[1729]=isC[2465]=isC[2821]=isC[6601]= isC[8911]=isC[10585]=isC[15841]=isC[29341]=isC[41041]= isC[46657]=isC[52633]=isC[62745]=isC[63973]=true; while(cin>>n && n) printf(isC[n] ? "The number %d is a Carmichael number.\n" : "%d is normal.\n", n); } */
1,719
813
#include <bits/stdc++.h> #define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0) using namespace std; int n, board = 1, board[1001], board, t; int main() { fastio; cin >> n; for (int i = 0; i <= n; ++i) { if (i < n) { cin >> board; board[++t] = board; } while (t && board[t] == board) { --t; ++board; } } cout << (t ? "Sad" : "Nice"); return 0; }
460
184
#include "BucketSort.hh" void BucketSort(Element Tablica[], long int pierwszy_element, long int ostatni_element) { Kubel Wiadro[11]; // stwรณrz tablice kubล‚รณw long int k = 0; // zmienna pomocnicza do obsล‚ugi tablicy for(long int i = pierwszy_element; i <= ostatni_element; i++) // Powtarzaj dla caล‚ej tablicy Wiadro[Tablica[i].getOcena()].addLast(Tablica[i]); // Wrzuฤ‡ elementy do odpowiedniego kubล‚a for(int j = 0; j <= 10; j++) // powtarzaj dla kaลผdego kubล‚a while(!Wiadro[j].isEmpty()) // Az kubeล‚ nie bฤ™dzie pusty Tablica[k++] = Wiadro[j].takeFront(); // Wrzucaj z kubล‚a do tablicy }
618
257
#include "ResourceAnimator.h" #include "imgui/imgui.h" #include "ModuleScene.h" #include "ModuleFileSystem.h" #include "Application.h" #include "Optick/include/optick.h" #include "ModuleTimeManager.h" #include "Application.h" #include "ResourceAvatar.h" #include "ModuleResourceManager.h" #include <assert.h> ResourceAnimator::ResourceAnimator(ResourceTypes type, uint uuid, ResourceData data, ResourceAnimatorData animator_data) : Resource(type, uuid, data), animator_data(animator_data) {} ResourceAnimator::~ResourceAnimator() { } bool ResourceAnimator::LoadInMemory() { return true; } bool ResourceAnimator::UnloadFromMemory() { return true; } void ResourceAnimator::OnPanelAssets() { #ifndef GAMEMODE ImGuiTreeNodeFlags flags = 0; flags |= ImGuiTreeNodeFlags_::ImGuiTreeNodeFlags_Leaf; if (App->scene->selectedObject == this) flags |= ImGuiTreeNodeFlags_::ImGuiTreeNodeFlags_Selected; char id[DEFAULT_BUF_SIZE]; sprintf(id, "%s##%d", data.name.data(), uuid); if (ImGui::TreeNodeEx(id, flags)) ImGui::TreePop(); if (ImGui::IsMouseReleased(0) && ImGui::IsItemHovered() /*&& (mouseDelta.x == 0 && mouseDelta.y == 0)*/) { SELECT(this); } if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { ImGui::SetDragDropPayload("ANIMATOR_INSPECTOR_SELECTOR", &uuid, sizeof(uint)); ImGui::EndDragDropSource(); } #endif // !GAMEMODE } bool ResourceAnimator::ImportFile(const char* file, std::string& name, std::string& outputFile) { assert(file != nullptr); // Search for the meta associated to the file char metaFile[DEFAULT_BUF_SIZE]; strcpy_s(metaFile, strlen(file) + 1, file); // file strcat_s(metaFile, strlen(metaFile) + strlen(EXTENSION_META) + 1, EXTENSION_META); // extension if (App->fs->Exists(metaFile)) { // Read the meta uint uuid = 0; int64_t lastModTime = 0; bool result = ResourceAnimator::ReadMeta(metaFile, lastModTime, uuid, name); assert(result); // The uuid of the resource would be the entry char entry[DEFAULT_BUF_SIZE]; sprintf_s(entry, "%u", uuid); outputFile = entry; } return true; } bool ResourceAnimator::ExportFile(ResourceData& resourceData, ResourceAnimatorData& animData, std::string& outputFile, bool overwrite) { bool ret = false; uint nameSize = DEFAULT_BUF_SIZE; // Name char animator_name[DEFAULT_BUF_SIZE]; strcpy_s(animator_name, DEFAULT_BUF_SIZE, animData.name.data()); uint animations_size = animData.animations_uuids.size(); uint meshes_size = animData.meshes_uuids.size(); uint size = sizeof(uint) + sizeof(uint) + sizeof(uint) * animations_size + sizeof(uint) + sizeof(uint) * meshes_size + sizeof(uint) + // name size sizeof(char) * nameSize; // name char* buffer = new char[size]; char* cursor = buffer; // 1. Store avatar uuid uint bytes = sizeof(uint); memcpy(cursor, &animData.avatar_uuid, bytes); cursor += bytes; // 2. Store animations size bytes = sizeof(uint); memcpy(cursor, &animations_size, bytes); cursor += bytes; // 3. Store animations for (uint i = 0; i < animations_size; ++i) { bytes = sizeof(uint); memcpy(cursor, &animData.animations_uuids[i], bytes); cursor += bytes; } // 4. Store meshes size bytes = sizeof(uint); memcpy(cursor, &meshes_size, bytes); cursor += bytes; // 5. Store Meshes for (uint i = 0; i < meshes_size; ++i) { bytes = sizeof(uint); memcpy(cursor, &animData.meshes_uuids[i], bytes); cursor += bytes; } // 2. Store name size bytes = sizeof(uint); memcpy(cursor, &nameSize, bytes); cursor += bytes; // 3. Store name bytes = sizeof(char) * nameSize; memcpy(cursor, &animator_name, bytes); //cursor += bytes; // -------------------------------------------------- // Build the path of the file if (overwrite) outputFile = resourceData.file; else outputFile = resourceData.name; // Save the file ret = App->fs->SaveInGame(buffer, size, FileTypes::AnimatorFile, outputFile, overwrite) > 0; if (ret) { CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully saved Animator '%s'", outputFile.data()); } else CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not save Animator '%s'", outputFile.data()); RELEASE_ARRAY(buffer); return ret; } uint ResourceAnimator::CreateMeta(const char* file, uint animatorUuid, std::string& name, std::string& outputMetaFile) { assert(file != nullptr); uint uuidsSize = 1; uint nameSize = DEFAULT_BUF_SIZE; // Name char animator_name[DEFAULT_BUF_SIZE]; strcpy_s(animator_name, DEFAULT_BUF_SIZE, name.data()); // -------------------------------------------------- uint size = sizeof(int64_t) + sizeof(uint) + sizeof(uint) * uuidsSize + sizeof(uint) + // name size sizeof(char) * nameSize; char* data = new char[size]; char* cursor = data; // 1. Store last modification time int64_t lastModTime = App->fs->GetLastModificationTime(file); assert(lastModTime > 0); uint bytes = sizeof(int64_t); memcpy(cursor, &lastModTime, bytes); cursor += bytes; // 2. Store uuids size bytes = sizeof(uint); memcpy(cursor, &uuidsSize, bytes); cursor += bytes; // 3. Store animator uuid bytes = sizeof(uint) * uuidsSize; memcpy(cursor, &animatorUuid, bytes); cursor += bytes; // 4. Store animator name size bytes = sizeof(uint); memcpy(cursor, &nameSize, bytes); cursor += bytes; // 5. Store animator name bytes = sizeof(char) * nameSize; memcpy(cursor, animator_name, bytes); cursor += bytes; // -------------------------------------------------- // Build the path of the meta file and save it outputMetaFile = file; outputMetaFile.append(EXTENSION_META); uint resultSize = App->fs->Save(outputMetaFile.data(), data, size); if (resultSize > 0) { CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully saved meta '%s'", outputMetaFile.data()); } else { CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not save meta '%s'", outputMetaFile.data()); return 0; } return lastModTime; } bool ResourceAnimator::ReadMeta(const char* metaFile, int64_t& lastModTime, uint& animatorUuid, std::string& name) { assert(metaFile != nullptr); char* buffer; uint size = App->fs->Load(metaFile, &buffer); if (size > 0) { char* cursor = (char*)buffer; // 1. Load last modification time uint bytes = sizeof(int64_t); memcpy(&lastModTime, cursor, bytes); cursor += bytes; // 2. Load uuids size uint uuidsSize = 0; bytes = sizeof(uint); memcpy(&uuidsSize, cursor, bytes); assert(uuidsSize > 0); cursor += bytes; // 3. Load animation uuid bytes = sizeof(uint) * uuidsSize; memcpy(&animatorUuid, cursor, bytes); cursor += bytes; // 4. Load animation name size uint nameSize = 0; bytes = sizeof(uint); memcpy(&nameSize, cursor, bytes); assert(nameSize > 0); cursor += bytes; // 5. Load animation name name.resize(nameSize); bytes = sizeof(char) * nameSize; memcpy(&name[0], cursor, bytes); CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully loaded meta '%s'", metaFile); RELEASE_ARRAY(buffer); } else { CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not load meta '%s'", metaFile); return false; } return true; } bool ResourceAnimator::LoadFile(const char* file, ResourceAnimatorData& outputAnimationData) { assert(file != nullptr); bool ret = false; char* buffer; uint size = App->fs->Load(file, &buffer); if (size > 0) { char* cursor = (char*)buffer; // 1. Load avatar uuid uint bytes = sizeof(uint); memcpy(&outputAnimationData.avatar_uuid, cursor, bytes); cursor += bytes; // 2. Load animations size uint animations_size = 0u; bytes = sizeof(uint); memcpy(&animations_size, cursor, bytes); cursor += bytes; // 3. Load animations outputAnimationData.animations_uuids.reserve(animations_size); for (uint i = 0; i < animations_size; ++i) { bytes = sizeof(uint); uint anim_uuid = 0u; memcpy(&anim_uuid, cursor, bytes); outputAnimationData.animations_uuids.push_back(anim_uuid); cursor += bytes; } outputAnimationData.animations_uuids.shrink_to_fit(); // 2. Load meshes size uint meshes_size = 0u; bytes = sizeof(uint); memcpy(&meshes_size, cursor, bytes); cursor += bytes; // 3. Load meshes outputAnimationData.meshes_uuids.reserve(meshes_size); for (uint i = 0; i < meshes_size; ++i) { bytes = sizeof(uint); uint mesh_uuid = 0u; memcpy(&mesh_uuid, cursor, bytes); outputAnimationData.meshes_uuids.push_back(mesh_uuid); cursor += bytes; } outputAnimationData.meshes_uuids.shrink_to_fit(); // 2. Load name size bytes = sizeof(uint); uint nameSize = 0; memcpy(&nameSize, cursor, bytes); assert(nameSize > 0); cursor += bytes; // 3. Load name if (nameSize > 0) { bytes = sizeof(char) * nameSize; outputAnimationData.name.resize(nameSize); memcpy(&outputAnimationData.name[0], cursor, bytes); } CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully loaded Animator '%s'", file); RELEASE_ARRAY(buffer); } else CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not load Animator '%s'", file); return ret; } bool ResourceAnimator::GenerateLibraryFiles() const { assert(data.file.data() != nullptr); // Search for the meta associated to the file char metaFile[DEFAULT_BUF_SIZE]; strcpy_s(metaFile, strlen(data.file.data()) + 1, data.file.data()); // file strcat_s(metaFile, strlen(metaFile) + strlen(EXTENSION_META) + 1, EXTENSION_META); // extension // 1. Copy meta if (App->fs->Exists(metaFile)) { std::string outputFile; uint size = App->fs->Copy(metaFile, DIR_LIBRARY_ANIMATORS, outputFile); if (size > 0) { // 2. Copy Animator outputFile.clear(); uint size = App->fs->Copy(data.file.data(), DIR_LIBRARY_ANIMATORS, outputFile); if (size > 0) return true; } } return false; } uint ResourceAnimator::SetNameToMeta(const char* metaFile, const std::string& name) { assert(metaFile != nullptr); int64_t lastModTime = 0; uint materialUuid = 0; std::string oldName; ReadMeta(metaFile, lastModTime, materialUuid, oldName); uint uuidsSize = 1; uint nameSize = DEFAULT_BUF_SIZE; // Name char materialName[DEFAULT_BUF_SIZE]; strcpy_s(materialName, DEFAULT_BUF_SIZE, name.data()); uint size = sizeof(int64_t) + sizeof(uint) + sizeof(uint) * uuidsSize + sizeof(uint) + // name size sizeof(char) * nameSize; // name char* data = new char[size]; char* cursor = data; // 1. Store last modification time uint bytes = sizeof(int64_t); memcpy(cursor, &lastModTime, bytes); cursor += bytes; // 2. Store uuids size bytes = sizeof(uint); memcpy(cursor, &uuidsSize, bytes); cursor += bytes; // 3. Store animator uuid bytes = sizeof(uint) * uuidsSize; memcpy(cursor, &materialUuid, bytes); cursor += bytes; // 4. Store animator name size bytes = sizeof(uint); memcpy(cursor, &nameSize, bytes); cursor += bytes; // 5. Store animator name bytes = sizeof(char) * nameSize; memcpy(cursor, materialName, bytes); cursor += bytes; // -------------------------------------------------- // Build the path of the meta file and save it uint retSize = App->fs->Save(metaFile, data, size); if (retSize > 0) { CONSOLE_LOG(LogTypes::Normal, "Resource Animator: Successfully saved meta '%s'", metaFile); } else { CONSOLE_LOG(LogTypes::Error, "Resource Animator: Could not save meta '%s'", metaFile); return 0; } return lastModTime; } void ResourceAnimator::InitAnimator() { if (current_anim) { current_anim->interpolate = true; current_anim->loop = true; } anim_state = AnimationState::PLAYING; } bool ResourceAnimator::Update() { #ifndef GAMEMODE OPTICK_CATEGORY("ResourceAnimator_Update", Optick::Category::Animation); #endif // GAMEMODE //if (App->GetEngineState() != engine_states::ENGINE_PLAY) //return update_status::UPDATE_CONTINUE; if (stop_all) return update_status::UPDATE_CONTINUE; if (current_anim == nullptr) return update_status::UPDATE_CONTINUE; float dt = App->timeManager->GetDt(); float predicted_time = dt + current_anim->anim_timer; if (predicted_time >= current_anim->duration && current_anim->duration > 0.0f) { current_anim->finished = true; if (!current_anim->loop) anim_state = AnimationState::STOPPED; else current_anim->anim_timer = 0.0f; } else { current_anim->finished = false; } switch (anim_state) { case AnimationState::PLAYING: { current_anim->anim_timer += dt * current_anim->anim_speed * animation_speed_mod; ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid); if (tmp_avatar) { tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer); } } break; case AnimationState::PAUSED: break; case AnimationState::STOPPED: { ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid); if (tmp_avatar) { tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer); } current_anim->anim_timer = 0.0f; PauseAnimation(); } break; case AnimationState::BLENDING: { last_anim->anim_timer += dt * last_anim->anim_speed * animation_speed_mod; current_anim->anim_timer += dt * current_anim->anim_speed * animation_speed_mod; blend_timer += dt; float blend_percentage = blend_timer / 1.0f; ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid); if (tmp_avatar) { tmp_avatar->StepBones(last_anim->animation_uuid, last_anim->anim_timer, blend_percentage); tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer, blend_percentage); } if (blend_percentage >= blend_timelapse) anim_state = PLAYING; } break; } return true; } void ResourceAnimator::SetAnimationSpeed(float new_speed) { animation_speed_mod = new_speed; } void ResourceAnimator::SetAnimationBlendTime(float new_blend) { blend_timelapse = new_blend; } void ResourceAnimator::ClearAnimations() { for (uint i = 0u; i < animations.size(); i++) { Animation* animation = animations[i]; delete animation; } animations.clear(); current_anim = nullptr; } void ResourceAnimator::AddAnimationFromAnimationResource(ResourceAnimation * res) { Animation* animation = new Animation(); animation->name = res->animationData.name; animation->animation_uuid = res->GetUuid(); animation->duration = res->animationData.duration; animation->numKeys = res->animationData.numKeys; animation->boneKeys = res->animationData.boneKeys; animations.push_back(animation); current_anim = animations[0]; current_anim->interpolate = true; current_anim->loop = true; } float ResourceAnimator::GetCurrentAnimationTime() const { return current_anim->anim_timer; } const char * ResourceAnimator::GetAnimationName(int index) const { return animations[index]->name.c_str(); } uint ResourceAnimator::GetAnimationsNumber() const { return (uint)animations.size(); } ResourceAnimator::Animation * ResourceAnimator::GetCurrentAnimation() const { return current_anim; } void ResourceAnimator::SetCurrentAnimationTime(float time) { current_anim->anim_timer = time; ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid); if (tmp_avatar) { tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer); } } bool ResourceAnimator::SetCurrentAnimation(const char * anim_name) { for (uint i = 0u; i < animations.size(); i++) { Animation* it_anim = animations[i]; if (strcmp(it_anim->name.c_str(), anim_name) == 0) { anim_state = BLENDING; blend_timer = 0.0f; last_anim = current_anim; current_anim = it_anim; SetCurrentAnimationTime(0.0f); current_anim->finished = false; current_anim->anim_timer = 0.0f; return true; } } return false; } void ResourceAnimator::PlayAnimation() { anim_state = AnimationState::PLAYING; current_anim->anim_timer = 0.0f; current_anim->finished = false; ResourceAvatar* ava = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid); ava->SetIsAnimated(true); } void ResourceAnimator::PauseAnimation() { anim_state = AnimationState::PAUSED; ResourceAvatar* ava = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid); //ava->SetIsAnimated(false); } void ResourceAnimator::StopAnimation() { anim_state = AnimationState::STOPPED; ResourceAvatar* ava = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid); //ava->SetIsAnimated(false); } void ResourceAnimator::StepBackwards() { if (current_anim->anim_timer > 0.0f) { float dt = 0.0f; dt = App->GetDt(); #ifdef GAMEMODE dt = App->timeManager->GetDt(); #endif // GAMEMODE current_anim->anim_timer -= dt * current_anim->anim_speed; if (current_anim->anim_timer < 0.0f) current_anim->anim_timer = 0.0f; else { ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid); if (tmp_avatar) { tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer); } } PauseAnimation(); } } void ResourceAnimator::StepForward() { if (current_anim->anim_timer < current_anim->duration) { float dt = 0.0f; dt = App->GetDt(); #ifdef GAMEMODE dt = App->timeManager->GetDt(); #endif // GAMEMODE current_anim->anim_timer += dt * current_anim->anim_speed; if (current_anim->anim_timer > current_anim->duration) current_anim->anim_timer = 0.0f; else { ResourceAvatar* tmp_avatar = (ResourceAvatar*)App->res->GetResource(this->animator_data.avatar_uuid); if (tmp_avatar) { tmp_avatar->StepBones(current_anim->animation_uuid, current_anim->anim_timer); } } PauseAnimation(); } }
17,704
6,774
#ifndef ISP_IMP_HPP #define ISP_IMP_HPP #include "stm32f4xx.h" extern "C" void CAN1_RX0_IRQHandler(void); extern "C" void CAN2_RX0_IRQHandler(void); extern "C" void USART6_IRQHandler(void); #endif
200
104
/** * Adam Lamers * December 6th, 2010 * CURL HTTP Downloader class */ #include "CURLDownloader.h" #include <iostream> #include <stdlib.h> size_t write_data(void *ptr, size_t size, size_t nmemb, dataBuffer *buffer) { if(buffer->size == 0) { int dataLength = size * nmemb; buffer->size = dataLength; buffer->data = (byte*)malloc(buffer->size); if(!buffer->data) return 0; memcpy(buffer->data, ptr, dataLength); buffer->pos = dataLength; return dataLength; } else { int dataLength = size * nmemb; if(buffer->data) { buffer->size += dataLength; buffer->data = (byte*)realloc(buffer->data, buffer->size); if(!buffer->data) return 0; memcpy((char*)buffer->data + buffer->pos, ptr, dataLength); buffer->pos += dataLength; } else return 0; return dataLength; } } size_t write_data_file(void *ptr, size_t size, size_t nmemb, FILE *stream) { size_t written = fwrite(ptr, size, nmemb, stream); return written; } CURLDownloader::CURLDownloader() { } int CURLDownloader::downloadToFile(const char *URL, const char *localFilename) { CURL *curl = curl_easy_init(); if(curl) { FILE *localFile = fopen(localFilename, "wb"); curl_easy_setopt(curl, CURLOPT_URL, URL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_file); curl_easy_setopt(curl, CURLOPT_WRITEDATA, localFile); m_curlRes = curl_easy_perform(curl); curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &m_lastHTTPResponseCode); curl_easy_cleanup(curl); fclose(localFile); } return m_curlRes; } int CURLDownloader::downloadToBuffer(const char *URL, dataBuffer *buffer) { CURL *curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, URL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer); m_curlRes = curl_easy_perform(curl); curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &m_lastHTTPResponseCode); curl_easy_cleanup(curl); } return m_curlRes; } long CURLDownloader::lastHTTPResponseCode() { return m_lastHTTPResponseCode; } CURLDownloader::~CURLDownloader() { }
2,366
801
#include "stdafx.h" #include "VRDemoHotKeyManager.h" #include "util\l4util.h" #include "VRDemoConfigurator.h" #include "VRDemoTogglesWrapper.h" const std::string VRDemoHotKeyManager::HOT_KEY_PAUSE = "HotKeyPause"; VRDemoHotKeyManager::VRDemoHotKeyManager() { } VRDemoHotKeyManager::~VRDemoHotKeyManager() { } void VRDemoHotKeyManager::configurate(HWND wnd) { // TODO: to make it configuable /* const VRDemoConfigurator::KeyValueMap *helperSection = VRDemoConfigurator::getInstance().getHelperSection(); if (helperSection) { VRDemoConfigurator::KeyValueMap::const_iterator it = helperSection->find(l4util::toUpper(HOT_KEY_PAUSE)); std::string keyPause; if (it != helperSection->end()) { keyPause = it->second; } } */ RegisterHotKey(wnd, 1, 0, VK_F8); }
830
309
#include <iostream> #include <functional> #include <SFML/Graphics.hpp> #include "ball.hpp" #include "entity.hpp" #include "character.hpp" #include "wall.hpp" class action { private: std::function< bool() > condition; std::function< void() > work; public: action( std::function< bool() > condition, std::function< void() > work ) : condition( condition ), work( work ) {} action( sf::Keyboard::Key key, std::function< void() > work ) : condition( [ key ]()->bool { return sf::Keyboard::isKeyPressed( key ); } ), work(work) {} action( sf::Mouse::Button button, std::function< void() > work ) : condition( [ button ]()->bool { return sf::Mouse::isButtonPressed( button ); } ), work(work) {} action( entity *thisEntity, entity *otherEntity, std::function< void() > work ) : condition( [ thisEntity, otherEntity ]()->bool {return thisEntity->getBoundingBox().intersects(otherEntity->getBoundingBox()); } ), work(work) {} void operator()(){ if( condition() ){ work(); } } }; int main( int argc, char *argv[] ){ std::cout << "Starting application 2\n"; sf::RenderWindow window{ sf::VideoMode{ 640, 480 }, "2" }; std::vector<entity*> entityList; entityList.push_back(new character(sf::Vector2f{160.0, 240.0}, sf::Vector2f{40.0,40.0}, sf::Color::Blue)); entityList.push_back(new wall(sf::Vector2f{0.0, 0.0}, sf::Vector2f{640.0, 10.0}, sf::Color::Red)); entityList.push_back(new wall(sf::Vector2f{0.0, 10.0}, sf::Vector2f{10.0, 460.0}, sf::Color::Blue)); entityList.push_back(new wall(sf::Vector2f{630.0, 10.0}, sf::Vector2f{10.0, 460.0}, sf::Color::Red)); entityList.push_back(new wall(sf::Vector2f{0.0, 470.0}, sf::Vector2f{640.0, 10.0}, sf::Color::Blue)); entityList.push_back(new ball(sf::Vector2f{400.0, 300.0}, sf::Vector2f{20.0, 0.0}, sf::Color::Red)); action actions[] = { action( sf::Keyboard::Left, [&](){ entityList[0]->move( sf::Vector2f( -10.0, 0.0 )); }), action( sf::Keyboard::Right, [&](){ entityList[0]->move( sf::Vector2f( +10.0, 0.0 )); }), action( sf::Keyboard::Up, [&](){ entityList[0]->move( sf::Vector2f( 0.0, -10.0 )); }), action( sf::Keyboard::Down, [&](){ entityList[0]->move( sf::Vector2f( 0.0, +10.0 )); }), action( sf::Keyboard::Escape, [&](){ window.close(); }) }; while (window.isOpen()) { window.clear(); for(auto & entity : entityList){ for(auto & otherEntity : entityList){ if(entity != otherEntity){ auto testcollision = action(entity, otherEntity, [&](){ entity->changeColor(); entity->collide(*otherEntity); }); testcollision(); } } entity->draw(window); } for( auto & action : actions ){ action(); } window.display(); sf::sleep( sf::milliseconds( 20 )); sf::Event event; while( window.pollEvent(event) ){ if( event.type == sf::Event::Closed ){ window.close(); } } } std::cout << "Terminating application\n"; return 0; }
2,961
1,275
#pragma once #include <vector> #include <memory> #include <cmath> #include <cassert> #include <set> #include <chrono> #include <random> #include <ratio> #include <type_traits> #include "../RandomPlayer/RandomPlayer.hpp" template <typename Game, typename ActGen, unsigned int Iterations, typename Ratio = std::ratio<14, 10>, typename Rollout = RandomPlayer<Game, ActGen>> class MCTS { static_assert(Iterations > 0); static_assert(std::is_same_v<Game, typename Rollout::GameType>); public: inline static constexpr unsigned int PlayerCount = Game::PlayerCount; using GameType = Game; using Action = typename Game::Action; using Result = typename Game::Result; private: inline static constexpr double C = static_cast<double>(Ratio::num) / Ratio::den; static_assert(C >= 0); class Node { friend class MCTS; private: Node *_Parent = nullptr; Action _Action; std::vector<std::unique_ptr<Node>> _Children; std::unique_ptr<Game> _Game; std::unique_ptr<ActGen> _ActGen; unsigned int _NextPlayer; std::array<double, PlayerCount> _Value{}; unsigned int _Count = 0; public: inline explicit Node(const Game &game, const ActGen &actGen) : _Game(std::make_unique<Game>(game)), _ActGen(std::make_unique<ActGen>(actGen)), _NextPlayer(_Game->GetNextPlayer()) {} inline explicit Node(std::unique_ptr<Game> game, std::unique_ptr<ActGen> actGen, Action action, Node &parent) : _Parent(&parent), _Action(action), _Game(std::move(game)), _ActGen(std::move(actGen)), _NextPlayer(_Game->GetNextPlayer()) {} }; const Game *_Game; ActGen _ActGen; public: inline explicit MCTS(const Game &game) : _Game(&game), _ActGen(game) {} inline explicit MCTS(const Game &game, const std::vector<Action> &) : MCTS(game) {} MCTS(const MCTS &) = delete; MCTS &operator=(const MCTS &) = delete; inline MCTS(MCTS &&) = default; inline MCTS &operator=(MCTS &&) = default; inline void Notify(Action act) { _ActGen.Notify(act); } Action operator()() { Node root(*_Game, _ActGen); for (unsigned int iter = 0; iter < Iterations; ++iter) { // Selection Node *p = &root; // While p is not a leaf node while (p->_Children.size() != 0) { auto player = p->_NextPlayer; double maxUCB = 0; unsigned int index = -1; for (unsigned int i = 0; i < p->_Children.size(); ++i) { auto &node = *p->_Children[i]; // Avoid 0 as divider // When n_i == 0, UCB is infinite if (node._Count == 0) { index = i; break; } double ucb = node._Value[player] / node._Count; ucb += C * std::sqrt(std::log(p->_Count) / node._Count); if (ucb > maxUCB) { maxUCB = ucb; index = i; } } assert(index < p->_Children.size()); p = p->_Children[index].get(); } // Expansion if (p->_Count != 0 && !p->_Game->GetResult()) { for (auto act : *p->_ActGen) { auto game = std::make_unique<Game>(*p->_Game); auto actGen = std::make_unique<ActGen>(*p->_ActGen); actGen->SetGame(*game); (*game)(act); actGen->Notify(act); auto node = std::make_unique<Node>(std::move(game), std::move(actGen), act, *p); p->_Children.push_back(std::move(node)); } assert(p->_Children.size() > 0); p->_Game = nullptr; p->_ActGen = nullptr; p = p->_Children[0].get(); } // Rollout Game game = *p->_Game; Rollout roll(game); auto value = game.GetResult(); while (!value) { auto act = roll(); game(act); roll.Notify(act); value = game.GetResult(); } // Back propagation while (true) { ++p->_Count; for (unsigned int i = 0; i < PlayerCount; ++i) p->_Value[i] += (*value)[i]; if (p == &root) break; p = p->_Parent; } } // Choose best move std::set<unsigned int> bestSet; double bestWinRate = 0; for (unsigned int i = 0; i < root._Children.size(); ++i) { double rate = root._Children[i]->_Value[_Game->GetNextPlayer()] / root._Children[i]->_Count; if (rate == bestWinRate) bestSet.insert(i); else if (rate > bestWinRate) { bestSet.clear(); bestSet.insert(i); bestWinRate = rate; } } std::vector<unsigned int> bests(bestSet.cbegin(), bestSet.cend()); static auto seed = std::chrono::system_clock::now().time_since_epoch().count(); static std::default_random_engine e(seed); std::uniform_int_distribution<unsigned int> random(0, bests.size() - 1); return root._Children[bests[random(e)]]->_Action; } };
5,737
1,655
/* * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include <stdio.h> #include <stdlib.h> #include "jvmti.h" #include "agent_common.h" #include "JVMTITools.h" extern "C" { #define STATUS_FAILED 2 #define PASSED 0 static jvmtiEnv *jvmti; static jvmtiCapabilities caps; static jvmtiEventCallbacks callbacks; static int watch_ev = 0; /* ignore JVMTI events by default */ static int gen_ev = 0; /* number of generated events */ static jvmtiError popframe_err = JVMTI_ERROR_NONE; static jrawMonitorID watch_ev_monitor; static void set_watch_ev(int value) { jvmti->RawMonitorEnter(watch_ev_monitor); watch_ev = value; jvmti->RawMonitorExit(watch_ev_monitor); } void JNICALL FramePop(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thread, jmethodID method, jboolean wasPopedByException) { jvmti->RawMonitorEnter(watch_ev_monitor); if (watch_ev) { printf("#### FramePop event occurred ####\n"); gen_ev++; } jvmti->RawMonitorExit(watch_ev_monitor); } void JNICALL MethodExit(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thr, jmethodID method, jboolean was_poped_by_exc, jvalue return_value) { jvmti->RawMonitorEnter(watch_ev_monitor); if (watch_ev) { printf("#### MethodExit event occurred ####\n"); gen_ev++; } jvmti->RawMonitorExit(watch_ev_monitor); } JNIEXPORT jint JNICALL Java_nsk_jvmti_PopFrame_popframe011_doPopFrame(JNIEnv *env, jclass cls, jint t_case, jobject frameThr) { if (!caps.can_pop_frame) { return PASSED; } if (t_case != 6 && t_case != 7) { /* * Only enable this event for test cases where the event * should not happen. */ popframe_err = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_METHOD_EXIT, frameThr); if (popframe_err != JVMTI_ERROR_NONE) { printf("Failed to enable METHOD_EXIT event: %s (%d)\n", TranslateError(popframe_err), popframe_err); return STATUS_FAILED; } } popframe_err = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FRAME_POP, frameThr); if ((t_case == 6 || t_case == 7) && popframe_err == JVMTI_ERROR_THREAD_NOT_ALIVE) { // Our target thread has exited which is okay. return PASSED; } if (popframe_err != JVMTI_ERROR_NONE) { printf("Failed to enable FRAME_POP event: %s (%d)\n", TranslateError(popframe_err), popframe_err); return STATUS_FAILED; } switch (t_case) { /* NULL pointer to the thread in debug mode */ case 1: printf("\nInvoke PopFrame() with NULL pointer to a thread...\n"); fflush(stdout); // fallthrough /* NULL pointer to the thread */ case 0: set_watch_ev(1); /* watch JVMTI events */ popframe_err = (jvmti->PopFrame(NULL)); /* explode the bomb */ if (popframe_err != JVMTI_ERROR_INVALID_THREAD) { printf("TEST FAILED: the function PopFrame() returned the error %d: %s\n", popframe_err, TranslateError(popframe_err)); printf("\tBut it should return the error JVMTI_ERROR_INVALID_THREAD.\n"); return STATUS_FAILED; } break; /* invalid thread in debug mode */ case 3: printf("\nInvoke PopFrame() for an invalid thread...\n"); fflush(stdout); // fallthrough /* invalid thread */ case 2: set_watch_ev(1); /* watch JVMTI events */ popframe_err = (jvmti->PopFrame(cls)); /* explode the bomb */ set_watch_ev(0); /* ignore again JVMTI events */ if (popframe_err != JVMTI_ERROR_INVALID_THREAD) { printf("TEST FAILED: the function PopFrame() returned the error %d: %s\n", popframe_err, TranslateError(popframe_err)); printf("\tBut it should return the error JVMTI_ERROR_INVALID_THREAD.\n"); return STATUS_FAILED; } break; /* non suspended thread in debug mode */ case 5: printf("\nInvoke PopFrame() for a non suspended thread...\n"); fflush(stdout); // fallthrough /* non suspended thread */ case 4: set_watch_ev(1); /* watch JVMTI events */ popframe_err = (jvmti->PopFrame(frameThr)); /* explode the bomb */ set_watch_ev(0); /* ignore again JVMTI events */ if (popframe_err != JVMTI_ERROR_THREAD_NOT_SUSPENDED) { printf("TEST FAILED: the function PopFrame() returned the error %d: %s\n", popframe_err, TranslateError(popframe_err)); printf("\tBut it should return the error JVMTI_ERROR_THREAD_NOT_SUSPENDED.\n"); return STATUS_FAILED; } break; /* non suspended and exiting thread in debug mode */ case 7: printf("\nInvoke PopFrame() for a non suspended and exiting thread...\n"); fflush(stdout); // fallthrough /* non suspended and exiting thread */ case 6: set_watch_ev(1); /* watch JVMTI events */ popframe_err = (jvmti->PopFrame(frameThr)); /* explode the bomb */ set_watch_ev(0); /* ignore again JVMTI events */ if (popframe_err != JVMTI_ERROR_THREAD_NOT_SUSPENDED && popframe_err != JVMTI_ERROR_THREAD_NOT_ALIVE) { printf("TEST FAILED: the function PopFrame() returned the error %d: %s\n", popframe_err, TranslateError(popframe_err)); printf("\tBut it should return the error JVMTI_ERROR_THREAD_NOT_SUSPENDED or JVMTI_ERROR_THREAD_NOT_ALIVE.\n"); return STATUS_FAILED; } break; } if (gen_ev) { printf("TEST FAILED: %d JVMTI events were generated by the function PopFrame()\n", gen_ev); return STATUS_FAILED; } else if (t_case == 1 || t_case == 3 || t_case == 5 || t_case == 7) printf("Check #%d PASSED: No JVMTI events were generated by the function PopFrame()\n", t_case+1); set_watch_ev(0); /* ignore again JVMTI events */ if (t_case != 6 && t_case != 7) { /* * Only disable this event for test cases where the event * should not happen. */ popframe_err = jvmti->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_METHOD_EXIT, frameThr); if (popframe_err != JVMTI_ERROR_NONE) { printf("Failed to disable METHOD_EXIT event: %s (%d)\n", TranslateError(popframe_err), popframe_err); return STATUS_FAILED; } } popframe_err = jvmti->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_FRAME_POP, frameThr); if ((t_case == 6 || t_case == 7) && popframe_err == JVMTI_ERROR_THREAD_NOT_ALIVE) { // Our target thread has exited which is okay. return PASSED; } if (popframe_err != JVMTI_ERROR_NONE) { printf("Failed to disable FRAME_POP event: %s (%d)\n", TranslateError(popframe_err), popframe_err); return STATUS_FAILED; } return PASSED; } JNIEXPORT jboolean JNICALL Java_nsk_jvmti_PopFrame_popframe011_isThreadNotAliveError(JNIEnv *env, jclass cls) { if (popframe_err == JVMTI_ERROR_THREAD_NOT_ALIVE) { return JNI_TRUE; } return JNI_FALSE; } #ifdef STATIC_BUILD JNIEXPORT jint JNICALL Agent_OnLoad_popframe011(JavaVM *jvm, char *options, void *reserved) { return Agent_Initialize(jvm, options, reserved); } JNIEXPORT jint JNICALL Agent_OnAttach_popframe011(JavaVM *jvm, char *options, void *reserved) { return Agent_Initialize(jvm, options, reserved); } JNIEXPORT jint JNI_OnLoad_popframe011(JavaVM *jvm, char *options, void *reserved) { return JNI_VERSION_1_8; } #endif jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) { jint res; jvmtiError err; res = jvm->GetEnv((void **) &jvmti, JVMTI_VERSION_1_1); if (res != JNI_OK || jvmti == NULL) { printf("Wrong result of a valid call to GetEnv!\n"); return JNI_ERR; } err = jvmti->GetPotentialCapabilities(&caps); if (err != JVMTI_ERROR_NONE) { printf("(GetPotentialCapabilities) unexpected error: %s (%d)\n", TranslateError(err), err); return JNI_ERR; } err = jvmti->AddCapabilities(&caps); if (err != JVMTI_ERROR_NONE) { printf("(AddCapabilities) unexpected error: %s (%d)\n", TranslateError(err), err); return JNI_ERR; } err = jvmti->GetCapabilities(&caps); if (err != JVMTI_ERROR_NONE) { printf("(GetCapabilities) unexpected error: %s (%d)\n", TranslateError(err), err); return JNI_ERR; } if (!caps.can_pop_frame) { printf("Warning: PopFrame is not implemented\n"); return JNI_OK; } if (caps.can_generate_frame_pop_events && caps.can_generate_method_exit_events) { callbacks.MethodExit = &MethodExit; callbacks.FramePop = &FramePop; err = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); if (err != JVMTI_ERROR_NONE) { printf("(SetEventCallbacks) unexpected error: %s (%d)\n", TranslateError(err), err); return JNI_ERR; } } else { printf("Warning: FramePop or MethodExit event is not implemented\n"); } err = jvmti->CreateRawMonitor("watch_ev_monitor", &watch_ev_monitor); if (err != JVMTI_ERROR_NONE) { printf("(CreateRawMonitor) unexpected error: %s (%d)\n", TranslateError(err), err); return JNI_ERR; } return JNI_OK; } }
10,626
3,588
#include <iostream> #include <vector> #include <algorithm> #include <random> #include <chrono> #include <cassert> template<typename Iterator> void qsort1(Iterator b, Iterator e) { using std::swap; if (b >= e) { return; } Iterator geb = b, unb = b; auto pivot = std::prev(e); while (unb != pivot) { if (*unb < *pivot) { swap(*unb, *geb); ++geb; } ++unb; } swap(*geb, *pivot); qsort1(b, geb); qsort1(std::next(geb), e); } template<typename Iterator> void qsort2(Iterator b, Iterator e) { using std::swap; if (b >= e) { return; } Iterator eqb = b, gtb = b, index = b; auto pivot = std::prev(e); while (index != pivot) { if (*index < *pivot) { swap(*index, *eqb); if (eqb != gtb) swap(*index, *gtb); ++eqb; ++gtb; } else if (*pivot < *index) { // } else { swap(*index, *gtb); ++gtb; } ++index; } swap(*gtb, *pivot); ++gtb; qsort2(b, eqb); qsort2(gtb, e); } class TimerGuard { public: TimerGuard() { begin = std::chrono::system_clock::now(); } ~TimerGuard() { auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed = end - begin; std::cout << elapsed.count() << "s\n"; } private: std::chrono::system_clock::time_point begin; }; int main() { constexpr size_t VSIZE = 100000; std::vector<int> v(VSIZE); std::random_device dev; std::mt19937 g(dev()); std::default_random_engine e(dev()); std::uniform_int_distribution<int> dist(0, 100000000); for (auto& i: v) { i = dist(e); } std::shuffle(v.begin(), v.end(), g); std::cout << std::endl; auto v3 = v; { TimerGuard tg; qsort1(v.begin(), v.end()); if (std::is_sorted(v.begin(), v.end())) { std::cout << "sorted\n"; } else { std::cout << "unsorted\n"; } } std::vector<int> v2(VSIZE, 1); auto v4 = v2; { TimerGuard tg; qsort1(v2.begin(), v2.end()); if (std::is_sorted(v2.begin(), v2.end())) { std::cout << "sorted\n"; } else { std::cout << "unsorted\n"; } } { TimerGuard tg; qsort2(v3.begin(), v3.end()); if (std::is_sorted(v3.begin(), v3.end())) { std::cout << "sorted\n"; } else { std::cout << "unsorted\n"; std::for_each(v3.begin(), v3.end(), [](const auto& i){std::cout << i << ' ';}); } } { TimerGuard tg; qsort2(v4.begin(), v4.end()); if (std::is_sorted(v4.begin(), v4.end())) { std::cout << "sorted\n"; } else { std::cout << "unsorted\n"; } } }
2,418
1,176
/* * Copyright 2003-2013, Axel Dรถrfler, axeld@pinc-software.de. * Distributed under the terms of the MIT License. */ #include "RootFileSystem.h" #include <OS.h> #include <string.h> #include <fcntl.h> RootFileSystem::RootFileSystem() { } RootFileSystem::~RootFileSystem() { struct entry *entry = NULL; while ((entry = fList.RemoveHead()) != NULL) { entry->root->Release(); delete entry; } } status_t RootFileSystem::Open(void **_cookie, int mode) { EntryIterator *iterator = new (std::nothrow) EntryIterator(&fList); if (iterator == NULL) return B_NO_MEMORY; *_cookie = iterator; return B_OK; } status_t RootFileSystem::Close(void *cookie) { delete (EntryIterator *)cookie; return B_OK; } Node* RootFileSystem::LookupDontTraverse(const char* name) { EntryIterator iterator = fLinks.GetIterator(); struct entry *entry; // first check the links while ((entry = iterator.Next()) != NULL) { if (!strcmp(name, entry->name)) { entry->root->Acquire(); return entry->root; } } // then all mounted file systems iterator = fList.GetIterator(); while ((entry = iterator.Next()) != NULL) { char entryName[B_OS_NAME_LENGTH]; if (entry->root->GetName(entryName, sizeof(entryName)) != B_OK) continue; if (!strcmp(entryName, name)) { entry->root->Acquire(); return entry->root; } } return NULL; } status_t RootFileSystem::GetNextEntry(void *_cookie, char *name, size_t size) { EntryIterator *iterator = (EntryIterator *)_cookie; struct entry *entry; entry = iterator->Next(); if (entry != NULL) return entry->root->GetName(name, size); return B_ENTRY_NOT_FOUND; } status_t RootFileSystem::GetNextNode(void *_cookie, Node **_node) { EntryIterator *iterator = (EntryIterator *)_cookie; struct entry *entry; entry = iterator->Next(); if (entry != NULL) { *_node = entry->root; return B_OK; } return B_ENTRY_NOT_FOUND; } status_t RootFileSystem::Rewind(void *_cookie) { EntryIterator *iterator = (EntryIterator *)_cookie; iterator->Rewind(); return B_OK; } bool RootFileSystem::IsEmpty() { return fList.IsEmpty(); } status_t RootFileSystem::AddVolume(Directory *volume, Partition *partition) { struct entry *entry = new (std::nothrow) RootFileSystem::entry(); if (entry == NULL) return B_NO_MEMORY; volume->Acquire(); entry->name = NULL; entry->root = volume; entry->partition = partition; fList.Add(entry); return B_OK; } status_t RootFileSystem::AddLink(const char *name, Directory *target) { struct entry *entry = new (std::nothrow) RootFileSystem::entry(); if (entry == NULL) return B_NO_MEMORY; target->Acquire(); entry->name = name; entry->root = target; fLinks.Add(entry); return B_OK; } status_t RootFileSystem::GetPartitionFor(Directory *volume, Partition **_partition) { EntryIterator iterator = fList.GetIterator(); struct entry *entry; while ((entry = iterator.Next()) != NULL) { if (entry->root == volume) { *_partition = entry->partition; return B_OK; } } return B_ENTRY_NOT_FOUND; }
3,038
1,155
#include<bits/stdc++.h> using namespace std; int phi[100000]; void phiSieve(int n) { for(int i=1; i<=n;i++) phi[i] = i; for(int i=2; i<=n; i++ ) { if(phi[i]==i) { phi[i] = i-1; for(int j= 2*i;j<=n;j+=i) { phi[j] = (phi[j]/i)*(i-1); } } } } int main() { int n = 10; phiSieve(n); for(int i=1;i<=n;i++) { cout<<i<<" "<<phi[i]<<endl; } }
480
239
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/tf2xla/type_util.h" #include "tensorflow/compiler/tf2xla/xla_compiler.h" #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/core/framework/kernel_def_builder.h" namespace tensorflow { namespace { // This OpKernel implements the _Arg Op for XLA JIT devices. It // associates its output with one of the arguments to a // subcomputation. class ArgOp : public XlaOpKernel { public: explicit ArgOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("index", &index_)); } void Compile(XlaOpKernelContext* ctx) override { // If 'frame' is non-null, this is a function call inside an outer JIT // compilation. Use the usual implementation of _Arg. auto frame = ctx->call_frame(); if (frame != nullptr) { Tensor val; OP_REQUIRES_OK(ctx, frame->GetArg(index_, &val)); OP_REQUIRES(ctx, val.dtype() == dtype_, errors::InvalidArgument( "Type mismatch: actual ", DataTypeString(val.dtype()), " vs. expect ", DataTypeString(dtype_))); // Forwards the argument from the frame. ctx->op_kernel_context()->set_output(0, val); return; } XlaContext& xc = XlaContext::Get(ctx); const XlaContext::Argument& arg = xc.args()[index_]; if (arg.is_resource) { XlaResource::Kind kind; switch (arg.kind) { case XlaCompiler::Argument::kVariable: kind = XlaResource::kVariable; break; case XlaCompiler::Argument::kTensorArray: kind = XlaResource::kTensorArray; break; case XlaCompiler::Argument::kStack: kind = XlaResource::kStack; break; default: CHECK(false); } // TODO(phawkins): this code assumes that variables do not alias. XlaResource* resource; OP_REQUIRES_OK(ctx, xc.CreateResource(kind, index_, arg.name, arg.value.type, arg.value.handle, &resource)); resource->tensor_array_size = arg.tensor_array_size; ctx->SetResourceOutput(0, resource); } else if (arg.value.is_constant) { ctx->SetConstantOutput(0, arg.value.constant_value); } else { ctx->SetOutput(0, arg.value.handle); } } private: int index_; DataType dtype_; TF_DISALLOW_COPY_AND_ASSIGN(ArgOp); }; REGISTER_XLA_OP(Name("_Arg").AllowResourceTypes(), ArgOp); } // namespace } // namespace tensorflow
3,346
1,044
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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 "open3d/core/linalg/Det.h" #include "open3d/core/linalg/LU.h" #include "open3d/core/linalg/kernel/Matrix.h" namespace open3d { namespace core { double Det(const Tensor& A) { AssertTensorDtypes(A, {Float32, Float64}); const Dtype dtype = A.GetDtype(); double det = 1.0; if (A.GetShape() == open3d::core::SizeVector({3, 3})) { DISPATCH_FLOAT_DTYPE_TO_TEMPLATE(dtype, [&]() { core::Tensor A_3x3 = A.To(core::Device("CPU:0"), false).Contiguous(); const scalar_t* A_3x3_ptr = A_3x3.GetDataPtr<scalar_t>(); det = static_cast<double>(linalg::kernel::det3x3(A_3x3_ptr)); }); } else if (A.GetShape() == open3d::core::SizeVector({2, 2})) { DISPATCH_FLOAT_DTYPE_TO_TEMPLATE(dtype, [&]() { core::Tensor A_2x2 = A.To(core::Device("CPU:0"), false).Contiguous(); const scalar_t* A_2x2_ptr = A_2x2.GetDataPtr<scalar_t>(); det = static_cast<double>(linalg::kernel::det2x2(A_2x2_ptr)); }); } else { Tensor ipiv, output; LUIpiv(A, ipiv, output); // Sequential loop to compute determinant from LU output, is more // efficient on CPU. Tensor output_cpu = output.To(core::Device("CPU:0")); Tensor ipiv_cpu = ipiv.To(core::Device("CPU:0")); int n = A.GetShape()[0]; DISPATCH_FLOAT_DTYPE_TO_TEMPLATE(dtype, [&]() { scalar_t* output_ptr = output_cpu.GetDataPtr<scalar_t>(); int* ipiv_ptr = static_cast<int*>(ipiv_cpu.GetDataPtr()); for (int i = 0; i < n; i++) { det *= output_ptr[i * n + i]; if (ipiv_ptr[i] != i) { det *= -1; } } }); } return det; } } // namespace core } // namespace open3d
3,317
1,126
#include "SimMuon/MCTruth/interface/RPCHitAssociator.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" using namespace std; // Constructor RPCHitAssociator::RPCHitAssociator(const edm::ParameterSet &conf, edm::ConsumesCollector &&iC) : RPCdigisimlinkTag(conf.getParameter<edm::InputTag>("RPCdigisimlinkTag")), // CrossingFrame used or not ? crossingframe(conf.getParameter<bool>("crossingframe")), RPCsimhitsTag(conf.getParameter<edm::InputTag>("RPCsimhitsTag")), RPCsimhitsXFTag(conf.getParameter<edm::InputTag>("RPCsimhitsXFTag")) { if (crossingframe) { RPCsimhitsXFToken_ = iC.consumes<CrossingFrame<PSimHit>>(RPCsimhitsXFTag); } else if (!RPCsimhitsTag.label().empty()) { RPCsimhitsToken_ = iC.consumes<edm::PSimHitContainer>(RPCsimhitsTag); } RPCdigisimlinkToken_ = iC.consumes<edm::DetSetVector<RPCDigiSimLink>>(RPCdigisimlinkTag); } RPCHitAssociator::RPCHitAssociator(const edm::Event &e, const edm::EventSetup &eventSetup, const edm::ParameterSet &conf) : RPCdigisimlinkTag(conf.getParameter<edm::InputTag>("RPCdigisimlinkTag")), // CrossingFrame used or not ? crossingframe(conf.getParameter<bool>("crossingframe")), RPCsimhitsTag(conf.getParameter<edm::InputTag>("RPCsimhitsTag")), RPCsimhitsXFTag(conf.getParameter<edm::InputTag>("RPCsimhitsXFTag")) { initEvent(e, eventSetup); } void RPCHitAssociator::initEvent(const edm::Event &e, const edm::EventSetup &eventSetup) { if (crossingframe) { edm::Handle<CrossingFrame<PSimHit>> cf; LogTrace("RPCHitAssociator") << "getting CrossingFrame<PSimHit> collection - " << RPCsimhitsXFTag; e.getByLabel(RPCsimhitsXFTag, cf); std::unique_ptr<MixCollection<PSimHit>> RPCsimhits(new MixCollection<PSimHit>(cf.product())); LogTrace("RPCHitAssociator") << "... size = " << RPCsimhits->size(); // MixCollection<PSimHit> & simHits = *hits; for (MixCollection<PSimHit>::MixItr hitItr = RPCsimhits->begin(); hitItr != RPCsimhits->end(); ++hitItr) { _SimHitMap[hitItr->detUnitId()].push_back(*hitItr); } } else if (!RPCsimhitsTag.label().empty()) { edm::Handle<edm::PSimHitContainer> RPCsimhits; LogTrace("RPCHitAssociator") << "getting PSimHit collection - " << RPCsimhitsTag; e.getByLabel(RPCsimhitsTag, RPCsimhits); LogTrace("RPCHitAssociator") << "... size = " << RPCsimhits->size(); // arrange the hits by detUnit for (edm::PSimHitContainer::const_iterator hitItr = RPCsimhits->begin(); hitItr != RPCsimhits->end(); ++hitItr) { _SimHitMap[hitItr->detUnitId()].push_back(*hitItr); } } edm::Handle<edm::DetSetVector<RPCDigiSimLink>> thelinkDigis; LogTrace("RPCHitAssociator") << "getting RPCDigiSimLink collection - " << RPCdigisimlinkTag; e.getByLabel(RPCdigisimlinkTag, thelinkDigis); _thelinkDigis = thelinkDigis; } // end of constructor std::vector<RPCHitAssociator::SimHitIdpr> RPCHitAssociator::associateRecHit(const TrackingRecHit &hit) const { std::vector<SimHitIdpr> matched; const TrackingRecHit *hitp = &hit; const RPCRecHit *rpcrechit = dynamic_cast<const RPCRecHit *>(hitp); if (rpcrechit) { RPCDetId rpcDetId = rpcrechit->rpcId(); int fstrip = rpcrechit->firstClusterStrip(); int cls = rpcrechit->clusterSize(); int bx = rpcrechit->BunchX(); for (int i = fstrip; i < fstrip + cls; ++i) { std::set<RPCDigiSimLink> links = findRPCDigiSimLink(rpcDetId.rawId(), i, bx); if (links.empty()) LogTrace("RPCHitAssociator") << "*** WARNING in RPCHitAssociator::associateRecHit, RPCRecHit " << *rpcrechit << ", strip " << i << " has no associated RPCDigiSimLink !" << endl; for (std::set<RPCDigiSimLink>::iterator itlink = links.begin(); itlink != links.end(); ++itlink) { SimHitIdpr currentId(itlink->getTrackId(), itlink->getEventId()); if (find(matched.begin(), matched.end(), currentId) == matched.end()) matched.push_back(currentId); } } } else LogTrace("RPCHitAssociator") << "*** WARNING in RPCHitAssociator::associateRecHit, null " "dynamic_cast !"; return matched; } std::set<RPCDigiSimLink> RPCHitAssociator::findRPCDigiSimLink(uint32_t rpcDetId, int strip, int bx) const { std::set<RPCDigiSimLink> links; for (edm::DetSetVector<RPCDigiSimLink>::const_iterator itlink = _thelinkDigis->begin(); itlink != _thelinkDigis->end(); itlink++) { for (edm::DetSet<RPCDigiSimLink>::const_iterator digi_iter = itlink->data.begin(); digi_iter != itlink->data.end(); ++digi_iter) { uint32_t detid = digi_iter->getDetUnitId(); int str = digi_iter->getStrip(); int bunchx = digi_iter->getBx(); if (detid == rpcDetId && str == strip && bunchx == bx) { links.insert(*digi_iter); } } } return links; }
4,957
1,875
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "MergePrivatePCH.h" #include "SMergeTreeView.h" void SMergeTreeView::Construct(const FArguments InArgs , const FBlueprintMergeData& InData , FOnMergeNodeSelected SelectionCallback , TArray< TSharedPtr<FBlueprintDifferenceTreeEntry> >& OutTreeEntries , TArray< TSharedPtr<FBlueprintDifferenceTreeEntry> >& OutRealDifferences , TArray< TSharedPtr<FBlueprintDifferenceTreeEntry> >& OutConflicts) { Data = InData; CurrentDifference = -1; CurrentMergeConflict = -1; // generate controls: // EMergeParticipant::Remote { SCSViews.Push( MakeShareable(new FSCSDiff(InData.BlueprintRemote)) ); } // EMergeParticipant::Base { SCSViews.Push( MakeShareable(new FSCSDiff(InData.BlueprintBase)) ); } // EMergeParticipant::Local { SCSViews.Push( MakeShareable(new FSCSDiff(InData.BlueprintLocal)) ); } TArray< FSCSResolvedIdentifier > RemoteHierarchy = GetRemoteView()->GetDisplayedHierarchy(); TArray< FSCSResolvedIdentifier > BaseHierarchy = GetBaseView()->GetDisplayedHierarchy(); TArray< FSCSResolvedIdentifier > LocalHierarchy = GetLocalView()->GetDisplayedHierarchy(); FSCSDiffRoot RemoteDifferingProperties; DiffUtils::CompareUnrelatedSCS(InData.BlueprintBase, BaseHierarchy, InData.BlueprintRemote, RemoteHierarchy, RemoteDifferingProperties ); FSCSDiffRoot LocalDifferingProperties; DiffUtils::CompareUnrelatedSCS(InData.BlueprintBase, BaseHierarchy, InData.BlueprintLocal, LocalHierarchy, LocalDifferingProperties); DifferingProperties = RemoteDifferingProperties; DifferingProperties.Entries.Append( LocalDifferingProperties.Entries ); struct FSCSDiffPair { const FSCSDiffEntry* Local; const FSCSDiffEntry* Remote; }; TArray < FSCSDiffPair > ConflictingDifferences; /* This predicate sorts the list of differing properties so that those that are 'earlier' in the tree appear first. For example, if we get the following two trees back: B added at position (3, 2, 1) C removed at position (1, 2) and D added at position (4, 2, 1) the resulting list will be [C, B, D]: */ const auto SortTreePredicate = []( const FSCSDiffEntry& A, const FSCSDiffEntry& B ) { int32 Idx = 0; const TArray<int32>& ATreeAddress = A.TreeIdentifier.TreeLocation; const TArray<int32>& BTreeAddress = B.TreeIdentifier.TreeLocation; while(true) { if( !ATreeAddress.IsValidIndex(Idx) ) { // A has a shorter address, show it first: return true; } else if( !BTreeAddress.IsValidIndex(Idx) ) { // B has a shorter address, show it first: return false; } else if( ATreeAddress[Idx] < BTreeAddress[Idx] ) { // A has a lower index, show it first: return true; } else if( ATreeAddress[Idx] > BTreeAddress[Idx] ) { // B has a lower index, show it first: return false; } else { // tie, go to the next level of the tree: ++Idx; } } // fall back, just let diff type win: return A.DiffType < B.DiffType; }; RemoteDifferingProperties.Entries.Sort(SortTreePredicate); LocalDifferingProperties.Entries.Sort(SortTreePredicate); const FText RemoteLabel = NSLOCTEXT("SMergeTreeView", "RemoteLabel", "Remote"); const FText LocalLabel = NSLOCTEXT("SMergeTreeView", "LocalLabel", "Local"); struct FSCSMergeEntry { FText Label; FSCSIdentifier Identifier; FPropertySoftPath PropertyIdentifier; bool bConflicted; }; TArray<FSCSMergeEntry> Entries; bool bAnyConflict = false; int RemoteIter = 0; int LocalIter = 0; while( RemoteIter != RemoteDifferingProperties.Entries.Num() || LocalIter != LocalDifferingProperties.Entries.Num() ) { if (RemoteIter != RemoteDifferingProperties.Entries.Num() && LocalIter != LocalDifferingProperties.Entries.Num()) { // check for conflicts: const FSCSDiffEntry& Remote = RemoteDifferingProperties.Entries[RemoteIter]; const FSCSDiffEntry& Local = LocalDifferingProperties.Entries[LocalIter]; if( Remote.TreeIdentifier == Local.TreeIdentifier) { bool bConflicting = true; if( Remote.DiffType == ETreeDiffType::NODE_PROPERTY_CHANGED && Local.DiffType == ETreeDiffType::NODE_PROPERTY_CHANGED ) { // conflict only if property changed is the same: bConflicting = Remote.PropertyDiff.Identifier == Local.PropertyDiff.Identifier; } if( bConflicting ) { bAnyConflict = true; FSCSMergeEntry Entry = { FText::Format(NSLOCTEXT("SMergeTreeView", "ConflictIdentifier", "CONFLICT: {0} conflicts with {1}"), DiffViewUtils::SCSDiffMessage(Remote, RemoteLabel), DiffViewUtils::SCSDiffMessage(Local, LocalLabel)), Remote.TreeIdentifier, Remote.DiffType == ETreeDiffType::NODE_PROPERTY_CHANGED ? Remote.PropertyDiff.Identifier : Local.PropertyDiff.Identifier, true }; // create a tree entry that describes both the local and remote change.. Entries.Push( Entry ); ++RemoteIter; ++LocalIter; continue; } } } // no possibility of conflict, advance the entry that has a 'lower' tree identifier, keeping in mind that tree identifier // may be equal, and that in that case we need to use the property identifier as a tiebreaker: const FSCSDiffEntry* Remote = RemoteIter != RemoteDifferingProperties.Entries.Num() ? &RemoteDifferingProperties.Entries[RemoteIter] : nullptr; const FSCSDiffEntry* Local = LocalIter != LocalDifferingProperties.Entries.Num() ? &LocalDifferingProperties.Entries[LocalIter] : nullptr; if( Local && ( !Remote || SortTreePredicate( *Local, *Remote ) ) ) { FSCSMergeEntry Entry = { DiffViewUtils::SCSDiffMessage(*Local, LocalLabel), Local->TreeIdentifier, Local->PropertyDiff.Identifier, false }; Entries.Push( Entry ); ++LocalIter; } else { FSCSMergeEntry Entry = { DiffViewUtils::SCSDiffMessage(*Remote, RemoteLabel), Remote->TreeIdentifier, Remote->PropertyDiff.Identifier, false }; Entries.Push( Entry ); ++RemoteIter; } } const auto CreateSCSMergeWidget = [](FSCSMergeEntry Entry) -> TSharedRef<SWidget> { return SNew(STextBlock) .Text(Entry.Label) .ColorAndOpacity(Entry.bConflicted ? DiffViewUtils::Conflicting() : DiffViewUtils::Differs()); }; const auto FocusSCSDifferenceEntry = [](FSCSMergeEntry Entry, SMergeTreeView* Parent, FOnMergeNodeSelected InSelectionCallback) { InSelectionCallback.ExecuteIfBound(); Parent->HighlightDifference(Entry.Identifier, Entry.PropertyIdentifier); }; TArray< TSharedPtr<FBlueprintDifferenceTreeEntry> > Children; for ( const auto& Difference : Entries ) { auto Entry = TSharedPtr<FBlueprintDifferenceTreeEntry>( new FBlueprintDifferenceTreeEntry( FOnDiffEntryFocused::CreateStatic(FocusSCSDifferenceEntry, Difference, this, SelectionCallback) , FGenerateDiffEntryWidget::CreateStatic(CreateSCSMergeWidget, Difference) , TArray< TSharedPtr<FBlueprintDifferenceTreeEntry> >() ) ); Children.Push(Entry); OutRealDifferences.Push(Entry); if( Difference.bConflicted ) { OutConflicts.Push(Entry); } } DifferingProperties.Entries.Sort(SortTreePredicate); const auto ForwardSelection = [](FOnMergeNodeSelected InSelectionCallback) { // This allows the owning control to focus the correct tab (or do whatever else it likes): InSelectionCallback.ExecuteIfBound(); }; const bool bHasDiffferences = Children.Num() != 0; if( !bHasDiffferences ) { Children.Push( FBlueprintDifferenceTreeEntry::NoDifferencesEntry() ); } TSharedPtr<FBlueprintDifferenceTreeEntry> Category = FBlueprintDifferenceTreeEntry::CreateComponentsCategoryEntryForMerge( FOnDiffEntryFocused::CreateStatic(ForwardSelection, SelectionCallback) , Children , RemoteDifferingProperties.Entries.Num() != 0 , LocalDifferingProperties.Entries.Num() != 0 , bAnyConflict); OutTreeEntries.Push(Category); ChildSlot[ SNew(SSplitter) + SSplitter::Slot() [ GetRemoteView()->TreeWidget() ] + SSplitter::Slot() [ GetBaseView()->TreeWidget() ] + SSplitter::Slot() [ GetLocalView()->TreeWidget() ] ]; } void SMergeTreeView::HighlightDifference(FSCSIdentifier TreeIdentifier, FPropertySoftPath Property) { for (auto& View : SCSViews) { View->HighlightProperty(TreeIdentifier.Name, Property); } } TSharedRef<FSCSDiff>& SMergeTreeView::GetRemoteView() { return SCSViews[EMergeParticipant::Remote]; } TSharedRef<FSCSDiff>& SMergeTreeView::GetBaseView() { return SCSViews[EMergeParticipant::Base]; } TSharedRef<FSCSDiff>& SMergeTreeView::GetLocalView() { return SCSViews[EMergeParticipant::Local]; }
8,637
3,265
#include <iostream> using namespace std; int main() { double liczba; cout<<"Podaj liczbe (z zakresu 100-200): "; cin>>liczba; cout<<"Podana liczba jest "; if (liczba<150){ cout<<"mala"; } else if (liczba < 175){ cout<<"srednia"; } else { cout<<"duza"; } cout<<"."; return 0; }
347
147
/* Q Light Controller efxpreviewarea.cpp Copyright (c) Heikki Junnila 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.txt 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 <QPaintEvent> #include <QPainter> #include <QDebug> #include <QPen> #include "efxpreviewarea.h" #include "qlcmacros.h" #include "gradient.h" EFXPreviewArea::EFXPreviewArea(QWidget* parent) : QWidget(parent) , m_timer(this) , m_iter(0) , m_gradientBg(false) , m_bgAlpha(255) { QPalette p = palette(); p.setColor(QPalette::Window, p.color(QPalette::Base)); setPalette(p); connect(&m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout())); } EFXPreviewArea::~EFXPreviewArea() { } void EFXPreviewArea::setPolygon(const QPolygonF& polygon) { m_original = polygon; m_scaled = scale(m_original, size()); } int EFXPreviewArea::polygonsCount() const { return m_original.size(); } void EFXPreviewArea::setFixturePolygons(const QVector<QPolygonF> &fixturePoints) { m_originalFixturePoints.resize(fixturePoints.size()); m_fixturePoints.resize(fixturePoints.size()); for(int i = 0; i < m_fixturePoints.size(); ++i) { m_originalFixturePoints[i] = QPolygonF(fixturePoints[i]); m_fixturePoints[i] = scale(m_originalFixturePoints[i], size()); } } void EFXPreviewArea::draw(int timerInterval) { m_timer.stop(); m_iter = 0; m_timer.start(timerInterval); } void EFXPreviewArea::slotTimeout() { if (m_iter < m_scaled.size()) m_iter++; repaint(); } QPolygonF EFXPreviewArea::scale(const QPolygonF& poly, const QSize& target) { QPolygonF scaled; for (int i = 0; i < poly.size(); i++) { QPointF pt = poly.at(i); pt.setX((int) SCALE(qreal(pt.x()), qreal(0), qreal(255), qreal(0), qreal(target.width()))); pt.setY((int) SCALE(qreal(pt.y()), qreal(0), qreal(255), qreal(0), qreal(target.height()))); scaled << pt; } return scaled; } void EFXPreviewArea::resizeEvent(QResizeEvent* e) { m_scaled = scale(m_original, e->size()); for (int i = 0; i < m_fixturePoints.size(); ++i) m_fixturePoints[i] = scale(m_originalFixturePoints[i], e->size()); QWidget::resizeEvent(e); } void EFXPreviewArea::paintEvent(QPaintEvent* e) { QWidget::paintEvent(e); QPainter painter(this); QPen pen; QPointF point; QColor color = Qt::white; if (m_gradientBg) painter.drawImage(painter.window(), Gradient::getRGBGradient(256, 256)); else { color.setAlpha(m_bgAlpha); painter.fillRect(rect(), color); } /* Crosshairs */ color = palette().color(QPalette::Mid); painter.setPen(color); // Do division by two instead with a bitshift to prevent rounding painter.drawLine(width() >> 1, 0, width() >> 1, height()); painter.drawLine(0, height() >> 1, width(), height() >> 1); /* Plain points with text color */ color = palette().color(QPalette::Text); pen.setColor(color); painter.setPen(pen); painter.drawPolygon(m_scaled); // Draw the points from the point array if (m_iter < m_scaled.size() && m_iter >= 0) { painter.setBrush(Qt::white); pen.setColor(Qt::black); // drawing fixture positions from the end, // so that lower numbers are on top for (int i = m_fixturePoints.size() - 1; i >= 0; --i) { point = m_fixturePoints.at(i).at(m_iter); painter.drawEllipse(point, 8, 8); painter.drawText(point.x() - 4, point.y() + 5, QString::number(i+1)); } } else { //Change old behaviour from stop to restart restart(); } } void EFXPreviewArea::restart() { m_iter = 0; } void EFXPreviewArea::showGradientBackground(bool enable) { m_gradientBg = enable; repaint(); } void EFXPreviewArea::setBackgroundAlpha(int alpha) { m_bgAlpha = alpha; }
4,375
1,596
/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "seurat/geometry/quad_mesh.h" #include <vector> #include "ion/math/vector.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "seurat/base/color.h" namespace seurat { namespace geometry { namespace { using base::Color4f; using geometry::Quad3f; using image::Image4f; using ion::math::Point3f; // Test default constructor. TEST(QuadMeshTest, DefaultConstructor) { QuadMesh empty_quad_mesh; EXPECT_EQ(empty_quad_mesh.quads.size(), 0); EXPECT_EQ(empty_quad_mesh.textures.size(), 0); } // Test indexed constructor. TEST(QuadMeshTest, IndexedConstructor) { const Quad3f quad{{{0.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}}}; const std::array<float, 4> texcoord_w{{1.0f, 1.0f, 1.0f, 1.0f}}; const int kFirstTexture = 0; std::vector<IndexedQuad> quads; quads.push_back(IndexedQuad(quad, texcoord_w, kFirstTexture)); const Color4f kRed(1.0f, 0.0f, 0.0f, 1.0f); std::vector<Image4f> textures{{{2, 2}, kRed}}; QuadMesh single_quad_mesh{quads, textures}; EXPECT_EQ(single_quad_mesh.quads.size(), quads.size()); EXPECT_EQ(single_quad_mesh.textures.size(), textures.size()); } // Test indexed constructor catches errors. TEST(QuadMeshTest, IndexConstructorValidation) { const Quad3f quad{{{0.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}}}; const std::array<float, 4> texcoord_w{{1.0f, 1.0f, 1.0f, 1.0f}}; const int kNonExistentTexture = -1; std::vector<IndexedQuad> invalid_quads; invalid_quads.push_back(IndexedQuad(quad, texcoord_w, kNonExistentTexture)); const Color4f kRed(1.0f, 0.0f, 0.0f, 1.0f); std::vector<Image4f> textures{{{2, 2}, kRed}}; EXPECT_DEATH(QuadMesh(invalid_quads, textures), "non-existent texture"); } } // namespace } // namespace geometry } // namespace seurat
2,514
1,029
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* * $Id: AttrImpl.cpp 568078 2007-08-21 11:43:25Z amassari $ * * <p><b>WARNING</b>: Some of the code here is partially duplicated in * ParentNode, be careful to keep these two classes in sync! */ #include "AttrImpl.hpp" #include "DOM_DOMException.hpp" #include "DocumentImpl.hpp" #include "TextImpl.hpp" #include "ElementImpl.hpp" #include "DStringPool.hpp" #include "NodeIDMap.hpp" #include "RangeImpl.hpp" XERCES_CPP_NAMESPACE_BEGIN /* * The handling of the value field being either the first child node (a * ChildNode*) or directly the value (a DOMString) is rather tricky. In the * DOMString case we need to get the field in the right type so that the * compiler is happy and the appropriate operator gets called. This is * essential for the reference counts of the DOMStrings involved to be updated * as due. * This is consistently achieved by taking the address of the value field and * changing it into a DOMString*, and then dereferencing it to get a DOMString. * The typical piece of code is: * DOMString *x = (DomString *)&value; * ... use of *x which is the DOMString ... * This was amended by neilg after memory management was * introduced. Now a union exists which is either a * DOMString * or a ChildNode *. This will be less efficient * (one more dereference per access) but actually works on all the * compilers we support. */ AttrImpl::AttrImpl(DocumentImpl *ownerDoc, const DOMString &aName) : NodeImpl (ownerDoc) { name = aName.clone(); isSpecified(true); hasStringValue(true); value.child = null; }; AttrImpl::AttrImpl(const AttrImpl &other, bool /*deep*/) : NodeImpl(other) { name = other.name.clone(); isSpecified(other.isSpecified()); /* We must initialize the void* value to null in *all* cases. Failing to do * so would cause, in case of assignment to a DOMString later, its content * to be derefenced as a DOMString, which would lead the ref count code to * be called on something that is not actually a DOMString... Really bad * things would then happen!!! */ value.child = null; hasStringValue(other.hasStringValue()); if (other.isIdAttr()) { isIdAttr(true); this->getOwnerDocument()->getNodeIDMap()->add(this); } // take care of case where there are kids if (!hasStringValue()) { cloneChildren(other); } else { if(other.value.str == null) { if(value.str != null) { *(value.str) = null; delete value.str; value.str = null; } } else { // get the address of the value field of this as a DOMString* DOMString *x = (value.str == null ?(value.str = new (getOwnerDocument()->getMemoryManager()) DOMString()) :value.str ); // and the address of the value field of other as a DOMString* DOMString *y = other.value.str; // We can now safely do the cloning and assignement, both operands // being a DOMString their ref counts will be updated appropriately *x = y->clone(); } } }; AttrImpl::~AttrImpl() { if (hasStringValue()) { // if value is a DOMString we must make sure its ref count is updated. // this is achieved by changing the address of the value field into a // DOMString* and setting the value field to null if(value.str != null) { *(value.str) = null; delete value.str; value.str = null; } } } // create a real Text node as child if we don't have one yet void AttrImpl::makeChildNode() { if (hasStringValue()) { if (value.child != null) { // change the address of the value field into a DOMString* DOMString *x = (value.str == null ?(value.str = new (getOwnerDocument()->getMemoryManager()) DOMString()) :value.str ); // create a Text node passing the DOMString it points to TextImpl *text = (TextImpl *) getOwnerDocument()->createTextNode(*x); // get the DOMString ref count to be updated by setting the value // field to null *x = null; delete x; // finally reassign the value to the node address value.child = text; text->isFirstChild(true); text->previousSibling = text; text->ownerNode = this; text->isOwned(true); } hasStringValue(false); } } NodeImpl * AttrImpl::cloneNode(bool deep) { return new (getOwnerDocument()->getMemoryManager()) AttrImpl(*this, deep); }; DOMString AttrImpl::getNodeName() { return name; }; short AttrImpl::getNodeType() { return DOM_Node::ATTRIBUTE_NODE; }; DOMString AttrImpl::getName() { return name; }; DOMString AttrImpl::getNodeValue() { return getValue(); }; bool AttrImpl::getSpecified() { return isSpecified(); }; DOMString AttrImpl::getValue() { if (value.child == null) { return 0; // return ""; } if (hasStringValue()) { // change value into a DOMString* DOMString *x = (value.str == null ?(value.str = new (getOwnerDocument()->getMemoryManager()) DOMString()) :value.str ); // return the DOMString it points to return *x; } ChildNode *firstChild = value.child; ChildNode *node = firstChild->nextSibling; if (node == null) { return firstChild->getNodeValue().clone(); } int length = 0; for (node = firstChild; node != null; node = node->nextSibling) length += node->getNodeValue().length(); DOMString retString; retString.reserve(length); for (node = firstChild; node != null; node = node->nextSibling) { retString.appendData(node->getNodeValue()); }; return retString; }; bool AttrImpl::isAttrImpl() { return true; }; void AttrImpl::setNodeValue(const DOMString &val) { setValue(val); }; void AttrImpl::setSpecified(bool arg) { isSpecified(arg); }; void AttrImpl::setValue(const DOMString &newvalue) { if (isReadOnly()) { throw DOM_DOMException ( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null ); } // If this attribute was of type ID and in the map, take it out, // then put it back in with the new name. For now, we don't worry // about what happens if the new name conflicts // if (isIdAttr()) this->getOwnerDocument()->getNodeIDMap()->remove(this); if (!hasStringValue() && value.str != null) { NodeImpl *kid; while ((kid = value.child) != null) { // Remove existing kids removeChild(kid); if (kid->nodeRefCount == 0) NodeImpl::deleteIf(kid); } } // directly store the string as the value by changing the value field // into a DOMString DOMString *x = (value.str == null ?(value.str = new (getOwnerDocument()->getMemoryManager()) DOMString()) :value.str ); if (newvalue != null) { *x = newvalue.clone(); } else { *x = null; delete x; value.str = null; } hasStringValue(true); isSpecified(true); changed(); if (isIdAttr()) this->getOwnerDocument()->getNodeIDMap()->add(this); }; DOMString AttrImpl::toString() { DOMString retString; retString.appendData(name); retString.appendData(DOMString("=\"")); retString.appendData(getValue()); retString.appendData(DOMString("\"")); return retString; } //Introduced in DOM Level 2 ElementImpl *AttrImpl::getOwnerElement() { // if we have an owner, ownerNode is our ownerElement, otherwise it's // our ownerDocument and we don't have an ownerElement return (ElementImpl *) (isOwned() ? ownerNode : null); } //internal use by parser only void AttrImpl::setOwnerElement(ElementImpl *ownerElem) { ownerNode = ownerElem; isOwned(false); } // ParentNode stuff void AttrImpl::cloneChildren(const NodeImpl &other) { // for (NodeImpl *mykid = other.getFirstChild(); for (NodeImpl *mykid = ((NodeImpl&)other).getFirstChild(); mykid != null; mykid = mykid->getNextSibling()) { this->appendChild(mykid->cloneNode(true)); } } NodeListImpl *AttrImpl::getChildNodes() { return this; } NodeImpl * AttrImpl::getFirstChild() { makeChildNode(); return value.child; } NodeImpl * AttrImpl::getLastChild() { return lastChild(); } ChildNode * AttrImpl::lastChild() { // last child is stored as the previous sibling of first child makeChildNode(); return value.child != null ? (value.child)->previousSibling : null; } void AttrImpl::lastChild(ChildNode *node) { // store lastChild as previous sibling of first child if (value.child != null) { (value.child)->previousSibling = node; } } unsigned int AttrImpl::getLength() { if (hasStringValue()) { return 1; } ChildNode *node = value.child; int length = 0; while (node != null) { length++; node = node->nextSibling; } return length; } bool AttrImpl::hasChildNodes() { return value.child != null; }; NodeImpl *AttrImpl::insertBefore(NodeImpl *newChild, NodeImpl *refChild) { DocumentImpl *ownerDocument = getOwnerDocument(); bool errorChecking = ownerDocument->getErrorChecking(); if (newChild->isDocumentFragmentImpl()) { // SLOW BUT SAFE: We could insert the whole subtree without // juggling so many next/previous pointers. (Wipe out the // parent's child-list, patch the parent pointers, set the // ends of the list.) But we know some subclasses have special- // case behavior they add to insertBefore(), so we don't risk it. // This approch also takes fewer bytecodes. // NOTE: If one of the children is not a legal child of this // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children // have been transferred. (Alternative behaviors would be to // reparent up to the first failure point or reparent all those // which are acceptable to the target node, neither of which is // as robust. PR-DOM-0818 isn't entirely clear on which it // recommends????? // No need to check kids for right-document; if they weren't, // they wouldn't be kids of that DocFrag. if (errorChecking) { for (NodeImpl *kid = newChild->getFirstChild(); // Prescan kid != null; kid = kid->getNextSibling()) { if (!DocumentImpl::isKidOK(this, kid)) { throw DOM_DOMException( DOM_DOMException::HIERARCHY_REQUEST_ERR, null); } } } while (newChild->hasChildNodes()) { // Move insertBefore(newChild->getFirstChild(), refChild); } return newChild; } // it's a no-op if refChild is the same as newChild if (refChild == newChild) { return newChild; } if (errorChecking) { if (isReadOnly()) { throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); } if (newChild->getOwnerDocument() != ownerDocument) { throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null); } if (!DocumentImpl::isKidOK(this, newChild)) { throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR, null); } // refChild must be a child of this node (or null) if (refChild != null && refChild->getParentNode() != this) { throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null); } // Prevent cycles in the tree // newChild cannot be ancestor of this Node, // and actually cannot be this bool treeSafe = true; for (NodeImpl *a = this; treeSafe && a != null; a = a->getParentNode()) { treeSafe = (newChild != a); } if (!treeSafe) { throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR, null); } } makeChildNode(); // make sure we have a node and not a string // Convert to internal type, to avoid repeated casting ChildNode * newInternal = (ChildNode *)newChild; NodeImpl *oldparent = newInternal->getParentNode(); if (oldparent != null) { oldparent->removeChild(newInternal); } // Convert to internal type, to avoid repeated casting ChildNode *refInternal = (ChildNode *)refChild; // Attach up newInternal->ownerNode = this; newInternal->isOwned(true); // Attach before and after // Note: firstChild.previousSibling == lastChild!! ChildNode *firstChild = value.child; if (firstChild == null) { // this our first and only child value.child = newInternal; // firstChild = newInternal newInternal->isFirstChild(true); newInternal->previousSibling = newInternal; } else { if (refInternal == null) { // this is an append ChildNode *lastChild = firstChild->previousSibling; lastChild->nextSibling = newInternal; newInternal->previousSibling = lastChild; firstChild->previousSibling = newInternal; } else { // this is an insert if (refChild == firstChild) { // at the head of the list firstChild->isFirstChild(false); newInternal->nextSibling = firstChild; newInternal->previousSibling = firstChild->previousSibling; firstChild->previousSibling = newInternal; value.child = newInternal; // firstChild = newInternal; newInternal->isFirstChild(true); } else { // somewhere in the middle ChildNode *prev = refInternal->previousSibling; newInternal->nextSibling = refInternal; prev->nextSibling = newInternal; refInternal->previousSibling = newInternal; newInternal->previousSibling = prev; } } } changed(); if (this->getOwnerDocument() != null) { typedef RefVectorOf<RangeImpl> RangeImpls; RangeImpls* ranges = this->getOwnerDocument()->getRanges(); if ( ranges != null) { unsigned int sz = ranges->size(); for (unsigned int i =0; i<sz; i++) { ranges->elementAt(i)->updateRangeForInsertedNode(newInternal); } } } return newInternal; } NodeImpl *AttrImpl::item(unsigned int index) { if (hasStringValue()) { if (index != 0 || value.child == null) { return null; } else { makeChildNode(); return (NodeImpl *) (value.child); } } ChildNode *nodeListNode = value.child; for (unsigned int nodeListIndex = 0; nodeListIndex < index && nodeListNode != null; nodeListIndex++) { nodeListNode = nodeListNode->nextSibling; } return nodeListNode; } NodeImpl *AttrImpl::removeChild(NodeImpl *oldChild) { DocumentImpl *ownerDocument = getOwnerDocument(); if (ownerDocument->getErrorChecking()) { if (isReadOnly()) { throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); } if (oldChild == null || oldChild->getParentNode() != this) { throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null); } } // fix other ranges for change before deleting the node if (getOwnerDocument() != null) { typedef RefVectorOf<RangeImpl> RangeImpls; RangeImpls* ranges = this->getOwnerDocument()->getRanges(); if (ranges != null) { unsigned int sz = ranges->size(); if (sz != 0) { for (unsigned int i =0; i<sz; i++) { if (ranges->elementAt(i) != null) ranges->elementAt(i)->updateRangeForDeletedNode(oldChild); } } } } ChildNode * oldInternal = (ChildNode *) oldChild; // Patch linked list around oldChild // Note: lastChild == firstChild->previousSibling if (oldInternal == value.child) { // removing first child oldInternal->isFirstChild(false); value.child = oldInternal->nextSibling; // firstChild = oldInternal->nextSibling ChildNode *firstChild = value.child; if (firstChild != null) { firstChild->isFirstChild(true); firstChild->previousSibling = oldInternal->previousSibling; } } else { ChildNode *prev = oldInternal->previousSibling; ChildNode *next = oldInternal->nextSibling; prev->nextSibling = next; if (next == null) { // removing last child ChildNode *firstChild = value.child; firstChild->previousSibling = prev; } else { // removing some other child in the middle next->previousSibling = prev; } } // Remove oldInternal's references to tree oldInternal->ownerNode = getOwnerDocument(); oldInternal->isOwned(false); oldInternal->nextSibling = null; oldInternal->previousSibling = null; changed(); return oldInternal; }; NodeImpl *AttrImpl::replaceChild(NodeImpl *newChild, NodeImpl *oldChild) { insertBefore(newChild, oldChild); if (newChild != oldChild) { removeChild(oldChild); } // changed() already done. return oldChild; } void AttrImpl::setReadOnly(bool readOnl, bool deep) { NodeImpl::setReadOnly(readOnl, deep); if (deep) { if (hasStringValue()) { return; } // Recursively set kids for (ChildNode *mykid = value.child; mykid != null; mykid = mykid->nextSibling) if(! (mykid->isEntityReference())) mykid->setReadOnly(readOnl,true); } } //Introduced in DOM Level 2 void AttrImpl::normalize() { if (hasStringValue()) { return; } ChildNode *kid, *next; for (kid = value.child; kid != null; kid = next) { next = kid->nextSibling; // If kid and next are both Text nodes (but _not_ CDATASection, // which is a subclass of Text), they can be merged. if (next != null && kid->isTextImpl() && !(kid->isCDATASectionImpl()) && next->isTextImpl() && !(next->isCDATASectionImpl()) ) { ((TextImpl *) kid)->appendData(((TextImpl *) next)->getData()); removeChild(next); if (next->nodeRefCount == 0) deleteIf(next); next = kid; // Don't advance; there might be another. } // Otherwise it might be an Element, which is handled recursively else if (kid->isElementImpl()) kid->normalize(); }; // changed() will have occurred when the removeChild() was done, // so does not have to be reissued. }; XERCES_CPP_NAMESPACE_END
20,505
5,881
#include "PID.h" /** * TODO: Complete the PID class. You may add any additional desired functions. */ // -------------------------------------------------------------------------------------------------------------------- PID::PID() { i_steer_error_ = 0.0; i_throtle_error_ = 0.0; } // -------------------------------------------------------------------------------------------------------------------- PID::~PID() { } // -------------------------------------------------------------------------------------------------------------------- void PID::Init(double kp_steer, double ki_steer, double kd_steer, double kp_throtle, double ki_throtle, double kd_throtle) { kp_steer_ = kp_steer; ki_steer_ = ki_steer; kd_steer_ = kd_steer; i_steer_error_ = 0.0; kp_throtle_ = kp_throtle; ki_throtle_ = ki_throtle; kd_throtle_ = kd_throtle; i_throtle_error_ = 0.0; } // -------------------------------------------------------------------------------------------------------------------- void PID::UpdateSteerError(double cte, double delta_t) { p_steer_error_ = cte; d_steer_error_ = (cte - prev_steer_cte_) / delta_t; i_steer_error_ += cte; prev_steer_cte_ = cte; } // -------------------------------------------------------------------------------------------------------------------- double PID::TotalSteerError() { return -(kp_steer_ * p_steer_error_ + kd_steer_ * d_steer_error_ + ki_steer_ * i_steer_error_); } // -------------------------------------------------------------------------------------------------------------------- void PID::UpdateThrotleError(double speed, double target_speed, double delta_t) { double cte = speed - target_speed; p_throtle_error_ = cte; d_throtle_error_ = (cte - prev_throtle_cte_) / delta_t; i_throtle_error_ += cte; prev_throtle_cte_ = cte; } // -------------------------------------------------------------------------------------------------------------------- double PID::TotaThrotleError() { return -(kp_throtle_ * p_throtle_error_ + kd_throtle_ * d_throtle_error_ + ki_throtle_ * i_throtle_error_); } // --------------------------------------------------------------------------------------------------------------------
2,216
700
// // window.cpp // Author: Samuel Vargas // Date: 08/25/2019 // #include <iostream> #include "window.h" // https://learnopengl.com/In-Practice/Debugging void APIENTRY glDebugOutput(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, void *userParam) { // ignore non-significant error/warning codes if(id == 131169 || id == 131185 || id == 131218 || id == 131204) return; std::cout << "---------------" << std::endl; std::cout << "Debug message (" << id << "): " << message << std::endl; switch (source) { case GL_DEBUG_SOURCE_API: std::cout << "Source: API"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: std::cout << "Source: Window System"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER: std::cout << "Source: Shader Compiler"; break; case GL_DEBUG_SOURCE_THIRD_PARTY: std::cout << "Source: Third Party"; break; case GL_DEBUG_SOURCE_APPLICATION: std::cout << "Source: Application"; break; case GL_DEBUG_SOURCE_OTHER: std::cout << "Source: Other"; break; } std::cout << std::endl; switch (type) { case GL_DEBUG_TYPE_ERROR: std::cout << "Type: Error"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: std::cout << "Type: Deprecated Behaviour"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: std::cout << "Type: Undefined Behaviour"; break; case GL_DEBUG_TYPE_PORTABILITY: std::cout << "Type: Portability"; break; case GL_DEBUG_TYPE_PERFORMANCE: std::cout << "Type: Performance"; break; case GL_DEBUG_TYPE_MARKER: std::cout << "Type: Marker"; break; case GL_DEBUG_TYPE_PUSH_GROUP: std::cout << "Type: Push Group"; break; case GL_DEBUG_TYPE_POP_GROUP: std::cout << "Type: Pop Group"; break; case GL_DEBUG_TYPE_OTHER: std::cout << "Type: Other"; break; } std::cout << std::endl; switch (severity) { case GL_DEBUG_SEVERITY_HIGH: std::cout << "Severity: high"; break; case GL_DEBUG_SEVERITY_MEDIUM: std::cout << "Severity: medium"; break; case GL_DEBUG_SEVERITY_LOW: std::cout << "Severity: low"; break; case GL_DEBUG_SEVERITY_NOTIFICATION: std::cout << "Severity: notification"; break; } std::cout << std::endl; std::cout << std::endl; } Window::Window() { //SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Init GLFW3 window = glfwCreateWindow(1280, 720, "raytracer", nullptr, nullptr); if (window == nullptr) { throw std::runtime_error("Unable to init Window."); } glfwMakeContextCurrent(window); // Init GLEW if (glewInit() != GLEW_OK ){ throw std::runtime_error("Unable to init GLEW"); } int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glClearColor(1, 1, 1, 1); glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(reinterpret_cast<GLDEBUGPROC>(glDebugOutput), nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); } Window::~Window() { glfwDestroyWindow(window); } bool Window::shouldClose() { return glfwWindowShouldClose(window) == GLFW_TRUE; } void Window::clear() { glClearColor(0, 0, 0, 1); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); } GLFWwindow *Window::getWindowPointer() { return window; } void Window::swapBuffers() { glfwSwapBuffers(window); } // GLFW Callbacks void Window::onFrameBufferResize(GLFWwindow* window, int x, int y) { glViewport(0, 0, x, y); }
3,997
1,405
#include "EU4Leader.h" #include "../ID.h" #include "Log.h" #include "ParserHelpers.h" EU4::Leader::Leader(std::istream& theStream) { registerKeyword("name", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString nameString(theStream); name = nameString.getString(); }); registerKeyword("type", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString typeString(theStream); leaderType = typeString.getString(); }); registerKeyword("female", [this](const std::string& unused, std::istream& theStream) { commonItems::ignoreItem(unused, theStream); female = true; }); registerKeyword("manuever", [this](const std::string& unused, std::istream& theStream) { // don't fix PDX typo! const commonItems::singleInt theValue(theStream); maneuver = theValue.getInt(); }); registerKeyword("fire", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleInt theValue(theStream); fire = theValue.getInt(); }); registerKeyword("shock", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleInt theValue(theStream); shock = theValue.getInt(); }); registerKeyword("siege", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleInt theValue(theStream); siege = theValue.getInt(); }); registerKeyword("country", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString countryString(theStream); country = countryString.getString(); }); registerKeyword("activation", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString dateString(theStream); activationDate = date(dateString.getString()); }); registerKeyword("id", [this](const std::string& idType, std::istream& theStream) { const ID theID(theStream); leaderID = theID.getIDNum(); }); registerRegex("[a-zA-Z0-9_\\.:]+", commonItems::ignoreItem); parseStream(theStream); clearRegisteredKeywords(); } bool EU4::Leader::isLand() const { if (leaderType == "general" || leaderType == "conquistador") return true; if (leaderType == "explorer" || leaderType == "admiral") return false; LOG(LogLevel::Warning) << "Unknown leader type " << leaderType; return false; }
2,356
853
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/tracing_data.hpp" #include <cstdint> #include "caf/actor_system.hpp" #include "caf/deserializer.hpp" #include "caf/error.hpp" #include "caf/logger.hpp" #include "caf/sec.hpp" #include "caf/serializer.hpp" #include "caf/tracing_data_factory.hpp" namespace caf { tracing_data::~tracing_data() { // nop } namespace { template <class Serializer> auto inspect_impl(Serializer& sink, const tracing_data_ptr& x) { if (x == nullptr) { uint8_t dummy = 0; return sink(dummy); } uint8_t dummy = 1; if (auto err = sink(dummy)) return err; return x->serialize(sink); } template <class Deserializer> typename Deserializer::result_type inspect_impl(Deserializer& source, tracing_data_ptr& x) { uint8_t dummy = 0; if (auto err = source(dummy)) return err; if (dummy == 0) { x.reset(); return {}; } auto ctx = source.context(); if (ctx == nullptr) return sec::no_context; auto tc = ctx->system().tracing_context(); if (tc == nullptr) return sec::no_tracing_context; return tc->deserialize(source, x); } } // namespace error inspect(serializer& sink, const tracing_data_ptr& x) { return inspect_impl(sink, x); } error_code<sec> inspect(binary_serializer& sink, const tracing_data_ptr& x) { return inspect_impl(sink, x); } error inspect(deserializer& source, tracing_data_ptr& x) { return inspect_impl(source, x); } error_code<sec> inspect(binary_deserializer& source, tracing_data_ptr& x) { return inspect_impl(source, x); } } // namespace caf
2,885
889
/* * Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2008 Rob Buis <buis@kde.org> * Copyright (C) 2005, 2007 Eric Seidel <eric@webkit.org> * Copyright (C) 2009 Google, Inc. * Copyright (C) 2009 Dirk Schulze <krit@webkit.org> * Copyright (C) Research In Motion Limited 2010. All rights reserved. * Copyright (C) 2009 Jeff Schiller <codedread@gmail.com> * Copyright (C) 2011 Renata Hodovan <reni@webkit.org> * Copyright (C) 2011 University of Szeged * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "third_party/blink/renderer/core/layout/svg/layout_svg_shape.h" #include "third_party/blink/renderer/core/layout/hit_test_result.h" #include "third_party/blink/renderer/core/layout/pointer_events_hit_rules.h" #include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.h" #include "third_party/blink/renderer/core/layout/svg/layout_svg_root.h" #include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h" #include "third_party/blink/renderer/core/layout/svg/svg_resources.h" #include "third_party/blink/renderer/core/layout/svg/transform_helper.h" #include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h" #include "third_party/blink/renderer/core/paint/svg_shape_painter.h" #include "third_party/blink/renderer/core/svg/svg_geometry_element.h" #include "third_party/blink/renderer/core/svg/svg_length_context.h" #include "third_party/blink/renderer/platform/graphics/stroke_data.h" #include "third_party/blink/renderer/platform/wtf/math_extras.h" #include "ui/gfx/geometry/point_f.h" namespace blink { namespace { void ClampBoundsToFinite(gfx::RectF& bounds) { bounds.set_x(ClampTo<float>(bounds.x())); bounds.set_y(ClampTo<float>(bounds.y())); bounds.set_width(ClampTo<float>(bounds.width())); bounds.set_height(ClampTo<float>(bounds.height())); } } // namespace LayoutSVGShape::LayoutSVGShape(SVGGeometryElement* node, StrokeGeometryClass geometry_class) : LayoutSVGModelObject(node), // Geometry classification - used to compute stroke bounds more // efficiently. geometry_class_(geometry_class), // Default is false, the cached rects are empty from the beginning. needs_boundaries_update_(false), // Default is true, so we grab a Path object once from SVGGeometryElement. needs_shape_update_(true), // Default is true, so we grab a AffineTransform object once from // SVGGeometryElement. needs_transform_update_(true), transform_uses_reference_box_(false) {} LayoutSVGShape::~LayoutSVGShape() = default; void LayoutSVGShape::StyleDidChange(StyleDifference diff, const ComputedStyle* old_style) { NOT_DESTROYED(); LayoutSVGModelObject::StyleDidChange(diff, old_style); transform_uses_reference_box_ = TransformHelper::DependsOnReferenceBox(StyleRef()); SVGResources::UpdatePaints(*GetElement(), old_style, StyleRef()); // Most of the stroke attributes (caps, joins, miters, width, etc.) will cause // a re-layout which will clear the stroke-path cache; however, there are a // couple of additional properties that *won't* cause a layout, but are // significant enough to require invalidating the cache. if (!diff.NeedsFullLayout() && old_style && stroke_path_cache_) { const ComputedStyle& style = StyleRef(); if (old_style->StrokeDashOffset() != style.StrokeDashOffset() || *old_style->StrokeDashArray() != *style.StrokeDashArray()) { stroke_path_cache_.reset(); } } SetTransformAffectsVectorEffect(HasNonScalingStroke()); } void LayoutSVGShape::WillBeDestroyed() { NOT_DESTROYED(); SVGResources::ClearPaints(*GetElement(), Style()); LayoutSVGModelObject::WillBeDestroyed(); } void LayoutSVGShape::ClearPath() { NOT_DESTROYED(); path_.reset(); stroke_path_cache_.reset(); } void LayoutSVGShape::CreatePath() { NOT_DESTROYED(); if (!path_) path_ = std::make_unique<Path>(); *path_ = To<SVGGeometryElement>(GetElement())->AsPath(); // When the path changes, we need to ensure the stale stroke path cache is // cleared. Because this is done in all callsites, we can just DCHECK that it // has been cleared here. DCHECK(!stroke_path_cache_); } float LayoutSVGShape::DashScaleFactor() const { NOT_DESTROYED(); if (!StyleRef().HasDashArray()) return 1; return To<SVGGeometryElement>(*GetElement()).PathLengthScaleFactor(); } void LayoutSVGShape::UpdateShapeFromElement() { NOT_DESTROYED(); CreatePath(); fill_bounding_box_ = GetPath().TightBoundingRect(); ClampBoundsToFinite(fill_bounding_box_); if (HasNonScalingStroke()) { // NonScalingStrokeTransform may depend on LocalTransform which in turn may // depend on ObjectBoundingBox, thus we need to call them in this order. local_transform_ = CalculateLocalTransform(); UpdateNonScalingStrokeData(); } stroke_bounding_box_ = CalculateStrokeBoundingBox(); } namespace { bool HasMiterJoinStyle(const ComputedStyle& style) { return style.JoinStyle() == kMiterJoin; } bool HasSquareCapStyle(const ComputedStyle& style) { return style.CapStyle() == kSquareCap; } } // namespace gfx::RectF LayoutSVGShape::ApproximateStrokeBoundingBox( const gfx::RectF& shape_bounds) const { NOT_DESTROYED(); gfx::RectF stroke_box = shape_bounds; // Implementation of // https://drafts.fxtf.org/css-masking/#compute-stroke-bounding-box // except that we ignore whether the stroke is none. const float stroke_width = StrokeWidth(); if (stroke_width <= 0) return stroke_box; float delta = stroke_width / 2; if (geometry_class_ != kSimple) { const ComputedStyle& style = StyleRef(); if (geometry_class_ != kNoMiters && HasMiterJoinStyle(style)) { const float miter = style.StrokeMiterLimit(); if (miter < M_SQRT2 && HasSquareCapStyle(style)) delta *= M_SQRT2; else delta *= std::max(miter, 1.0f); } else if (HasSquareCapStyle(style)) { delta *= M_SQRT2; } } stroke_box.Outset(delta); return stroke_box; } gfx::RectF LayoutSVGShape::HitTestStrokeBoundingBox() const { NOT_DESTROYED(); if (StyleRef().HasStroke()) return stroke_bounding_box_; return ApproximateStrokeBoundingBox(fill_bounding_box_); } bool LayoutSVGShape::ShapeDependentStrokeContains( const HitTestLocation& location) { NOT_DESTROYED(); if (!stroke_path_cache_) { // In case the subclass didn't create path during UpdateShapeFromElement() // for optimization but still calls this method. if (!HasPath()) CreatePath(); StrokeData stroke_data; SVGLayoutSupport::ApplyStrokeStyleToStrokeData(stroke_data, StyleRef(), *this, DashScaleFactor()); if (HasNonScalingStroke()) { // The reason is similar to the above code about HasPath(). if (!rare_data_) UpdateNonScalingStrokeData(); // Un-scale to get back to the root-transform (cheaper than re-computing // the root transform from scratch). AffineTransform root_transform; root_transform.Scale(StyleRef().EffectiveZoom()) .Multiply(NonScalingStrokeTransform()); stroke_path_cache_ = std::make_unique<Path>( NonScalingStrokePath().StrokePath(stroke_data, root_transform)); } else { stroke_path_cache_ = std::make_unique<Path>( path_->StrokePath(stroke_data, ComputeRootTransform())); } } DCHECK(stroke_path_cache_); auto point = location.TransformedPoint(); if (HasNonScalingStroke()) point = NonScalingStrokeTransform().MapPoint(point); return stroke_path_cache_->Contains(point); } bool LayoutSVGShape::ShapeDependentFillContains( const HitTestLocation& location, const WindRule fill_rule) const { NOT_DESTROYED(); return GetPath().Contains(location.TransformedPoint(), fill_rule); } static bool HasPaintServer(const LayoutObject& object, const SVGPaint& paint) { if (paint.HasColor()) return true; if (paint.HasUrl()) { SVGResourceClient* client = SVGResources::GetClient(object); if (GetSVGResourceAsType<LayoutSVGResourcePaintServer>(*client, paint.Resource())) return true; } return false; } bool LayoutSVGShape::FillContains(const HitTestLocation& location, bool requires_fill, const WindRule fill_rule) { NOT_DESTROYED(); if (!fill_bounding_box_.InclusiveContains(location.TransformedPoint())) return false; if (requires_fill && !HasPaintServer(*this, StyleRef().FillPaint())) return false; return ShapeDependentFillContains(location, fill_rule); } bool LayoutSVGShape::StrokeContains(const HitTestLocation& location, bool requires_stroke) { NOT_DESTROYED(); // "A zero value causes no stroke to be painted." if (StyleRef().StrokeWidth().IsZero()) return false; if (requires_stroke) { if (!StrokeBoundingBox().InclusiveContains(location.TransformedPoint())) return false; if (!HasPaintServer(*this, StyleRef().StrokePaint())) return false; } else if (!HitTestStrokeBoundingBox().InclusiveContains( location.TransformedPoint())) { return false; } return ShapeDependentStrokeContains(location); } void LayoutSVGShape::UpdateLayout() { NOT_DESTROYED(); // The cached stroke may be affected by the ancestor transform, and so needs // to be cleared regardless of whether the shape or bounds have changed. stroke_path_cache_.reset(); bool update_parent_boundaries = false; bool bbox_changed = false; // UpdateShapeFromElement() also updates the object & stroke bounds - which // feeds into the visual rect - so we need to call it for both the // shape-update and the bounds-update flag. // We also need to update stroke bounds if HasNonScalingStroke() because the // shape may be affected by ancestor transforms. if (needs_shape_update_ || needs_boundaries_update_ || HasNonScalingStroke()) { gfx::RectF old_object_bounding_box = ObjectBoundingBox(); UpdateShapeFromElement(); if (old_object_bounding_box != ObjectBoundingBox()) { SetShouldDoFullPaintInvalidation(); bbox_changed = true; } needs_shape_update_ = false; needs_boundaries_update_ = false; update_parent_boundaries = true; } // Invalidate all resources of this client if our reference box changed. if (EverHadLayout() && bbox_changed) { SVGResourceInvalidator resource_invalidator(*this); resource_invalidator.InvalidateEffects(); resource_invalidator.InvalidatePaints(); } if (!needs_transform_update_ && transform_uses_reference_box_) { needs_transform_update_ = CheckForImplicitTransformChange(bbox_changed); if (needs_transform_update_) SetNeedsPaintPropertyUpdate(); } if (needs_transform_update_) { local_transform_ = CalculateLocalTransform(); needs_transform_update_ = false; update_parent_boundaries = true; } // If our bounds changed, notify the parents. if (update_parent_boundaries) LayoutSVGModelObject::SetNeedsBoundariesUpdate(); DCHECK(!needs_shape_update_); DCHECK(!needs_boundaries_update_); DCHECK(!needs_transform_update_); ClearNeedsLayout(); } AffineTransform LayoutSVGShape::ComputeRootTransform() const { NOT_DESTROYED(); const LayoutObject* root = this; while (root && !root->IsSVGRoot()) root = root->Parent(); return LocalToAncestorTransform(To<LayoutSVGRoot>(root)).ToAffineTransform(); } AffineTransform LayoutSVGShape::ComputeNonScalingStrokeTransform() const { NOT_DESTROYED(); // Compute the CTM to the SVG root. This should probably be the CTM all the // way to the "canvas" of the page ("host" coordinate system), but with our // current approach of applying/painting non-scaling-stroke, that can break in // unpleasant ways (see crbug.com/747708 for an example.) Maybe it would be // better to apply this effect during rasterization? AffineTransform host_transform; host_transform.Scale(1 / StyleRef().EffectiveZoom()) .Multiply(ComputeRootTransform()); // Width of non-scaling stroke is independent of translation, so zero it out // here. host_transform.SetE(0); host_transform.SetF(0); return host_transform; } void LayoutSVGShape::UpdateNonScalingStrokeData() { NOT_DESTROYED(); DCHECK(HasNonScalingStroke()); const AffineTransform transform = ComputeNonScalingStrokeTransform(); auto& rare_data = EnsureRareData(); if (rare_data.non_scaling_stroke_transform_ != transform) { SetShouldDoFullPaintInvalidation(PaintInvalidationReason::kStyle); rare_data.non_scaling_stroke_transform_ = transform; } rare_data.non_scaling_stroke_path_ = *path_; rare_data.non_scaling_stroke_path_.Transform(transform); } void LayoutSVGShape::Paint(const PaintInfo& paint_info) const { NOT_DESTROYED(); SVGShapePainter(*this).Paint(paint_info); } bool LayoutSVGShape::NodeAtPoint(HitTestResult& result, const HitTestLocation& hit_test_location, const PhysicalOffset& accumulated_offset, HitTestAction hit_test_action) { NOT_DESTROYED(); DCHECK_EQ(accumulated_offset, PhysicalOffset()); // We only draw in the foreground phase, so we only hit-test then. if (hit_test_action != kHitTestForeground) return false; if (IsShapeEmpty()) return false; const ComputedStyle& style = StyleRef(); const PointerEventsHitRules hit_rules( PointerEventsHitRules::kSvgGeometryHitTesting, result.GetHitTestRequest(), style.UsedPointerEvents()); if (hit_rules.require_visible && style.Visibility() != EVisibility::kVisible) return false; TransformedHitTestLocation local_location(hit_test_location, LocalToSVGParentTransform()); if (!local_location) return false; if (!SVGLayoutSupport::IntersectsClipPath(*this, fill_bounding_box_, *local_location)) return false; if (HitTestShape(result.GetHitTestRequest(), *local_location, hit_rules)) { UpdateHitTestResult(result, PhysicalOffset::FromPointFRound( local_location->TransformedPoint())); if (result.AddNodeToListBasedTestResult(GetElement(), *local_location) == kStopHitTesting) return true; } return false; } bool LayoutSVGShape::HitTestShape(const HitTestRequest& request, const HitTestLocation& local_location, PointerEventsHitRules hit_rules) { NOT_DESTROYED(); if (hit_rules.can_hit_bounding_box && local_location.Intersects(ObjectBoundingBox())) return true; // TODO(chrishtr): support rect-based intersections in the cases below. const ComputedStyle& style = StyleRef(); if (hit_rules.can_hit_stroke && (style.HasStroke() || !hit_rules.require_stroke) && StrokeContains(local_location, hit_rules.require_stroke)) return true; WindRule fill_rule = style.FillRule(); if (request.SvgClipContent()) fill_rule = style.ClipRule(); if (hit_rules.can_hit_fill && (style.HasFill() || !hit_rules.require_fill) && FillContains(local_location, hit_rules.require_fill, fill_rule)) return true; return false; } gfx::RectF LayoutSVGShape::CalculateStrokeBoundingBox() const { NOT_DESTROYED(); if (!StyleRef().HasStroke() || IsShapeEmpty()) return fill_bounding_box_; if (HasNonScalingStroke()) return CalculateNonScalingStrokeBoundingBox(); return ApproximateStrokeBoundingBox(fill_bounding_box_); } gfx::RectF LayoutSVGShape::CalculateNonScalingStrokeBoundingBox() const { NOT_DESTROYED(); DCHECK(path_); DCHECK(StyleRef().HasStroke()); DCHECK(HasNonScalingStroke()); gfx::RectF stroke_bounding_box = fill_bounding_box_; const auto& non_scaling_transform = NonScalingStrokeTransform(); if (non_scaling_transform.IsInvertible()) { gfx::RectF stroke_bounding_rect = ApproximateStrokeBoundingBox(NonScalingStrokePath().BoundingRect()); stroke_bounding_rect = non_scaling_transform.Inverse().MapRect(stroke_bounding_rect); stroke_bounding_box.Union(stroke_bounding_rect); } return stroke_bounding_box; } float LayoutSVGShape::StrokeWidth() const { NOT_DESTROYED(); SVGLengthContext length_context(GetElement()); return length_context.ValueForLength(StyleRef().StrokeWidth()); } float LayoutSVGShape::StrokeWidthForMarkerUnits() const { NOT_DESTROYED(); float stroke_width = StrokeWidth(); if (HasNonScalingStroke()) { const auto& non_scaling_transform = NonScalingStrokeTransform(); if (!non_scaling_transform.IsInvertible()) return 0; float scale_factor = ClampTo<float>(sqrt((non_scaling_transform.XScaleSquared() + non_scaling_transform.YScaleSquared()) / 2)); stroke_width /= scale_factor; } return stroke_width; } LayoutSVGShapeRareData& LayoutSVGShape::EnsureRareData() const { NOT_DESTROYED(); if (!rare_data_) rare_data_ = std::make_unique<LayoutSVGShapeRareData>(); return *rare_data_.get(); } RasterEffectOutset LayoutSVGShape::VisualRectOutsetForRasterEffects() const { NOT_DESTROYED(); // Account for raster expansions due to SVG stroke hairline raster effects. const ComputedStyle& style = StyleRef(); if (style.HasVisibleStroke()) { if (style.CapStyle() != kButtCap) return RasterEffectOutset::kWholePixel; return RasterEffectOutset::kHalfPixel; } return RasterEffectOutset::kNone; } } // namespace blink
18,587
5,918
#include <unistd.h> //This allows the program to run on Linux/Unix systems #include <iostream> #include <cstdlib> //The cstdlib library adds the 'sleep' function using namespace std; int main() { int w, wl; // w will be the weight in kilograms, wl will be the weight in pounds string select; cout << "Would you like to use pounds, or kilograms? Input 'lbs' or 'kg'" << endl; cin >> select; cout << "Enter your weight "; cin >> w; //The user inputs the variable's value if( select == "lbs") w = w/2; // We convert pounds to kilos else if ( select == "kg") w = w; // If the user chose kilos, we change nothing. else { while ( 1>0) { //Our program enters a loop, that lasts forever { cout.flush(); sleep(1); //The program is put on hold for a given amout of time, in this instance one second cout << "ERROR 0001. WEIGHT UNIT DOES NOT EXIST"; } } cout << "Calculating"; for(int a=0; a<7; a++) //Our program enters a loop { cout.flush(); sleep(1); //The program is put on hold for a given amout of time, in this instance one second cout << "."; } cout<< "ur fat" << endl; //The program exits the loop and prints the final text, after which the program returns 0 and terminates return 0; } //Enjoy
1,260
415
#ifndef SAMPLES_LIB_WINDOW_H #define SAMPLES_LIB_WINDOW_H #include <framework/framework.hpp> namespace sampleslib { template<vg::SpaceType type> struct SpaceObjectInfo { using SceneType = void; using CameraType = void; }; template<> struct SpaceObjectInfo<vg::SpaceType::SPACE_2> { using SceneType = vg::Scene2; using CameraType = vg::CameraOP2; }; template<> struct SpaceObjectInfo<vg::SpaceType::SPACE_3> { using SceneType = vg::Scene3; using CameraType = vg::Camera3; }; template <vg::SpaceType SPACE_TYPE> class Window : public vgf::Window { public: using PointType = typename vg::SpaceTypeInfo<SPACE_TYPE>::PointType; using RotationType = typename vg::SpaceTypeInfo<SPACE_TYPE>::RotationType; using RotationDimType = typename vg::SpaceTypeInfo<SPACE_TYPE>::RotationDimType; using SceneType = typename SpaceObjectInfo<SPACE_TYPE>::SceneType; using CameraType = typename SpaceObjectInfo<SPACE_TYPE>::CameraType; using TimePointType = typename std::chrono::time_point<std::chrono::steady_clock>; Window(uint32_t width , uint32_t height , const char* title ); Window(std::shared_ptr<GLFWwindow> pWindow , std::shared_ptr<vk::SurfaceKHR> pSurface ); protected: float m_rotationSpeed; TimePointType m_startTimeFrame; TimePointType m_endTimeFrame; bool m_isPause; /** * Costing time of per frame (s) */ float m_frameTimer; /** * Passed time since starting application (s) **/ float m_passedTime; /** * The speed of time advaced [0, 1] **/ float m_timerSpeedFactor; uint32_t m_fpsTimer; uint32_t m_frameCounter; uint32_t m_lastFPS; uint32_t m_lastDrawCount; vg::Vector2 m_lastWinPos; vg::Vector2 m_lastWinSize; float m_cameraZoom; float m_cameraZoomSpeed; float m_cameraAspect; PointType m_cameraPosition; RotationDimType m_cameraRotation; RotationDimType m_worldRotation; struct { vgf::Bool32 left = VGF_FALSE; vgf::Bool32 right = VGF_FALSE; vgf::Bool32 middle = VGF_FALSE; } m_mouseButtons; double m_mousePos[2]; uint32_t m_sceneCount; std::vector<std::shared_ptr<SceneType>> m_pScenes; std::shared_ptr<SceneType> m_pScene; std::shared_ptr<CameraType> m_pCamera; vg::Bool32 m_preDepthScene; virtual void _onResize() override; virtual void _onPreReCreateSwapchain() override; virtual void _onPostReCreateSwapchain() override; virtual void _onPreUpdate() override; virtual void _onUpdate() override; virtual void _onPostUpdate() override; virtual void _onPreDraw() override; virtual void _onDraw() override; virtual void _onPostDraw() override; static std::vector<vg::Renderer::SceneInfo> mySceneInfos; virtual void _onPreRender(vg::Renderer::RenderInfo &info , vg::Renderer::RenderResultInfo &resultInfo) override; virtual void _onRender(vg::Renderer::RenderInfo &info , vg::Renderer::RenderResultInfo &resultInfo) override; virtual void _onPostRender(vg::Renderer::RenderInfo &info , vg::Renderer::RenderResultInfo &resultInfo) override; virtual void _init(); virtual void _initState(); private: void _createCamera(); void _createScene(); void _initUI(); void _initInputHanders(); void _updateCamera(); }; } #include "sampleslib/window.inl" #endif // !SAMPLES_LIB_WINDOW_H
3,896
1,214
#include <GBAemu/cpu/hostInstructions.h> #include <GBAemu/cpu/cpu.h> #include <GBAemu/cpu/armException.h> #include <GBAemu/gba.h> #include <GBAemu/util/log.h> #include <GBAemu/defines.h> #include <GBAemu/util/preprocessor.h> // 001xxxxxxxxx uint32_t Cpu::GetShifterOperandImm(uint32_t instruction) { uint32_t operand = instruction & 0xFF; uint8_t rotateImm = (instruction >> 8) & 0xF; if (rotateImm == 0) { return operand; } else { ROR(operand, rotateImm * 2, operand); } return operand; } uint32_t Cpu::GetShifterOperandLSL(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t shift = (instruction >> 7) & 0x1F; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; LSL(_registers[rm], shift, operand); return operand; } } uint32_t Cpu::GetShifterOperandLSLReg(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint32_t shift = _registers[rs]; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; LSL(_registers[rm], shift, operand); return operand; } } uint32_t Cpu::GetShifterOperandLSR(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t shift = (instruction >> 7) & 0x1F; if (shift == 0) { shift = 32; } uint32_t operand; LSR(_registers[rm], shift, operand); return operand; } uint32_t Cpu::GetShifterOperandLSRReg(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t shift = _registers[rs]; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; LSR(_registers[rm], shift, operand); return operand; } } uint32_t Cpu::GetShifterOperandASR(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t shift = (instruction >> 7) & 0x1F; if (shift == 0) { shift = 32; } uint32_t operand; ASR(_registers[rm], shift, operand); return operand; } uint32_t Cpu::GetShifterOperandASRReg(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t shift = _registers[rs]; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; ASR(_registers[rm], shift, operand); return operand; } } uint32_t Cpu::GetShifterOperandROR(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t shift = (instruction >> 7) & 0x1F; uint32_t operand; if (shift == 0) { RRX(_registers[rm], 1, operand, _hostFlags); } else { ROR(_registers[rm], shift, operand); } return operand; } uint32_t Cpu::GetShifterOperandRORReg(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t shift = _registers[rs]; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; ROR(_registers[rm], shift, operand); return operand; } } // 001xxxxxxxxx uint32_t Cpu::GetShifterOperandImmFlags(uint32_t instruction) { uint32_t operand = instruction & 0xFF; uint8_t rotateImm = (instruction >> 8) & 0xF; if (rotateImm == 0) { return operand; } else { ROR_CFLAG(operand, rotateImm * 2, operand, _hostFlags); } return operand; } uint32_t Cpu::GetShifterOperandLSLFlags(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t shift = (instruction >> 7) & 0x1F; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; LSL_CFLAG(_registers[rm], shift, operand, _hostFlags); return operand; } } uint32_t Cpu::GetShifterOperandLSLRegFlags(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint32_t shift = _registers[rs]; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; LSL_CFLAG(_registers[rm], shift, operand, _hostFlags); return operand; } } uint32_t Cpu::GetShifterOperandLSRFlags(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t shift = (instruction >> 7) & 0x1F; if (shift == 0) { shift = 32; } uint32_t operand; LSR_CFLAG(_registers[rm], shift, operand, _hostFlags); return operand; } uint32_t Cpu::GetShifterOperandLSRRegFlags(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t shift = _registers[rs]; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; LSR_CFLAG(_registers[rm], shift, operand, _hostFlags); return operand; } } uint32_t Cpu::GetShifterOperandASRFlags(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t shift = (instruction >> 7) & 0x1F; if (shift == 0) { shift = 32; } uint32_t operand; ASR_CFLAG(_registers[rm], shift, operand, _hostFlags); return operand; } uint32_t Cpu::GetShifterOperandASRRegFlags(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t shift = _registers[rs]; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; ASR_CFLAG(_registers[rm], shift, operand, _hostFlags); return operand; } } uint32_t Cpu::GetShifterOperandRORFlags(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t shift = (instruction >> 7) & 0x1F; uint32_t operand; if (shift == 0) { RRX_CFLAG(_registers[rm], 1, operand, _hostFlags); } else { ROR_CFLAG(_registers[rm], shift, operand, _hostFlags); } return operand; } uint32_t Cpu::GetShifterOperandRORRegFlags(uint32_t instruction) { uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t shift = _registers[rs]; if (shift == 0) { return _registers[rm]; } else { uint32_t operand; ROR_CFLAG(_registers[rm], shift, operand, _hostFlags); return operand; } } void Cpu::TickARM(bool step) { uint32_t instruction = _pipelineInstruction; _pipelineInstruction = _system._memory.Read32(_registers[REGPC] & 0xFFFFFFFC); if (step && IsBreakpoint(_registers[REGPC] - 4)) { instruction = _breakpoints.at(_registers[REGPC] - 4); } _registers[REGPC] += 4; uint8_t cond = instruction >> 28; if (!IsConditionMet(cond, _hostFlags)) { return; } uint16_t code = ((instruction >> 4) & 0xF) | (((instruction >> 20) & 0xFF) << 4); switch (code) { // ADC case 0x0A8: case 0x0A0: {// ADC <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0A1: { // ADC <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0AA: case 0x0A2: { // ADC <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0A3: { // ADC <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0AC: case 0x0A4: { // ADC <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0A5: { // ADC <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0AE: case 0x0A6: { // ADC <Rd>, <Rn>, <Rm>, ROR #<imm> // ADC <Rd>, <Rn>, <Rm>, RRX uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0A7: { // ADC <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0B8: case 0x0B0: {// ADCS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLFlags(instruction); if (rd == REGPC) { ADC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0B1: { // ADCS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0BA: case 0x0B2: { // ADCS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0B3: { // ADCS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0BC: case 0x0B4: { // ADCS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0B5: { // ADCS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0BE: case 0x0B6: { // ADCS <Rd>, <Rn>, <Rm>, ROR #<imm> // ADCS <Rd>, <Rn>, <Rm>, RRX uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0B7: { // ADCS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x2A0) { // ADC <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x2B0) { // ADC <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); ADC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); ADC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // ADD case 0x080: case 0x088: { // ADD <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); ADD(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x081: { // ADD <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); ADD(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x082: case 0x08A: { // ADD <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); ADD(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x083: { // ADD <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); ADD(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x084: case 0x08C: { // ADD <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); ADD(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x085: { // ADD <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); ADD(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x086: // ADD <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x08E: { // ADD <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); ADD(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x087: { // ADD <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); ADD(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x090: case 0x098: { // ADDS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); ADD(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x091: { // ADDS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); ADD(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x092: case 0x09A: { // ADDS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); ADD(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x093: { // ADDS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); ADD(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x094: case 0x09C: { // ADDS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); ADD(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x095: { // ADDS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); ADD(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x096: // ADDS <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x09E: { // ADDS <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); ADD(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x097: { // ADDS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); ADD(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x280) { // ADD <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); ADD(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x290) { // ADDS <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); ADD(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); ADD_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // AND case 0x000: case 0x008: { // AND <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); AND(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x001: { // AND <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); AND(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x002: case 0x00A: { // AND <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); AND(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x003: { // AND <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); AND(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x004: case 0x00C: { // AND <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); AND(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x005: { // AND <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); AND(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x006: // AND <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x00E: { // AND <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); AND(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x007: { // AND <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); AND(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x010: case 0x018: { // ANDS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); AND(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); } break; } case 0x011: { // ANDS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); AND(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x012: case 0x01A: { // ANDS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); AND(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x013: { // ANDS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); AND(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x014: case 0x01C: { // ANDS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); AND(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x015: { // ANDS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); AND(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x016: // ANDS <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x01E: { // ANDS <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); AND(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x017: { // ANDS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); AND(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x200) { // AND <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); AND(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x210) { // ANDS <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); AND(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); AND_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // B CASE_RANGE256(0xA00) { // B <target_address> uint32_t address = instruction & 0xFFFFFF; if ((address & 0x00800000) != 0) address |= 0xFF000000; address <<= 2; _registers[REGPC] += address; _pipelineInstruction = ARM_NOP; break; } // BL CASE_RANGE256(0xB00) { // BL <target_address> uint32_t address = instruction & 0xFFFFFF; if ((address & 0x00800000) != 0) address |= 0xFF000000; address <<= 2; _registers[REGLR] = _registers[REGPC] - 4; _registers[REGPC] += address; _pipelineInstruction = ARM_NOP; break; } // BIC case 0x1C0: case 0x1C8: { // BIC <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); BIC(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1C1: { // BIC <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); BIC(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1C2: case 0x1CA: { // BIC <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); BIC(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1C3: { // BIC <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); BIC(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1C4: case 0x1CC: { // BIC <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); BIC(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1C5: { // BIC <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); BIC(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1C6: // BIC <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x1CE: { // BIC <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); BIC(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1C7: { // BIC <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); BIC(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1D0: case 0x1D8: { // BICS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); BIC(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1D1: { // BICS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); BIC(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1D2: case 0x1DA: { // BICS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); BIC(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1D3: { // BICS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); BIC(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1D4: case 0x1DC: { // BICS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); BIC(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1D5: { // BICS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); BIC(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1D6: // BICS <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x1DE: { // BICS <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); BIC(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1D7: { // BICS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); BIC(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x3C0) { // BIC <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); BIC(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x3D0) { // BICS <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); BIC(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); BIC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // BKPT case 0x127: { // BKPT <imm_16> uint16_t imm = instruction & 0xF; imm |= (instruction >> 4) & 0xFFF0; throw BreakPointARMException(imm); break; } // BX case 0x121: { // BX <Rm> uint8_t rm = instruction & 0xF; uint32_t address = _registers[rm]; SetThumbMode((address & 0x1) != 0); _registers[REGPC] = address & 0xFFFFFFFE; _pipelineInstruction = ARM_NOP; break; } CASE_RANGE128_OFFSET(0xE00, 1) { // CDP <coproc>, <opcode_1>, <CRd>, <CRn>, <CRm>, <opcode_2> Log(Warn, "Coprocessor instruction found. Not supported."); __debugbreak(); break; } // CMN case 0x170: case 0x178: { // CMN <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSLFlags(instruction); CMN(_registers[rn], operand, _hostFlags); break; } case 0x171: { // CMN <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSLRegFlags(instruction); CMN(_registers[rn], operand, _hostFlags); break; } case 0x172: case 0x17A: { // CMN <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSRFlags(instruction); CMN(_registers[rn], operand, _hostFlags); break; } case 0x173: { // CMN <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSRRegFlags(instruction); CMN(_registers[rn], operand, _hostFlags); break; } case 0x174: case 0x17C: { // CMN <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandASRFlags(instruction); CMN(_registers[rn], operand, _hostFlags); break; } case 0x175: { // CMN <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandASRRegFlags(instruction); CMN(_registers[rn], operand, _hostFlags); break; } case 0x176: // CMN <Rn>, <Rm>, RRX #<imm> case 0x17E: { // CMN <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandRORFlags(instruction); CMN(_registers[rn], operand, _hostFlags); break; } case 0x177: { // CMN <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORRegFlags(instruction); CMN(_registers[rn], operand, _hostFlags); break; } CASE_RANGE16(0x370) { // CMN <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandImmFlags(instruction); CMN(_registers[rn], operand, _hostFlags); break; } // CMP case 0x150: case 0x158: { // CMP <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSLFlags(instruction); CMP(_registers[rn], operand, _hostFlags); break; } case 0x151: { // CMP <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSLRegFlags(instruction); CMP(_registers[rn], operand, _hostFlags); break; } case 0x152: case 0x15A: { // CMP <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSRFlags(instruction); CMP(_registers[rn], operand, _hostFlags); break; } case 0x153: { // CMP <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSRRegFlags(instruction); CMP(_registers[rn], operand, _hostFlags); break; } case 0x154: case 0x15C: { // CMP <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandASRFlags(instruction); CMP(_registers[rn], operand, _hostFlags); break; } case 0x155: { // CMP <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandASRRegFlags(instruction); CMP(_registers[rn], operand, _hostFlags); break; } case 0x156: // CMP <Rn>, <Rm>, RRX #<imm> case 0x15E: { // CMP <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandRORFlags(instruction); CMP(_registers[rn], operand, _hostFlags); break; } case 0x157: { // CMP <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandRORRegFlags(instruction); CMP(_registers[rn], operand, _hostFlags); break; } CASE_RANGE16(0x350) { // CMP <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandImmFlags(instruction); CMP(_registers[rn], operand, _hostFlags); break; } // EOR case 0x020: case 0x028: { // EOR <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); EOR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x021: { // EOR <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); EOR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x022: case 0x02A: { // EOR <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); EOR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x023: { // EOR <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); EOR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x024: case 0x02C: { // EOR <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); EOR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x025: { // EOR <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); EOR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x026: // EOR <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x02E: { // EOR <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); EOR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x027: { // EOR <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); EOR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x030: case 0x038: { // EORS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); EOR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x031: { // EORS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); EOR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x032: case 0x03A: { // EORS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); EOR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x033: { // EORS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); EOR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x034: case 0x03C: { // EORS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); EOR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x035: { // EORS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); EOR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x036: // EORS <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x03E: { // EORS <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); EOR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x037: { // EORS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); EOR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x220) { // EOR <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); EOR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x230) { // EORS <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); EOR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); EOR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // LDM CASE_RANGE16(0x810) { // LDMDA <Rn>, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if ((registerList & (1 << 15)) != 0) { _registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; address -= 4; } for (int i = 14; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { _registers[i] = _system._memory.Read32(address); address -= 4; } } break; } CASE_RANGE16(0x830) { // LDMDA <Rn>!, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if ((registerList & (1 << 15)) != 0) { _registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; address -= 4; } for (int i = 14; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { _registers[i] = _system._memory.Read32(address); address -= 4; } } _registers[rn] = address; break; } CASE_RANGE16(0x890) { // LDMIA <Rn>, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 0; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { _registers[i] = _system._memory.Read32(address); address += 4; } } if ((registerList & (1 << 15)) != 0) { _registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; address += 4; } break; } CASE_RANGE16(0x8B0) { // LDMIA <Rn>!, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 0; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { _registers[i] = _system._memory.Read32(address); address += 4; } } if ((registerList & (1 << 15)) != 0) { _registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; address += 4; } _registers[rn] = address; break; } CASE_RANGE16(0x910) { // LDMDB <Rn>, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if ((registerList & (1 << 15)) != 0) { _registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; address -= 4; } for (int i = 14; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { _registers[i] = _system._memory.Read32(address); address -= 4; } } break; } CASE_RANGE16(0x930) { // LDMDB <Rn>!, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if ((registerList & (1 << 15)) != 0) { address -= 4; _registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; } for (int i = 14; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _registers[i] = _system._memory.Read32(address); } } _registers[rn] = address; break; } CASE_RANGE16(0x990) { // LDMIB <Rn>, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 0; i >= 14; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _registers[i] = _system._memory.Read32(address); } } if ((registerList & (1 << 15)) != 0) { address += 4; _registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x9B0) { // LDMIB <Rn>!, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 0; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _registers[i] = _system._memory.Read32(address); } } if ((registerList & (1 << 15)) != 0) { address += 4; _registers[REGPC] = _system._memory.Read32(address) & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; } _registers[rn] = address; break; } CASE_RANGE16(0x850) { // LDMDA <Rn>, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if ((registerList & (1 << 15)) != 0) { address -= 4; _cpsr = _spsr; uint32_t pc = _system._memory.Read32(address); UpdateMode(); if (IsInThumbMode()) { _registers[15] = pc & 0xFFFFFFFE; } else { _registers[15] = pc & 0xFFFFFFFC; } _pipelineInstruction = ARM_NOP; } for (int i = 14; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _registersUser[i - 8] = _system._memory.Read32(address); } } for (int i = 7; i >= 0; i--) { address -= 4; _registers[i] = _system._memory.Read32(address); } } else { for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _registers[i] = _system._memory.Read32(address); if (i == REGPC) _pipelineInstruction = ARM_NOP; } } } break; } CASE_RANGE16(0x870) { // LDMDA <Rn>!, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if ((registerList & (1 << 15)) != 0) { address -= 4; _cpsr = _spsr; uint32_t pc = _system._memory.Read32(address); UpdateMode(); if (IsInThumbMode()) { _registers[15] = pc & 0xFFFFFFFE; } else { _registers[15] = pc & 0xFFFFFFFC; } _pipelineInstruction = ARM_NOP; } for (int i = 14; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _registersUser[i - 8] = _system._memory.Read32(address); } } for (int i = 7; i >= 0; i--) { address -= 4; _registers[i] = _system._memory.Read32(address); } } else { for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _registers[i] = _system._memory.Read32(address); if (i == REGPC) _pipelineInstruction = ARM_NOP; } } } _registers[rn] = address; break; } CASE_RANGE16(0x8D0) { // LDMIA <Rn>!, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { for (int i = 0; i <= 7; i++) { address += 4; _registers[i] = _system._memory.Read32(address); } for (int i = 8; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _registersUser[i - 8] = _system._memory.Read32(address); } } if ((registerList & (1 << 15)) != 0) { address += 4; _cpsr = _spsr; uint32_t pc = _system._memory.Read32(address); UpdateMode(); if (IsInThumbMode()) { _registers[15] = pc & 0xFFFFFFFE; } else { _registers[15] = pc & 0xFFFFFFFC; } _pipelineInstruction = ARM_NOP; } } else { for (int i = 0; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _registers[i] = _system._memory.Read32(address); } } if ((registerList & (1 << 15)) != 0) { address += 4; uint32_t pc = _system._memory.Read32(address); _registers[15] = pc & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; } } _registers[rn] = address; break; } CASE_RANGE16(0x8F0) { // LDMIA <Rn>, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { for (int i = 0; i <= 7; i++) { address += 4; _registers[i] = _system._memory.Read32(address); } for (int i = 8; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _registersUser[i - 8] = _system._memory.Read32(address); } } if ((registerList & (1 << 15)) != 0) { address += 4; _cpsr = _spsr; uint32_t pc = _system._memory.Read32(address); UpdateMode(); if (IsInThumbMode()) { _registers[15] = pc & 0xFFFFFFFE; } else { _registers[15] = pc & 0xFFFFFFFC; } _pipelineInstruction = ARM_NOP; } } else { for (int i = 0; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _registers[i] = _system._memory.Read32(address); } } if ((registerList & (1 << 15)) != 0) { address += 4; uint32_t pc = _system._memory.Read32(address); _registers[15] = pc & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; } } break; } CASE_RANGE16(0x950) { // LDMDB <Rn>, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if ((registerList & (1 << 15)) != 0) { _cpsr = _spsr; uint32_t pc = _system._memory.Read32(address); UpdateMode(); if (IsInThumbMode()) { _registers[15] = pc & 0xFFFFFFFE; } else { _registers[15] = pc & 0xFFFFFFFC; } _pipelineInstruction = ARM_NOP; address -= 4; } for (int i = 14; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { _registersUser[i - 8] = _system._memory.Read32(address); address -= 4; } } for (int i = 7; i >= 0; i--) { _registers[i] = _system._memory.Read32(address); address -= 4; } } else { if ((registerList & (1 << 15)) != 0) { uint32_t pc = _system._memory.Read32(address); _registers[15] = pc & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; address -= 4; } for (int i = 14; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { _registers[i] = _system._memory.Read32(address); address -= 4; } } } break; } CASE_RANGE16(0x970) { // LDMDB <Rn>!, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if ((registerList & (1 << 15)) != 0) { _cpsr = _spsr; uint32_t pc = _system._memory.Read32(address); UpdateMode(); if (IsInThumbMode()) { _registers[15] = pc & 0xFFFFFFFE; } else { _registers[15] = pc & 0xFFFFFFFC; } _pipelineInstruction = ARM_NOP; address -= 4; } for (int i = 14; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { _registersUser[i - 8] = _system._memory.Read32(address); address -= 4; } } for (int i = 7; i >= 0; i--) { _registers[i] = _system._memory.Read32(address); address -= 4; } } else { if ((registerList & (1 << 15)) != 0) { uint32_t pc = _system._memory.Read32(address); _registers[15] = pc & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; address -= 4; } for (int i = 14; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { _registers[i] = _system._memory.Read32(address); address -= 4; } } } _registers[rn] = address; break; } CASE_RANGE16(0x9D0) { // LDMIB <Rn>, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { for (int i = 0; i <= 7; i++) { _registers[i] = _system._memory.Read32(address); address += 4; } for (int i = 8; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { _registersUser[i - 8] = _system._memory.Read32(address); address += 4; } } if ((registerList & (1 << 15)) != 0) { _cpsr = _spsr; uint32_t pc = _system._memory.Read32(address); UpdateMode(); if (IsInThumbMode()) { _registers[15] = pc & 0xFFFFFFFE; } else { _registers[15] = pc & 0xFFFFFFFC; } _pipelineInstruction = ARM_NOP; address += 4; } } else { for (int i = 0; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { _registers[i] = _system._memory.Read32(address); address += 4; } } if ((registerList & (1 << 15)) != 0) { uint32_t pc = _system._memory.Read32(address); _registers[15] = pc & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; address += 4; } } break; } CASE_RANGE16(0x9F0) { // LDMIB <Rn>!, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { for (int i = 0; i <= 7; i++) { _registers[i] = _system._memory.Read32(address); address += 4; } for (int i = 8; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { _registersUser[i - 8] = _system._memory.Read32(address); address += 4; } } if ((registerList & (1 << 15)) != 0) { _cpsr = _spsr; uint32_t pc = _system._memory.Read32(address); UpdateMode(); if (IsInThumbMode()) { _registers[15] = pc & 0xFFFFFFFE; } else { _registers[15] = pc & 0xFFFFFFFC; } _pipelineInstruction = ARM_NOP; address += 4; } } else { for (int i = 0; i <= 14; i++) { if ((registerList & (1 << i)) != 0) { _registers[i] = _system._memory.Read32(address); address += 4; } } if ((registerList & (1 << 15)) != 0) { uint32_t pc = _system._memory.Read32(address); _registers[15] = pc & 0xFFFFFFFC; _pipelineInstruction = ARM_NOP; address += 4; } } _registers[rn] = address; break; } // LDR CASE_RANGE16(0x410) { // LDR <Rd>, [<Rn>], #-<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x490) { // LDR <Rd>, [<Rn>], #+<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x510) { // LDR <Rd>, [<Rn>, #-<offset_12>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x530) { // LDR <Rd>, [<Rn>, #-<offset_12>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x590) { // LDR <Rd>, [<Rn>, #+<offset_12>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x5B0) { // LDR <Rd>, [<Rn>, #+<offset_12>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x610: case 0x618:{ // LDR <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); _registers[rd] = _system._memory.Read32(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x612: case 0x61A: { // LDR <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); _registers[rd] = _system._memory.Read32(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x614: case 0x61C: { // LDR <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); _registers[rd] = _system._memory.Read32(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x616: case 0x61E: { // LDR <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); _registers[rd] = _system._memory.Read32(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x690: case 0x698: { // LDR <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); _registers[rd] = _system._memory.Read32(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x692: case 0x69A: { // LDR <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); _registers[rd] = _system._memory.Read32(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x694: case 0x69C: { // LDR <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); _registers[rd] = _system._memory.Read32(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x696: case 0x69E: { // LDR <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); _registers[rd] = _system._memory.Read32(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x710: case 0x718: { // LDR <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x712: case 0x71A: { // LDR <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x714: case 0x71C: { // LDR <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x716: case 0x71E: { // LDR <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x790: case 0x798: { // LDR <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x792: case 0x79A: { // LDR <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x794: case 0x79C: { // LDR <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x796: case 0x79E: { // LDR <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x730: case 0x738: { // LDR <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x732: case 0x73A: { // LDR <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x734: case 0x73C: { // LDR <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x736: case 0x73E: { // LDR <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7B0: case 0x7B8: { // LDR <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7B2: case 0x7BA: { // LDR <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7B4: case 0x7BC: { // LDR <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7B6: case 0x7BE: { // LDR <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read32(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } // LDRB CASE_RANGE16(0x450) { // LDRB <Rd>, [<Rn>], #-<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x4D0) { // LDRB <Rd>, [<Rn>], #+<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x550) { // LDRB <Rd>, [<Rn>, #-<offset_12>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x570) { // LDRB <Rd>, [<Rn>, #-<offset_12>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x5D0) { // LDRB <Rd>, [<Rn>, #+<offset_12>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x5F0) { // LDRB <Rd>, [<Rn>, #+<offset_12>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x650: case 0x658: { // LDRB <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); _registers[rd] = _system._memory.Read8(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x652: case 0x65A: { // LDRB <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); _registers[rd] = _system._memory.Read8(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x654: case 0x65C: { // LDRB <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); _registers[rd] = _system._memory.Read8(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x656: case 0x65E: { // LDRB <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); _registers[rd] = _system._memory.Read8(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x6D0: case 0x6D8: { // LDRB <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); _registers[rd] = _system._memory.Read8(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x6D2: case 0x6DA: { // LDRB <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); _registers[rd] = _system._memory.Read8(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x6D4: case 0x6DC: { // LDRB <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); _registers[rd] = _system._memory.Read8(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x6D6: case 0x6DE: { // LDRB <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); _registers[rd] = _system._memory.Read8(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x750: case 0x758: { // LDRB <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x752: case 0x75A: { // LDRB <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x754: case 0x75C: { // LDRB <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x756: case 0x75E: { // LDRB <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7D0: case 0x7D8: { // LDRB <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7D2: case 0x7DA: { // LDRB <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7D4: case 0x7DC: { // LDRB <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7D6: case 0x7DE: { // LDRB <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x770: case 0x778: { // LDRB <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x772: case 0x77A: { // LDRB <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x774: case 0x77C: { // LDRB <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x776: case 0x77E: { // LDRB <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7F0: case 0x7F8: { // LDRB <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7F2: case 0x7FA: { // LDRB <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7F4: case 0x7FC: { // LDRB <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x7F6: case 0x7FE: { // LDRB <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read8(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } //LDRBT CASE_RANGE16(0x470) { // LDRBT <Rd>, [<Rn>], #-<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } CASE_RANGE16(0x4F0) { // LDRBT <Rd>, [<Rn>], #+<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd-8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } case 0x670: case 0x678: { // LDRBT <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } case 0x672: case 0x67A: { // LDRBT <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } case 0x674: case 0x67C: { // LDRBT <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } case 0x676: case 0x67E: { // LDRBT <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } case 0x6F0: case 0x6F8: { // LDRBT <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } case 0x6F2: case 0x6FA: { // LDRBT <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } case 0x6F4: case 0x6FC: { // LDRBT <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } case 0x6F6: case 0x6FE: { // LDRBT <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read8(address); } } else { _registers[rd] = _system._memory.Read8(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } // LDRH case 0x01B: { // LDRH <Rd>, [<Rn>], -<Rm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn]; _registers[rd] = _system._memory.Read16(address); _registers[rn] = address - _registers[rm]; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x09B: { // LDRH <Rd>, [<Rn>], +<Rm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn]; _registers[rd] = _system._memory.Read16(address); _registers[rn] = address + _registers[rm]; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x05B: { // LDRH <Rd>, [<Rn>], #-<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn]; _registers[rd] = _system._memory.Read16(address); _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0DB: { // LDRH <Rd>, [<Rn>], #+<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn]; _registers[rd] = _system._memory.Read16(address); _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x11B: { // LDRH <Rd>, [<Rn>, -<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] - _registers[rm]; _registers[rd] = _system._memory.Read16(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x19B: { // LDRH <Rd>, [<Rn>, +<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] + _registers[rm]; _registers[rd] = _system._memory.Read16(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x15B: { // LDRH <Rd>, [<Rn>, #-<offset_8>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read16(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1DB: { // LDRH <Rd>, [<Rn>, #+<offset_8>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read16(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x13B: { // LDRH <Rd>, [<Rn>, -<Rm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] - _registers[rm]; _registers[rd] = _system._memory.Read16(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1BB: { // LDRH <Rd>, [<Rn>, +<Rm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] + _registers[rm]; _registers[rd] = _system._memory.Read16(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x17B: { // LDRH <Rd>, [<Rn>, #-<offset_8>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] - offset; _registers[rd] = _system._memory.Read16(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1FB: { // LDRH <Rd>, [<Rn>, #+<offset_8>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] + offset; _registers[rd] = _system._memory.Read16(address); _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } // LDRSB case 0x01D: { // LDRSB <Rd>, [<Rn>], -<Rm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn]; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; _registers[rn] = address - _registers[rm]; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x09D: { // LDRSB <Rd>, [<Rn>], +<Rm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn]; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; _registers[rn] = address + _registers[rm]; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x05D: { // LDRSB <Rd>, [<Rn>], #-<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn]; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0DD: { // LDRSB <Rd>, [<Rn>], #+<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn]; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x11D: { // LDRSB <Rd>, [<Rn>, -<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] - _registers[rm]; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x19D: { // LDRSB <Rd>, [<Rn>, +<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] + _registers[rm]; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x15D: { // LDRSB <Rd>, [<Rn>], #-<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] - offset; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1DD: { // LDRSB <Rd>, [<Rn>], #+<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] + offset; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x13D: { // LDRSB <Rd>, [<Rn>, -<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] - _registers[rm]; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1BD: { // LDRSB <Rd>, [<Rn>, +<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] + _registers[rm]; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x17D: { // LDRSB <Rd>, [<Rn>, #-<offset_8>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] - offset; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1FD: { // LDRSB <Rd>, [<Rn>, #+<offset_8>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] + offset; uint32_t value = _system._memory.Read8(address); if ((value & 0x80) != 0) value |= 0xFFFFFF00; _registers[rd] = value; _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } // LDRSH case 0x01F: { // LDRSH <Rd>, [<Rn>], -<Rm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn]; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; _registers[rn] = address - _registers[rm]; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x09F: { // LDRSH <Rd>, [<Rn>], +<Rm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn]; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; _registers[rn] = address + _registers[rm]; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x05F: { // LDRSH <Rd>, [<Rn>], #-<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn]; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; _registers[rn] = address - offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0DF: { // LDRSH <Rd>, [<Rn>], #+<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn]; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; _registers[rn] = address + offset; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x11F: { // LDRSH <Rd>, [<Rn>, -<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] - _registers[rm]; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x19F: { // LDRSH <Rd>, [<Rn>, +<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] + _registers[rm]; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x15F: { // LDRSH <Rd>, [<Rn>], #-<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] - offset; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1DF: { // LDRSH <Rd>, [<Rn>], #+<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] + offset; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x13F: { // LDRSH <Rd>, [<Rn>, -<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] - _registers[rm]; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1BF: { // LDRSH <Rd>, [<Rn>, +<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] + _registers[rm]; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x17F: { // LDRSH <Rd>, [<Rn>, #-<offset_8>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] - offset; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1FF: { // LDRSH <Rd>, [<Rn>, #+<offset_8>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] + offset; uint32_t value = _system._memory.Read16(address); if ((value & 0x8000) != 0) value |= 0xFFFF0000; _registers[rd] = value; _registers[rn] = address; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } // LDRT CASE_RANGE16(0x430) { // LDRT <Rd>, [<Rn>], #-<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } CASE_RANGE16(0x4B0) { // LDRT <Rd>, [<Rn>], #+<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } case 0x630: case 0x638: { // LDRT <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } case 0x632: case 0x63A: { // LDRT <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } case 0x634: case 0x63C: { // LDRT <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } case 0x636: case 0x63E: { // LDRT <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address - offset; break; } case 0x6B0: case 0x6B8: { // LDRT <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } case 0x6B2: case 0x6BA: { // LDRT <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } case 0x6B4: case 0x6BC: { // LDRT <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } case 0x6B6: case 0x6BE: { // LDRT <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } else { _registersUser[rd - 8] = _system._memory.Read32(address); } } else { _registers[rd] = _system._memory.Read32(address); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } _registers[rn] = address + offset; break; } // MLA case 0x029: { // MLA <Rd>, <Rm>, <Rs>, <Rn> uint8_t rd = (instruction >> 16) & 0xF; uint8_t rn = (instruction >> 12) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 0) & 0xF; MLA(_registers[rm], _registers[rs], _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x039: { // MLAS <Rd>, <Rm>, <Rs>, <Rn> uint8_t rd = (instruction >> 16) & 0xF; uint8_t rn = (instruction >> 12) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 0) & 0xF; MLA_FLAGS(_registers[rm], _registers[rs], _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } // MOV case 0x1A0: case 0x1A8: { // MOV <Rd>, <Rm>, LSL #<imm> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1A1: { // MOV <Rd>, <Rm>, LSL <Rs> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1A2: case 0x1AA: { // MOV <Rd>, <Rm>, LSR #<imm> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1A3: { // MOV <Rd>, <Rm>, LSR <Rs> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1A4: case 0x1AC: { // MOV <Rd>, <Rm>, ASR #<imm> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1A5: { // MOV <Rd>, <Rm>, ASR <Rs> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1A6: // MOV <Rd>, <Rm>, RRX #<imm> case 0x1AE: { // MOV <Rd>, <Rm>, ROR #<imm> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1A7: { // MOV <Rd>, <Rm>, ROR <Rs> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1B0: case 0x1B8: { // MOVS <Rd>, <Rm>, LSL #<imm> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); _registers[rd] = operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); MOV_FLAGS(operand, _hostFlags); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1B1: { // MOVS <Rd>, <Rm>, LSL <Rs> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); _registers[rd] = operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); MOV_FLAGS(operand, _hostFlags); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1B2: case 0x1BA: { // MOVS <Rd>, <Rm>, LSR #<imm> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); _registers[rd] = operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); MOV_FLAGS(operand, _hostFlags); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1B3: { // MOVS <Rd>, <Rm>, LSR <Rs> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); _registers[rd] = operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); MOV_FLAGS(operand, _hostFlags); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1B4: case 0x1BC: { // MOVS <Rd>, <Rm>, ASR #<imm> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); _registers[rd] = operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); MOV_FLAGS(operand, _hostFlags); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1B5: { // MOVS <Rd>, <Rm>, ASR <Rs> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); _registers[rd] = operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); MOV_FLAGS(operand, _hostFlags); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1B6: // MOVS <Rd>, <Rm>, RRX #<imm> case 0x1BE: { // MOVS <Rd>, <Rm>, ROR #<imm> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); _registers[rd] = operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); MOV_FLAGS(operand, _hostFlags); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1B7: { // MOVS <Rd>, <Rm>, ROR <Rs> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); _registers[rd] = operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); MOV_FLAGS(operand, _hostFlags); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x3A0) { // MOV <Rd>, #<immediate> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x3B0) { // MOVS <Rd>, #<immediate> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); _registers[rd] = operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); MOV_FLAGS(operand, _hostFlags); _registers[rd] = operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // MRS case 0x100: { // MRS <Rd>, CPSR uint8_t rd = (instruction >> 12) & 0xF; SaveHostFlagsToCPSR(); _registers[rd] = _cpsr; break; } case 0x140: { // MRS <Rd>, SPSR uint8_t rd = (instruction >> 12) & 0xF; _registers[rd] = _spsr; break; } // MSR CASE_RANGE16(0x320) { // MSR CPSR_<fields>, #<immediate> uint8_t rotImm = (instruction >> 8) & 0xF; uint8_t imm = instruction & 0xFF; uint32_t operand; ROR(imm, rotImm * 2, operand); uint32_t mask = 0; SaveHostFlagsToCPSR(); if ((instruction & (1 << 16)) != 0 && InAPrivilegedMode()) { mask |= 0xFF; } if ((instruction & (1 << 17)) != 0 && InAPrivilegedMode()) { mask |= 0xFF00; } if ((instruction & (1 << 18)) != 0 && InAPrivilegedMode()) { mask |= 0xFF0000; } if ((instruction & (1 << 19)) != 0) { mask |= 0xFF000000; } _cpsr = (_cpsr & ~mask) | (operand & mask); LoadHostFlagsFromCPSR(); UpdateMode(); break; } CASE_RANGE16(0x360) { // MSR SPSR_<fields>, #<immediate> uint8_t rotImm = (instruction >> 8) & 0xF; uint8_t imm = instruction & 0xFF; uint32_t operand; ROR(imm, rotImm * 2, operand); uint32_t mask = 0; if ((instruction & (1 << 16)) != 0 && InAPrivilegedMode()) { mask |= 0xFF; } if ((instruction & (1 << 17)) != 0 && InAPrivilegedMode()) { mask |= 0xFF00; } if ((instruction & (1 << 18)) != 0 && InAPrivilegedMode()) { mask |= 0xFF0000; } if ((instruction & (1 << 19)) != 0) { mask |= 0xFF000000; } _spsr = (_spsr & ~mask) | (operand & mask); break; } case 0x120: { // MSR CPSR_<fields>, <Rm> uint8_t rm = instruction & 0xF; uint32_t operand = _registers[rm]; uint32_t mask = 0; SaveHostFlagsToCPSR(); if ((instruction & (1 << 16)) != 0 && InAPrivilegedMode()) { mask |= 0xFF; } if ((instruction & (1 << 17)) != 0 && InAPrivilegedMode()) { mask |= 0xFF00; } if ((instruction & (1 << 18)) != 0 && InAPrivilegedMode()) { mask |= 0xFF0000; } if ((instruction & (1 << 19)) != 0) { mask |= 0xFF000000; } _cpsr = (_cpsr & ~mask) | (operand & mask); LoadHostFlagsFromCPSR(); UpdateMode(); break; } case 0x160: { // MSR SPSR_<fields>, <Rm> uint8_t rm = instruction & 0xF; uint32_t operand = _registers[rm]; uint32_t mask = 0; if ((instruction & (1 << 16)) != 0 && InAPrivilegedMode()) { mask |= 0xFF; } if ((instruction & (1 << 17)) != 0 && InAPrivilegedMode()) { mask |= 0xFF00; } if ((instruction & (1 << 18)) != 0 && InAPrivilegedMode()) { mask |= 0xFF0000; } if ((instruction & (1 << 19)) != 0) { mask |= 0xFF000000; _hostFlags &= ~((1 << 0) | (1 << 6) | (1 << 7) | (1 << 11)); if ((operand & CPSR_V_MASK) != 0) _hostFlags |= (1 << 11); if ((operand & CPSR_C_MASK) != 0) _hostFlags |= (1 << 0); if ((operand & CPSR_Z_MASK) != 0) _hostFlags |= (1 << 6); if ((operand & CPSR_N_MASK) != 0) _hostFlags |= (1 << 7); } _spsr = (_spsr & ~mask) | (operand & mask); break; } // MUL case 0x009: { // MUL <Rd>, <Rm>, <Rs> uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rd = (instruction >> 16) & 0xF; _registers[rd] = _registers[rm] * _registers[rs]; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x019: { // MULS <Rd>, <Rm>, <Rs> uint8_t rm = instruction & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rd = (instruction >> 16) & 0xF; MUL_FLAGS(_registers[rm], _registers[rs], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } // MVN case 0x1E0: case 0x1E8: { // MVN <Rd>, <Rm>, LSL #<imm> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1E1: { // MVN <Rd>, <Rm>, LSL <Rs> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1E2: case 0x1EA: { // MVN <Rd>, <Rm>, LSR #<imm> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1E3: { // MVN <Rd>, <Rm>, LSR <Rs> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1E4: case 0x1EC: { // MVN <Rd>, <Rm>, ASR #<imm> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1E5: { // MVN <Rd>, <Rm>, ASR <Rs> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1E6: // MVN <Rd>, <Rm>, RRX #<imm> case 0x1EE: { // MVN <Rd>, <Rm>, ROR #<imm> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1E7: { // MVN <Rd>, <Rm>, ROR <Rs> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x1F0: case 0x1F8: { // MVNS <Rd>, <Rm>, LSL #<imm> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); _registers[rd] = ~operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); MVN_FLAGS(operand, _hostFlags); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1F1: { // MVNS <Rd>, <Rm>, LSL <Rs> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); _registers[rd] = ~operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); MVN_FLAGS(operand, _hostFlags); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1F2: case 0x1FA: { // MVNS <Rd>, <Rm>, LSR #<imm> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); _registers[rd] = ~operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); MVN_FLAGS(operand, _hostFlags); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1F3: { // MVNS <Rd>, <Rm>, LSR <Rs> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); _registers[rd] = ~operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); MVN_FLAGS(operand, _hostFlags); _registers[rd] = ~operand; } break; } case 0x1F4: case 0x1FC: { // MVNS <Rd>, <Rm>, ASR #<imm> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); _registers[rd] = ~operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); MVN_FLAGS(operand, _hostFlags); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1F5: { // MVNS <Rd>, <Rm>, ASR <Rs> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); _registers[rd] = ~operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); MVN_FLAGS(operand, _hostFlags); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1F6: // MVNS <Rd>, <Rm>, RRX #<imm> case 0x1FE: { // MVNS <Rd>, <Rm>, ROR #<imm> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); _registers[rd] = ~operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); MVN_FLAGS(operand, _hostFlags); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x1F7: { // MVNS <Rd>, <Rm>, ROR <Rs> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); _registers[rd] = ~operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); MVN_FLAGS(operand, _hostFlags); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x3E0) { // MVN <Rd>, #<immediate> uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x3F0) { // MVNS <Rd>, #<immediate> uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); _registers[rd] = ~operand; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); MVN_FLAGS(operand, _hostFlags); _registers[rd] = ~operand; if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // ORR case 0x180: case 0x188: { // ORR <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); ORR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x181: { // ORR <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); ORR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x182: case 0x18A: { // ORR <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); ORR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x183: { // ORR <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); ORR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x184: case 0x18C: { // ORR <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); ORR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x185: { // ORR <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); ORR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x186: // ORR <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x18E: { // ORR <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); ORR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x187: { // ORR <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); ORR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x190: case 0x198: { // ORRS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); ORR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x191: { // ORRS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); ORR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x192: case 0x19A: { // ORRS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); ORR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x193: { // ORRS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); ORR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x194: case 0x19C: { // ORRS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); ORR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x195: { // ORRS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); ORR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x196: // ORRS <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x19E: { // ORRS <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); ORR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x197: { // ORRS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); ORR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x380) { // ORR <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); ORR(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x390) { // ORRS <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); ORR(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); ORR_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // RSB case 0x060: case 0x068: { // RSB <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); SUB(operand, _registers[rn], _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x061: { // RSB <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); SUB(operand, _registers[rn], _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x062: case 0x06A: { // RSB <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); SUB(operand, _registers[rn], _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x063: { // RSB <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); SUB(operand, _registers[rn], _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x064: case 0x06C: { // RSB <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); SUB(operand, _registers[rn], _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x065: { // RSB <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); SUB(operand, _registers[rn], _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x066: // RSB <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x06E: { // RSB <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); SUB(operand, _registers[rn], _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x067: { // RSB <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); SUB(operand, _registers[rn], _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x070: case 0x078: { // RSBS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); SUB(operand, _registers[rn], _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x071: { // RSBS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); SUB(operand, _registers[rn], _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x072: case 0x07A: { // RSBS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); SUB(operand, _registers[rn], _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x073: { // RSBS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); SUB(operand, _registers[rn], _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x074: case 0x07C: { // RSBS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); SUB(operand, _registers[rn], _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x075: { // RSBS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); SUB(operand, _registers[rn], _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x076: // RSBS <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x07E: { // RSBS <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); SUB(operand, _registers[rn], _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x077: { // RSBS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); SUB(operand, _registers[rn], _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x260) { // RSB <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); SUB(operand, _registers[rn], _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x270) { // RSBS <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); SUB(operand, _registers[rn], _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); SUB_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // RSC case 0x0E0: case 0x0E8: { // RSC <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0E1: { // RSC <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0E2: case 0x0EA: { // RSC <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0E3: { // RSC <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0E4: case 0x0EC: { // RSC <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0E5: { // RSC <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0E6: // RSC <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x0EE: { // RSC <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0E7: { // RSC <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0F0: case 0x0F8: { // RSCS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags);; _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0F1: { // RSCS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0F2: case 0x0FA: { // RSCS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0F3: { // RSCS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0F4: case 0x0FC: { // RSCS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0F5: { // RSCS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0F6: // RSCS <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x0FE: { // RSCS <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0F7: { // RSCS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x2E0) { // RSC <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x2F0) { // RSCS <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); SBC(operand, _registers[rn], _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); SBC_FLAGS(operand, _registers[rn], _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // SBC case 0x0C0: case 0x0C8: { // SBC <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0C1: { // SBC <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0C2: case 0x0CA: { // SBC <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0C3: { // SBC <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0C4: case 0x0CC: { // SBC <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0C5: { // SBC <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0C6: // SBC <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x0CE: { // SBC <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0C7: { // SBC <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0D0: case 0x0D8: { // SBCS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0D1: { // SBCS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0D2: case 0x0DA: { // SBCS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0D3: { // SBCS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0D4: case 0x0DC: { // SBCS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0D5: { // SBCS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0D6: // SBCS <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x0DE: { // SBCS <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x0D7: { // SBCS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x2C0) { // SBC <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x2D0) { // SBCS <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); SBC(_registers[rn], operand, _registers[rd], _hostFlags); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); SBC_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // SMLAL case 0x0E9: { // SMLAL <RdLo>, <RdHi>, <Rm>, <Rs> uint8_t rdLo = (instruction >> 12) & 0xF; uint8_t rdHi = (instruction >> 16) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 8) & 0xF; SMLAL(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi]); if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0F9: { // SMLALS <RdLo>, <RdHi>, <Rm>, <Rs> uint8_t rdLo = (instruction >> 12) & 0xF; uint8_t rdHi = (instruction >> 16) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 8) & 0xF; SMLAL_FLAGS(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi], _hostFlags); if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP; break; } // SMULL case 0x0C9: { // SMULL <RdLo>, <RdHi>, <Rm>, <Rs> uint8_t rdLo = (instruction >> 12) & 0xF; uint8_t rdHi = (instruction >> 16) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 8) & 0xF; SMULL(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi]); if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0D9: { // SMULLS <RdLo>, <RdHi>, <Rm>, <Rs> uint8_t rdLo = (instruction >> 12) & 0xF; uint8_t rdHi = (instruction >> 16) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 8) & 0xF; SMULL_FLAGS(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi], _hostFlags); if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP; break; } // STM CASE_RANGE16(0x800) { // STMDA <Rn>, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address -= 4; } } break; } CASE_RANGE16(0x820) { // STMDA <Rn>!, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address -= 4; } } _registers[rn] = address; break; } CASE_RANGE16(0x880) { // STMIA <Rn>, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 0; i <= 15; i++) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address += 4; } } break; } CASE_RANGE16(0x8A0) { // STMIA <Rn>!, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 0; i <= 15; i++) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address += 4; } } _registers[rn] = address; break; } CASE_RANGE16(0x900) { // STMDB <Rn>, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _system._memory.Write32(address, _registers[i]); } } break; } CASE_RANGE16(0x920) { // STMDB <Rn>!, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _system._memory.Write32(address, _registers[i]); } } _registers[rn] = address; break; } CASE_RANGE16(0x980) { // STMIB <Rn>, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 0; i >= 15; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _system._memory.Write32(address, _registers[i]); } } break; } CASE_RANGE16(0x9A0) { // STMIB <Rn>!, <registers> uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; for (int i = 0; i <= 15; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _system._memory.Write32(address, _registers[i]); } } _registers[rn] = address; break; } CASE_RANGE16(0x840) { // STMDA <Rn>, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if ((registerList & (1 << 15)) != 0) { _system._memory.Write32(address, _registers[REGPC]); address -= 4; } _system._memory.Write32(address, _registersUser[14-8]); address -= 4; _system._memory.Write32(address, _registersUser[13 - 8]); address -= 4; if (InABankedUserRegistersMode()) { for (int i = 12; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registersUser[i - 8]); address -= 4; } } } else { for (int i = 12; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address -= 4; } } } for (int i = 7; i >= 0; i--) { _system._memory.Write32(address, _registers[i]); address -= 4; } } else { for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address -= 4; } } } break; } CASE_RANGE16(0x860) { // STMDA <Rn>!, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if ((registerList & (1 << 15)) != 0) { _system._memory.Write32(address, _registers[REGPC]); address -= 4; } _system._memory.Write32(address, _registersUser[14 - 8]); address -= 4; _system._memory.Write32(address, _registersUser[13 - 8]); address -= 4; if (InABankedUserRegistersMode()) { for (int i = 12; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registersUser[i - 8]); address -= 4; } } } else { for (int i = 12; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address -= 4; } } } for (int i = 7; i >= 0; i--) { _system._memory.Write32(address, _registers[i]); address -= 4; } } else { for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address -= 4; } } } _registers[rn] = address; break; } CASE_RANGE16(0x8C0) { // STMIA <Rn>, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { for (int i = 0; i <= 7; i++) { _system._memory.Write32(address, _registers[i]); address += 4; } if (InABankedUserRegistersMode()) { for (int i = 8; i <= 12; i++) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registersUser[i - 8]); address += 4; } } } else { for (int i = 8; i <= 12; i++) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address += 4; } } } _system._memory.Write32(address, _registersUser[13 - 8]); address += 4; _system._memory.Write32(address, _registersUser[14 - 8]); address += 4; if ((registerList & (1 << 15)) != 0) { _system._memory.Write32(address, _registers[REGPC]); address += 4; } } else { for (int i = 0; i <= 15; i++) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address += 4; } } } break; } CASE_RANGE16(0x8E0) { // STMIA <Rn>!, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { for (int i = 0; i <= 7; i++) { _system._memory.Write32(address, _registers[i]); address += 4; } if (InABankedUserRegistersMode()) { for (int i = 8; i <= 12; i++) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registersUser[i - 8]); address += 4; } } } else { for (int i = 8; i <= 12; i++) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address += 4; } } } _system._memory.Write32(address, _registersUser[13 - 8]); address += 4; _system._memory.Write32(address, _registersUser[14 - 8]); address += 4; if ((registerList & (1 << 15)) != 0) { address += 4; _system._memory.Write32(address, _registers[REGPC]); } } else { for (int i = 0; i <= 15; i++) { if ((registerList & (1 << i)) != 0) { _system._memory.Write32(address, _registers[i]); address += 4; } } } _registers[rn] = address; break; } CASE_RANGE16(0x940) { // STMDB <Rn>, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if ((registerList & (1 << 15)) != 0) { address -= 4; _system._memory.Write32(address, _registers[REGPC]); } address -= 4; _system._memory.Write32(address, _registersUser[14 - 8]); address -= 4; _system._memory.Write32(address, _registersUser[13 - 8]); if (InABankedUserRegistersMode()) { for (int i = 12; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _system._memory.Write32(address, _registersUser[i - 8]); } } } else { for (int i = 12; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _system._memory.Write32(address, _registers[i]); } } } for (int i = 7; i >= 0; i--) { address -= 4; _system._memory.Write32(address, _registers[i]); } } else { for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _system._memory.Write32(address, _registers[i]); } } } break; } CASE_RANGE16(0x960) { // STMDB <Rn>!, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if ((registerList & (1 << 15)) != 0) { address -= 4; _system._memory.Write32(address, _registers[REGPC]); } address -= 4; _system._memory.Write32(address, _registersUser[14 - 8]); address -= 4; _system._memory.Write32(address, _registersUser[13 - 8]); if (InABankedUserRegistersMode()) { for (int i = 12; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _system._memory.Write32(address, _registersUser[i - 8]); } } } else { for (int i = 12; i >= 8; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _system._memory.Write32(address, _registers[i]); } } } for (int i = 7; i >= 0; i--) { address -= 4; _system._memory.Write32(address, _registers[i]); } } else { for (int i = 15; i >= 0; i--) { if ((registerList & (1 << i)) != 0) { address -= 4; _system._memory.Write32(address, _registers[i]); } } } _registers[rn] = address; break; } CASE_RANGE16(0x9C0) { // STMIB <Rn>, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { for (int i = 0; i <= 7; i++) { address += 4; _system._memory.Write32(address, _registers[i]); } if (InABankedUserRegistersMode()) { for (int i = 8; i <= 12; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _system._memory.Write32(address, _registersUser[i - 8]); } } } else { for (int i = 8; i <= 12; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _system._memory.Write32(address, _registers[i]); } } } address += 4; _system._memory.Write32(address, _registersUser[13 - 8]); address += 4; _system._memory.Write32(address, _registersUser[14 - 8]); if ((registerList & (1 << 15)) != 0) { address += 4; _system._memory.Write32(address, _registers[REGPC]); } } else { for (int i = 0; i <= 15; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _system._memory.Write32(address, _registers[i]); } } } break; } CASE_RANGE16(0x9E0) { // STMIB <Rn>!, <registers>^ uint16_t registerList = instruction & 0xFFFF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { for (int i = 0; i <= 7; i++) { address += 4; _system._memory.Write32(address, _registers[i]); } if (InABankedUserRegistersMode()) { for (int i = 8; i <= 12; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _system._memory.Write32(address, _registersUser[i - 8]); } } } else { for (int i = 8; i <= 12; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _system._memory.Write32(address, _registers[i]); } } } address += 4; _system._memory.Write32(address, _registersUser[13 - 8]); address += 4; _system._memory.Write32(address, _registersUser[14 - 8]); if ((registerList & (1 << 15)) != 0) { address += 4; _system._memory.Write32(address, _registers[REGPC]); } } else { for (int i = 0; i <= 15; i++) { if ((registerList & (1 << i)) != 0) { address += 4; _system._memory.Write32(address, _registers[i]); } } } _registers[rn] = address; break; } // STR CASE_RANGE16(0x400) { // STR <Rd>, [<Rn>], #-<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address - offset; break; } CASE_RANGE16(0x480) { // STR <Rd>, [<Rn>], #+<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address + offset; break; } CASE_RANGE16(0x500) { // STR <Rd>, [<Rn>, #-<offset_12>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); break; } CASE_RANGE16(0x520) { // STR <Rd>, [<Rn>, #-<offset_12>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } CASE_RANGE16(0x580) { // STR <Rd>, [<Rn>, #+<offset_12>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); break; } CASE_RANGE16(0x5A0) { // STR <Rd>, [<Rn>, #+<offset_12>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } case 0x600: case 0x608: { // STR <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); _system._memory.Write32(address, _registers[rd]); _registers[rn] = address - offset; break; } case 0x602: case 0x60A: { // STR <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); _system._memory.Write32(address, _registers[rd]); _registers[rn] = address - offset; break; } case 0x604: case 0x60C: { // STR <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); _system._memory.Write32(address, _registers[rd]); _registers[rn] = address - offset; break; } case 0x606: case 0x60E: { // STR <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); _system._memory.Write32(address, _registers[rd]); _registers[rn] = address - offset; break; } case 0x680: case 0x688: { // STR <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); _system._memory.Write32(address, _registers[rd]); _registers[rn] = address + offset; break; } case 0x682: case 0x68A: { // STR <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); _system._memory.Write32(address, _registers[rd]); _registers[rn] = address + offset; break; } case 0x684: case 0x68C: { // STR <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); _system._memory.Write32(address, _registers[rd]); _registers[rn] = address + offset; break; } case 0x686: case 0x68E: { // STR <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); _system._memory.Write32(address, _registers[rd]); _registers[rn] = address + offset; break; } case 0x700: case 0x708: { // STR <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); break; } case 0x702: case 0x70A: { // STR <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); break; } case 0x704: case 0x70C: { // STR <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); break; } case 0x706: case 0x70E: { // STR <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); break; } case 0x780: case 0x788: { // STR <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); break; } case 0x782: case 0x78A: { // STR <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); break; } case 0x784: case 0x78C: { // STR <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); break; } case 0x786: case 0x78E: { // STR <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); break; } case 0x720: case 0x728: { // STR <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } case 0x722: case 0x72A: { // STR <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } case 0x724: case 0x72C: { // STR <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } case 0x726: case 0x72E: { // STR <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } case 0x7A0: case 0x7A8: { // STR <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } case 0x7A2: case 0x7AA: { // STR <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } case 0x7A4: case 0x7AC: { // STR <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } case 0x7A6: case 0x7AE: { // STR <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write32(address, _registers[rd]); _registers[rn] = address; break; } // STRB CASE_RANGE16(0x440) { // STRB <Rd>, [<Rn>], #-<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address - offset; break; } CASE_RANGE16(0x4C0) { // STRB <Rd>, [<Rn>], #+<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address + offset; break; } CASE_RANGE16(0x540) { // STRB <Rd>, [<Rn>, #-<offset_12>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); break; } CASE_RANGE16(0x560) { // STRB <Rd>, [<Rn>, #-<offset_12>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } CASE_RANGE16(0x5C0) { // STRB <Rd>, [<Rn>, #+<offset_12>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); break; } CASE_RANGE16(0x5E0) { // STRB <Rd>, [<Rn>, #+<offset_12>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } case 0x640: case 0x648: { // STRB <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); _system._memory.Write8(address, _registers[rd]); _registers[rn] = address - offset; break; } case 0x642: case 0x64A: { // STRB <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); _system._memory.Write8(address, _registers[rd]); _registers[rn] = address - offset; break; } case 0x644: case 0x64C: { // STRB <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); _system._memory.Write8(address, _registers[rd]); _registers[rn] = address - offset; break; } case 0x646: case 0x64E: { // STRB <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); _system._memory.Write8(address, _registers[rd]); _registers[rn] = address - offset; break; } case 0x6C0: case 0x6C8: { // STRB <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); _system._memory.Write8(address, _registers[rd]); _registers[rn] = address + offset; break; } case 0x6C2: case 0x6CA: { // STRB <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); _system._memory.Write8(address, _registers[rd]); _registers[rn] = address + offset; break; } case 0x6C4: case 0x6CC: { // STRB <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); _system._memory.Write8(address, _registers[rd]); _registers[rn] = address + offset; break; } case 0x6C6: case 0x6CE: { // STRB <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); _system._memory.Write8(address, _registers[rd]); _registers[rn] = address + offset; break; } case 0x740: case 0x748: { // STRB <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); break; } case 0x742: case 0x74A: { // STRB <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); break; } case 0x744: case 0x74C: { // STRB <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); break; } case 0x746: case 0x74E: { // STRB <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); break; } case 0x7C0: case 0x7C8: { // STRB <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); break; } case 0x7C2: case 0x7CA: { // STRB <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); break; } case 0x7C4: case 0x7CC: { // LDRB <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); break; } case 0x7C6: case 0x7CE: { // LDRB <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); break; } case 0x760: case 0x768: { // LDRB <Rd>, [<Rn>, -<Rm>, LSL #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } case 0x762: case 0x76A: { // STRB <Rd>, [<Rn>, -<Rm>, LSR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } case 0x764: case 0x76C: { // STRB <Rd>, [<Rn>, -<Rm>, ASR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } case 0x766: case 0x76E: { // STRB <Rd>, [<Rn>, -<Rm>, ROR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] - offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } case 0x7E0: case 0x7E8: { // STRB <Rd>, [<Rn>, +<Rm>, LSL #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSL(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } case 0x7E2: case 0x7EA: { // STRB <Rd>, [<Rn>, +<Rm>, LSR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandLSR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } case 0x7E4: case 0x7EC: { // STRB <Rd>, [<Rn>, +<Rm>, ASR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandASR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } case 0x7E6: case 0x7EE: { // STRB <Rd>, [<Rn>, +<Rm>, ROR #<shift_imm>]! uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t offset = GetShifterOperandROR(instruction); uint32_t address = _registers[rn] + offset; _system._memory.Write8(address, _registers[rd]); _registers[rn] = address; break; } //STRBT CASE_RANGE16(0x460) { // STRBT <Rd>, [<Rn>], #-<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd-8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address - offset; break; } CASE_RANGE16(0x4E0) { // STRBT <Rd>, [<Rn>], #+<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd-8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address + offset; break; } case 0x660: case 0x668: { // STRBT <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd-8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address - offset; break; } case 0x662: case 0x66A: { // STRBT <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd-8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address - offset; break; } case 0x664: case 0x66C: { // STRBT <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd - 8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address - offset; break; } case 0x666: case 0x66E: { // STRBT <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd - 8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address - offset; break; } case 0x6E0: case 0x6E8: { // STRBT <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd - 8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address + offset; break; } case 0x6E2: case 0x6EA: { // STRBT <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd - 8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address + offset; break; } case 0x6E4: case 0x6EC: { // STRBT <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd - 8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address + offset; break; } case 0x6E6: case 0x6EE: { // STRBT <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write8(address, _registers[rd]); } else { _system._memory.Write8(address, _registersUser[rd - 8]); } } else { _system._memory.Write8(address, _registers[rd]); } _registers[rn] = address + offset; break; } // STRH case 0x00B: { // STRH <Rd>, [<Rn>], -<Rm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn]; _system._memory.Write16(address, _registers[rd]); _registers[rn] = address - _registers[rm]; break; } case 0x08B: { // STRH <Rd>, [<Rn>], +<Rm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn]; _system._memory.Write16(address, _registers[rd]); _registers[rn] = address + _registers[rm]; break; } case 0x04B: { // STRH <Rd>, [<Rn>], #-<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn]; _system._memory.Write16(address, _registers[rd]); _registers[rn] = address - offset; break; } case 0x0CB: { // STRH <Rd>, [<Rn>], #+<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn]; _system._memory.Write16(address, _registers[rd]); _registers[rn] = address + offset; break; } case 0x10B: { // STRH <Rd>, [<Rn>, -<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] - _registers[rm]; _system._memory.Write16(address, _registers[rd]); break; } case 0x18B: { // STRH <Rd>, [<Rn>, +<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] + _registers[rm]; _system._memory.Write16(address, _registers[rd]); break; } case 0x14B: { // STRH <Rd>, [<Rn>], #-<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] - offset; _system._memory.Write16(address, _registers[rd]); break; } case 0x1CB: { // STRH <Rd>, [<Rn>], #+<offset_8> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] + offset; _system._memory.Write16(address, _registers[rd]); break; } case 0x12B: { // STRH <Rd>, [<Rn>, -<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] - _registers[rm]; _system._memory.Write16(address, _registers[rd]); _registers[rn] = address; break; } case 0x1AB: { // STRH <Rd>, [<Rn>, +<Rm>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rm = instruction & 0xF; uint32_t address = _registers[rn] + _registers[rm]; _system._memory.Write16(address, _registers[rd]); _registers[rn] = address; break; } case 0x16B: { // STRH <Rd>, [<Rn>, #-<offset_8>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] - offset; _system._memory.Write16(address, _registers[rd]); _registers[rn] = address; break; } case 0x1EB: { // STRH <Rd>, [<Rn>, #+<offset_8>] uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t offset = (instruction & 0xF) | ((instruction >> 4) & 0xF0); uint32_t address = _registers[rn] + offset; _system._memory.Write16(address, _registers[rd]); _registers[rn] = address; break; } // STRT CASE_RANGE16(0x420) { // STRT <Rd>, [<Rn>], #-<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address - offset; break; } CASE_RANGE16(0x4A0) { // STRT <Rd>, [<Rn>], #+<offset_12> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint16_t offset = (instruction & 0xFFF); uint32_t address = _registers[rn]; if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address + offset; break; } case 0x620: case 0x628: { // STRT <Rd>, [<Rn>], -<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address - offset; break; } case 0x622: case 0x62A: { // STRT <Rd>, [<Rn>], -<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address - offset; break; } case 0x624: case 0x62C: { // STRT <Rd>, [<Rn>], -<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address - offset; break; } case 0x626: case 0x62E: { // STRT <Rd>, [<Rn>], -<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address - offset; break; } case 0x6A0: case 0x6A8: { // STRT <Rd>, [<Rn>], +<Rm>, LSL #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSL(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address + offset; break; } case 0x6A2: case 0x6AA: { // STRT <Rd>, [<Rn>], +<Rm>, LSR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandLSR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address + offset; break; } case 0x6A4: case 0x6AC: { // STRT <Rd>, [<Rn>], +<Rm>, ASR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandASR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address + offset; break; } case 0x6A6: case 0x6AE: { // STRT <Rd>, [<Rn>], +<Rm>, ROR #<shift_imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t address = _registers[rn]; uint32_t offset = GetShifterOperandROR(instruction); if (InAPrivilegedMode()) { if (rd == 15 || rd < 8 || (!InABankedUserRegistersMode() && rd < 13)) { _system._memory.Write32(address, _registers[rd]); } else { _system._memory.Write32(address, _registersUser[rd - 8]); } } else { _system._memory.Write32(address, _registers[rd]); } _registers[rn] = address + offset; break; } // SUB case 0x040: case 0x048: { // SUB <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSL(instruction); SUB(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x041: { // SUB <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSLReg(instruction); SUB(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x042: case 0x04A: { // SUB <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSR(instruction); SUB(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x043: { // SUB <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandLSRReg(instruction); SUB(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x044: case 0x04C: { // SUB <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASR(instruction); SUB(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x045: { // SUB <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandASRReg(instruction); SUB(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x046: // SUB <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x04E: { // SUB <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandROR(instruction); SUB(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x047: { // SUB <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandRORReg(instruction); SUB(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x050: case 0x058: { // SUBS <Rd>, <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSL(instruction); SUB(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLFlags(instruction); SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x051: { // SUBS <Rd>, <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSLReg(instruction); SUB(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSLRegFlags(instruction); SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x052: case 0x05A: { // SUBS <Rd>, <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSR(instruction); SUB(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRFlags(instruction); SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x053: { // SUBS <Rd>, <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandLSRReg(instruction); SUB(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandLSRRegFlags(instruction); SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x054: case 0x05C: { // SUBS <Rd>, <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASR(instruction); SUB(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRFlags(instruction); SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x055: { // SUBS <Rd>, <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandASRReg(instruction); SUB(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandASRRegFlags(instruction); SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x056: // SUBS <Rd>, <Rn>, <Rm>, RRX #<imm> case 0x05E: { // SUBS <Rd>, <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandROR(instruction); SUB(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORFlags(instruction); SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } case 0x057: { // SUBS <Rd>, <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandRORReg(instruction); SUB(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandRORRegFlags(instruction); SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } CASE_RANGE16(0x240) { // SUB <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint32_t operand = GetShifterOperandImm(instruction); SUB(_registers[rn], operand, _registers[rd]); if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } CASE_RANGE16(0x250) { // SUBS <Rd>, <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint8_t rd = (instruction >> 12) & 0xF; if (rd == REGPC) { uint32_t operand = GetShifterOperandImm(instruction); SUB(_registers[rn], operand, _registers[rd]); _cpsr = _spsr; UpdateMode(); _pipelineInstruction = ARM_NOP; } else { uint32_t operand = GetShifterOperandImmFlags(instruction); SUB_FLAGS(_registers[rn], operand, _registers[rd], _hostFlags); if (rd == REGPC) _pipelineInstruction = ARM_NOP; } break; } // SWI CASE_RANGE256(0xF00) { // SWI <immed_24> uint32_t imm = instruction & 0xFFFFFF; SoftwareInterrupt(imm); break; } // SWP case 0x109: { // SWP <Rd>, <Rm>, [<Rn>] uint8_t rm = (instruction)& 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; uint32_t temp = _system._memory.Read32(address); ROR(temp, (address & 0x3) * 8, temp); _system._memory.Write32(address, _registers[rm]); _registers[rd] = temp; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } // SWPB case 0x149: { // SWPB <Rd>, <Rm>, [<Rn>] uint8_t rm = (instruction)& 0xF; uint8_t rd = (instruction >> 12) & 0xF; uint8_t rn = (instruction >> 16) & 0xF; uint32_t address = _registers[rn]; uint8_t temp = _system._memory.Read8(address); _system._memory.Write8(address, _registers[rm]); _registers[rd] = temp; if (rd == REGPC) _pipelineInstruction = ARM_NOP; break; } // TEQ case 0x130: case 0x138: { // TEQ <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSLFlags(instruction); TEQ(_registers[rn], operand, _hostFlags); break; } case 0x131: { // TEQ <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSLRegFlags(instruction); TEQ(_registers[rn], operand, _hostFlags); break; } case 0x132: case 0x13A: { // TEQ <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSRFlags(instruction); TEQ(_registers[rn], operand, _hostFlags); break; } case 0x133: { // TEQ <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSRRegFlags(instruction); TEQ(_registers[rn], operand, _hostFlags); break; } case 0x134: case 0x13C: { // TEQ <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandASRFlags(instruction); TEQ(_registers[rn], operand, _hostFlags); break; } case 0x135: { // TEQ <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandASRRegFlags(instruction); TEQ(_registers[rn], operand, _hostFlags); break; } case 0x136: // TEQ <Rn>, <Rm>, RRX #<imm> case 0x13E: { // TEQ <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandRORFlags(instruction); TEQ(_registers[rn], operand, _hostFlags); break; } case 0x137: { // TEQ <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandRORRegFlags(instruction); TEQ(_registers[rn], operand, _hostFlags); break; } CASE_RANGE16(0x330) { // TEQ <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandImmFlags(instruction); TEQ(_registers[rn], operand, _hostFlags); break; } // TST case 0x110: case 0x118: { // TST <Rn>, <Rm>, LSL #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSLFlags(instruction); TST(_registers[rn], operand, _hostFlags); break; } case 0x111: { // TST <Rn>, <Rm>, LSL <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSLRegFlags(instruction); TST(_registers[rn], operand, _hostFlags); break; } case 0x112: case 0x11A: { // TST <Rn>, <Rm>, LSR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSRFlags(instruction); TST(_registers[rn], operand, _hostFlags); break; } case 0x113: { // TST <Rn>, <Rm>, LSR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandLSRRegFlags(instruction); TST(_registers[rn], operand, _hostFlags); break; } case 0x114: case 0x11C: { // TST <Rn>, <Rm>, ASR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandASRFlags(instruction); TST(_registers[rn], operand, _hostFlags); break; } case 0x115: { // TST <Rn>, <Rm>, ASR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandASRRegFlags(instruction); TST(_registers[rn], operand, _hostFlags); break; } case 0x116: // TST <Rn>, <Rm>, RRX #<imm> case 0x11E: { // TST <Rn>, <Rm>, ROR #<imm> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandRORFlags(instruction); TST(_registers[rn], operand, _hostFlags); break; } case 0x117: { // TST <Rn>, <Rm>, ROR <Rs> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandRORRegFlags(instruction); TST(_registers[rn], operand, _hostFlags); break; } CASE_RANGE16(0x310) { // TST <Rn>, #<immediate> uint8_t rn = (instruction >> 16) & 0xF; uint32_t operand = GetShifterOperandImmFlags(instruction); TST(_registers[rn], operand, _hostFlags); break; } // UMLAL case 0x0A9: { // UMLAL <RdLo>, <RdHi>, <Rm>, <Rs> uint8_t rdLo = (instruction >> 12) & 0xF; uint8_t rdHi = (instruction >> 16) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 8) & 0xF; UMLAL(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi]); if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x0B9: { // UMLALS <RdLo>, <RdHi>, <Rm>, <Rs> uint8_t rdLo = (instruction >> 12) & 0xF; uint8_t rdHi = (instruction >> 16) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 8) & 0xF; UMLAL_FLAGS(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi], _hostFlags); if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP; break; } // UMULL case 0x089: { // UMULL <RdLo>, <RdHi>, <Rm>, <Rs> uint8_t rdLo = (instruction >> 12) & 0xF; uint8_t rdHi = (instruction >> 16) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 8) & 0xF; UMULL(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi]); if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP; break; } case 0x099: { // UMULLS <RdLo>, <RdHi>, <Rm>, <Rs> uint8_t rdLo = (instruction >> 12) & 0xF; uint8_t rdHi = (instruction >> 16) & 0xF; uint8_t rs = (instruction >> 8) & 0xF; uint8_t rm = (instruction >> 8) & 0xF; UMULL_FLAGS(_registers[rm], _registers[rs], _registers[rdLo], _registers[rdHi], _hostFlags); if (rdLo == REGPC || rdHi == REGPC) _pipelineInstruction = ARM_NOP; break; } default: { Log(Error, "Unknown ARM instruction found: 0x%08x at PC=0x%08x", instruction, _registers[REGPC] - 8); throw BreakPointARMException(0); __debugbreak(); break; } } }
229,759
116,189
// Copyright 2019 The Souper Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "InterpreterInfra.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" #include "souper/Infer/Interpreter.h" #include "souper/Infer/AbstractInterpreter.h" #include "souper/Util/LLVMUtils.h" namespace { static llvm::cl::opt<bool> DebugMode("debug-mode", llvm::cl::desc("Print debugging information."), llvm::cl::init(false)); } using namespace souper; using namespace llvm; // EvalValueKB implementation // ----------------------------- EvalValueKB::EvalValueKB(KnownBits Val) { K = ValueKind::Val; ValueKB = Val; } EvalValueKB::EvalValueKB(EvalValue &Val) : EvalValue(Val) { if (hasValue()) { ValueKB.One = Val.getValue(); ValueKB.Zero = ~Val.getValue(); } } KnownBits EvalValueKB::getValueKB() { if (K != ValueKind::Val) { llvm::errs() << "EvalValueKB: KnownBits not initialized.\n"; llvm::report_fatal_error("exiting"); } return ValueKB; } // KBTesting implementation // ----------------------------- EvalValueKB KBTesting::merge(EvalValueKB a, EvalValueKB b) { if (!a.hasValue()) return b; if (!b.hasValue()) return a; // FIXME: Handle other ValueKind types. how? assert(a.hasValue() && b.hasValue()); return EvalValueKB(KnownBitsAnalysis::mergeKnownBits({a.getValueKB(), b.getValueKB()})); } KnownBits KBTesting::setLowest(KnownBits x) { for (int i = 0; i < x.getBitWidth(); i++) { if (!x.Zero[i] && !x.One[i]) { x.One.setBit(i); return x; } } report_fatal_error("faulty setLowest!"); } KnownBits KBTesting::clearLowest(KnownBits x) { for (int i = 0; i < x.getBitWidth(); i++) { if (!x.Zero[i] && !x.One[i]) { x.Zero.setBit(i); return x; } } report_fatal_error("faulty clearLowest!"); } llvm::APInt concat(llvm::APInt A, llvm::APInt B) { auto W = A.getBitWidth() + B.getBitWidth(); return (A.zext(W) << B.getBitWidth()) | B.zext(W); } EvalValueKB KBTesting::bruteForce(KnownBits x, KnownBits y, llvm::KnownBits z, Inst::Kind Pred) { if (!x.isConstant()) return merge(bruteForce(setLowest(x), y, z, Pred), bruteForce(clearLowest(x), y, z, Pred)); if (!y.isConstant()) return merge(bruteForce(x, setLowest(y), z, Pred), bruteForce(x, clearLowest(y), z, Pred)); if (!z.isConstant()) return merge(bruteForce(x, y, setLowest(z), Pred), bruteForce(x, y, clearLowest(z), Pred)); auto xc = x.getConstant(); auto yc = y.getConstant(); auto zc = z.getConstant(); EvalValue Result; switch (Pred) { case Inst::Select: Result = (xc != 0) ? yc : zc; break; case Inst::FShl: Result = (concat(xc, yc) << (zc.urem(WIDTH))).trunc(WIDTH); break; case Inst::FShr: Result = (concat(xc, yc).lshr(zc.urem(WIDTH))).trunc(WIDTH); break; default: report_fatal_error("Unhandled ternary operator."); } return Result; } EvalValueKB KBTesting::bruteForce(KnownBits x, KnownBits y, Inst* I) { if (!x.isConstant()) return merge(bruteForce(setLowest(x), y, I), bruteForce(clearLowest(x), y, I)); if (!y.isConstant()) return merge(bruteForce(x, setLowest(y), I), bruteForce(x, clearLowest(y), I)); auto xc = x.getConstant(); auto yc = y.getConstant(); ValueCache Vals{{I->Ops[0], xc}, {I->Ops[1], yc}}; ConcreteInterpreter C(Vals); EvalValue Result = C.evaluateInst(I); return Result; } bool KBTesting::nextKB(llvm::KnownBits &x) { for (int i = 0; i < x.getBitWidth(); i++) { if (!x.Zero[i] && !x.One[i]) { x.Zero.setBit(i); return true; } if (x.Zero[i] && !x.One[i]) { x.Zero.clearBit(i); x.One.setBit(i); return true; } if (!x.Zero[i] && x.One[i]) { x.Zero.clearBit(i); x.One.clearBit(i); continue; } // gtest doesn't allow putting fatal failures in non-void returning // functions; report_fatal_error("faulty nextKB!"); } return false; } bool testKB(llvm::KnownBits Calculated, EvalValueKB Expected, Inst::Kind K, const std::vector<llvm::KnownBits> &KBS) { // expected value is poison/ub; so let binary transfer functions do // whatever they want without complaining if (!Expected.hasValue()) return true; if (Calculated.getBitWidth() != Expected.ValueKB.getBitWidth()) { llvm::errs() << "Expected and Given have unequal bitwidths - Expected: " << Expected.ValueKB.getBitWidth() << ", Given: " << Calculated.getBitWidth() << '\n'; return false; } if (Calculated.hasConflict() || Expected.ValueKB.hasConflict()) { llvm::errs() << "Expected or Given result has a conflict\n"; return false; } if (KnownBitsAnalysis::isConflictingKB(Calculated, Expected.ValueKB)) { outs() << "Unsound!! " << Inst::getKindName(K) << "\nInputs: "; for (auto KB : KBS) { outs() << KnownBitsAnalysis::knownBitsString(KB) << " "; } outs() << "\nCalculated: " << KnownBitsAnalysis::knownBitsString(Calculated) << '\n'; outs() << "Expected: " << KnownBitsAnalysis::knownBitsString(Expected.ValueKB) << '\n'; return false; } return true; } bool KBTesting::testTernaryFn(Inst::Kind K, size_t Op0W, size_t Op1W, size_t Op2W) { llvm::KnownBits x(Op0W); do { llvm::KnownBits y(Op1W); do { llvm::KnownBits z(Op2W); do { InstContext IC; auto Op0 = IC.createVar(Op0W, "Op0"); auto Op1 = IC.createVar(Op1W, "Op1"); auto Op2 = IC.createVar(Op2W, "Op2"); auto I = IC.getInst(K, WIDTH, {Op0, Op1, Op2}); std::unordered_map<Inst *, llvm::KnownBits> C{{Op0, x}, {Op1, y}, {Op2, z}}; KnownBitsAnalysis KB(C); ConcreteInterpreter BlankCI; auto Calculated = KB.findKnownBits(I, BlankCI, false); auto Expected = bruteForce(x, y, z, K); if (!testKB(Calculated, Expected, K, {x, y, z})) { return false; } } while (nextKB(z)); } while (nextKB(y)); } while (nextKB(x)); return true; } bool KBTesting::testFn(Inst::Kind K) { llvm::KnownBits x(WIDTH); do { llvm::KnownBits y(WIDTH); do { InstContext IC; auto Op0 = IC.createVar(WIDTH, "Op0"); auto Op1 = IC.createVar(WIDTH, "Op1"); auto I = IC.getInst(K, WIDTH, {Op0, Op1}); std::unordered_map<Inst *, llvm::KnownBits> C{{Op0, x}, {Op1, y}}; KnownBitsAnalysis KB(C); ConcreteInterpreter BlankCI; auto Calculated = KB.findKnownBits(I, BlankCI, false); EvalValueKB Expected = bruteForce(x, y, I); if (!testKB(Calculated, Expected, K, {x, y})) return false; } while(nextKB(y)); } while(nextKB(x)); return true; } // CRTesting Implementation // ----------------------------- bool CRTesting::rangeContainsAll(const ConstantRange &R, const bool Table[]) { const int Range = 1 << WIDTH; for (int i = 0; i < Range; ++i) { if (Table[i]) { APInt a(WIDTH, i); if (!R.contains(a)) return false; } } return true; } // Find the largest hole and build a ConstantRange around it ConstantRange CRTesting::bestCR(const bool Table[], const int Width) { const int Range = 1 << Width; unsigned Pop = 0; unsigned Any; for (unsigned i = 0; i < Range; ++i) if (Table[i]) { ++Pop; Any = i; } if (Pop == 0) return ConstantRange(Width, /*isFullSet=*/false); if (Pop == Range) return ConstantRange(Width, /*isFullSet=*/true); unsigned Hole = 0, MaxHole = 0, MaxSize = 0; bool inHole = false; for (unsigned i = 0; i < Range; ++i) { if (Table[i]) { if (inHole) { inHole = false; if ((i - Hole) > MaxSize) { MaxHole = Hole; MaxSize = i - Hole; } } } else { if (!inHole) { inHole = true; Hole = i; } } } if (inHole && ((Range - Hole) > MaxSize)) { MaxHole = Hole; MaxSize = Range - Hole; } unsigned Bottom = 0; while (!Table[Bottom]) ++Bottom; unsigned Top = Range - 1; while (!Table[Top]) --Top; ConstantRange R(Width, false); if ((Bottom + (Range - 1 - Top)) > MaxSize) { APInt Lo(Width, Bottom); APInt Hi(Width, (Top + 1) % Range); R = ConstantRange(Lo, Hi); } else { APInt Lo(Width, (MaxHole + MaxSize) % Range); APInt Hi(Width, MaxHole); R = ConstantRange(Lo, Hi); } assert(rangeContainsAll(R, Table)); if (Pop == 1) { assert(R.getLower().getLimitedValue() == Any); assert(R.getUpper().getLimitedValue() == (Any + 1) % Range); } else { APInt L1 = R.getLower() + 1; ConstantRange R2(L1, R.getUpper()); assert(!rangeContainsAll(R2, Table)); ConstantRange R3(R.getLower(), R.getUpper() - 1); assert(!rangeContainsAll(R3, Table)); } return R; } ConstantRange CRTesting::exhaustive(const ConstantRange &L, const ConstantRange &R, Inst::Kind pred, const ConstantRange &Untrusted) { if (L.isEmptySet() || R.isEmptySet()) return ConstantRange(WIDTH, /*isFullSet=*/false); bool Table[1 << WIDTH]; for (int i = 0; i < (1 << WIDTH); ++i) Table[i] = false; auto LI = L.getLower(); do { auto RI = R.getLower(); do { APInt Val; switch (pred) { case Inst::And: Val = LI & RI; break; case Inst::Or: Val = LI | RI; break; case Inst::Add: Val = LI + RI; break; case Inst::Sub: Val = LI - RI; break; case Inst::Shl: Val = LI.shl(RI); break; case Inst::LShr: Val = LI.lshr(RI); break; case Inst::AShr: Val = LI.ashr(RI); break; default: report_fatal_error("unknown opcode"); } if (!Untrusted.contains(Val)) { outs() << "Unsound! " << Inst::getKindName(pred) << '\n'; outs() << L << ' ' << Inst::getKindName(pred) << ' ' << R << '\n'; outs() << "Calculated value " << Untrusted << " must contain: " << Val << '\n'; report_fatal_error("Unsound!"); } Table[Val.getLimitedValue()] = true; ++RI; } while (RI != R.getUpper()); ++LI; } while (LI != L.getUpper()); return bestCR(Table, WIDTH); } void CRTesting::check(const ConstantRange &L, const ConstantRange &R, Inst::Kind pred) { ConstantRange FastRes(WIDTH, true); switch (pred) { case Inst::Or: FastRes = BinaryTransferFunctionsCR::binaryOr(L, R); break; case Inst::And: FastRes = BinaryTransferFunctionsCR::binaryAnd(L, R); break; default: report_fatal_error("unsupported opcode"); } ConstantRange PreciseRes = exhaustive(L, R, pred, FastRes); assert(getSetSize(PreciseRes).ule(getSetSize(FastRes))); } ConstantRange CRTesting::nextCR(const ConstantRange &CR) { auto L = CR.getLower(); auto U = CR.getUpper(); do { if (U.isMaxValue()) ++L; ++U; } while (L == U && !L.isMinValue() && !L.isMaxValue()); return ConstantRange(L, U); } bool CRTesting::testFn(Inst::Kind pred) { ConstantRange L(WIDTH, /*isFullSet=*/false); ConstantRange R(WIDTH, /*isFullSet=*/false); do { do { check(L, R, pred); R = nextCR(R); } while (!R.isEmptySet()); L = nextCR(L); } while (!L.isEmptySet()); return true; } // RBTesting Implementation // ----------------------------- bool RBTesting::nextRB(llvm::APInt &Val) { if (Val.isAllOnesValue()) { return false; } else { ++Val; return true; } } std::vector<llvm::APInt> explodeUnrestrictedBits(const llvm::APInt &Value, const llvm::APInt &Mask, const int WIDTH) { std::vector<llvm::APInt> Result { Value }; for (int i = 0; i < WIDTH; ++i) { if ( (Mask & (1 << i)) == 0 ) { auto Copy = Result; for (auto &Y : Copy) { Result.push_back(Y | (1 << i)); } } } return Result; } // Probably refactor to unify these two std::vector<llvm::APInt> explodeRestrictedBits(const llvm::APInt &X, const int WIDTH) { std::vector<llvm::APInt> Result { llvm::APInt(WIDTH, 0) }; for (int i = 0; i < WIDTH; ++i) { if ( (X & (1 << i)) != 0 ) { auto Copy = Result; for (auto &Y : Copy) { Result.push_back(Y | 1 << i); } } } return Result; } llvm::APInt exhaustiveRB(Inst *I, Inst *X, Inst *Y, const llvm::APInt &RBX, const llvm::APInt &RBY, const int WIDTH) { llvm::APInt RB(WIDTH, 0); auto XPartial = explodeRestrictedBits(RBX, X->Width); auto YPartial = explodeRestrictedBits(RBY, Y->Width); int cases = 0; for (auto P0 : XPartial) { for (auto P1 : YPartial) { if (DebugMode) { llvm::outs() << "Restricted EXP: " << getPaddedBinaryString(P0) << "\t" << getPaddedBinaryString(P1) << "\n"; } auto I0 = explodeUnrestrictedBits(P0, P0 | RBX, X->Width); auto I1 = explodeUnrestrictedBits(P1, P1 | RBY, Y->Width); std::map<int, std::pair<bool, bool>> Seen; for (auto i0 : I0) { for (auto i1 : I1) { if (DebugMode) { llvm::outs() << "Unrestricted EXP: " << getPaddedBinaryString(i0) << "\t" << getPaddedBinaryString(i1) << "\n"; } ++cases; ValueCache C = {{{X, i0}, {Y, i1}}}; ConcreteInterpreter Interp(C); auto Val_ = Interp.evaluateInst(I); if (!Val_.hasValue()) { continue; } auto Val = Val_.getValue(); for (int i = 0; i < WIDTH; ++i) { if ((Val & (1 << i)) == 0) Seen[i].first = true; if ((Val & (1 << i)) != 0) Seen[i].second = true; } } } for (int i = 0 ; i < WIDTH; ++i) { if (!Seen[i].first || !Seen[i].second) { RB = RB | (1 << i); } } } } if (DebugMode) { llvm::outs() << "Cases : " << cases << "\n"; } return RB; } void compareRB(const llvm::APInt &RBComputed, const llvm::APInt &RBExhaustive, bool &fail, bool &FoundMorePrecise, double &ImpreciseCount) { for (int i = 0; i < RBComputed.getBitWidth(); ++i) { if (((RBComputed & (1 << i)) == 0) && ((RBExhaustive & (1 << i)) != 0)) fail = true; if (((RBExhaustive & (1 << i)) == 0) && ((RBComputed & (1 << i)) != 0)) { FoundMorePrecise = true; // FIXME add the number of bits, not the number of incorrect cases ++ImpreciseCount; } } } bool RBTesting::testFn(const Inst::Kind K, const bool CheckPrecision) { llvm::APInt RB0(WIDTH, 0); InstContext IC; Inst *X = IC.createVar(WIDTH, "X"); Inst *Y = IC.createVar(WIDTH, "Y"); std::pair<size_t, size_t> Stats; double ImpreciseCount = 0; do { llvm::APInt RB1(WIDTH, 0); do { auto EffectiveWidth = WIDTH; if (K == Inst::Eq || K == Inst::Ne || K == Inst::Sle || K == Inst::Slt || K == Inst::Ule || K == Inst::Ult) { EffectiveWidth = 1; } auto Expr = IC.getInst(K, EffectiveWidth, {X, Y}); RestrictedBitsAnalysis RBA{{{X, RB0}, {Y, RB1}}}; if (DebugMode) { llvm::outs() << "RBInputs : " << getPaddedBinaryString(RB0) << "\t" << getPaddedBinaryString(RB1) << "\n"; } auto RBComputed = RBA.findRestrictedBits(Expr); auto RBExhaustive = exhaustiveRB(Expr, X, Y, RB0, RB1, EffectiveWidth); bool fail = false; bool FoundMorePrecise = false; compareRB(RBComputed, RBExhaustive, fail, FoundMorePrecise, ImpreciseCount); Stats.first++; if (fail) { llvm::outs() << Inst::getKindName(K) << ":\t"; llvm::outs() << "Inputs: " << getPaddedBinaryString(RB0) << ", " << getPaddedBinaryString(RB1) << "\n"; llvm::outs() << "Computed: " << getPaddedBinaryString(RBComputed) << "\n"; llvm::outs() << "Exhaustive: " << getPaddedBinaryString(RBExhaustive) << " <-- UNSOUND!!!!\n"; return false; } if (CheckPrecision) { llvm::outs() << Inst::getKindName(K) << ":\t"; llvm::outs() << "Inputs: " << getPaddedBinaryString(RB0) << ", " << getPaddedBinaryString(RB1) << "\t"; llvm::outs() << "Computed:\t" << getPaddedBinaryString(RBComputed) << "\t"; llvm::outs() << "Exhaustive:\t" << getPaddedBinaryString(RBExhaustive); if (FoundMorePrecise) { llvm::outs() << " <-- imprecise!"; Stats.second++; } llvm::outs() << "\n"; } } while (nextRB(RB1)); } while (nextRB(RB0)); if (CheckPrecision) { llvm::outs() << "TOTAL imprecise results: " << Inst::getKindName(K) << " : " << Stats.second << "/" << Stats.first << "\n"; llvm::outs() << "TOTAL imprecise bits: " << ImpreciseCount << "\n\n"; } return true; } llvm::APInt exhaustiveRBTernary(Inst *I, Inst *X, Inst *Y, Inst *Z, const llvm::APInt &RBX, const llvm::APInt &RBY, const llvm::APInt &RBZ, const int WIDTH) { llvm::APInt RB(WIDTH, 0); auto XPartial = explodeRestrictedBits(RBX, X->Width); auto YPartial = explodeRestrictedBits(RBY, Y->Width); auto ZPartial = explodeRestrictedBits(RBZ, Z->Width); int cases = 0; double ImpreciseCount = 0; for (auto P0 : XPartial) { for (auto P1 : YPartial) { for (auto P2 : ZPartial) { if (DebugMode) { llvm::outs() << "Restricted EXP: " << getPaddedBinaryString(P0) << "\t" << getPaddedBinaryString(P1) << "\t" << getPaddedBinaryString(P2) << "\n"; } auto I0 = explodeUnrestrictedBits(P0, P0 | RBX, X->Width); auto I1 = explodeUnrestrictedBits(P1, P1 | RBY, Y->Width); auto I2 = explodeUnrestrictedBits(P2, P2 | RBZ, Z->Width); std::map<int, std::pair<bool, bool>> Seen; for (auto i0 : I0) { for (auto i1 : I1) { for (auto i2 : I2) { if (DebugMode) { llvm::outs() << "Unrestricted EXP: " << getPaddedBinaryString(i0) << "\t" << getPaddedBinaryString(i1) << "\t" << getPaddedBinaryString(i2) << "\n"; } ++cases; ValueCache C = {{{X, i0}, {Y, i1}, {Z, i2}}}; ConcreteInterpreter Interp(C); auto Val_ = Interp.evaluateInst(I); if (!Val_.hasValue()) { continue; } auto Val = Val_.getValue(); for (int i = 0; i < WIDTH; ++i) { if ((Val & (1 << i)) == 0) Seen[i].first = true; if ((Val & (1 << i)) != 0) Seen[i].second = true; } } } } for (int i = 0; i < WIDTH; ++i) { if (!Seen[i].first || !Seen[i].second) { RB = RB | (1 << i); } } } } } if (DebugMode) { llvm::outs() << "Cases : " << cases << "\n"; } return RB; } bool RBTesting::testFnTernary(const Inst::Kind K, const bool CheckPrecision) { llvm::APInt RB0(WIDTH, 0); InstContext IC; Inst *X = IC.createVar(WIDTH, "X"); if (K == Inst::Select) { X = IC.createVar(1, "X"); RB0 = llvm::APInt(1, 0); } Inst *Y = IC.createVar(WIDTH, "Y"); Inst *Z = IC.createVar(WIDTH, "Z"); std::pair<size_t, size_t> Stats; double ImpreciseCount = 0; do { llvm::APInt RB1(WIDTH, 0); do { llvm::APInt RB2(WIDTH, 0); do { auto EffectiveWidth = WIDTH; if (K == Inst::Eq || K == Inst::Ne || K == Inst::Sle || K == Inst::Slt || K == Inst::Ule || K == Inst::Ult) { EffectiveWidth = 1; } std::vector<Inst *> Ops = {X, Y, Z}; std::unordered_map<Inst *, llvm::APInt> RBCache = {{X, RB0}, {Y, RB1}, {Z, RB2}}; auto Expr = IC.getInst(K, EffectiveWidth, Ops); RestrictedBitsAnalysis RBA{RBCache}; if (DebugMode) { llvm::outs() << "RBInputs : " << getPaddedBinaryString(RB0) << "\t" << getPaddedBinaryString(RB1) << '\t' << getPaddedBinaryString(RB2); llvm::outs() << '\n'; } auto RBComputed = RBA.findRestrictedBits(Expr); auto RBExhaustive = exhaustiveRBTernary(Expr, X, Y, Z, RB0, RB1, RB2, EffectiveWidth); bool fail = false; bool FoundMorePrecise = false; compareRB(RBComputed, RBExhaustive, fail, FoundMorePrecise, ImpreciseCount); Stats.first++; if (CheckPrecision || fail) { llvm::outs() << Inst::getKindName(K) << ":\t"; llvm::outs() << "Inputs: " << getPaddedBinaryString(RB0) << ", " << getPaddedBinaryString(RB1) << ", " << getPaddedBinaryString(RB2); llvm::outs() << "\t"; llvm::outs() << "Computed: " << getPaddedBinaryString(RBComputed) << "\t"; llvm::outs() << "Exhaustive: " << getPaddedBinaryString(RBExhaustive); if (fail) { llvm::outs() << " <-- UNSOUND!!!!\n"; return false; } else if (FoundMorePrecise) { llvm::outs() << " <-- imprecise!"; Stats.second++; } llvm::outs() << "\n"; } } while (nextRB(RB2)); } while (nextRB(RB1)); } while (nextRB(RB0)); if (CheckPrecision) { llvm::outs() << "TOTAL imprecise results: " << Inst::getKindName(K) << " : " << Stats.second << "/" << Stats.first << "\n"; llvm::outs() << "TOTAL imprecise bits: " << ImpreciseCount << "\n\n"; } return true; }
22,602
8,371
#include "rendering/records/SlideGpuRecord.h" #include "rendering/utility/gl/GLTexture.h" SlideGpuRecord::SlideGpuRecord( std::shared_ptr<GLTexture> texture ) : m_texture( texture ), m_activeLevel( 0 ) { } std::weak_ptr<GLTexture> SlideGpuRecord::texture() { return m_texture; }
295
117
/* * */ #include "hemerageneratorsconfigureplugin_p.h" namespace Hemera { namespace Generators { ConfigurePlugin::ConfigurePlugin(QObject* parent) : QObject(parent) , d(new Private) { } ConfigurePlugin::~ConfigurePlugin() { delete d; } BaseConfigure *ConfigurePlugin::baseConfigure() { return d->baseGenerator; } } }
341
121
#include "generator/x86_64/generator.h" #include <iostream> #include <sstream> using namespace generator::x86_64; namespace { std::array<std::array<const char *, 4>, REG_COUNT> reg_names = { std::array<const char *, 4>{"rax", "eax", "ax", "al"}, {"rbx", "ebx", "bx", "bl"}, {"rcx", "ecx", "cx", "cl"}, {"rdx", "edx", "dx", "dl"}, {"rdi", "edi", "di", "dil"}, {"rsi", "esi", "si", "sil"}, {"r8", "r8d", "r8w", "r8b"}, {"r9", "r9d", "r9w", "r9b"}, {"r10", "r10d", "r10w", "r10b"}, {"r11", "r11d", "r11w", "r11b"}, {"r12", "r12d", "r12w", "r12b"}, {"r13", "r13d", "r13w", "r13b"}, {"r14", "r14d", "r14w", "r14b"}, {"r15", "r15d", "r15w", "r15b"}, }; std::array<const char *, FP_REG_COUNT> fp_reg_names = {"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"}; std::array<REGISTER, 6> call_reg = {REG_DI, REG_SI, REG_D, REG_C, REG_8, REG_9}; // only for integers const char *reg_name(const REGISTER reg, const Type type) { const auto &arr = reg_names[reg]; switch (type) { case Type::imm: case Type::i64: return arr[0]; case Type::i32: return arr[1]; case Type::i16: return arr[2]; case Type::i8: return arr[3]; default: assert(0); exit(1); } } const char *mem_size(const Type type) { switch (type) { case Type::imm: case Type::i64: return "QWORD PTR"; case Type::i32: return "DWORD PTR"; case Type::i16: return "WORD PTR"; case Type::i8: return "BYTE PTR"; case Type::f32: case Type::f64: case Type::mt: assert(0); exit(1); } assert(0); exit(1); } Type choose_type(SSAVar *typ1, SSAVar *typ2) { assert(typ1->type == typ2->type || typ1->is_immediate() || typ2->is_immediate()); if (typ1->is_immediate() && typ2->is_immediate()) { return Type::i64; } else if (typ1->is_immediate()) { return typ2->type; } else { return typ1->type; } } } // namespace void RegAlloc::compile_blocks() { auto compiled_blocks = std::vector<BasicBlock *>{}; for (const auto &bb : gen->ir->basic_blocks) { if (bb->gen_info.compiled) { continue; } if (!is_block_top_level(bb.get())) { continue; } auto supported = true; for (auto *input : bb->inputs) { if (!std::holds_alternative<size_t>(input->info)) { supported = false; break; } const auto static_idx = std::get<size_t>(input->info); input->gen_info.location = SSAVar::GeneratorInfoX64::STATIC; input->gen_info.static_idx = static_idx; } if (!supported) { assert(0); continue; } if (!bb->gen_info.input_map_setup) { generate_input_map(bb.get()); } size_t max_stack_frame = 0; compiled_blocks.clear(); compile_block(bb.get(), true, max_stack_frame, compiled_blocks); translation_blocks.clear(); asm_buf.clear(); } // when blocks have a self-contained circular reference chain, they do not get recognized as top-level so // we compile them here and use the lowest-id-block (which should later be the lowest-address one) as the first for (const auto &bb : gen->ir->basic_blocks) { if (bb->gen_info.compiled) { continue; } auto supported = true; for (auto *input : bb->inputs) { if (!std::holds_alternative<size_t>(input->info)) { supported = false; break; } const auto static_idx = std::get<size_t>(input->info); input->gen_info.location = SSAVar::GeneratorInfoX64::STATIC; input->gen_info.static_idx = static_idx; } if (!supported) { assert(0); continue; } // only for testing if (!bb->gen_info.input_map_setup) { generate_input_map(bb.get()); } size_t max_stack_frame = 0; compiled_blocks.clear(); bb->gen_info.manual_top_level = true; compile_block(bb.get(), true, max_stack_frame, compiled_blocks); translation_blocks.clear(); asm_buf.clear(); } } // compile all bblocks with an id greater than this with the normal generator constexpr size_t BB_OLD_COMPILE_ID_TIL = static_cast<size_t>(-1); // only merge bblocks with an id <= BB_MERGE_TIL_ID, otherwise mark them as a top-level block and pass inputs through statics constexpr size_t BB_MERGE_TIL_ID = static_cast<size_t>(-1); void RegAlloc::compile_block(BasicBlock *bb, const bool first_block, size_t &max_stack_frame_size, std::vector<BasicBlock *> &compiled_blocks) { RegMap reg_map = {}; FPRegMap fp_reg_map = {}; StackMap stack_map = {}; cur_bb = bb; cur_reg_map = &reg_map; cur_fp_reg_map = &fp_reg_map; cur_stack_map = &stack_map; // TODO: this hack is needed because syscalls have a continuation mapping so we cant create the input mapping in the previous' block // cfop if (!bb->gen_info.input_map_setup) { for (auto *input : bb->inputs) { if (!std::holds_alternative<size_t>(input->info)) { assert(0); exit(1); return; } const auto static_idx = std::get<size_t>(input->info); input->gen_info.location = SSAVar::GeneratorInfoX64::STATIC; input->gen_info.static_idx = static_idx; BasicBlock::GeneratorInfo::InputInfo info; info.location = BasicBlock::GeneratorInfo::InputInfo::STATIC; info.static_idx = static_idx; bb->gen_info.input_map.push_back(info); } bb->gen_info.input_map_setup = true; } if (bb->id > BB_OLD_COMPILE_ID_TIL) { gen->compile_block(bb); bb->gen_info.compiled = true; } else { // fill in reg_map and stack_map from inputs for (auto *var : bb->inputs) { if (var->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER) { reg_map[var->gen_info.reg_idx].cur_var = var; reg_map[var->gen_info.reg_idx].alloc_time = 0; } else if (var->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER) { fp_reg_map[var->gen_info.reg_idx].cur_var = var; fp_reg_map[var->gen_info.reg_idx].alloc_time = 0; } else if (var->gen_info.location == SSAVar::GeneratorInfoX64::STACK_FRAME) { const auto stack_slot = var->gen_info.stack_slot; if (stack_map.size() <= stack_slot) { stack_map.resize(stack_slot + 1); } stack_map[stack_slot].free = false; stack_map[stack_slot].var = var; } } if (!first_block) { if (!(gen->optimizations & Generator::OPT_NO_TRANS_BBS) || is_block_jumpable(bb)) { generate_translation_block(bb); } print_asm("b%zu_reg_alloc:\n", bb->id); print_asm("# MBRA\n"); // multi-block register allocation print_asm("# Virt Start: %#lx\n# Virt End: %#lx\n", bb->virt_start_addr, bb->virt_end_addr); } init_time_of_use(bb); compile_vars(bb); prepare_cf_ops(bb); max_stack_frame_size = std::max(max_stack_frame_size, stack_map.size()); { auto asm_block = AssembledBlock{}; asm_block.bb = bb; asm_block.assembly = asm_buf; asm_buf.clear(); asm_block.reg_map = reg_map; asm_block.fp_reg_map = fp_reg_map; asm_block.stack_map = std::move(stack_map); assembled_blocks.push_back(std::move(asm_block)); } cur_bb = nullptr; cur_stack_map = nullptr; cur_reg_map = nullptr; cur_fp_reg_map = nullptr; bb->gen_info.compiled = true; compiled_blocks.push_back(bb); // TODO: prioritize jumps so we can omit the jmp bX_reg_alloc for (const auto &cf_op : bb->control_flow_ops) { auto *target = cf_op.target(); if (target && !target->gen_info.compiled && target->id <= BB_MERGE_TIL_ID && !is_block_top_level(target) && !target->gen_info.call_cont_block) { compile_block(target, false, max_stack_frame_size, compiled_blocks); } if (cf_op.type == CFCInstruction::call) { // sometimes there are cases where a block is a call target and continuation block, // e.g. with noreturn calls the next block will be recognized as a continuation block auto *cont_block = std::get<CfOp::CallInfo>(cf_op.info).continuation_block; if (!cont_block->gen_info.compiled && !is_block_top_level(cont_block)) { compile_block(cont_block, false, max_stack_frame_size, compiled_blocks); } } else if (cf_op.type == CFCInstruction::icall) { auto *cont_block = std::get<CfOp::ICallInfo>(cf_op.info).continuation_block; if (!cont_block->gen_info.compiled && !is_block_top_level(cont_block)) { compile_block(cont_block, false, max_stack_frame_size, compiled_blocks); } } } if (first_block) { // need to add a bit of space to the stack since the cfops might need to spill to the stack max_stack_frame_size += gen->ir->statics.size(); // align to 16 bytes max_stack_frame_size = (((max_stack_frame_size * 8) + 15) & 0xFFFFFFFF'FFFFFFF0); for (auto *bb : compiled_blocks) { bb->gen_info.max_stack_size = max_stack_frame_size; } fprintf(gen->out_fd, "b%zu:\nsub rsp, %zu\n", bb->id, max_stack_frame_size); fprintf(gen->out_fd, "# MBRA\n"); // multi-block register allocation fprintf(gen->out_fd, "# Virt Start: %#lx\n# Virt End: %#lx\n", bb->virt_start_addr, bb->virt_end_addr); write_assembled_blocks(max_stack_frame_size, compiled_blocks); fprintf(gen->out_fd, "\n# Translation Blocks\n"); for (const auto &pair : translation_blocks) { fprintf(gen->out_fd, "b%zu:\nsub rsp, %zu\n", pair.first, max_stack_frame_size); fprintf(gen->out_fd, "# MBRATB\n"); // multi-block register allocation translation block fprintf(gen->out_fd, "%s\n", pair.second.c_str()); } fprintf(gen->out_fd, "\n"); translation_blocks.clear(); assembled_blocks.clear(); } } } void RegAlloc::compile_vars(BasicBlock *bb) { auto &reg_map = *cur_reg_map; std::ostringstream ir_stream; for (size_t var_idx = 0; var_idx < bb->variables.size(); ++var_idx) { auto *var = bb->variables[var_idx].get(); const auto cur_time = var_idx; // print ir for better readability // TODO: add flag for this to reduce useless stuff in asm file // TODO: when we merge ops, we need to print ir before the merged op ir_stream.str(""); var->print(ir_stream, gen->ir); print_asm("# %s\n", ir_stream.str().c_str()); if (var->gen_info.already_generated) { continue; } // TODO: this essentially skips input vars but we should have a seperate if for that // since the location of the input vars is supplied by the previous block if (var->is_immediate() || std::holds_alternative<size_t>(var->info)) { // skip immediates and statics, we load them on-demand continue; } if (!std::holds_alternative<std::unique_ptr<Operation>>(var->info)) { // skip vars that depend on ops of other vars for example continue; } auto *op = std::get<std::unique_ptr<Operation>>(var->info).get(); if (is_float(op->lifter_info.in_op_size) || is_float(var->type)) { compile_fp_op(var, cur_time); continue; } switch (op->type) { case Instruction::add: [[fallthrough]]; case Instruction::sub: [[fallthrough]]; case Instruction::shl: [[fallthrough]]; case Instruction::shr: [[fallthrough]]; case Instruction::sar: [[fallthrough]]; case Instruction::_or: [[fallthrough]]; case Instruction::_and: [[fallthrough]]; case Instruction::_xor: [[fallthrough]]; case Instruction::umax: [[fallthrough]]; case Instruction::umin: [[fallthrough]]; case Instruction::max: [[fallthrough]]; case Instruction::min: [[fallthrough]]; case Instruction::mul_l: [[fallthrough]]; case Instruction::ssmul_h: [[fallthrough]]; case Instruction::uumul_h: [[fallthrough]]; case Instruction::div: [[fallthrough]]; case Instruction::udiv: { auto *in1 = op->in_vars[0].get(); auto *in2 = op->in_vars[1].get(); auto *dst = op->out_vars[0]; // TODO: the imm-branch and not-imm-branch can probably be merged if we use a string as the second operand // and just put the imm in there if (in2->is_immediate() && !std::get<SSAVar::ImmInfo>(in2->info).binary_relative) { const auto imm_val = std::get<SSAVar::ImmInfo>(in2->info).val; REGISTER in1_reg; if (op->type != Instruction::ssmul_h && op->type != Instruction::uumul_h && op->type != Instruction::div && op->type != Instruction::udiv) { in1_reg = load_val_in_reg(cur_time, in1); } else { // need to load into rax and clear rdx in1_reg = load_val_in_reg(cur_time, in1, REG_A); // rdx gets clobbered by mul and used by div if (reg_map[REG_D].cur_var && reg_map[REG_D].cur_var->gen_info.last_use_time > cur_time) { save_reg(REG_D); } clear_reg(cur_time, REG_D); if (op->type == Instruction::div) { if (var->type == Type::i32) { print_asm("cdq\n"); } else { print_asm("cqo\n"); } } else if (op->type == Instruction::udiv) { print_asm("xor edx, edx\n"); } } const auto in1_reg_name = reg_name(in1_reg, choose_type(in1, in2)); REGISTER dst_reg = REG_NONE; if (op->type != Instruction::add || in1->gen_info.last_use_time == cur_time) { dst_reg = in1_reg; } else { // check if there is a free register for (size_t reg = 0; reg < REG_COUNT; ++reg) { if (reg_map[reg].cur_var == nullptr) { dst_reg = static_cast<REGISTER>(reg); break; } auto *var = reg_map[reg].cur_var; if (var->gen_info.last_use_time < cur_time) { dst_reg = static_cast<REGISTER>(reg); break; } } if (dst_reg == REG_NONE) { size_t in1_next_use = 0; for (auto use : in1->gen_info.uses) { if (use > cur_time) { in1_next_use = use; break; } } // check if there is a variable thats already saved on the stack and used after the dst auto check_unsaved_vars = !in1->gen_info.saved_in_stack; for (size_t reg = 0; reg < REG_COUNT; ++reg) { auto *var = reg_map[reg].cur_var; if (!check_unsaved_vars && !var->gen_info.saved_in_stack) { continue; } size_t var_next_use = 0; for (auto use : var->gen_info.uses) { if (use > cur_time) { var_next_use = use; break; } } if (var_next_use > in1_next_use) { dst_reg = static_cast<REGISTER>(reg); break; } } if (dst_reg == REG_NONE) { dst_reg = in1_reg; } } } const auto dst_reg_name = reg_name(dst_reg, choose_type(in1, in2)); if (reg_map[dst_reg].cur_var && reg_map[dst_reg].cur_var->gen_info.last_use_time > cur_time) { save_reg(dst_reg); } auto did_merge = false; if ((gen->optimizations & Generator::OPT_MERGE_OP) && dst && dst->ref_count == 1 && bb->variables.size() > var_idx + 1) { if (op->type == Instruction::add) { // check if next instruction is a load auto *next_var = bb->variables[var_idx + 1].get(); if (std::holds_alternative<std::unique_ptr<Operation>>(next_var->info)) { auto *next_op = std::get<std::unique_ptr<Operation>>(next_var->info).get(); if (!is_float(next_var->type) && !is_float(next_op->lifter_info.in_op_size)) { if (next_op->type == Instruction::load && next_op->in_vars[0] == dst) { auto *load_dst = next_op->out_vars[0]; // check for zero/sign-extend if (load_dst->ref_count == 1 && bb->variables.size() > var_idx + 2) { auto *nnext_var = bb->variables[var_idx + 2].get(); if (std::holds_alternative<std::unique_ptr<Operation>>(nnext_var->info)) { auto *nnext_op = std::get<std::unique_ptr<Operation>>(nnext_var->info).get(); if (nnext_op->in_vars[0] == load_dst && nnext_op->type == Instruction::zero_extend) { auto *ext_dst = nnext_op->out_vars[0]; if (imm_val != INT64_MIN && std::abs(imm_val) < 0x7FFFFFFF) { if (load_dst->type == Type::i32) { print_asm("mov %s, [%s + %ld]\n", reg_names[dst_reg][1], in1_reg_name, imm_val); } else { print_asm("movzx %s, %s [%s + %ld]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, imm_val); } } else { const auto imm_reg = load_val_in_reg(cur_time, in2); if (load_dst->type == Type::i32) { print_asm("mov %s, [%s + %s]\n", reg_names[dst_reg][1], in1_reg_name, reg_names[imm_reg][0]); } else { print_asm("movzx %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, reg_names[imm_reg][0]); } } clear_reg(cur_time, dst_reg); set_var_to_reg(cur_time, ext_dst, dst_reg); load_dst->gen_info.already_generated = true; ext_dst->gen_info.already_generated = true; did_merge = true; } else if (nnext_op->in_vars[0] == load_dst && nnext_op->type == Instruction::sign_extend) { auto *ext_dst = nnext_op->out_vars[0]; if (imm_val != INT64_MIN && std::abs(imm_val) < 0x7FFFFFFF) { if (load_dst->type == Type::i32) { assert(ext_dst->type == Type::i32 || ext_dst->type == Type::i64); print_asm("movsxd %s, %s [%s + %ld]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, imm_val); } else { print_asm("movsx %s, %s [%s + %ld]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, imm_val); } } else { const auto imm_reg = load_val_in_reg(cur_time, in2); if (load_dst->type == Type::i32) { assert(ext_dst->type == Type::i32 || ext_dst->type == Type::i64); print_asm("movsxd %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, reg_names[imm_reg][0]); } else { print_asm("movsx %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, reg_names[imm_reg][0]); } } clear_reg(cur_time, dst_reg); set_var_to_reg(cur_time, ext_dst, dst_reg); load_dst->gen_info.already_generated = true; ext_dst->gen_info.already_generated = true; did_merge = true; } } } if (!did_merge) { // merge add and load if (imm_val != INT64_MIN && std::abs(imm_val) < 0x7FFFFFFF) { print_asm("mov %s, [%s + %ld]\n", reg_name(dst_reg, load_dst->type), in1_reg_name, imm_val); } else { const auto imm_reg = load_val_in_reg(cur_time, in2); print_asm("mov %s, [%s + %s]\n", reg_name(dst_reg, load_dst->type), in1_reg_name, reg_names[imm_reg][0]); } clear_reg(cur_time, dst_reg); set_var_to_reg(cur_time, load_dst, dst_reg); load_dst->gen_info.already_generated = true; did_merge = true; } } else if (next_op->type == Instruction::cast) { // detect add/cast/store sequence auto *cast_var = next_op->out_vars[0]; if (cast_var->ref_count == 1 && bb->variables.size() > var_idx + 2) { auto *nnext_var = bb->variables[var_idx + 2].get(); if (std::holds_alternative<std::unique_ptr<Operation>>(nnext_var->info)) { auto *nnext_op = std::get<std::unique_ptr<Operation>>(nnext_var->info).get(); if (nnext_op->type == Instruction::store && nnext_op->in_vars[0] == dst && nnext_op->in_vars[1] == cast_var) { auto *store_dst = nnext_op->out_vars[0]; // should be == nnext_var // load source of cast const auto cast_reg = load_val_in_reg(cur_time, next_op->in_vars[0].get()); print_asm("mov [%s + %ld], %s\n", in1_reg_name, imm_val, reg_name(cast_reg, cast_var->type)); cast_var->gen_info.already_generated = true; store_dst->gen_info.already_generated = true; did_merge = true; } } } } else if (next_op->type == Instruction::store && next_op->in_vars[0].get() == dst) { // merge add/store auto *store_src = next_op->in_vars[1].get(); if (store_src->is_immediate() && !store_src->get_immediate().binary_relative) { const auto store_imm_val = store_src->get_immediate().val; if (store_imm_val != INT64_MIN && std::abs(store_imm_val) < 0x7FFFFFFF) { print_asm("mov %s [%s + %ld], %ld\n", mem_size(next_op->lifter_info.in_op_size), in1_reg_name, imm_val, store_imm_val); next_op->out_vars[0]->gen_info.already_generated = true; did_merge = true; } } if (!did_merge) { const auto src_reg = load_val_in_reg(cur_time, store_src); print_asm("mov [%s + %ld], %s\n", in1_reg_name, imm_val, reg_name(src_reg, store_src->type)); next_op->out_vars[0]->gen_info.already_generated = true; did_merge = true; } } } } } else if ((gen->optimizations & Generator::OPT_ARCH_BMI2) && op->type == Instruction::_and && op->in_vars[1]->is_immediate()) { // v2 <- and v0, 31/63 // (cast i32 v3 <- i64 v1) // shl/shr/sar v3/v1, v2 if (std::get<SSAVar::ImmInfo>(op->in_vars[1]->info).val == 0x1F && bb->variables.size() > var_idx + 2) { // check for cast auto *next_var = bb->variables[var_idx + 1].get(); if (next_var->ref_count == 1 && next_var->type == Type::i32 && std::holds_alternative<std::unique_ptr<Operation>>(next_var->info)) { auto *next_op = std::get<std::unique_ptr<Operation>>(next_var->info).get(); if (next_op->type == Instruction::cast && !is_float(next_var->type) && !is_float(next_op->lifter_info.in_op_size)) { // check for shift auto *nnext_var = bb->variables[var_idx + 2].get(); if (std::holds_alternative<std::unique_ptr<Operation>>(nnext_var->info)) { auto *nnext_op = std::get<std::unique_ptr<Operation>>(nnext_var->info).get(); if ((nnext_op->type == Instruction::shl || nnext_op->type == Instruction::shr || nnext_op->type == Instruction::sar) && nnext_op->in_vars[0] == next_var && nnext_op->in_vars[1] == dst) { // this can be merged into a single shift const auto cast_reg = load_val_in_reg(cur_time, next_op->in_vars[0].get()); if (nnext_op->type == Instruction::shl) { print_asm("shlx %s, %s, %s\n", reg_names[dst_reg][1], reg_names[cast_reg][1], reg_names[in1_reg][1]); } else if (nnext_op->type == Instruction::shr) { print_asm("shrx %s, %s, %s\n", reg_names[dst_reg][1], reg_names[cast_reg][1], reg_names[in1_reg][1]); } else if (nnext_op->type == Instruction::sar) { print_asm("sarx %s, %s, %s\n", reg_names[dst_reg][1], reg_names[cast_reg][1], reg_names[in1_reg][1]); } clear_reg(cur_time, dst_reg); set_var_to_reg(cur_time, nnext_var, dst_reg); next_var->gen_info.already_generated = true; nnext_var->gen_info.already_generated = true; did_merge = true; } } } } } else if (std::get<SSAVar::ImmInfo>(op->in_vars[1]->info).val == 0x3F) { auto *next_var = bb->variables[var_idx + 1].get(); if (std::holds_alternative<std::unique_ptr<Operation>>(next_var->info)) { auto *next_op = std::get<std::unique_ptr<Operation>>(next_var->info).get(); if ((next_op->type == Instruction::shl || next_op->type == Instruction::shr || next_op->type == Instruction::sar) && !is_float(next_var->type)) { // check if the shift operand is 64bit and we shift the anded value if (next_op->in_vars[0]->type == Type::i64 && next_op->in_vars[1] == dst) { const auto shift_reg = load_val_in_reg(cur_time, next_op->in_vars[0].get()); if (next_op->type == Instruction::shl) { print_asm("shlx %s, %s, %s\n", reg_names[dst_reg][0], reg_names[shift_reg][0], reg_names[in1_reg][0]); } else if (next_op->type == Instruction::shr) { print_asm("shrx %s, %s, %s\n", reg_names[dst_reg][0], reg_names[shift_reg][0], reg_names[in1_reg][0]); } else if (next_op->type == Instruction::sar) { print_asm("sarx %s, %s, %s\n", reg_names[dst_reg][0], reg_names[shift_reg][0], reg_names[in1_reg][0]); } next_var->gen_info.already_generated = true; clear_reg(cur_time, dst_reg); set_var_to_reg(cur_time, next_var, dst_reg); did_merge = true; } } } } } } if (did_merge) { break; } const auto op_with_imm32 = [imm_val, this, in1_reg_name, cur_time, in1, in2](const char *op_str) { // 0x8000'0000'0000'0000 cannot be represented as uint64_t if (imm_val != INT64_MIN && std::abs(imm_val) <= 0x7FFF'FFFF) { print_asm("%s %s, 0x%lx\n", op_str, in1_reg_name, imm_val); } else { auto imm_reg = alloc_reg(cur_time); print_asm("mov %s, 0x%lx\n", reg_names[imm_reg][0], imm_val); print_asm("%s %s, %s\n", op_str, in1_reg_name, reg_name(imm_reg, choose_type(in1, in2))); } }; switch (op->type) { case Instruction::add: if (dst_reg == in1_reg) { op_with_imm32("add"); } else { if (imm_val != INT64_MIN && std::abs(imm_val) <= 0x7FFF'FFFF) { print_asm("lea %s, [%s + %ld]\n", dst_reg_name, in1_reg_name, imm_val); } else { auto imm_reg = alloc_reg(cur_time); print_asm("mov %s, %ld\n", reg_names[imm_reg][0], imm_val); print_asm("lea %s, [%s + %s]\n", reg_names[dst_reg][0], reg_names[in1_reg][0], reg_names[imm_reg][0]); } } break; case Instruction::sub: op_with_imm32("sub"); break; case Instruction::shl: print_asm("shl %s, %ld\n", in1_reg_name, imm_val); break; case Instruction::shr: print_asm("shr %s, %ld\n", in1_reg_name, imm_val); break; case Instruction::sar: print_asm("sar %s, %ld\n", in1_reg_name, imm_val); break; case Instruction::_or: op_with_imm32("or"); break; case Instruction::_and: op_with_imm32("and"); break; case Instruction::_xor: op_with_imm32("xor"); break; case Instruction::umax: op_with_imm32("cmp"); print_asm("jae b%zu_%zu_max\n", bb->id, var_idx); print_asm("mov %s, %ld\n", in1_reg_name, imm_val); print_asm("b%zu_%zu_max:\n", bb->id, var_idx); break; case Instruction::umin: op_with_imm32("cmp"); print_asm("jbe b%zu_%zu_min\n", bb->id, var_idx); print_asm("mov %s, %ld\n", in1_reg_name, imm_val); print_asm("b%zu_%zu_min:\n", bb->id, var_idx); break; case Instruction::max: op_with_imm32("cmp"); print_asm("jge b%zu_%zu_smax\n", bb->id, var_idx); print_asm("mov %s, %ld\n", in1_reg_name, imm_val); print_asm("b%zu_%zu_smax:\n", bb->id, var_idx); break; case Instruction::min: op_with_imm32("cmp"); print_asm("jle b%zu_%zu_smin\n", bb->id, var_idx); print_asm("mov %s, %ld\n", in1_reg_name, imm_val); print_asm("b%zu_%zu_smin:\n", bb->id, var_idx); break; case Instruction::mul_l: op_with_imm32("imul"); break; case Instruction::ssmul_h: { const auto imm_reg = load_val_in_reg(cur_time, in2); print_asm("imul %s\n", reg_name(imm_reg, in1->type)); break; } case Instruction::uumul_h: { const auto imm_reg = load_val_in_reg(cur_time, in2); print_asm("mul %s\n", reg_name(imm_reg, in1->type)); break; } case Instruction::div: { const auto imm_reg = load_val_in_reg(cur_time, in2, REG_NONE, REG_D); print_asm("idiv %s\n", reg_name(imm_reg, in1->type)); break; } case Instruction::udiv: { const auto imm_reg = load_val_in_reg(cur_time, in2, REG_NONE, REG_D); print_asm("div %s\n", reg_name(imm_reg, in1->type)); break; } default: // should never be hit assert(0); exit(1); } clear_reg(cur_time, dst_reg); if (op->type == Instruction::ssmul_h || op->type == Instruction::uumul_h) { // result is in rdx set_var_to_reg(cur_time, dst, REG_D); } else if (op->type == Instruction::div || op->type == Instruction::udiv) { if (dst) { set_var_to_reg(cur_time, dst, REG_A); } if (op->out_vars[1]) { set_var_to_reg(cur_time, op->out_vars[1], REG_D); } } else { set_var_to_reg(cur_time, dst, dst_reg); } break; } // TODO: when in1 == imm & in2 != imm and we have a sub we can neg in2, add in2, in1 REGISTER in1_reg, in2_reg; if (op->type == Instruction::ssmul_h || op->type == Instruction::uumul_h) { // TODO: here we could optimise and accept either in1 or in2 in reg a if one of them already is or is already in a register in1_reg = load_val_in_reg(cur_time, in1, REG_A); // rdx gets clobbered but it's fine to use it as a source operand in2_reg = load_val_in_reg(cur_time, in2); if (reg_map[REG_D].cur_var && reg_map[REG_D].cur_var->gen_info.last_use_time > cur_time) { save_reg(REG_D); } clear_reg(cur_time, REG_D); } else if (op->type == Instruction::div || op->type == Instruction::udiv) { in1_reg = load_val_in_reg(cur_time, in1, REG_A); // div uses rdx so we cannot have a source in it in2_reg = load_val_in_reg(cur_time, in2, REG_NONE, REG_D); if (reg_map[REG_D].cur_var && reg_map[REG_D].cur_var->gen_info.last_use_time > cur_time) { save_reg(REG_D); } clear_reg(cur_time, REG_D); if (op->type == Instruction::div) { if (var->type == Type::i32) { print_asm("cdq\n"); } else { print_asm("cqo\n"); } } else { print_asm("xor edx, edx\n"); } } else if (op->type == Instruction::shl || op->type == Instruction::shr || op->type == Instruction::sar) { if (!(gen->optimizations & Generator::OPT_ARCH_BMI2) || (op->in_vars[0]->type != Type::i64 && op->in_vars[0]->type != Type::i32)) { // when we shift 16/8 bit values we need to use the shl/shr/sar instructions so the shift val needs to be in cl in2_reg = load_val_in_reg(cur_time, in2, REG_C); } else { in2_reg = load_val_in_reg(cur_time, in2); } in1_reg = load_val_in_reg(cur_time, in1); } else { in1_reg = load_val_in_reg(cur_time, in1); in2_reg = load_val_in_reg(cur_time, in2); } const auto type = choose_type(in1, in2); const auto in1_reg_name = reg_name(in1_reg, type); const auto in2_reg_name = reg_name(in2_reg, type); if (in1->gen_info.last_use_time > cur_time) { save_reg(in1_reg); } if (merge_op_bin(cur_time, var_idx, in1_reg)) { break; } const auto write_shift = [this, in1_reg_name, in2_reg_name, op](const char *instr_name) { if (!(gen->optimizations & Generator::OPT_ARCH_BMI2) || (op->in_vars[0]->type != Type::i64 && op->in_vars[0]->type != Type::i32)) { print_asm("%s %s, cl\n", instr_name, in1_reg_name); } else { print_asm("%sx %s, %s, %s\n", instr_name, in1_reg_name, in1_reg_name, in2_reg_name); } }; switch (op->type) { case Instruction::add: print_asm("add %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::sub: print_asm("sub %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::shl: write_shift("shl"); break; case Instruction::shr: write_shift("shr"); break; case Instruction::sar: write_shift("sar"); break; case Instruction::_or: print_asm("or %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::_and: print_asm("and %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::_xor: print_asm("xor %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::umax: print_asm("cmp %s, %s\n", in1_reg_name, in2_reg_name); print_asm("cmovb %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::umin: print_asm("cmp %s, %s\n", in1_reg_name, in2_reg_name); print_asm("cmova %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::max: print_asm("cmp %s, %s\n", in1_reg_name, in2_reg_name); print_asm("cmovl %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::min: print_asm("cmp %s, %s\n", in1_reg_name, in2_reg_name); print_asm("cmovg %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::mul_l: print_asm("imul %s, %s\n", in1_reg_name, in2_reg_name); break; case Instruction::ssmul_h: print_asm("imul %s\n", in2_reg_name); break; case Instruction::uumul_h: print_asm("mul %s\n", in2_reg_name); break; case Instruction::div: print_asm("idiv %s\n", in2_reg_name); break; case Instruction::udiv: print_asm("div %s\n", in2_reg_name); break; default: // should never be hit assert(0); exit(1); } clear_reg(cur_time, in1_reg); if (op->type == Instruction::ssmul_h || op->type == Instruction::uumul_h) { // result is in rdx set_var_to_reg(cur_time, dst, REG_D); } else if (op->type == Instruction::div || op->type == Instruction::udiv) { if (dst) { set_var_to_reg(cur_time, dst, REG_A); } if (op->out_vars[1]) { set_var_to_reg(cur_time, op->out_vars[1], REG_D); } } else { set_var_to_reg(cur_time, dst, in1_reg); } break; } case Instruction::load: { auto *addr = op->in_vars[0].get(); auto *dst = op->out_vars[0]; // TODO: when addr is a (binary-relative) immediate it should be foldable into one instruction const auto addr_reg = load_val_in_reg(cur_time, addr); if (addr->gen_info.last_use_time > cur_time) { save_reg(addr_reg); } print_asm("mov %s, [%s]\n", reg_name(addr_reg, dst->type), reg_names[addr_reg][0]); clear_reg(cur_time, addr_reg); set_var_to_reg(cur_time, dst, addr_reg); break; } case Instruction::store: { auto *addr = op->in_vars[0].get(); auto *val = op->in_vars[1].get(); assert(addr->is_immediate() || addr->type == Type::i64); // TODO: when addr is a (binary-relative) immediate this can be omitted sometimes const auto addr_reg = load_val_in_reg(cur_time, addr); if (val->is_immediate() && !val->get_immediate().binary_relative) { const auto imm_val = val->get_immediate().val; if (imm_val != INT64_MIN && std::abs(imm_val) < 0x7FFFFFFF) { print_asm("mov %s [%s], %ld\n", mem_size(op->lifter_info.in_op_size), reg_names[addr_reg][0], imm_val); break; } } const auto val_reg = load_val_in_reg(cur_time, val); print_asm("mov [%s], %s\n", reg_names[addr_reg][0], reg_name(val_reg, op->lifter_info.in_op_size)); break; } case Instruction::_not: { auto *val = op->in_vars[0].get(); auto *dst = op->out_vars[0]; assert(val->type == dst->type || val->is_immediate()); const auto val_reg = load_val_in_reg(cur_time, val); if (val->gen_info.last_use_time > cur_time) { save_reg(val_reg); } print_asm("not %s\n", reg_name(val_reg, val->is_immediate() ? Type::i64 : val->type)); clear_reg(cur_time, val_reg); set_var_to_reg(cur_time, dst, val_reg); break; } case Instruction::seq: [[fallthrough]]; case Instruction::slt: [[fallthrough]]; case Instruction::sltu: { auto *cmp1 = op->in_vars[0].get(); auto *cmp2 = op->in_vars[1].get(); auto *val1 = op->in_vars[2].get(); auto *val2 = op->in_vars[3].get(); auto *dst = op->out_vars[0]; const auto cmp1_reg = load_val_in_reg(cur_time, cmp1); if (cmp1->gen_info.last_use_time > cur_time) { save_reg(cmp1_reg); } if (val1->is_immediate() && val2->is_immediate()) { const auto &val1_info = std::get<SSAVar::ImmInfo>(val1->info); const auto &val2_info = std::get<SSAVar::ImmInfo>(val2->info); if (val1_info.val == 1 && !val1_info.binary_relative && val2_info.val == 0 && !val2_info.binary_relative) { if (cmp2->is_immediate() && !std::get<SSAVar::ImmInfo>(cmp2->info).binary_relative && std::get<SSAVar::ImmInfo>(cmp2->info).val != INT64_MIN && std::abs(cmp2->get_immediate().val) < 0x7FFF'FFFF) { const auto type = cmp1->is_immediate() ? Type::i64 : cmp1->type; print_asm("cmp %s, %ld\n", reg_name(cmp1_reg, type), std::get<SSAVar::ImmInfo>(cmp2->info).val); } else { const auto cmp2_reg = load_val_in_reg(cur_time, cmp2); auto type = choose_type(cmp1, cmp2); print_asm("cmp %s, %s\n", reg_name(cmp1_reg, type), reg_name(cmp2_reg, type)); } if (!cmp1->is_immediate() || std::get<SSAVar::ImmInfo>(cmp1->info).binary_relative || static_cast<uint64_t>(std::get<SSAVar::ImmInfo>(cmp1->info).val) > 255) { // dont need to clear if we know the register holds a value that fits into 1 byte print_asm("mov %s, 0\n", reg_names[cmp1_reg][0]); } if (op->type == Instruction::seq) { print_asm("sete %s\n", reg_names[cmp1_reg][3]); } else if (op->type == Instruction::slt) { print_asm("setl %s\n", reg_names[cmp1_reg][3]); } else { print_asm("setb %s\n", reg_names[cmp1_reg][3]); } clear_reg(cur_time, cmp1_reg); set_var_to_reg(cur_time, dst, cmp1_reg); break; } } const auto val1_reg = load_val_in_reg(cur_time, val1); const auto val2_reg = load_val_in_reg(cur_time, val2); if (cmp2->is_immediate() && !std::get<SSAVar::ImmInfo>(cmp2->info).binary_relative && std::get<SSAVar::ImmInfo>(cmp2->info).val != INT64_MIN && std::abs(std::get<SSAVar::ImmInfo>(cmp2->info).val) <= 0x7FFFFFFF) { const auto type = cmp1->is_immediate() ? Type::i64 : cmp1->type; print_asm("cmp %s, %ld\n", reg_name(cmp1_reg, type), std::get<SSAVar::ImmInfo>(cmp2->info).val); } else { const auto cmp2_reg = load_val_in_reg(cur_time, cmp2); auto type = choose_type(cmp1, cmp2); print_asm("cmp %s, %s\n", reg_name(cmp1_reg, type), reg_name(cmp2_reg, type)); } if (op->type == Instruction::seq) { print_asm("cmove %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val1_reg, dst->type)); print_asm("cmovne %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val2_reg, dst->type)); } else if (op->type == Instruction::slt) { print_asm("cmovl %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val1_reg, dst->type)); print_asm("cmovge %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val2_reg, dst->type)); } else { print_asm("cmovb %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val1_reg, dst->type)); print_asm("cmovae %s, %s\n", reg_name(cmp1_reg, dst->type), reg_name(val2_reg, dst->type)); } clear_reg(cur_time, cmp1_reg); set_var_to_reg(cur_time, dst, cmp1_reg); break; } case Instruction::setup_stack: { auto *dst = op->out_vars[0]; assert(dst->type == Type::i64); const auto dst_reg = alloc_reg(cur_time); print_asm("mov %s, [init_stack_ptr]\n", reg_names[dst_reg][0]); set_var_to_reg(cur_time, dst, dst_reg); break; } case Instruction::cast: [[fallthrough]]; case Instruction::sign_extend: [[fallthrough]]; case Instruction::zero_extend: { auto *input = op->in_vars[0].get(); auto *output = op->out_vars[0]; if (input->is_immediate() && !std::get<SSAVar::ImmInfo>(input->info).binary_relative) { // cast,sign_extend and zero_extend are no-ops auto imm = std::get<SSAVar::ImmInfo>(input->info).val; switch (output->type) { case Type::i64: break; case Type::i32: imm = imm & 0xFFFFFFFF; break; case Type::i16: imm = imm & 0xFFFF; break; case Type::i8: imm = imm & 0xFF; break; default: assert(0); exit(1); } const auto dst_reg = alloc_reg(cur_time); const auto dst_reg_name = reg_name(dst_reg, output->type); print_asm("mov %s, %ld\n", dst_reg_name, imm); set_var_to_reg(cur_time, output, dst_reg); break; } const auto dst_reg = load_val_in_reg(cur_time, input); const auto dst_reg_name = reg_name(dst_reg, input->type); if (input->gen_info.last_use_time > cur_time) { save_reg(dst_reg); } // TODO: in theory you could simply alias the input var for cast and zero_extend if (op->type == Instruction::sign_extend) { print_asm("movsx %s, %s\n", reg_name(dst_reg, output->type), dst_reg_name); } else if (input->type != output->type) { // clear upper parts of register // find smallest type auto type = input->type; if (output->type == Type::i8) { type = Type::i8; } else if (output->type == Type::i16 && type != Type::i8) { type = Type::i16; } else if (output->type == Type::i32 && type != Type::i8 && type != Type::i16) { type = Type::i32; } if (type == Type::i32) { const auto name = reg_name(dst_reg, type); print_asm("mov %s, %s\n", name, name); } else { if (type == Type::i16) { print_asm("and %s, 0xFFFF\n", reg_names[dst_reg][0]); } else if (type == Type::i8) { print_asm("and %s, 0xFF\n", reg_names[dst_reg][0]); } // nothing to do for 64 bit } } clear_reg(cur_time, dst_reg); set_var_to_reg(cur_time, output, dst_reg); break; } default: fprintf(stderr, "Encountered unknown instruction in generator\n"); assert(0); exit(1); } } } void RegAlloc::compile_fp_op(SSAVar *var, size_t cur_time) { const auto *op = std::get<std::unique_ptr<Operation>>(var->info).get(); SSAVar *in1 = op->in_vars[0]; // handles binary fp operations auto bin_op = [this, var, op, in1, cur_time](const char *instruction) { assert(is_float(var->type) && var->type == op->in_vars[0]->type && var->type == op->in_vars[1]->type); const FP_REGISTER in1_reg = load_val_in_fp_reg(cur_time, op->in_vars[0]); const FP_REGISTER in2_reg = load_val_in_fp_reg(cur_time, op->in_vars[1]); if (in1->gen_info.last_use_time > cur_time) { save_fp_reg(in1_reg); } print_asm("%s%s %s, %s\n", instruction, Generator::fp_op_size_from_type(var->type), fp_reg_names[in1_reg], fp_reg_names[in2_reg]); clear_fp_reg(cur_time, in1_reg); set_var_to_fp_reg(cur_time, var, in1_reg); }; // handles fused multiply add operations auto fma_op = [this, var, op, in1, cur_time](const char *fma_instruction, const char *second_instruction, const bool negate_mul_res = false) { assert(is_float(var->type) && var->type == in1->type && var->type == op->in_vars[1]->type && var->type == op->in_vars[2]->type); const FP_REGISTER in1_reg = load_val_in_fp_reg(cur_time, in1); const FP_REGISTER in2_reg = load_val_in_fp_reg(cur_time, op->in_vars[1]); const FP_REGISTER in3_reg = load_val_in_fp_reg(cur_time, op->in_vars[2]); if (in1->gen_info.last_use_time > cur_time) { save_fp_reg(in1_reg); } if (gen->optimizations & Generator::OPT_ARCH_FMA3) { print_asm("%s%s %s, %s, %s\n", fma_instruction, Generator::fp_op_size_from_type(var->type), fp_reg_names[in1_reg], fp_reg_names[in2_reg], fp_reg_names[in3_reg]); } else { assert(is_float(var->type) && var->type == in1->type && var->type == op->in_vars[1]->type && var->type == op->in_vars[2]->type); print_asm("muls%s %s, %s\n", Generator::fp_op_size_from_type(var->type), fp_reg_names[in1_reg], fp_reg_names[in2_reg]); if (negate_mul_res) { const REGISTER tempr_reg = alloc_reg(cur_time); print_asm("mov %s, %lu\n", reg_name(tempr_reg, Type::i64), (var->type == Type::f32 ? 0x8000'0000 : 0x8000'0000'0000'0000)); print_asm("push %s\n", reg_name(tempr_reg, Type::i64)); print_asm("push QWORD PTR 0\n"); print_asm("pxor %s, [rsp]\n", fp_reg_names[in1_reg]); print_asm("add rsp, 16\n"); } print_asm("%s%s %s, %s\n", second_instruction, Generator::fp_op_size_from_type(var->type), fp_reg_names[in1_reg], fp_reg_names[in3_reg]); } clear_fp_reg(cur_time, in1_reg); set_var_to_fp_reg(cur_time, var, in1_reg); }; auto cmp_op = [this, var, op, in1, cur_time](const char *cc) { SSAVar *cmp2 = op->in_vars[1]; SSAVar *val1 = op->in_vars[2]; SSAVar *val2 = op->in_vars[3]; assert(is_float(in1->type) && in1->type == cmp2->type && val1->type == Type::imm && val2->type == Type::imm); FP_REGISTER cmp1_reg = load_val_in_fp_reg(cur_time, in1); FP_REGISTER cmp2_reg = load_val_in_fp_reg(cur_time, cmp2); REGISTER val1_reg = load_val_in_reg(cur_time, val1); REGISTER val2_reg = load_val_in_reg(cur_time, val2); if (val1->gen_info.last_use_time > cur_time) { save_reg(val1_reg); } print_asm("comis%s %s, %s\n", Generator::fp_op_size_from_type(in1->type), fp_reg_names[cmp1_reg], fp_reg_names[cmp2_reg]); print_asm("cmov%s %s, %s\n", cc, reg_name(val1_reg, var->type), reg_name(val2_reg, var->type)); clear_reg(cur_time, val1_reg); set_var_to_reg(cur_time, var, val1_reg); }; switch (op->type) { case Instruction::min: bin_op("mins"); break; case Instruction::max: bin_op("maxs"); break; case Instruction::add: bin_op("adds"); break; case Instruction::sub: bin_op("subs"); break; case Instruction::fmul: bin_op("muls"); break; case Instruction::fdiv: bin_op("divs"); break; case Instruction::fmadd: fma_op("vfmadd213s", "adds"); break; case Instruction::fmsub: fma_op("vfmsub213s", "subs"); break; case Instruction::fnmadd: fma_op("vfnmadd213s", "adds", true); break; case Instruction::fnmsub: fma_op("vfnmsub213s", "subs", true); break; case Instruction::fsqrt: { assert(is_float(var->type) && var->type == in1->type); const FP_REGISTER in1_reg = load_val_in_fp_reg(cur_time, in1); const FP_REGISTER dest_reg = alloc_fp_reg(cur_time); print_asm("sqrts%s %s, %s\n", Generator::fp_op_size_from_type(var->type), fp_reg_names[dest_reg], fp_reg_names[in1_reg]); clear_fp_reg(cur_time, dest_reg); set_var_to_fp_reg(cur_time, var, dest_reg); break; } case Instruction::slt: cmp_op("ae"); break; case Instruction::sle: cmp_op("a"); break; case Instruction::seq: cmp_op("ne"); break; case Instruction::load: { assert(in1->type == Type::i64 || in1->type == Type::imm); const REGISTER addr_reg = load_val_in_reg(cur_time, in1); if (in1->gen_info.last_use_time > cur_time) { save_reg(addr_reg); } const FP_REGISTER dest_reg = alloc_fp_reg(cur_time); print_asm("mov%s %s, [%s]\n", (var->type == Type::f32 ? "d" : "q"), fp_reg_names[dest_reg], reg_names[addr_reg][0]); set_var_to_fp_reg(cur_time, var, dest_reg); break; } case Instruction::store: { auto *val = op->in_vars[1].get(); assert(in1->type == Type::imm || in1->type == Type::i64); assert(is_float(val->type)); const REGISTER addr_reg = load_val_in_reg(cur_time, in1); const FP_REGISTER val_reg = load_val_in_fp_reg(cur_time, val); print_asm("mov%s [%s], %s\n", (val->type == Type::f32 ? "d" : "q"), reg_names[addr_reg][0], fp_reg_names[val_reg]); break; } case Instruction::zero_extend: assert(is_float(var->type) && is_float(in1->type)); [[fallthrough]]; case Instruction::cast: { assert(is_float(var->type) || is_float(in1->type)); if (is_float(in1->type)) { if (is_float(var->type)) { const FP_REGISTER dst_reg = load_val_in_fp_reg(cur_time, in1); if (in1->gen_info.last_use_time > cur_time) { save_fp_reg(dst_reg); } clear_fp_reg(cur_time, dst_reg); set_var_to_fp_reg(cur_time, var, dst_reg); } else { const FP_REGISTER in_reg = load_val_in_fp_reg(cur_time, in1); const REGISTER dest_reg = alloc_reg(cur_time); print_asm("mov%s %s, %s\n", (in1->type == Type::f32 ? "d" : "q"), reg_name(dest_reg, var->type), fp_reg_names[in_reg]); set_var_to_reg(cur_time, var, dest_reg); } } else { const REGISTER in_reg = load_val_in_reg(cur_time, in1); const FP_REGISTER dest_reg = alloc_fp_reg(cur_time); print_asm("mov%s %s, %s\n", (var->type == Type::f32 ? "d" : "q"), fp_reg_names[dest_reg], reg_name(in_reg, in1->type)); set_var_to_fp_reg(cur_time, var, dest_reg); } break; } case Instruction::convert: { assert(is_float(var->type) || is_float(in1->type)); // evalute convert names const char *conv_name_1 = Generator::convert_name_from_type(in1->type); const char *conv_name_2 = Generator::convert_name_from_type(var->type); if (is_float(in1->type)) { FP_REGISTER in_reg = load_val_in_fp_reg(cur_time, in1); // floating point -> integer if (is_float(var->type)) { // floating point -> floating point const FP_REGISTER dest_reg = alloc_fp_reg(cur_time); compile_rounding_mode(cur_time, op, alloc_reg(cur_time)); print_asm("cvt%s2%s %s, %s\n", conv_name_1, conv_name_2, fp_reg_names[dest_reg], fp_reg_names[in_reg]); set_var_to_fp_reg(cur_time, var, dest_reg); break; } else { const REGISTER dest_reg = alloc_reg(cur_time); in_reg = compile_rounding_mode(cur_time, op, dest_reg, true, in_reg); // compile_rounding_mode(cur_time, op, dest_reg); print_asm("cvt%s2%s %s, %s\n", conv_name_1, conv_name_2, reg_name(dest_reg, var->type), fp_reg_names[in_reg]); set_var_to_reg(cur_time, var, dest_reg); } } else { // integer -> floating point compile_rounding_mode(cur_time, op, alloc_reg(cur_time)); const REGISTER in_reg = load_val_in_reg(cur_time, in1); const FP_REGISTER dest_reg = alloc_fp_reg(cur_time); print_asm("cvt%s2%s %s, %s\n", conv_name_1, conv_name_2, fp_reg_names[dest_reg], reg_name(in_reg, in1->type)); set_var_to_fp_reg(cur_time, var, dest_reg); } break; } case Instruction::uconvert: { assert(is_float(in1->type) ^ is_float(var->type)); compile_rounding_mode(cur_time, op, alloc_reg(cur_time)); const char *conv_name_1 = Generator::convert_name_from_type(in1->type); const char *conv_name_2 = Generator::convert_name_from_type(var->type); if (is_float(in1->type)) { // floating point -> unsigned integer assert(var->type == Type::i32 || var->type == Type::i64); const FP_REGISTER in_reg = load_val_in_fp_reg(cur_time, in1); const REGISTER dest_reg = alloc_reg(cur_time); const bool single_precision = in1->type == Type::f32; const char *dest_reg_name = reg_name(dest_reg, var->type); print_asm("cvt%s2si %s, %s\n", conv_name_1, dest_reg_name, fp_reg_names[in_reg]); print_asm("mov%s %s, %s\n", (single_precision ? "d" : "q"), (single_precision ? "ebp" : "rbp"), fp_reg_names[in_reg]); print_asm("sar rbp, %d\n", (single_precision ? 31 : 63)); if (var->type == Type::i64 && single_precision) { print_asm("movsxd rbp, ebp\n"); } print_asm("not rbp\n"); print_asm("and %s, %s\n", dest_reg_name, (var->type == Type::i32 ? "ebp" : "rbp")); print_asm("xor rbp, rbp\n"); set_var_to_reg(cur_time, var, dest_reg); } else { // unsigned integer -> floating point assert(in1->type == Type::i32 || in1->type == Type::i64); const REGISTER in_reg = load_val_in_reg(cur_time, in1); const FP_REGISTER dest_reg = alloc_fp_reg(cur_time); const REGISTER help_reg = alloc_reg(cur_time, REG_NONE, in_reg); if (in1->type == Type::i32) { // "zero extend" and then convert: use 64bit register print_asm("mov %s, %s\n", reg_names[in_reg][1], reg_names[in_reg][1]); print_asm("cvt%s2%s %s, %s\n", Generator::convert_name_from_type(Type::i64), conv_name_2, fp_reg_names[dest_reg], reg_names[in_reg][0]); } else if (in1->type == Type::i64) { // method taken from gcc compiler const char *in_reg_name = reg_names[in_reg][0], *help_reg_name = reg_names[help_reg][0], *dest_reg_name = fp_reg_names[dest_reg]; // test if msb is set: if set, then handle else use normal (signed) convert print_asm("test %s, %s\n", in_reg_name, in_reg_name); print_asm("js 0f\n"); print_asm("cvtsi2%s %s, %s\n", conv_name_2, dest_reg_name, in_reg_name); print_asm("jmp 2f\n"); print_asm("0:\n"); // test for edge case print_asm("mov %s, -1\n", help_reg_name); print_asm("cmp %s, %s\n", in_reg_name, help_reg_name); print_asm("je 1f\n"); // use gcc method to convert unsigned values print_asm("mov %s, %s\n", help_reg_name, in_reg_name); print_asm("shr %s, 1\n", help_reg_name); print_asm("and %s, 1\n", reg_name(in_reg, Type::i32)); print_asm("or %s, %s\n", in_reg_name, help_reg_name); print_asm("cvtsi2%s %s, %s\n", conv_name_2, dest_reg_name, in_reg_name); print_asm("adds%s %s, %s\n", Generator::fp_op_size_from_type(var->type), dest_reg_name, dest_reg_name); print_asm("jmp 2f\n"); print_asm("1:\n"); // handle edge case if (var->type == Type::f32) { print_asm("mov %s, 0x5f800000\n", reg_name(help_reg, Type::i32)); print_asm("movd %s, %s\n", dest_reg_name, reg_name(help_reg, Type::i32)); } else { print_asm("mov %s, 0x43F0000000000000\n", help_reg_name); print_asm("movq %s, %s\n", dest_reg_name, help_reg_name); } print_asm("2:\n"); } set_var_to_fp_reg(cur_time, var, dest_reg); } break; } default: fprintf(stderr, "Encountered a unknown floating point instruction in the generator!\n"); assert(0); break; } } bool RegAlloc::merge_op_bin(size_t cur_time, size_t var_idx, REGISTER dst_reg) { // we know the current var has an operation and two inputs which are both in registers auto *op = std::get<std::unique_ptr<Operation>>(cur_bb->variables[var_idx]->info).get(); auto *dst = op->out_vars[0]; auto *in1 = op->in_vars[0].get(); auto *in2 = op->in_vars[1].get(); // check if optimizations are enabled and we can merge anything if (!(gen->optimizations & Generator::OPT_MERGE_OP) || cur_bb->variables.size() <= var_idx + 1 || !dst || dst->ref_count > 1) { return false; } // add,load or add,(cast),store if (op->type == Instruction::add) { const auto try_merge_add = [this, var_idx, dst, dst_reg, in1, in2, cur_time]() -> bool { auto *next_var = cur_bb->variables[var_idx + 1].get(); if (!std::holds_alternative<std::unique_ptr<Operation>>(next_var->info)) return false; auto *next_op = std::get<std::unique_ptr<Operation>>(next_var->info).get(); if (is_float(next_var->type) || is_float(next_op->lifter_info.in_op_size)) { return false; } if (next_op->type == Instruction::load) { if (next_op->in_vars[0] != dst) { return false; } assert((in1->type == Type::i64 || in1->is_immediate()) && (in2->type == Type::i64 || in2->is_immediate())); const auto *in1_reg_name = reg_names[in1->gen_info.reg_idx][0]; const auto *in2_reg_name = reg_names[in2->gen_info.reg_idx][0]; // check if there is a zero/sign-extend afterwards auto *load_dst = next_op->out_vars[0]; if (load_dst->ref_count == 1 && cur_bb->variables.size() > var_idx + 2) { if (std::holds_alternative<std::unique_ptr<Operation>>(cur_bb->variables[var_idx + 2]->info)) { auto *ext_op = std::get<std::unique_ptr<Operation>>(cur_bb->variables[var_idx + 2]->info).get(); auto *ext_dst = ext_op->out_vars[0]; if (ext_op->in_vars[0] == load_dst) { if (ext_op->type == Instruction::zero_extend) { if (load_dst->type == Type::i32) { print_asm("mov %s, [%s + %s]\n", reg_names[dst_reg][1], in1_reg_name, in2_reg_name); } else { print_asm("movzx %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, in2_reg_name); } } else if (ext_op->type == Instruction::sign_extend) { if (load_dst->type == Type::i32) { assert(ext_dst->type == Type::i32 || ext_dst->type == Type::i64); print_asm("movsxd %s, DWORD PTR [%s + %s]\n", reg_name(dst_reg, ext_dst->type), in1_reg_name, in2_reg_name); } else { print_asm("movsx %s, %s [%s + %s]\n", reg_name(dst_reg, ext_dst->type), mem_size(load_dst->type), in1_reg_name, in2_reg_name); } } if (ext_op->type == Instruction::zero_extend || ext_op->type == Instruction::sign_extend) { clear_reg(cur_time, dst_reg); set_var_to_reg(cur_time, ext_dst, dst_reg); load_dst->gen_info.already_generated = true; ext_dst->gen_info.already_generated = true; return true; } } } } // no extension print_asm("mov %s, [%s + %s]\n", reg_name(dst_reg, load_dst->type), in1_reg_name, in2_reg_name); clear_reg(cur_time, dst_reg); set_var_to_reg(cur_time, load_dst, dst_reg); load_dst->gen_info.already_generated = true; return true; } else if (next_op->type == Instruction::store) { // add,store auto *addr_src = next_op->in_vars[0].get(); auto *val_src = next_op->in_vars[1].get(); if (addr_src != dst) { return false; } assert((in1->type == Type::i64 || in1->is_immediate()) && (in2->type == Type::i64 || in2->is_immediate())); const auto *in1_reg_name = reg_names[in1->gen_info.reg_idx][0]; const auto *in2_reg_name = reg_names[in2->gen_info.reg_idx][0]; if (val_src->is_immediate() && !val_src->get_immediate().binary_relative) { const auto store_imm_val = val_src->get_immediate().val; if (store_imm_val != INT64_MIN && std::abs(store_imm_val) < 0x7FFFFFFF) { print_asm("mov %s [%s + %s], %ld\n", mem_size(next_op->lifter_info.in_op_size), in1_reg_name, in2_reg_name, store_imm_val); next_op->out_vars[0]->gen_info.already_generated = true; return true; } } const auto val_reg = load_val_in_reg(cur_time, val_src); print_asm("mov [%s + %s], %s\n", in1_reg_name, in2_reg_name, reg_name(val_reg, next_op->lifter_info.in_op_size)); next_op->out_vars[0]->gen_info.already_generated = true; return true; } else if (next_op->type == Instruction::cast) { // add,cast,store auto *cast_var = next_op->out_vars[0]; if (cast_var->ref_count != 1 || cur_bb->variables.size() <= var_idx + 2) { return false; } if (!std::holds_alternative<std::unique_ptr<Operation>>(cur_bb->variables[var_idx + 2]->info)) { return false; } auto *store_op = std::get<std::unique_ptr<Operation>>(cur_bb->variables[var_idx + 2]->info).get(); if (store_op->type != Instruction::store || store_op->in_vars[0] != dst || store_op->in_vars[1] != cast_var) { return false; } assert((in1->type == Type::i64 || in1->is_immediate()) && (in2->type == Type::i64 || in2->is_immediate())); const auto *in1_reg_name = reg_names[in1->gen_info.reg_idx][0]; const auto *in2_reg_name = reg_names[in2->gen_info.reg_idx][0]; const auto cast_reg = load_val_in_reg(cur_time, next_op->in_vars[0].get()); print_asm("mov [%s + %s], %s\n", in1_reg_name, in2_reg_name, reg_name(cast_reg, cast_var->type)); store_op->out_vars[0]->gen_info.already_generated = true; cast_var->gen_info.already_generated = true; return true; } return false; }; return try_merge_add(); } return false; } FP_REGISTER RegAlloc::compile_rounding_mode(size_t cur_time, const Operation *op, const REGISTER help_reg, const bool use_rounds, const FP_REGISTER fp_in_reg) { if (std::holds_alternative<RoundingMode>(op->rounding_info)) { const RoundingMode rounding_mode = std::get<RoundingMode>(op->rounding_info); SSAVar *in1 = op->in_vars[0]; if (use_rounds && gen->optimizations & Generator::OPT_ARCH_SSE4) { const char *x86_64_rounding_mode; switch (rounding_mode) { case RoundingMode::NEAREST: x86_64_rounding_mode = "0b00"; break; case RoundingMode::DOWN: x86_64_rounding_mode = "0b01"; break; case RoundingMode::UP: x86_64_rounding_mode = "0b10"; break; case RoundingMode::ZERO: x86_64_rounding_mode = "0b11"; break; default: assert(0); break; } const FP_REGISTER help_fp_reg = alloc_fp_reg(cur_time); assert(fp_in_reg != FP_REG_NONE); print_asm("rounds%s %s, %s, %s\n", Generator::fp_op_size_from_type(in1->type), fp_reg_names[help_fp_reg], fp_reg_names[fp_in_reg], x86_64_rounding_mode); return help_fp_reg; } else { uint32_t x86_64_rounding_mode; switch (std::get<RoundingMode>(op->rounding_info)) { case RoundingMode::NEAREST: x86_64_rounding_mode = 0x0000; break; case RoundingMode::DOWN: x86_64_rounding_mode = 0x2000; break; case RoundingMode::UP: x86_64_rounding_mode = 0x4000; break; case RoundingMode::ZERO: x86_64_rounding_mode = 0x6000; break; default: assert(0); break; } // use dest_reg to set mxcsr const char *round_reg_name = reg_name(help_reg, Type::i32); print_asm("sub rsp, 4\n"); print_asm("stmxcsr [rsp]\n"); print_asm("mov %s, [rsp]\n", round_reg_name); print_asm("and %s, 0xFFFF1FFF\n", round_reg_name); if (x86_64_rounding_mode != 0) { print_asm("or %s, %d\n", round_reg_name, x86_64_rounding_mode); } print_asm("mov [rsp], %s\n", round_reg_name); print_asm("ldmxcsr [rsp]\n"); print_asm("add rsp, 4\n"); return fp_in_reg; } } else if (std::holds_alternative<RefPtr<SSAVar>>(op->rounding_info)) { // let helper handle dynamic rounding SSAVar *rm_var = std::get<RefPtr<SSAVar>>(op->rounding_info).get(); const REGISTER reg = load_val_in_reg(cur_time, rm_var, REG_DI); if (rm_var->gen_info.last_use_time > cur_time) { save_reg(REG_DI); } assert(reg == REG_DI); clear_reg(cur_time, REG_DI); // TODO: Stack alignment? print_asm("push rax\npush rcx\npush rdx\npush rsi\n"); print_asm("call resolve_dynamic_rounding\n"); print_asm("pop rsi\npop rdx\npop rcx\npop rax\n"); return fp_in_reg; } return FP_REG_NONE; } void RegAlloc::prepare_cf_ops(BasicBlock *bb) { // just set the input maps when the cf-op targets do not yet have a input mapping for (auto &cf_op : bb->control_flow_ops) { auto *target = cf_op.target(); if (!target || target->gen_info.input_map_setup) { continue; } if (target->gen_info.call_cont_block) { set_bb_inputs_from_static(target); continue; } switch (cf_op.type) { case CFCInstruction::jump: set_bb_inputs(target, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs); break; case CFCInstruction::cjump: set_bb_inputs(target, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs); break; case CFCInstruction::syscall: // TODO: we don't need this, just need to respect the clobbered registers from a syscall set_bb_inputs_from_static(target); break; case CFCInstruction::call: { set_bb_inputs_from_static(target); auto *cont_block = std::get<CfOp::CallInfo>(cf_op.info).continuation_block; if (!cont_block->gen_info.input_map_setup) { set_bb_inputs_from_static(cont_block); } break; } default: break; } } } void RegAlloc::compile_cf_ops(BasicBlock *bb, RegMap &reg_map, FPRegMap &fp_reg_map, StackMap &stack_map, size_t max_stack_frame_size, BasicBlock *next_bb, std::vector<BasicBlock *> &compiled_blocks) { // TODO: when there is one cfop and it's a jump we can already omit the jmp bX_reg_alloc if the block isn't compiled yet // since it will get compiled straight after auto reg_map_bak = reg_map; auto fp_reg_map_bak = fp_reg_map; auto stack_map_bak = stack_map; std::vector<SSAVar::GeneratorInfoX64> gen_infos; for (auto &var : bb->variables) { gen_infos.emplace_back(var->gen_info); } for (size_t cf_idx = 0; cf_idx < bb->control_flow_ops.size(); ++cf_idx) { auto cur_time = bb->variables.size(); // clear allocations from previous cfop since they dont exist here // clear_after_alloc_time(cur_time); if (cf_idx != 0) { reg_map = reg_map_bak; fp_reg_map = fp_reg_map_bak; stack_map = stack_map_bak; for (size_t i = 0; i < bb->variables.size(); ++i) { bb->variables[i]->gen_info = gen_infos[i]; } } const auto &cf_op = bb->control_flow_ops[cf_idx]; print_asm("b%zu_reg_alloc_cf%zu:\n", bb->id, cf_idx); auto target_top_level = false; if (auto *target = cf_op.target(); target != nullptr) { target_top_level = is_block_top_level(target); } auto cjump_asm = std::string{}; if (cf_op.type == CFCInstruction::cjump) { auto *cmp1 = cf_op.in_vars[0].get(); auto *cmp2 = cf_op.in_vars[1].get(); assert(!is_float(cmp1->type)); assert(!is_float(cmp2->type)); const auto cmp1_reg = load_val_in_reg(cur_time, cmp1); const auto type = choose_type(cmp1, cmp2); if (cmp2->is_immediate() && !std::get<SSAVar::ImmInfo>(cmp2->info).binary_relative && static_cast<uint64_t>(cmp2->get_immediate().val) != 0x80000000'00000000 && std::abs(cmp2->get_immediate().val) <= 0x7FFFFFFF) { // TODO: only 32bit immediates which are safe to sign extend print_asm("cmp %s, %ld\n", reg_name(cmp1_reg, type), std::get<SSAVar::ImmInfo>(cmp2->info).val); } else { const auto cmp2_reg = load_val_in_reg(cur_time, cmp2); print_asm("cmp %s, %s\n", reg_name(cmp1_reg, type), reg_name(cmp2_reg, type)); } gen_infos.clear(); reg_map_bak = reg_map; fp_reg_map_bak = fp_reg_map; stack_map_bak = stack_map; for (auto &var : bb->variables) { gen_infos.emplace_back(var->gen_info); } /*std::swap(cjump_asm, asm_buf); write_target_inputs(cf_op.target(), cur_time, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs); std::swap(cjump_asm, asm_buf); if (!target_top_level && cjump_asm.empty() && std::find(compiled_blocks.begin(), compiled_blocks.end(), cf_op.target()) != compiled_blocks.end()) { // generate a direct jump switch (std::get<CfOp::CJumpInfo>(cf_op.info).type) { case CfOp::CJumpInfo::CJumpType::eq: print_asm("je "); break; case CfOp::CJumpInfo::CJumpType::neq: print_asm("jne "); break; case CfOp::CJumpInfo::CJumpType::lt: print_asm("jb "); break; case CfOp::CJumpInfo::CJumpType::gt: print_asm("ja "); break; case CfOp::CJumpInfo::CJumpType::slt: print_asm("jl "); break; case CfOp::CJumpInfo::CJumpType::sgt: print_asm("jg "); break; } print_asm("b%zu_reg_alloc\n", cf_op.target()->id); continue; }*/ switch (std::get<CfOp::CJumpInfo>(cf_op.info).type) { case CfOp::CJumpInfo::CJumpType::eq: print_asm("jne"); break; case CfOp::CJumpInfo::CJumpType::neq: print_asm("je"); break; case CfOp::CJumpInfo::CJumpType::lt: print_asm("jae"); break; case CfOp::CJumpInfo::CJumpType::gt: print_asm("jbe"); break; case CfOp::CJumpInfo::CJumpType::slt: print_asm("jge"); break; case CfOp::CJumpInfo::CJumpType::sgt: print_asm("jle"); break; } print_asm(" b%zu_reg_alloc_cf%zu\n", bb->id, cf_idx + 1); } switch (cf_op.type) { case CFCInstruction::jump: { auto *target = std::get<CfOp::JumpInfo>(cf_op.info).target; const auto out_of_group = std::find(compiled_blocks.begin(), compiled_blocks.end(), target) == compiled_blocks.end(); if (out_of_group && !target_top_level) { if (!target->gen_info.compiled) { target->gen_info.needs_trans_bb = true; // TODO: this can be fixed with the assembler by compiling all cfops at the end and holding trans bbs until the end before throwing out unneeded ones auto static_mapping = std::vector<std::pair<RefPtr<SSAVar>, size_t>>{}; for (size_t i = 0; i < target->inputs.size(); ++i) { static_mapping.emplace_back(std::get<CfOp::JumpInfo>(cf_op.info).target_inputs[i], std::get<size_t>(target->inputs[i]->info)); } write_static_mapping(target, cur_time, static_mapping); print_asm("add rsp, %zu\n", max_stack_frame_size); print_asm("jmp b%zu\n", target->id); break; } if (target->gen_info.max_stack_size > max_stack_frame_size) { const size_t delta = target->gen_info.max_stack_size - max_stack_frame_size; print_asm("sub rsp, %zu\n", delta); for (auto &var : bb->variables) { if (var->gen_info.saved_in_stack) { var->gen_info.stack_slot += delta / 8; } } for (size_t i = 0; i < (delta / 8); ++i) { stack_map.insert(stack_map.begin(), StackSlot{}); } write_target_inputs(target, cur_time, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs); } else { const size_t delta = max_stack_frame_size - target->gen_info.max_stack_size; for (auto &input : target->gen_info.input_map) { if (input.location == BasicBlock::GeneratorInfo::InputInfo::STACK) { input.stack_slot += delta / 8; } } write_target_inputs(target, cur_time, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs); for (auto &input : target->gen_info.input_map) { if (input.location == BasicBlock::GeneratorInfo::InputInfo::STACK) { input.stack_slot -= delta / 8; } } print_asm("add rsp, %zu\n", delta); } } else { write_target_inputs(target, cur_time, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs); } if (target_top_level) { print_asm("# destroy stack space\n"); print_asm("add rsp, %zu\n", max_stack_frame_size); print_asm("jmp b%zu\n", target->id); } else { if (cf_idx != bb->control_flow_ops.size() - 1 || target != next_bb) { print_asm("jmp b%zu_reg_alloc\n", target->id); } } break; } case CFCInstruction::cjump: { auto *target = std::get<CfOp::CJumpInfo>(cf_op.info).target; // asm_buf += cjump_asm; const auto out_of_group = std::find(compiled_blocks.begin(), compiled_blocks.end(), target) == compiled_blocks.end(); if (out_of_group && !target_top_level) { if (!target->gen_info.compiled) { target->gen_info.needs_trans_bb = true; // TODO: this can be fixed with the assembler by compiling all cfops at the end and holding trans bbs until the end before throwing out unneeded ones auto static_mapping = std::vector<std::pair<RefPtr<SSAVar>, size_t>>{}; for (size_t i = 0; i < target->inputs.size(); ++i) { static_mapping.emplace_back(std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs[i], std::get<size_t>(target->inputs[i]->info)); } write_static_mapping(target, cur_time, static_mapping); print_asm("add rsp, %zu\n", max_stack_frame_size); print_asm("jmp b%zu\n", target->id); break; } if (target->gen_info.max_stack_size > max_stack_frame_size) { const size_t delta = target->gen_info.max_stack_size - max_stack_frame_size; print_asm("sub rsp, %zu\n", delta); for (auto &var : bb->variables) { if (var->gen_info.saved_in_stack) { var->gen_info.stack_slot += delta / 8; } } for (size_t i = 0; i < (delta / 8); ++i) { stack_map.insert(stack_map.begin(), StackSlot{}); } write_target_inputs(target, cur_time, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs); } else { const size_t delta = max_stack_frame_size - target->gen_info.max_stack_size; for (auto &input : target->gen_info.input_map) { if (input.location == BasicBlock::GeneratorInfo::InputInfo::STACK) { input.stack_slot += delta / 8; } } write_target_inputs(target, cur_time, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs); for (auto &input : target->gen_info.input_map) { if (input.location == BasicBlock::GeneratorInfo::InputInfo::STACK) { input.stack_slot -= delta / 8; } } print_asm("add rsp, %zu\n", delta); } } else { write_target_inputs(target, cur_time, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs); } if (target_top_level) { print_asm("# destroy stack space\n"); print_asm("add rsp, %zu\n", max_stack_frame_size); print_asm("jmp b%zu\n", target->id); } else { print_asm("jmp b%zu_reg_alloc\n", target->id); } break; } case CFCInstruction::unreachable: { gen->err_msgs.emplace_back(Generator::ErrType::unreachable, bb); print_asm("lea rdi, [rip + err_unreachable_b%zu]\n", bb->id); print_asm("jmp panic\n"); break; } case CFCInstruction::ijump: { const auto &info = std::get<CfOp::IJumpInfo>(cf_op.info); write_static_mapping((info.targets.empty() ? nullptr : info.targets[0]), cur_time, info.mapping); // TODO: we get a problem if the dst is in a static that has already been written out (so overwritten) auto *dst = cf_op.in_vars[0].get(); load_val_in_reg(cur_time + 1 + info.mapping.size(), dst, REG_B); assert(dst->type == Type::imm || dst->type == Type::i64); print_asm("# destroy stack space\n"); print_asm("add rsp, %zu\n", max_stack_frame_size); print_asm("jmp ijump_lookup\n"); break; } case CFCInstruction::syscall: { // TODO: allocate over inlined syscall or syscall helper call // TODO: inline syscalls if they are just passthrough const auto &info = std::get<CfOp::SyscallInfo>(cf_op.info); write_static_mapping(info.continuation_block, cur_time, info.continuation_mapping); // cur_time += 1 + info.continuation_mapping.size(); for (size_t i = 0; i < call_reg.size(); ++i) { auto *var = cf_op.in_vars[i].get(); if (var == nullptr) break; if (var->type == Type::mt) continue; const auto reg = call_reg[i]; if (reg_map[reg].cur_var && reg_map[reg].cur_var->gen_info.last_use_time >= cur_time) { save_reg(reg); } load_val_in_reg(cur_time, var, call_reg[i]); } if (cf_op.in_vars[6] == nullptr) { print_asm("sub rsp, 16\n"); } else { // TODO: clear rax before when we have inputs < 64 bit if (reg_map[REG_A].cur_var && reg_map[REG_A].cur_var->gen_info.last_use_time >= cur_time) { save_reg(REG_A); } load_val_in_reg(cur_time, cf_op.in_vars[6].get(), REG_A); print_asm("sub rsp, 8\n"); print_asm("push rax\n"); } print_asm("call syscall_impl\n"); if (info.static_mapping.size() > 0) { print_asm("mov [s%zu], rax\n", info.static_mapping.at(0)); } print_asm("# destroy stack space\n"); if (is_block_top_level(info.continuation_block)) { print_asm("add rsp, %zu\n", max_stack_frame_size + 16); } else { print_asm("add rsp, 16\n"); } // need to jump to translation block // TODO: technically we don't need to if the block didn't have a input mapping before // so only do that when the next block does have an input mapping or more than one predecessor? print_asm("jmp b%zu%s\n", info.continuation_block->id, is_block_top_level(info.continuation_block) ? "" : "_reg_alloc"); break; } case CFCInstruction::call: { auto &info = std::get<CfOp::CallInfo>(cf_op.info); // write_target_inputs(info.target, cur_time, info.target_inputs); auto static_mapping = std::vector<std::pair<RefPtr<SSAVar>, size_t>>{}; for (size_t i = 0; i < info.target->inputs.size(); ++i) { static_mapping.emplace_back(std::get<CfOp::CallInfo>(cf_op.info).target_inputs[i], std::get<size_t>(info.target->inputs[i]->info)); } write_static_mapping(info.target, cur_time, static_mapping); // prevent overflow print_asm("mov rax, [init_ret_stack_ptr]\n"); print_asm("lea rax, [rax - %zu]\n", max_stack_frame_size); print_asm("cmp rsp, stack_space + 524288\n"); // max depth ~65k print_asm("cmovb rsp, rax\n"); if (info.continuation_block->virt_start_addr <= 0x7FFFFFFF) { print_asm("push %lu\n", info.continuation_block->virt_start_addr); } else { print_asm("mov rax, %lu\n", info.continuation_block->virt_start_addr); print_asm("push rax\n"); } print_asm("call b%zu\n", info.target->id); if (bb->control_flow_ops.size() != 1 || info.continuation_block != next_bb || is_block_top_level(info.continuation_block)) { if (is_block_top_level(info.continuation_block) || std::find(compiled_blocks.begin(), compiled_blocks.end(), info.continuation_block) == compiled_blocks.end()) { print_asm("add rsp, %zu\n", max_stack_frame_size + 8); print_asm("jmp b%zu\n", info.continuation_block->id); } else { print_asm("add rsp, 8\n"); print_asm("jmp b%zu_reg_alloc\n", info.continuation_block->id); } } else { print_asm("add rsp, 8\n"); } break; } case CFCInstruction::_return: { write_static_mapping(nullptr, cur_time, std::get<CfOp::RetInfo>(cf_op.info).mapping); // TODO: write out ret addr last and keep it in reg const auto ret_reg = load_val_in_reg(cur_time + std::get<CfOp::RetInfo>(cf_op.info).mapping.size(), cf_op.in_vars[0]); const auto dst_reg_name = reg_names[ret_reg][0]; print_asm("# destroy stack space\n"); print_asm("add rsp, %zu\n", max_stack_frame_size); print_asm("cmp [rsp + 8], %s\n", dst_reg_name); print_asm("jnz 0f\n"); print_asm("ret\n"); print_asm("0:\n"); // reset ret stack print_asm("mov rsp, [init_ret_stack_ptr]\n"); // do ijump print_asm("mov rbx, %s\n", dst_reg_name); print_asm("jmp ijump_lookup\n"); break; } case CFCInstruction::icall: { const auto &info = std::get<CfOp::ICallInfo>(cf_op.info); write_static_mapping((info.targets.empty() ? nullptr : info.targets[0]), cur_time, info.mapping); // TODO: we get a problem if the dst is in a static that has already been written out (so overwritten) auto *dst = cf_op.in_vars[0].get(); const auto dst_reg = load_val_in_reg(cur_time + 1 + info.mapping.size(), dst, REG_B); assert(dst->type == Type::imm || dst->type == Type::i64); const auto overflow_reg = alloc_reg(cur_time + 1 + info.mapping.size(), REG_NONE, dst_reg); const auto of_reg_name = reg_names[overflow_reg][0]; // prevent overflow print_asm("mov %s, [init_ret_stack_ptr]\n", of_reg_name); print_asm("lea %s, [%s - %zu]\n", of_reg_name, of_reg_name, max_stack_frame_size); print_asm("cmp rsp, stack_space + 524288\n"); // max depth ~65k print_asm("cmovb rsp, %s\n", of_reg_name); if (info.continuation_block->virt_start_addr <= 0x7FFFFFFF) { print_asm("push %lu\n", info.continuation_block->virt_start_addr); } else { const auto tmp_reg = alloc_reg(cur_time + 1 + info.mapping.size()); print_asm("mov %s, %lu\n", reg_names[tmp_reg][0], info.continuation_block->virt_start_addr); print_asm("push %s\n", reg_names[tmp_reg][0]); } print_asm("call ijump_lookup\n"); if (bb->control_flow_ops.size() != 1 || info.continuation_block != next_bb || is_block_top_level(info.continuation_block)) { if (is_block_top_level(info.continuation_block) || std::find(compiled_blocks.begin(), compiled_blocks.end(), info.continuation_block) == compiled_blocks.end()) { print_asm("add rsp, %zu\n", max_stack_frame_size + 8); print_asm("jmp b%zu\n", info.continuation_block->id); } else { print_asm("add rsp, 8\n"); print_asm("jmp b%zu_reg_alloc\n", info.continuation_block->id); } } else { print_asm("add rsp, 8\n"); } break; } default: { assert(0); exit(1); } } } } void RegAlloc::write_assembled_blocks(size_t max_stack_frame_size, std::vector<BasicBlock *> &compiled_blocks) { for (size_t i = 0; i < assembled_blocks.size(); ++i) { auto &block = assembled_blocks[i]; fprintf(gen->out_fd, "%s\n", block.assembly.c_str()); asm_buf.clear(); cur_bb = block.bb; cur_reg_map = &block.reg_map; cur_fp_reg_map = &block.fp_reg_map; cur_stack_map = &block.stack_map; auto *next_bb = (i + 1 >= assembled_blocks.size()) ? nullptr : assembled_blocks[i + 1].bb; compile_cf_ops(block.bb, block.reg_map, block.fp_reg_map, block.stack_map, max_stack_frame_size, next_bb, compiled_blocks); fprintf(gen->out_fd, "%s\n", asm_buf.c_str()); } cur_bb = nullptr; cur_reg_map = nullptr; cur_fp_reg_map = nullptr; cur_stack_map = nullptr; } void RegAlloc::generate_translation_block(BasicBlock *bb) { std::string tmp_buf = {}; std::swap(tmp_buf, asm_buf); bool rax_input = false; size_t rax_static = 0; for (size_t i = 0; i < bb->inputs.size(); ++i) { auto *var = bb->inputs[i]; if (var->type == Type::mt) { continue; } const auto &input_info = bb->gen_info.input_map[i]; // only allow static inputs for now assert(std::holds_alternative<size_t>(var->info)); const auto src_static = std::get<size_t>(var->info); switch (input_info.location) { case BasicBlock::GeneratorInfo::InputInfo::REGISTER: if (input_info.reg_idx == REG_A) { rax_input = true; rax_static = src_static; break; } print_asm("mov %s, [s%zu]\n", reg_names[input_info.reg_idx][0], src_static); break; case BasicBlock::GeneratorInfo::InputInfo::FP_REGISTER: print_asm("movq %s, [s%zu]\n", fp_reg_names[input_info.reg_idx], src_static); break; case BasicBlock::GeneratorInfo::InputInfo::STACK: print_asm("mov rax, [s%zu]\n", src_static); print_asm("mov [rsp + 8 * %zu], rax\n", input_info.stack_slot); break; case BasicBlock::GeneratorInfo::InputInfo::STATIC: if (input_info.static_idx != src_static) { // TODO: this can break when two statics are swapped print_asm("mov rax, [s%zu]\n", src_static); print_asm("mov [s%zu], rax\n", input_info.static_idx); } break; default: // other cases shouldn't happen assert(0); exit(1); } } if (rax_input) { print_asm("mov rax, [s%zu]\n", rax_static); } print_asm("jmp b%zu_reg_alloc\n", bb->id); std::swap(tmp_buf, asm_buf); translation_blocks.push_back(std::make_pair(bb->id, std::move(tmp_buf))); } void RegAlloc::set_bb_inputs(BasicBlock *target, const std::vector<RefPtr<SSAVar>> &inputs) { // TODO: when there are multiple blocks that follow only generate an input mapping once auto &reg_map = *cur_reg_map; auto &fp_reg_map = *cur_fp_reg_map; const auto cur_time = cur_bb->variables.size(); // fix for immediate inputs for (size_t i = 0; i < inputs.size(); ++i) { auto *input_var = inputs[i].get(); if (input_var->type == Type::mt) { continue; } if (input_var->gen_info.location != SSAVar::GeneratorInfoX64::NOT_CALCULATED) { continue; } assert(input_var->is_immediate()); load_val_in_reg<false>(cur_time, input_var); } assert(target->inputs.size() == inputs.size()); if (target->id > BB_MERGE_TIL_ID || is_block_top_level(target)) { // cheap fix to force single block register allocation set_bb_inputs_from_static(target); } else { for (size_t i = 0; i < inputs.size(); ++i) { auto *input = inputs[i].get(); input->gen_info.allocated_to_input = false; if (input->is_static() && input->gen_info.location == SSAVar::GeneratorInfoX64::STATIC && input->gen_info.static_idx != target->inputs[i]->get_static()) { // force into register because translation blocks might generate incorrect code otherwise load_val_in_reg<false>(cur_time, input); } } bool rax_used = false, xmm0_used = false; SSAVar *rax_input, *xmm0_input; // just write input locations, compile the input map and we done for (size_t i = 0; i < inputs.size(); ++i) { auto *input_var = inputs[i].get(); auto *target_var = target->inputs[i]; if (input_var->type == Type::mt) { continue; } if (input_var->gen_info.allocated_to_input) { // this var was already used as an input so we need to create a new location to store it // since there might be a different predecessor that stores it somewhere else const auto stack_slot = allocate_stack_slot(input_var); target_var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME; target_var->gen_info.saved_in_stack = true; target_var->gen_info.stack_slot = stack_slot; // move var to stack slot if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER) { print_asm("mov [rsp + 8 * %zu], %s\n", stack_slot, reg_names[input_var->gen_info.reg_idx][0]); } else if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER) { print_asm("movq [rsp + 8 * %zu], %s\n", stack_slot, fp_reg_names[input_var->gen_info.reg_idx]); } else if (is_float(input_var->type)) { FP_REGISTER reg = FP_REG_NONE; // find free/unused register for (size_t i = 0; i < FP_REG_COUNT; ++i) { if (fp_reg_map[i].cur_var == nullptr || fp_reg_map[i].cur_var->gen_info.last_use_time < cur_time) { reg = static_cast<FP_REGISTER>(i); break; } } if (reg == FP_REG_NONE) { // use xmm0 to transfer reg = REG_XMM0; if (xmm0_used) { save_fp_reg(REG_XMM0); clear_fp_reg(cur_time, REG_XMM0); } load_val_in_fp_reg(cur_time, input_var, REG_XMM0); } print_asm("movq [rsp + 8 * %zu], %s\n", stack_slot, fp_reg_names[reg]); } else { auto reg = REG_NONE; // find free/unused register for (size_t i = 0; i < REG_COUNT; ++i) { if (reg_map[i].cur_var == nullptr || reg_map[i].cur_var->gen_info.last_use_time < cur_time) { reg = static_cast<REGISTER>(i); break; } } if (reg == REG_NONE) { // use rax to transfer reg = REG_A; if (rax_used) { save_reg(REG_A); clear_reg(cur_time, REG_A); } load_val_in_reg<false>(cur_time, input_var, REG_A); } print_asm("mov [rsp + 8 * %zu], %s\n", stack_slot, reg_names[reg][0]); if (!input_var->gen_info.saved_in_stack) { input_var->gen_info.saved_in_stack = true; input_var->gen_info.stack_slot = stack_slot; } } continue; } assert(input_var->gen_info.location != SSAVar::GeneratorInfoX64::NOT_CALCULATED); input_var->gen_info.allocated_to_input = true; target_var->gen_info.location = input_var->gen_info.location; target_var->gen_info.loc_info = input_var->gen_info.loc_info; // TODO: make translation blocks/cfops put the values in the registers/statics *and* stack locations // if applicable if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::STACK_FRAME) { target_var->gen_info.saved_in_stack = true; target_var->gen_info.stack_slot = input_var->gen_info.stack_slot; } if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER && input_var->gen_info.reg_idx == REG_A) { rax_used = true; rax_input = input_var; } if (input_var->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER && input_var->gen_info.reg_idx == REG_XMM0) { xmm0_used = true; xmm0_input = input_var; } } if (rax_used && rax_input->gen_info.location != SSAVar::GeneratorInfoX64::REGISTER) { assert(reg_map[REG_A].cur_var->gen_info.saved_in_stack || reg_map[REG_A].cur_var->is_immediate()); clear_reg(cur_time, REG_A); load_val_in_reg(cur_time, rax_input, REG_A); } if (xmm0_used && xmm0_input->gen_info.location != SSAVar::GeneratorInfoX64::FP_REGISTER) { assert(fp_reg_map[REG_XMM0].cur_var->gen_info.saved_in_stack); clear_fp_reg(cur_time, REG_XMM0); load_val_in_fp_reg(cur_time, xmm0_input, REG_XMM0); } generate_input_map(target); } } void RegAlloc::set_bb_inputs_from_static(BasicBlock *target) { for (size_t i = 0; i < target->inputs.size(); ++i) { auto *var = target->inputs[i]; assert(std::holds_alternative<size_t>(var->info)); BasicBlock::GeneratorInfo::InputInfo info; info.location = BasicBlock::GeneratorInfo::InputInfo::STATIC; info.static_idx = std::get<size_t>(var->info); var->gen_info.location = SSAVar::GeneratorInfoX64::STATIC; var->gen_info.static_idx = info.static_idx; target->gen_info.input_map.push_back(info); } target->gen_info.input_map_setup = true; } void RegAlloc::generate_input_map(BasicBlock *bb) { for (size_t i = 0; i < bb->inputs.size(); ++i) { // namespaces :D using InputInfo = BasicBlock::GeneratorInfo::InputInfo; using GenInfo = SSAVar::GeneratorInfoX64; auto *var = bb->inputs[i]; if (var->type == Type::mt) { // we lie a little InputInfo info; info.location = InputInfo::STATIC; info.static_idx = 32; bb->gen_info.input_map.push_back(info); continue; } InputInfo info; const auto var_loc = var->gen_info.location; assert(var_loc == GenInfo::REGISTER || var_loc == GenInfo::FP_REGISTER || var_loc == GenInfo::STACK_FRAME || var_loc == GenInfo::STATIC); if (var_loc == GenInfo::STATIC) { info.location = InputInfo::STATIC; info.static_idx = var->gen_info.static_idx; } else if (var_loc == GenInfo::REGISTER) { info.location = InputInfo::REGISTER; info.reg_idx = var->gen_info.reg_idx; } else if (var_loc == GenInfo::FP_REGISTER) { info.location = InputInfo::FP_REGISTER; info.reg_idx = var->gen_info.reg_idx; } else if (var_loc == GenInfo::STACK_FRAME) { info.location = InputInfo::STACK; info.stack_slot = var->gen_info.stack_slot; } bb->gen_info.input_map.push_back(info); } bb->gen_info.input_map_setup = true; } void RegAlloc::write_static_mapping([[maybe_unused]] BasicBlock *bb, size_t cur_time, const std::vector<std::pair<RefPtr<SSAVar>, size_t>> &mapping) { // TODO: this is a bit unfaithful to the time calculation since we write out registers first but that should be fine auto written_out = std::vector<bool>{}; written_out.resize(mapping.size()); // TODO: here we could write out all register that do not overwrite a static that is uses as an input // but that involves a bit more housekeeping // load all static inputs into a register so we don't have to worry about that anymore for (size_t i = 0; i < mapping.size(); ++i) { const auto &pair = mapping[i]; auto *var = pair.first.get(); if (var->type == Type::mt) { continue; } if (var->gen_info.location != SSAVar::GeneratorInfoX64::STATIC) { continue; } // skip identity-mapped statics if (var->gen_info.static_idx == pair.second) { written_out[i] = true; continue; } if (is_float(var->type)) { load_val_in_fp_reg(cur_time, var); } else { load_val_in_reg(cur_time, var); } } // write out all registers for (size_t i = 0; i < mapping.size(); ++i) { const auto &pair = mapping[i]; auto *var = pair.first.get(); if (var->type == Type::mt) { continue; } auto location = var->gen_info.location; if (location != SSAVar::GeneratorInfoX64::REGISTER && location != SSAVar::GeneratorInfoX64::FP_REGISTER) { continue; } if (std::holds_alternative<size_t>(var->info)) { auto should_skip = false; for (size_t i = 0; i < cur_bb->inputs.size(); ++i) { if (cur_bb->inputs[i] == var) { const auto &info = cur_bb->gen_info.input_map[i]; if (info.location == BasicBlock::GeneratorInfo::InputInfo::STATIC && info.static_idx == pair.second) { should_skip = true; } break; } } if (should_skip) { continue; } } if (location == SSAVar::GeneratorInfoX64::FP_REGISTER) { print_asm("movq [s%zu], %s\n", pair.second, fp_reg_names[var->gen_info.reg_idx]); continue; } print_asm("mov [s%zu], %s\n", pair.second, reg_names[var->gen_info.reg_idx][0]); written_out[i] = true; } // write out stuff in stack for (size_t var_idx = 0; var_idx < mapping.size(); ++var_idx) { auto *var = mapping[var_idx].first.get(); if (var->type == Type::mt) { continue; } const auto static_idx = mapping[var_idx].second; if (written_out[var_idx]) { continue; } if (std::holds_alternative<size_t>(var->info)) { auto should_skip = false; for (size_t i = 0; i < cur_bb->inputs.size(); ++i) { if (cur_bb->inputs[i] == var) { const auto &info = cur_bb->gen_info.input_map[i]; if (info.location == BasicBlock::GeneratorInfo::InputInfo::STATIC && info.static_idx == static_idx) { should_skip = true; } break; } } if (should_skip) { continue; } } // TODO: cant do that here since the syscall cfop needs some vars later on // TODO: really need to fix this time management if (is_float(var->type)) { const auto reg = load_val_in_fp_reg(cur_time, var); print_asm("movq [s%zu], %s\n", static_idx, fp_reg_names[reg]); } else { const auto reg = load_val_in_reg(cur_time /*+ var_idx*/, var); print_asm("mov [s%zu], %s\n", static_idx, reg_names[reg][0]); } } } void RegAlloc::write_target_inputs(BasicBlock *target, size_t cur_time, const std::vector<RefPtr<SSAVar>> &inputs) { // Here we have multiple problems: // - we could need to write to a static that is needed to be somewhere else later // - we could need to write to a register that is needed somewhere else later // - we could need to write to a stack-slot that is needed somewhere else later // the dumbest thing to solve these would be to recognize them, force-allocate new stack-slots and load them from there when needed // so that's what we do :) // register conflicts should be resolved by load_from_reg though assert(target->gen_info.input_map_setup); assert(target->inputs.size() == target->gen_info.input_map.size()); const auto &input_map = target->gen_info.input_map; // mark all stack slots used as inputs as non-free auto &stack_map = *cur_stack_map; for (size_t i = 0; i < input_map.size(); ++i) { if (input_map[i].location != BasicBlock::GeneratorInfo::InputInfo::STACK) { continue; } const auto stack_slot = input_map[i].stack_slot; if (stack_map.size() <= stack_slot) { stack_map.resize(stack_slot + 1); } stack_map[stack_slot].free = false; } // fixup time calculation // TODO: do this at the start for (auto &input : inputs) { input->gen_info.last_use_time = 0; input->gen_info.uses.clear(); } size_t cur_write_time = cur_time + 1; const auto set_use_times = [&cur_write_time, &input_map, &inputs](BasicBlock::GeneratorInfo::InputInfo::LOCATION loc) { for (size_t i = 0; i < inputs.size(); ++i) { if (input_map[i].location != loc) { continue; } inputs[i]->gen_info.last_use_time = cur_write_time; inputs[i]->gen_info.uses.emplace_back(cur_write_time); cur_write_time++; } }; // we write out statics first set_use_times(BasicBlock::GeneratorInfo::InputInfo::STATIC); // stack second set_use_times(BasicBlock::GeneratorInfo::InputInfo::STACK); // registers last set_use_times(BasicBlock::GeneratorInfo::InputInfo::REGISTER); set_use_times(BasicBlock::GeneratorInfo::InputInfo::FP_REGISTER); // figure out static conflicts for (size_t i = 0; i < inputs.size(); ++i) { if (inputs[i]->gen_info.location != SSAVar::GeneratorInfoX64::STATIC) { continue; } if (inputs[i]->type == Type::mt) { continue; } // it is a problem when another input needs to be at this static auto conflict = false; for (size_t j = 0; j < inputs.size(); ++j) { if (j == i) { continue; } if (inputs[j]->type != Type::mt && input_map[j].location == BasicBlock::GeneratorInfo::InputInfo::STATIC && input_map[j].static_idx == inputs[i]->gen_info.static_idx) { conflict = true; break; } } if (!conflict) { continue; } // just load it in a register if (is_float(inputs[i].get()->type)) { load_val_in_fp_reg(cur_time, inputs[i].get()); } else { load_val_in_reg(cur_time, inputs[i].get()); } } // stack conflicts for (size_t i = 0; i < inputs.size(); ++i) { auto *var = inputs[i].get(); if (!var->gen_info.saved_in_stack) { continue; } // when two stack slots overlap and they don't correspond to the same stack slot auto conflict = false; for (size_t j = 0; j < inputs.size(); ++j) { if (i == j || input_map[j].location != BasicBlock::GeneratorInfo::InputInfo::STACK) { continue; } if (var->gen_info.stack_slot == input_map[j].stack_slot) { conflict = true; break; } } if (!conflict) { continue; } // load in register, delete stack slot and save again if (is_float(var->type)) { const auto reg = load_val_in_fp_reg(cur_time, var); var->gen_info.saved_in_stack = false; save_fp_reg(reg); } else { const auto reg = load_val_in_reg(cur_time, var); var->gen_info.saved_in_stack = false; save_reg(reg); } } cur_write_time = cur_time + 1; // write out statics for (size_t var_idx = 0; var_idx < inputs.size(); ++var_idx) { if (input_map[var_idx].location != BasicBlock::GeneratorInfo::InputInfo::STATIC) { continue; } if (inputs[var_idx]->type == Type::mt) { cur_write_time++; continue; } if (inputs[var_idx]->gen_info.location == SSAVar::GeneratorInfoX64::STATIC && inputs[var_idx]->gen_info.static_idx == input_map[var_idx].static_idx) { cur_write_time++; continue; } auto *var = inputs[var_idx].get(); if (std::holds_alternative<size_t>(var->info)) { auto should_skip = false; for (size_t i = 0; i < cur_bb->inputs.size(); ++i) { if (cur_bb->inputs[i] == var) { const auto &info = cur_bb->gen_info.input_map[i]; if (info.location == BasicBlock::GeneratorInfo::InputInfo::STATIC && info.static_idx == input_map[var_idx].static_idx) { should_skip = true; } break; } } if (should_skip) { cur_write_time++; continue; } } if (is_float(var->type)) { const auto reg = load_val_in_fp_reg(cur_write_time, var); print_asm("movq [s%zu], %s\n", input_map[var_idx].static_idx, fp_reg_names[reg]); } else { const auto reg = load_val_in_reg(cur_write_time, var); print_asm("mov [s%zu], %s\n", input_map[var_idx].static_idx, reg_names[reg][0]); } cur_write_time++; } // write out stack for (size_t var_idx = 0; var_idx < inputs.size(); ++var_idx) { auto &info = input_map[var_idx]; if (info.location != BasicBlock::GeneratorInfo::InputInfo::STACK) { continue; } auto *input = inputs[var_idx].get(); if (input->gen_info.saved_in_stack && input->gen_info.stack_slot == info.stack_slot) { cur_write_time++; continue; } if (is_float(input->type)) { const auto reg = load_val_in_fp_reg(cur_write_time, input); print_asm("movq [rsp + 8 * %zu], %s\n", info.stack_slot, fp_reg_names[reg]); } else { const auto reg = load_val_in_reg(cur_write_time, input); print_asm("mov [rsp + 8 * %zu], %s\n", info.stack_slot, reg_names[reg][0]); } cur_write_time++; } // write out registers auto &reg_map = *cur_reg_map; for (size_t var_idx = 0; var_idx < inputs.size(); ++var_idx) { if (input_map[var_idx].location != BasicBlock::GeneratorInfo::InputInfo::REGISTER) { continue; } const auto reg = static_cast<REGISTER>(input_map[var_idx].reg_idx); auto *input = inputs[var_idx].get(); if (input->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER) { if (input->gen_info.reg_idx == reg) { cur_write_time++; continue; } // just emit a mov and evict the other var if (reg_map[reg].cur_var && reg_map[reg].cur_var->gen_info.last_use_time > cur_write_time) { save_reg(reg); } clear_reg(cur_write_time, reg); print_asm("mov %s, %s\n", reg_names[reg][0], reg_names[input->gen_info.reg_idx][0]); reg_map[reg].cur_var = input; reg_map[reg].alloc_time = cur_write_time; } else { load_val_in_reg(cur_write_time, input, reg); } cur_write_time++; } // write out fp registers auto &fp_reg_map = *cur_fp_reg_map; for (size_t var_idx = 0; var_idx < inputs.size(); ++var_idx) { if (input_map[var_idx].location != BasicBlock::GeneratorInfo::InputInfo::FP_REGISTER) { continue; } const auto reg = static_cast<FP_REGISTER>(input_map[var_idx].reg_idx); auto *input = inputs[var_idx].get(); if (input->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER) { if (input->gen_info.reg_idx == reg) { cur_write_time++; continue; } // just emit a mov and evict the other var if (fp_reg_map[reg].cur_var && fp_reg_map[reg].cur_var->gen_info.last_use_time > cur_write_time) { save_fp_reg(reg); } clear_fp_reg(cur_write_time, reg); print_asm("movq %s, %s\n", fp_reg_names[reg], fp_reg_names[input->gen_info.reg_idx]); fp_reg_map[reg].cur_var = input; fp_reg_map[reg].alloc_time = cur_write_time; } else { load_val_in_fp_reg(cur_write_time, input, reg); } cur_write_time++; } } void RegAlloc::init_time_of_use(BasicBlock *bb) { for (size_t i = 0; i < bb->variables.size(); ++i) { auto *var = bb->variables[i].get(); if (!std::holds_alternative<std::unique_ptr<Operation>>(var->info)) { continue; } auto *op = std::get<std::unique_ptr<Operation>>(var->info).get(); for (auto &input : op->in_vars) { if (!input) { continue; } input->gen_info.last_use_time = i; // max(last_use_time, i)? input->gen_info.uses.push_back(i); } if (std::holds_alternative<RefPtr<SSAVar>>(op->rounding_info)) { SSAVar *rounding_info = std::get<RefPtr<SSAVar>>(op->rounding_info).get(); rounding_info->gen_info.last_use_time = i; rounding_info->gen_info.uses.push_back(i); } } const auto set_time_cont_mapping = [](const size_t time_off, std::vector<std::pair<RefPtr<SSAVar>, size_t>> &mapping) { for (size_t i = 0; i < mapping.size(); ++i) { auto &info = mapping[i].first->gen_info; info.last_use_time = std::max(info.last_use_time, time_off + i); info.uses.push_back(time_off + i); } }; const auto set_time_inputs = [](const size_t time_off, std::vector<RefPtr<SSAVar>> &mapping) { for (size_t i = 0; i < mapping.size(); ++i) { auto &info = mapping[i]->gen_info; info.last_use_time = std::max(info.last_use_time, time_off + i); info.uses.push_back(time_off + i); } }; for (auto &cf_op : bb->control_flow_ops) { // we treat cf_ops as running in parallel auto time_off = bb->variables.size(); for (auto &input : cf_op.in_vars) { if (!input) { continue; } input->gen_info.last_use_time = std::max(input->gen_info.last_use_time, time_off); input->gen_info.uses.push_back(time_off); } time_off++; switch (cf_op.type) { case CFCInstruction::jump: set_time_inputs(time_off, std::get<CfOp::JumpInfo>(cf_op.info).target_inputs); break; case CFCInstruction::ijump: set_time_cont_mapping(time_off, std::get<CfOp::IJumpInfo>(cf_op.info).mapping); break; case CFCInstruction::cjump: set_time_inputs(time_off, std::get<CfOp::CJumpInfo>(cf_op.info).target_inputs); break; case CFCInstruction::call: { auto &info = std::get<CfOp::CallInfo>(cf_op.info); set_time_inputs(time_off, info.target_inputs); time_off += info.target_inputs.size(); break; } case CFCInstruction::icall: { auto &info = std::get<CfOp::ICallInfo>(cf_op.info); set_time_cont_mapping(time_off, info.mapping); time_off += info.mapping.size(); break; } case CFCInstruction::_return: set_time_cont_mapping(time_off, std::get<CfOp::RetInfo>(cf_op.info).mapping); break; case CFCInstruction::unreachable: break; case CFCInstruction::syscall: set_time_cont_mapping(time_off, std::get<CfOp::SyscallInfo>(cf_op.info).continuation_mapping); break; } } } template <bool evict_imms, typename... Args> REGISTER RegAlloc::alloc_reg(size_t cur_time, REGISTER only_this_reg, Args... clear_regs) { static_assert((std::is_same_v<Args, REGISTER> && ...)); auto &reg_map = *cur_reg_map; if (only_this_reg != REG_NONE) { auto &cur_var = reg_map[only_this_reg].cur_var; if (cur_var != nullptr) { save_reg(only_this_reg, !evict_imms); cur_var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME; cur_var = nullptr; } return only_this_reg; } REGISTER reg = REG_NONE; // try to find free register for (size_t i = 0; i < REG_COUNT; ++i) { if (((i == clear_regs) || ...)) { // NOLINT(clang-diagnostic-parentheses-equality) continue; } if (reg_map[i].cur_var == nullptr) { reg = static_cast<REGISTER>(i); break; } } if (reg == REG_NONE) { // try to find reg with unused var for (size_t i = 0; i < REG_COUNT; ++i) { if (((i == clear_regs) || ...)) { // NOLINT(clang-diagnostic-parentheses-equality) continue; } if (reg_map[i].cur_var->gen_info.last_use_time < cur_time) { reg = static_cast<REGISTER>(i); break; } } if (reg == REG_NONE) { // find var that's the farthest from being used again // TODO: prefer variables that are used less often so that the stack ptr for example stays in a register size_t farthest_use_time = 0; REGISTER farthest_use_reg = REG_NONE; for (size_t i = 0; i < REG_COUNT; ++i) { if (((i == clear_regs) || ...)) { // NOLINT(clang-diagnostic-parentheses-equality) continue; } size_t next_use = 0; for (const auto use_time : reg_map[i].cur_var->gen_info.uses) { if (use_time == cur_time) { // var is used in this step so don't reuse it next_use = 0; break; } if (use_time > cur_time) { next_use = use_time; break; } } if (next_use == 0) { // var is needed in this step continue; } if (farthest_use_time < next_use) { farthest_use_time = next_use; farthest_use_reg = static_cast<REGISTER>(i); } } assert(farthest_use_reg != REG_NONE); reg = farthest_use_reg; // in cfops imms need to be saved to stack cause there's not other means to pass them save_reg(farthest_use_reg, !evict_imms); } } clear_reg(cur_time, reg, !evict_imms); reg_map[reg].cur_var = nullptr; reg_map[reg].alloc_time = cur_time; return reg; } template <typename... Args> FP_REGISTER RegAlloc::alloc_fp_reg(size_t cur_time, FP_REGISTER only_this_reg, Args... clear_regs) { static_assert((std::is_same_v<Args, FP_REGISTER> && ...)); auto &reg_map = *cur_fp_reg_map; if (only_this_reg != FP_REG_NONE) { auto &cur_var = reg_map[only_this_reg].cur_var; if (cur_var != nullptr) { save_fp_reg(only_this_reg); cur_var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME; cur_var = nullptr; } return only_this_reg; } FP_REGISTER reg = FP_REG_NONE; // try to find free register for (size_t i = 0; i < FP_REG_COUNT; ++i) { if (((i == clear_regs) || ...)) { continue; } if (reg_map[i].cur_var == nullptr) { reg = static_cast<FP_REGISTER>(i); break; } } if (reg == FP_REG_NONE) { // try to find reg with unused var for (size_t i = 0; i < FP_REG_COUNT; ++i) { if (((i == clear_regs) || ...)) { continue; } if (reg_map[i].cur_var->gen_info.last_use_time < cur_time) { reg = static_cast<FP_REGISTER>(i); break; } } if (reg == FP_REG_NONE) { // find var that's the farthest from being used again // TODO: prefer variables that are used less often so that the stack ptr for example stays in a register size_t farthest_use_time = 0; FP_REGISTER farthest_use_reg = FP_REG_NONE; for (size_t i = 0; i < FP_REG_COUNT; ++i) { if (((i == clear_regs) || ...)) { continue; } size_t next_use = 0; for (const auto use_time : reg_map[i].cur_var->gen_info.uses) { if (use_time == cur_time) { // var is used in this step so don't reuse it next_use = 0; break; } if (use_time > cur_time) { next_use = use_time; break; } } if (next_use == 0) { // var is needed in this step continue; } if (farthest_use_time < next_use) { farthest_use_time = next_use; farthest_use_reg = static_cast<FP_REGISTER>(i); } } assert(farthest_use_reg != FP_REG_NONE); reg = farthest_use_reg; // in cfops imms need to be saved to stack cause there's not other means to pass them save_fp_reg(farthest_use_reg); } } clear_fp_reg(cur_time, reg); reg_map[reg].cur_var = nullptr; reg_map[reg].alloc_time = cur_time; return reg; } template <bool evict_imms, typename... Args> REGISTER RegAlloc::load_val_in_reg(size_t cur_time, SSAVar *var, REGISTER only_this_reg, Args... clear_regs) { static_assert((std::is_same_v<Args, REGISTER> && ...)); auto &reg_map = *cur_reg_map; if (var->gen_info.location == SSAVar::GeneratorInfoX64::REGISTER) { if (only_this_reg == REG_NONE || var->gen_info.reg_idx == only_this_reg) { if (((var->gen_info.reg_idx == clear_regs) || ...)) { // NOLINT(clang-diagnostic-parentheses-equality) // clear_regs take precedent over only_this_reg though it should never happen assert(((only_this_reg != clear_regs) && ...)); const auto new_reg = alloc_reg(cur_time, REG_NONE, clear_regs...); print_asm("mov %s, %s\n", reg_names[new_reg][0], reg_names[var->gen_info.reg_idx][0]); reg_map[var->gen_info.reg_idx].cur_var = nullptr; reg_map[new_reg].cur_var = var; reg_map[new_reg].alloc_time = cur_time; var->gen_info.reg_idx = new_reg; return new_reg; } return static_cast<REGISTER>(var->gen_info.reg_idx); } // TODO: add a thing in the regmap that tells the allocater that the var may only be in this register // TODO: this will bug out when you alloc a reg and then alloc one if only_this_reg and they end up in the same register if (auto *other_var = reg_map[only_this_reg].cur_var; other_var && other_var->gen_info.last_use_time >= cur_time) { // TODO: disabled this as it doesn't cope well when a var needs to be in two registers at the same time, // e.g. in cfops /*print_asm("xchg %s, %s\n", reg_names[only_this_reg][0], reg_names[var->gen_info.reg_idx][0]); std::swap(reg_map[only_this_reg], reg_map[var->gen_info.reg_idx]); std::swap(var->gen_info.reg_idx, other_var->gen_info.reg_idx); return only_this_reg;*/ save_reg(only_this_reg); } clear_reg(cur_time, only_this_reg); print_asm("mov %s, %s\n", reg_names[only_this_reg][0], reg_names[var->gen_info.reg_idx][0]); reg_map[var->gen_info.reg_idx].cur_var = nullptr; reg_map[only_this_reg].cur_var = var; var->gen_info.reg_idx = only_this_reg; return only_this_reg; } const auto reg = alloc_reg<evict_imms>(cur_time, only_this_reg, clear_regs...); if (var->is_immediate()) { auto &info = std::get<SSAVar::ImmInfo>(var->info); if (info.binary_relative) { print_asm("lea %s, [binary + %ld]\n", reg_names[reg][0], info.val); } else { print_asm("mov %s, %ld\n", reg_names[reg][0], info.val); } } else { // non-immediates should have been calculated before assert(var->gen_info.location != SSAVar::GeneratorInfoX64::NOT_CALCULATED); if (var->gen_info.location == SSAVar::GeneratorInfoX64::STATIC) { print_asm("mov %s, [s%zu]\n", reg_name(reg, var->type), var->gen_info.static_idx); } else { print_asm("mov %s, [rsp + 8 * %zu]\n", reg_name(reg, var->type), var->gen_info.stack_slot); } } reg_map[reg].cur_var = var; var->gen_info.location = SSAVar::GeneratorInfoX64::REGISTER; var->gen_info.reg_idx = reg; return reg; } template <typename... Args> FP_REGISTER RegAlloc::load_val_in_fp_reg(size_t cur_time, SSAVar *var, FP_REGISTER only_this_reg, Args... clear_regs) { static_assert((std::is_same_v<Args, FP_REGISTER> && ...)); auto &reg_map = *cur_fp_reg_map; assert(var->gen_info.location != SSAVar::GeneratorInfoX64::REGISTER); if (var->gen_info.location == SSAVar::GeneratorInfoX64::FP_REGISTER) { if (only_this_reg == FP_REG_NONE || var->gen_info.reg_idx == only_this_reg) { if (((var->gen_info.reg_idx == clear_regs) || ...)) { // clear_regs take precedent over only_this_reg though it should never happen assert(((only_this_reg != clear_regs) && ...)); const auto new_reg = alloc_fp_reg(cur_time, FP_REG_NONE, clear_regs...); print_asm("movq %s, %s\n", fp_reg_names[new_reg], fp_reg_names[var->gen_info.reg_idx]); reg_map[var->gen_info.reg_idx].cur_var = nullptr; reg_map[new_reg].cur_var = var; reg_map[new_reg].alloc_time = cur_time; var->gen_info.reg_idx = new_reg; return new_reg; } return static_cast<FP_REGISTER>(var->gen_info.reg_idx); } // TODO: add a thing in the regmap that tells the allocater that the var may only be in this register // TODO: this will bug out when you alloc a reg and then alloc one if only_this_reg and they end up in the same register if (auto *other_var = reg_map[only_this_reg].cur_var; other_var && other_var->gen_info.last_use_time >= cur_time) { // swap register contents /*print_asm("pxor %s, %s\n", fp_reg_names[only_this_reg], fp_reg_names[var->gen_info.reg_idx]); print_asm("pxor %s, %s\n", fp_reg_names[var->gen_info.reg_idx], fp_reg_names[only_this_reg]); print_asm("pxor %s, %s\n", fp_reg_names[only_this_reg], fp_reg_names[var->gen_info.reg_idx]); std::swap(reg_map[only_this_reg], reg_map[var->gen_info.reg_idx]); std::swap(var->gen_info.reg_idx, other_var->gen_info.reg_idx); return only_this_reg; */ save_fp_reg(only_this_reg); } clear_fp_reg(cur_time, only_this_reg); print_asm("movq %s, %s\n", fp_reg_names[only_this_reg], fp_reg_names[var->gen_info.reg_idx]); reg_map[var->gen_info.reg_idx].cur_var = nullptr; reg_map[only_this_reg].cur_var = var; var->gen_info.reg_idx = only_this_reg; return only_this_reg; } const auto reg = alloc_fp_reg(cur_time, only_this_reg, clear_regs...); // non-immediates should have been calculated before assert(var->gen_info.location != SSAVar::GeneratorInfoX64::NOT_CALCULATED); if (var->gen_info.location == SSAVar::GeneratorInfoX64::STATIC) { print_asm("movq %s, [s%zu]\n", fp_reg_names[reg], var->gen_info.static_idx); } else { print_asm("movq %s, [rsp + 8 * %zu]\n", fp_reg_names[reg], var->gen_info.stack_slot); } reg_map[reg].cur_var = var; var->gen_info.location = SSAVar::GeneratorInfoX64::FP_REGISTER; var->gen_info.reg_idx = reg; return reg; } void RegAlloc::clear_reg(size_t cur_time, REGISTER reg, bool imm_to_stack) { auto &reg_map = *cur_reg_map; auto *var = reg_map[reg].cur_var; if (!var) { return; } if (var->is_immediate() && !imm_to_stack) { // we simply calculate the value on demand var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED; } else if (var->gen_info.saved_in_stack) { var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME; } else { // var that was never saved on stack and is not needed anymore // TODO: <? assert(var->gen_info.last_use_time <= cur_time); var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED; } reg_map[reg].cur_var = nullptr; } void RegAlloc::clear_fp_reg(size_t cur_time, FP_REGISTER reg) { auto &reg_map = *cur_fp_reg_map; auto *var = reg_map[reg].cur_var; if (!var) { return; } if (var->gen_info.saved_in_stack) { var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME; } else { // var that was never saved on stack and is not needed anymore assert(var->gen_info.last_use_time <= cur_time); var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED; } reg_map[reg].cur_var = nullptr; } size_t RegAlloc::allocate_stack_slot(SSAVar *var) { auto &stack_map = *cur_stack_map; // find slot for var size_t stack_slot = 0; { auto stack_slot_found = false; for (size_t i = 0; i < stack_map.size(); ++i) { if (stack_map[i].free) { stack_slot_found = true; stack_slot = i; break; } } if (!stack_slot_found) { stack_slot = stack_map.size(); stack_map.emplace_back(); } } stack_map[stack_slot].free = false; stack_map[stack_slot].var = var; return stack_slot; } void RegAlloc::save_reg(REGISTER reg, bool imm_to_stack) { auto &reg_map = *cur_reg_map; auto *var = reg_map[reg].cur_var; if (!var) { return; } if (var->gen_info.saved_in_stack) { // var was already saved, no need to save it again return; } if (var->is_immediate() && !imm_to_stack) { // no need to save immediates i think return; } // find slot for var size_t stack_slot = allocate_stack_slot(var); print_asm("mov [rsp + 8 * %zu], %s\n", stack_slot, reg_name(reg, var->type)); var->gen_info.saved_in_stack = true; var->gen_info.stack_slot = stack_slot; } void RegAlloc::save_fp_reg(FP_REGISTER reg) { auto &reg_map = *cur_fp_reg_map; auto *var = reg_map[reg].cur_var; if (!var) { return; } if (var->gen_info.saved_in_stack) { // var was already saved, no need to save it again return; } // find slot for var size_t stack_slot = allocate_stack_slot(var); print_asm("movq [rsp + 8 * %zu], %s\n", stack_slot, fp_reg_names[reg]); var->gen_info.saved_in_stack = true; var->gen_info.stack_slot = stack_slot; } void RegAlloc::clear_after_alloc_time(size_t alloc_time) { // TODO: doesnt work auto &reg_map = *cur_reg_map; for (size_t i = 0; i < REG_COUNT; ++i) { if (reg_map[i].alloc_time < alloc_time) { continue; } auto *var = reg_map[i].cur_var; if (!var) { return; } if (var->is_immediate()) { // we simply calculate the value on demand var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED; } else if (var->gen_info.saved_in_stack) { var->gen_info.location = SSAVar::GeneratorInfoX64::STACK_FRAME; } else { var->gen_info.location = SSAVar::GeneratorInfoX64::NOT_CALCULATED; } reg_map[i].cur_var = nullptr; } } bool RegAlloc::is_block_top_level(BasicBlock *bb) { if (bb->id > BB_OLD_COMPILE_ID_TIL || bb->id > BB_MERGE_TIL_ID || bb->gen_info.manual_top_level || bb->gen_info.call_target) { return true; } for (auto *pred : bb->predecessors) { if (pred != bb) { return false; } } return true; }
145,952
47,330
/*************************************************************************** copyright : (C) 2009 by Lukas Lalinsky email : lukas@oxygene.sk ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <string> #include <stdio.h> #include <tag.h> #include <tbytevectorlist.h> #include <aifffile.h> #include <cppunit/extensions/HelperMacros.h> #include "utils.h" using namespace std; using namespace TagLib; class TestAIFF : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TestAIFF); CPPUNIT_TEST(testAiffProperties); CPPUNIT_TEST(testAiffCProperties); CPPUNIT_TEST(testSaveID3v2); CPPUNIT_TEST(testSaveID3v23); CPPUNIT_TEST(testDuplicateID3v2); CPPUNIT_TEST(testFuzzedFile1); CPPUNIT_TEST(testFuzzedFile2); CPPUNIT_TEST_SUITE_END(); public: void testAiffProperties() { RIFF::AIFF::File f(TEST_FILE_PATH_C("empty.aiff")); CPPUNIT_ASSERT(f.audioProperties()); CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->lengthInSeconds()); CPPUNIT_ASSERT_EQUAL(67, f.audioProperties()->lengthInMilliseconds()); CPPUNIT_ASSERT_EQUAL(706, f.audioProperties()->bitrate()); CPPUNIT_ASSERT_EQUAL(44100, f.audioProperties()->sampleRate()); CPPUNIT_ASSERT_EQUAL(1, f.audioProperties()->channels()); CPPUNIT_ASSERT_EQUAL(16, f.audioProperties()->bitsPerSample()); CPPUNIT_ASSERT_EQUAL(2941U, f.audioProperties()->sampleFrames()); CPPUNIT_ASSERT_EQUAL(false, f.audioProperties()->isAiffC()); } void testAiffCProperties() { RIFF::AIFF::File f(TEST_FILE_PATH_C("alaw.aifc")); CPPUNIT_ASSERT(f.audioProperties()); CPPUNIT_ASSERT_EQUAL(0, f.audioProperties()->lengthInSeconds()); CPPUNIT_ASSERT_EQUAL(37, f.audioProperties()->lengthInMilliseconds()); CPPUNIT_ASSERT_EQUAL(355, f.audioProperties()->bitrate()); CPPUNIT_ASSERT_EQUAL(44100, f.audioProperties()->sampleRate()); CPPUNIT_ASSERT_EQUAL(1, f.audioProperties()->channels()); CPPUNIT_ASSERT_EQUAL(16, f.audioProperties()->bitsPerSample()); CPPUNIT_ASSERT_EQUAL(1622U, f.audioProperties()->sampleFrames()); CPPUNIT_ASSERT_EQUAL(true, f.audioProperties()->isAiffC()); CPPUNIT_ASSERT_EQUAL(ByteVector("ALAW"), f.audioProperties()->compressionType()); CPPUNIT_ASSERT_EQUAL(String("SGI CCITT G.711 A-law"), f.audioProperties()->compressionName()); } void testSaveID3v2() { ScopedFileCopy copy("empty", ".aiff"); string newname = copy.fileName(); { RIFF::AIFF::File f(newname.c_str()); CPPUNIT_ASSERT(!f.hasID3v2Tag()); f.tag()->setTitle(L"TitleXXX"); f.save(); CPPUNIT_ASSERT(f.hasID3v2Tag()); } { RIFF::AIFF::File f(newname.c_str()); CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT_EQUAL(String(L"TitleXXX"), f.tag()->title()); f.tag()->setTitle(""); f.save(); CPPUNIT_ASSERT(!f.hasID3v2Tag()); } { RIFF::AIFF::File f(newname.c_str()); CPPUNIT_ASSERT(!f.hasID3v2Tag()); } } void testSaveID3v23() { ScopedFileCopy copy("empty", ".aiff"); string newname = copy.fileName(); String xxx = ByteVector(254, 'X'); { RIFF::AIFF::File f(newname.c_str()); CPPUNIT_ASSERT_EQUAL(false, f.hasID3v2Tag()); f.tag()->setTitle(xxx); f.tag()->setArtist("Artist A"); f.save(ID3v2::v3); CPPUNIT_ASSERT_EQUAL(true, f.hasID3v2Tag()); } { RIFF::AIFF::File f2(newname.c_str()); CPPUNIT_ASSERT_EQUAL((unsigned int)3, f2.tag()->header()->majorVersion()); CPPUNIT_ASSERT_EQUAL(String("Artist A"), f2.tag()->artist()); CPPUNIT_ASSERT_EQUAL(xxx, f2.tag()->title()); } } void testDuplicateID3v2() { ScopedFileCopy copy("duplicate_id3v2", ".aiff"); // duplicate_id3v2.aiff has duplicate ID3v2 tag chunks. // title() returns "Title2" if can't skip the second tag. RIFF::AIFF::File f(copy.fileName().c_str()); CPPUNIT_ASSERT(f.hasID3v2Tag()); CPPUNIT_ASSERT_EQUAL(String("Title1"), f.tag()->title()); f.save(); CPPUNIT_ASSERT_EQUAL(7030L, f.length()); CPPUNIT_ASSERT_EQUAL(-1L, f.find("Title2")); } void testFuzzedFile1() { RIFF::AIFF::File f(TEST_FILE_PATH_C("segfault.aif")); CPPUNIT_ASSERT(!f.isValid()); } void testFuzzedFile2() { RIFF::AIFF::File f(TEST_FILE_PATH_C("excessive_alloc.aif")); CPPUNIT_ASSERT(!f.isValid()); } }; CPPUNIT_TEST_SUITE_REGISTRATION(TestAIFF);
5,905
2,127
๏ปฟ #include "bubble_border.h" #include "base/logging.h" #include "SkBitmap.h" #include "ui_gfx/canvas_skia.h" #include "ui_gfx/path.h" #include "ui_gfx/rect.h" #include "ui_base/resource/resource_bundle.h" #include "view/view.h" #include "../../resource/resource.h" // static SkBitmap* BubbleBorder::left_ = NULL; SkBitmap* BubbleBorder::top_left_ = NULL; SkBitmap* BubbleBorder::top_ = NULL; SkBitmap* BubbleBorder::top_right_ = NULL; SkBitmap* BubbleBorder::right_ = NULL; SkBitmap* BubbleBorder::bottom_right_ = NULL; SkBitmap* BubbleBorder::bottom_ = NULL; SkBitmap* BubbleBorder::bottom_left_ = NULL; SkBitmap* BubbleBorder::top_arrow_ = NULL; SkBitmap* BubbleBorder::bottom_arrow_ = NULL; SkBitmap* BubbleBorder::left_arrow_ = NULL; SkBitmap* BubbleBorder::right_arrow_ = NULL; // static int BubbleBorder::arrow_offset_; // The height inside the arrow image, in pixels. static const int kArrowInteriorHeight = 7; gfx::Rect BubbleBorder::GetBounds(const gfx::Rect& position_relative_to, const gfx::Size& contents_size) const { // Desired size is size of contents enlarged by the size of the border images. gfx::Size border_size(contents_size); gfx::Insets insets; GetInsets(&insets); border_size.Enlarge(insets.left() + insets.right(), insets.top() + insets.bottom()); // Screen position depends on the arrow location. // The arrow should overlap the target by some amount since there is space // for shadow between arrow tip and bitmap bounds. const int kArrowOverlap = 3; int x = position_relative_to.x(); int y = position_relative_to.y(); int w = position_relative_to.width(); int h = position_relative_to.height(); int arrow_offset = override_arrow_offset_ ? override_arrow_offset_ : arrow_offset_; // Calculate bubble x coordinate. switch(arrow_location_) { case TOP_LEFT: case BOTTOM_LEFT: x += w / 2 - arrow_offset; break; case TOP_RIGHT: case BOTTOM_RIGHT: x += w / 2 + arrow_offset - border_size.width() + 1; break; case LEFT_TOP: case LEFT_BOTTOM: x += w - kArrowOverlap; break; case RIGHT_TOP: case RIGHT_BOTTOM: x += kArrowOverlap - border_size.width(); break; case NONE: case FLOAT: x += w / 2 - border_size.width() / 2; break; } // Calculate bubble y coordinate. switch(arrow_location_) { case TOP_LEFT: case TOP_RIGHT: y += h - kArrowOverlap; break; case BOTTOM_LEFT: case BOTTOM_RIGHT: y += kArrowOverlap - border_size.height(); break; case LEFT_TOP: case RIGHT_TOP: y += h / 2 - arrow_offset; break; case LEFT_BOTTOM: case RIGHT_BOTTOM: y += h / 2 + arrow_offset - border_size.height() + 1; break; case NONE: y += h; break; case FLOAT: y += h / 2 - border_size.height() / 2; break; } return gfx::Rect(x, y, border_size.width(), border_size.height()); } void BubbleBorder::GetInsets(gfx::Insets* insets) const { int top = top_->height(); int bottom = bottom_->height(); int left = left_->width(); int right = right_->width(); switch(arrow_location_) { case TOP_LEFT: case TOP_RIGHT: top = std::max(top, top_arrow_->height()); break; case BOTTOM_LEFT: case BOTTOM_RIGHT: bottom = std::max(bottom, bottom_arrow_->height()); break; case LEFT_TOP: case LEFT_BOTTOM: left = std::max(left, left_arrow_->width()); break; case RIGHT_TOP: case RIGHT_BOTTOM: right = std::max(right, right_arrow_->width()); break; case NONE: case FLOAT: // Nothing to do. break; } insets->Set(top, left, bottom, right); } int BubbleBorder::SetArrowOffset(int offset, const gfx::Size& contents_size) { gfx::Size border_size(contents_size); gfx::Insets insets; GetInsets(&insets); border_size.Enlarge(insets.left() + insets.right(), insets.top() + insets.bottom()); offset = std::max(arrow_offset_, std::min(offset, (is_arrow_on_horizontal(arrow_location_) ? border_size.width() : border_size.height()) - arrow_offset_)); override_arrow_offset_ = offset; return override_arrow_offset_; } // static void BubbleBorder::InitClass() { static bool initialized = false; if(!initialized) { // Load images. ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); left_ = rb.GetBitmapNamed(IDR_BUBBLE_L); top_left_ = rb.GetBitmapNamed(IDR_BUBBLE_TL); top_ = rb.GetBitmapNamed(IDR_BUBBLE_T); top_right_ = rb.GetBitmapNamed(IDR_BUBBLE_TR); right_ = rb.GetBitmapNamed(IDR_BUBBLE_R); bottom_right_ = rb.GetBitmapNamed(IDR_BUBBLE_BR); bottom_ = rb.GetBitmapNamed(IDR_BUBBLE_B); bottom_left_ = rb.GetBitmapNamed(IDR_BUBBLE_BL); left_arrow_ = rb.GetBitmapNamed(IDR_BUBBLE_L_ARROW); top_arrow_ = rb.GetBitmapNamed(IDR_BUBBLE_T_ARROW); right_arrow_ = rb.GetBitmapNamed(IDR_BUBBLE_R_ARROW); bottom_arrow_ = rb.GetBitmapNamed(IDR_BUBBLE_B_ARROW); // Calculate horizontal and vertical insets for arrow by ensuring that // the widest arrow and corner images will have enough room to avoid overlap int offset_x = (std::max(top_arrow_->width(), bottom_arrow_->width()) / 2) + std::max(std::max(top_left_->width(), top_right_->width()), std::max(bottom_left_->width(), bottom_right_->width())); int offset_y = (std::max(left_arrow_->height(), right_arrow_->height()) / 2) + std::max(std::max(top_left_->height(), top_right_->height()), std::max(bottom_left_->height(), bottom_right_->height())); arrow_offset_ = std::max(offset_x, offset_y); initialized = true; } } void BubbleBorder::Paint(const view::View& view, gfx::Canvas* canvas) const { // Convenience shorthand variables. const int tl_width = top_left_->width(); const int tl_height = top_left_->height(); const int t_height = top_->height(); const int tr_width = top_right_->width(); const int tr_height = top_right_->height(); const int l_width = left_->width(); const int r_width = right_->width(); const int br_width = bottom_right_->width(); const int br_height = bottom_right_->height(); const int b_height = bottom_->height(); const int bl_width = bottom_left_->width(); const int bl_height = bottom_left_->height(); gfx::Insets insets; GetInsets(&insets); const int top = insets.top() - t_height; const int bottom = view.height() - insets.bottom() + b_height; const int left = insets.left() - l_width; const int right = view.width() - insets.right() + r_width; const int height = bottom - top; const int width = right - left; // |arrow_offset| is offset of arrow from the begining of the edge. int arrow_offset = arrow_offset_; if(override_arrow_offset_) { arrow_offset = override_arrow_offset_; } else if(is_arrow_on_horizontal(arrow_location_) && !is_arrow_on_left(arrow_location_)) { arrow_offset = view.width() - arrow_offset - 1; } else if(!is_arrow_on_horizontal(arrow_location_) && !is_arrow_on_top(arrow_location_)) { arrow_offset = view.height() - arrow_offset - 1; } // Left edge. if(arrow_location_==LEFT_TOP || arrow_location_==LEFT_BOTTOM) { int start_y = top + tl_height; int before_arrow = arrow_offset - start_y - left_arrow_->height() / 2; int after_arrow = height - tl_height - bl_height - left_arrow_->height() - before_arrow; DrawArrowInterior(canvas, false, left_arrow_->width() - kArrowInteriorHeight, start_y + before_arrow + left_arrow_->height() / 2, kArrowInteriorHeight, left_arrow_->height() / 2 - 1); DrawEdgeWithArrow(canvas, false, left_, left_arrow_, left, start_y, before_arrow, after_arrow, left_->width() - left_arrow_->width()); } else { canvas->TileImageInt(*left_, left, top + tl_height, l_width, height - tl_height - bl_height); } // Top left corner. canvas->DrawBitmapInt(*top_left_, left, top); // Top edge. if(arrow_location_==TOP_LEFT || arrow_location_==TOP_RIGHT) { int start_x = left + tl_width; int before_arrow = arrow_offset - start_x - top_arrow_->width() / 2; int after_arrow = width - tl_width - tr_width - top_arrow_->width() - before_arrow; DrawArrowInterior(canvas, true, start_x + before_arrow + top_arrow_->width() / 2, top_arrow_->height() - kArrowInteriorHeight, 1 - top_arrow_->width() / 2, kArrowInteriorHeight); DrawEdgeWithArrow(canvas, true, top_, top_arrow_, start_x, top, before_arrow, after_arrow, top_->height() - top_arrow_->height()); } else { canvas->TileImageInt(*top_, left + tl_width, top, width - tl_width - tr_width, t_height); } // Top right corner. canvas->DrawBitmapInt(*top_right_, right - tr_width, top); // Right edge. if(arrow_location_==RIGHT_TOP || arrow_location_==RIGHT_BOTTOM) { int start_y = top + tr_height; int before_arrow = arrow_offset - start_y - right_arrow_->height() / 2; int after_arrow = height - tl_height - bl_height - right_arrow_->height() - before_arrow; DrawArrowInterior(canvas, false, right - r_width + kArrowInteriorHeight, start_y + before_arrow + right_arrow_->height() / 2, -kArrowInteriorHeight, right_arrow_->height() / 2 - 1); DrawEdgeWithArrow(canvas, false, right_, right_arrow_, right - r_width, start_y, before_arrow, after_arrow, 0); } else { canvas->TileImageInt(*right_, right - r_width, top + tr_height, r_width, height - tr_height - br_height); } // Bottom right corner. canvas->DrawBitmapInt(*bottom_right_, right - br_width, bottom - br_height); // Bottom edge. if(arrow_location_==BOTTOM_LEFT || arrow_location_==BOTTOM_RIGHT) { int start_x = left + bl_width; int before_arrow = arrow_offset - start_x - bottom_arrow_->width() / 2; int after_arrow = width - bl_width - br_width - bottom_arrow_->width() - before_arrow; DrawArrowInterior(canvas, true, start_x + before_arrow + bottom_arrow_->width() / 2, bottom - b_height + kArrowInteriorHeight, 1 - bottom_arrow_->width() / 2, -kArrowInteriorHeight); DrawEdgeWithArrow(canvas, true, bottom_, bottom_arrow_, start_x, bottom - b_height, before_arrow, after_arrow, 0); } else { canvas->TileImageInt(*bottom_, left + bl_width, bottom - b_height, width - bl_width - br_width, b_height); } // Bottom left corner. canvas->DrawBitmapInt(*bottom_left_, left, bottom - bl_height); } void BubbleBorder::DrawEdgeWithArrow(gfx::Canvas* canvas, bool is_horizontal, SkBitmap* edge, SkBitmap* arrow, int start_x, int start_y, int before_arrow, int after_arrow, int offset) const { /* Here's what the parameters mean: * start_x * . * . โ”Œโ”€โ”€โ”€โ” โ”ฌ offset * start_y..........โ”Œโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ–ฒ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ” * โ”‚ / โ”‚--------โ”‚โˆ™ โˆ™โ”‚--------โ”‚ \ โ”‚ * โ”‚ / โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค \ โ”‚ * โ”œโ”€โ”€โ”€โ”ฌโ”˜ โ””โ”ฌโ”€โ”€โ”€โ”ค * โ””โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜ * before_arrow โ”€โ”˜ โ””โ”€ after_arrow */ if(before_arrow) { canvas->TileImageInt(*edge, start_x, start_y, is_horizontal ? before_arrow : edge->width(), is_horizontal ? edge->height() : before_arrow); } canvas->DrawBitmapInt(*arrow, start_x + (is_horizontal ? before_arrow : offset), start_y + (is_horizontal ? offset : before_arrow)); if(after_arrow) { start_x += (is_horizontal ? before_arrow + arrow->width() : 0); start_y += (is_horizontal ? 0 : before_arrow + arrow->height()); canvas->TileImageInt(*edge, start_x, start_y, is_horizontal ? after_arrow : edge->width(), is_horizontal ? edge->height() : after_arrow); } } void BubbleBorder::DrawArrowInterior(gfx::Canvas* canvas, bool is_horizontal, int tip_x, int tip_y, int shift_x, int shift_y) const { /* This function fills the interior of the arrow with background color. * It draws isosceles triangle under semitransparent arrow tip. * * Here's what the parameters mean: * * โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ |tip_x| * โ”Œโ”€โ”€โ”€โ”€โ”€โ” * โ”‚ โ–ฒ โ”‚ โ”€โ”€โ”€โ”€ |tip y| * โ”‚โˆ™โˆ™โˆ™โˆ™โˆ™โ”‚ โ” * โ””โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€ |shift_x| (offset from tip to vertexes of isosceles triangle) * โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ |shift_y| */ SkPaint paint; paint.setStyle(SkPaint::kFill_Style); paint.setColor(background_color_); gfx::Path path; path.incReserve(4); path.moveTo(SkIntToScalar(tip_x), SkIntToScalar(tip_y)); path.lineTo(SkIntToScalar(tip_x + shift_x), SkIntToScalar(tip_y + shift_y)); if(is_horizontal) { path.lineTo(SkIntToScalar(tip_x - shift_x), SkIntToScalar(tip_y + shift_y)); } else { path.lineTo(SkIntToScalar(tip_x + shift_x), SkIntToScalar(tip_y - shift_y)); } path.close(); canvas->AsCanvasSkia()->drawPath(path, paint); } void BubbleBackground::Paint(gfx::Canvas* canvas, view::View* view) const { // The border of this view creates an anti-aliased round-rect region for the // contents, which we need to fill with the background color. // NOTE: This doesn't handle an arrow location of "NONE", which has square top // corners. SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setColor(border_->background_color()); gfx::Path path; gfx::Rect bounds(view->GetContentsBounds()); SkRect rect; rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()), SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom())); SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius()); path.addRoundRect(rect, radius, radius); canvas->AsCanvasSkia()->drawPath(path, paint); }
15,563
5,056
// // Created by krab1k on 24.1.19. // #include <vector> #include <fmt/format.h> #include <gemmi/pdb.hpp> #include "chargefw2.h" #include "../config.h" #include "pdb.h" #include "common.h" #include "bonds.h" #include "../periodic_table.h" MoleculeSet PDB::read_file(const std::string &filename) { gemmi::Structure structure; try { structure = gemmi::read_pdb_file(filename); } catch (std::exception &) { fmt::print(stderr, "Cannot load structure from file: {}\n", filename); exit(EXIT_FILE_ERROR); } auto molecules = std::make_unique<std::vector<Molecule>>(); auto atoms = std::make_unique<std::vector<Atom>>(); /* Read first model only */ auto model = structure.models[0]; size_t idx = 0; for (const auto &chain: model.chains) { for (const auto &residue: chain.residues) { bool hetatm = residue.het_flag == 'H'; for (const auto &atom: residue.atoms) { double x = atom.pos.x; double y = atom.pos.y; double z = atom.pos.z; int residue_id = residue.seqid.num.value; const Element *element; try { element = PeriodicTable::pte().get_element_by_symbol(get_element_symbol(atom.element.name())); } catch (std::exception &e) { fmt::print(stderr, "Error when reading {}: {}\n", structure.name, e.what()); /* Return empty set */ return MoleculeSet(std::move(molecules)); } if (not atom.has_altloc() or atom.altloc == 'A') { if ((not hetatm) or (config::read_hetatm and residue.name != "HOH") or (config::read_hetatm and not config::ignore_water)) { atoms->emplace_back(idx, element, x, y, z, atom.name, residue_id, residue.name, chain.name, hetatm); atoms->back()._set_formal_charge(atom.charge); idx++; } } } } } if (atoms->empty()) { fmt::print(stderr, "Error when reading {}: No atoms were loaded\n", structure.name); } else { auto bonds = get_bonds(atoms); std::string name = structure.name; auto it = structure.info.find("_entry.id"); if (it != structure.info.end()) { name = it->second; } molecules->emplace_back(sanitize_name(name), std::move(atoms), std::move(bonds)); } return MoleculeSet(std::move(molecules)); } PDB::PDB() = default;
2,654
846
/* Copyright 2015 NumScale SAS Copyright 2015 LRI UMR 8623 CNRS/University Paris Sud XI Copyright 2015 Glen Joseph Fernandes (glenjofe@gmail.com) Distributed under the Boost Software License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_ALIGN_DETAIL_ASSUME_ALIGNED_GCC_HPP #define BOOST_ALIGN_DETAIL_ASSUME_ALIGNED_GCC_HPP #define BOOST_ALIGN_ASSUME_ALIGNED(p, n) \ (p) = static_cast<__typeof__(p)>(__builtin_assume_aligned((p), (n))) #endif
470
216
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "lstm_gemm_kernel_base.h" #include "kernel_selector_utils.h" #include "common_tools.h" namespace kernel_selector { JitConstants LSTMGemmKernelBase::GetJitConstants(const lstm_gemm_params& params) const { JitConstants jit = MakeBaseParamsJitConstants(params); const auto& weights = params.weights; const auto& recurrent = params.recurrent; const auto& hidden = params.hidden; const auto& bias = params.bias; if (params.hasBias) { jit.AddConstants({MakeJitConstant("BIAS", bias), MakeJitConstant("BIAS_TERM", true)}); } if (params.hasHidden) { jit.AddConstants({MakeJitConstant("HIDDEN", hidden), MakeJitConstant("HIDDEN_TERM", true), MakeJitConstant("RECURRENT", recurrent), MakeJitConstant("HIDDEN_DIRECTION", params.hidden_direction)}); } jit.AddConstants({MakeJitConstant("WEIGHTS", weights)}); jit.AddConstants({MakeJitConstant("DIRECTION", params.direction)}); jit.AddConstants({MakeJitConstant("INPUT_DIRECTION", params.input_direction)}); return jit; } KernelsData LSTMGemmKernelBase::GetCommonKernelsData(const Params& params, const optional_params& options) const { if (!Validate(params, options)) { return {}; } const lstm_gemm_params& orgParams = static_cast<const lstm_gemm_params&>(params); KernelData kd = KernelData::Default<lstm_gemm_params>(params, orgParams.inputs.size()); const auto& input = orgParams.inputs[0]; auto newParams = orgParams; newParams.inputs.resize(1); newParams.inputs[0] = input; auto out = newParams.outputs[0]; // TODO: reorder weights if needed auto& kernel = kd.kernels[0]; auto cldnnJit = GetJitConstants(newParams); auto entryPoint = GetEntryPoint(kernelName, newParams.layerID, params, options); auto jit = CreateJit(kernelName, cldnnJit, entryPoint); kernel.params.workGroups.global = {out.X().v, out.Batch().v, 1}; kernel.code.kernelString = GetKernelString(kernelName, jit, entryPoint, params.engineInfo); kernel.params.arguments.push_back({ArgumentDescriptor::Types::INPUT, 0}); kernel.params.arguments.push_back({ArgumentDescriptor::Types::OUTPUT, 0}); kernel.params.arguments.push_back({ArgumentDescriptor::Types::WEIGHTS, 0}); if (orgParams.hasHidden) { kernel.params.arguments.push_back({ArgumentDescriptor::Types::HIDDEN, 0}); kernel.params.arguments.push_back({ArgumentDescriptor::Types::RECURRENT, 0}); } if (orgParams.hasBias) { kernel.params.arguments.push_back({ArgumentDescriptor::Types::BIAS, 0}); } return {kd}; } } // namespace kernel_selector
2,787
921
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 <fstream> #include "itkRawImageIO.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" // Specific ImageIO test template <typename TPixel> class RawImageReaderAndWriter { public: using PixelType = unsigned char; using RawImageIOType = itk::RawImageIO< PixelType, 2 >; using ImageType = itk::Image< PixelType, 2 >; public: RawImageReaderAndWriter() { m_Image = ImageType::New(); typename ImageType::RegionType region; typename ImageType::SizeType size; typename ImageType::IndexType start; start.Fill(0); size[0] = 16; // To fill the range of 8 bits image size[1] = 16; region.SetSize( size ); region.SetIndex( start ); m_Image->SetRegions( region ); m_Image->Allocate(); PixelType value = itk::NumericTraits< PixelType >::ZeroValue(); // Fill the image with incremental values. using IteratorType = itk::ImageRegionIterator< ImageType >; IteratorType it( m_Image, region ); it.GoToBegin(); while( !it.IsAtEnd() ) { it.Set( value ); ++value; ++it; } m_Error = false; } void Write() { using WriterType = itk::ImageFileWriter< ImageType >; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( m_FileName.c_str() ); writer->SetInput( m_Image ); RawImageIOType::Pointer rawImageIO = RawImageIOType::New(); writer->SetImageIO( rawImageIO ); writer->Update(); } void Read() { using ReaderType = itk::ImageFileReader< ImageType >; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( m_FileName.c_str() ); RawImageIOType::Pointer rawImageIO = RawImageIOType::New(); reader->SetImageIO( rawImageIO ); unsigned int dim[2] = {16,16}; double spacing[2] = {1.0, 1.0}; double origin[2] = {0.0,0.0}; for(unsigned int i=0; i<2; i++) { rawImageIO->SetDimensions(i,dim[i]); rawImageIO->SetSpacing(i,spacing[i]); rawImageIO->SetOrigin(i,origin[i]); } rawImageIO->SetHeaderSize(0); rawImageIO->SetByteOrderToLittleEndian(); rawImageIO->SetNumberOfComponents(1); reader->Update(); ImageType::ConstPointer image = reader->GetOutput(); // // Verify the content of the image. // using ConstIteratorType = itk::ImageRegionConstIterator< ImageType >; ConstIteratorType it1( m_Image, m_Image->GetLargestPossibleRegion() ); ConstIteratorType it2( image, image->GetLargestPossibleRegion() ); it1.GoToBegin(); it2.GoToBegin(); m_Error = false; while( it1.IsAtEnd() ) { if( it1.Get() != it2.Get() ) { m_Error = true; break; } ++it1; ++it2; } } void SetFileName( const std::string & filename ) { m_FileName = filename; } bool GetError() const { return m_Error; } private: std::string m_FileName; typename ImageType::Pointer m_Image; bool m_Error; }; int itkRawImageIOTest5(int argc, char*argv[]) { if(argc < 2) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " TemporaryDirectoryName" << std::endl; return EXIT_FAILURE; } std::string directory = argv[1]; // // Test the pixel type = "char" // std::cout << "Testing for pixel type = char " << std::endl; RawImageReaderAndWriter< char > tester1; std::string filename = directory + "/RawImageIOTest5a.raw"; tester1.SetFileName( filename ); try { tester1.Write(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception caught while writing char type." << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } try { tester1.Read(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception caught while reading char type." << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } if( tester1.GetError() ) { std::cerr << "Error while comparing the char type images." << std::endl; return EXIT_FAILURE; } // // Test the pixel type = "signed char" // std::cout << "Testing for pixel type = signed char " << std::endl; RawImageReaderAndWriter< signed char > tester2; filename = directory + "/RawImageIOTest5b.raw"; tester2.SetFileName( filename ); try { tester2.Write(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception caught while writing signed char type." << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } try { tester2.Read(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception caught while reading signed char type." << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } if( tester2.GetError() ) { std::cerr << "Error while comparing the signed char type images." << std::endl; return EXIT_FAILURE; } // // Test the pixel type = "unsigned char" // std::cout << "Testing for pixel type = unsigned char " << std::endl; RawImageReaderAndWriter< unsigned char > tester3; filename = directory + "/RawImageIOTest5c.raw"; tester3.SetFileName( filename ); try { tester3.Write(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception caught while writing unsigned char type." << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } try { tester3.Read(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception caught while reading unsigned char type." << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } if( tester3.GetError() ) { std::cerr << "Error while comparing the unsigned char type images." << std::endl; return EXIT_FAILURE; } std::cout << "Test PASSED !!" << std::endl << std::endl; return EXIT_SUCCESS; }
6,760
2,316
class Solution { public: bool isUnique(string astr) { if ( astr.empty() ) { return true; } // 1. ไฝฟ็”จset ่ฎฐๅฝ•ๅญ—็ฌฆๆ˜ฏๅฆๅ‡บ็Žฐ่ฟ‡ set<char> s; for ( auto it = astr.begin(); it != astr.end(); it++ ){ if ( s.count(*it) > 0 ){ return false; } else { s.insert(*it); } } return true; } };
418
134
#include "mbed.h" #define MYDEBUG #define COMPLETE 1 #define INCOMPLETE 0 #define END_OF_PACKET '\n' #define SIZE_OF_SEND_PACKET 16 #define CHECK_CHUTTER_US 500000 #define ALERT_CYCLE_SEC 1 #define ARERT_MAX_CNT 60 #define CHECK_CONNECT_SEC 2 #define BUZZER_ON 1 #define BUZZER_OFF 0 #define SW_LED_ON 1 #define SW_LED_OFF 0 #define ALERT_START 1 #define ALERT_STOP 0 // alert "bit" definition #define ALERT_1 1 #define ALERT_2 2 #define ALERT_3 4 #define ALERT_NON 0 // connect "bit" definition #define CONNECT_1 1 #define CONNECT_2 2 #define CONNECT_3 4 #define CONNECT_NON 0 #define ON_SIGNAL_1 1 #define ON_SIGNAL_2 2 #define ON_SIGNAL_3 4 #define ON_SIGNAL_NON 0 DigitalOut myled(LED1); #ifdef MYDEBUG Serial pc(USBTX, USBRX); #endif Serial uart(PTE0, PTE1); // tx, rx DigitalOut buz(PTA13); InterruptIn sw1(PTD1); DigitalOut sw_led1(PTB0); InterruptIn sw2(PTD5); DigitalOut sw_led2(PTD0); InterruptIn sw3(PTD3); DigitalOut sw_led3(PTD2); void offBuzzer(); void onBuzzer(); void toggleBuzzer(); void stopAlert1(); void stopAlert2(); void stopAlert3(); void startAlert1(); void startAlert2(); void startAlert3(); void offCheckSignal1(); void offCheckSignal2(); void offCheckSignal3(); uint8_t receiveSize=0; uint8_t sendSize=0; uint8_t receiveComplete = INCOMPLETE; uint8_t sendComplete = INCOMPLETE; uint8_t rBuffIndex=0; uint8_t sBuffIndex=0; char receiveBuff[50]; char sendBuff[50]; Ticker chatTimer; Ticker AlertTimer; Ticker CheckConnectTimer; uint8_t intCnt; uint8_t intCnt2; uint8_t intCnt3; uint8_t buzzer_state=BUZZER_OFF; uint8_t alert=ALERT_STOP; uint8_t alert_number=ALERT_NON; uint8_t alert_cnt=0; uint8_t check_connect=CONNECT_NON; uint8_t on_signal=ON_SIGNAL_NON; void checkConnectCallback() // if go into this func, check connect is failed { if((check_connect & CONNECT_1) != 0) { check_connect &= ~(CONNECT_1); startAlert1(); } if((check_connect & CONNECT_2) != 0) { check_connect &= ~(CONNECT_2); startAlert2(); } if((check_connect & CONNECT_3) != 0) { check_connect &= ~(CONNECT_3); startAlert3(); } } void periodicCallback1() { chatTimer.detach(); intCnt = 0; } void push1() { if(intCnt == 0) { if((on_signal & ON_SIGNAL_1) != 0) { on_signal &= ~(ON_SIGNAL_1); offCheckSignal1(); } else if(alert_number == ALERT_NON) { check_connect &= ~(CONNECT_1); uart.putc('t'); //check connection message to device 0001 uart.putc('x'); uart.putc('d'); uart.putc('t'); uart.putc(' '); uart.putc('0'); uart.putc('0'); uart.putc('1'); uart.putc('0'); uart.putc('0'); uart.putc('2'); uart.putc('0'); uart.putc('1'); uart.putc('0'); uart.putc('1'); uart.putc('\r'); uart.putc('\n'); CheckConnectTimer.attach(checkConnectCallback, CHECK_CONNECT_SEC); } else { stopAlert1(); } chatTimer.attach_us(periodicCallback1, CHECK_CHUTTER_US); //start detecting chattering } intCnt++; } void periodicCallback2() { chatTimer.detach(); intCnt2 = 0; } void push2() { if(intCnt2 == 0) { if((on_signal & ON_SIGNAL_2) != 0) { on_signal &= ~(ON_SIGNAL_2); offCheckSignal2(); } else if(alert_number == ALERT_NON) { check_connect &= ~(CONNECT_2); uart.putc('t'); //check connection message to device 0002 uart.putc('x'); uart.putc('d'); uart.putc('t'); uart.putc(' '); uart.putc('0'); uart.putc('0'); uart.putc('1'); uart.putc('0'); uart.putc('0'); uart.putc('2'); uart.putc('0'); uart.putc('1'); uart.putc('0'); uart.putc('2'); uart.putc('\r'); uart.putc('\n'); CheckConnectTimer.attach(checkConnectCallback, CHECK_CONNECT_SEC); } else { stopAlert2(); } chatTimer.attach_us(periodicCallback2, CHECK_CHUTTER_US); //start detecting chattering } intCnt2++; } void periodicCallback3() { chatTimer.detach(); intCnt3 = 0; } void push3() { if(intCnt3 == 0) { if((on_signal & ON_SIGNAL_3) != 0) { on_signal &= ~(ON_SIGNAL_3); offCheckSignal3(); } else if(alert_number == ALERT_NON) { check_connect &= ~(CONNECT_3); uart.putc('t'); //check connection message to device 0003 uart.putc('x'); uart.putc('d'); uart.putc('t'); uart.putc(' '); uart.putc('0'); uart.putc('0'); uart.putc('1'); uart.putc('0'); uart.putc('0'); uart.putc('2'); uart.putc('0'); uart.putc('1'); uart.putc('0'); uart.putc('3'); uart.putc('\r'); uart.putc('\n'); CheckConnectTimer.attach(checkConnectCallback, CHECK_CONNECT_SEC); } else { stopAlert3(); } chatTimer.attach_us(periodicCallback3, CHECK_CHUTTER_US); //start detecting chattering } intCnt3++; } void uartCB(void) { char ch; while(uart.readable()) { ch = uart.getc(); if(receiveComplete == INCOMPLETE) { receiveBuff[receiveSize] = ch; receiveSize++; if(ch == END_OF_PACKET) { receiveComplete = COMPLETE; } } } } #ifdef MYDEBUG void pcCB(void) { char ch; while(pc.readable()) { ch = pc.getc(); pc.putc('['); // ้€ไฟก pc.putc(ch); // ้€ไฟก sendBuff[sendSize] = ch; sendSize++; if(ch == END_OF_PACKET) { sendComplete = COMPLETE; } } } #endif void offBuzzer() { buzzer_state = BUZZER_OFF; buz = BUZZER_OFF; } void onBuzzer() { buzzer_state = BUZZER_ON; buz = BUZZER_ON; } void toggleBuzzer() { if(buzzer_state == BUZZER_OFF) { onBuzzer(); } else { offBuzzer(); } } void alertCallback() { if(alert_cnt >= ARERT_MAX_CNT) { offBuzzer(); } else { toggleBuzzer(); alert_cnt++; } if((alert_number & ALERT_1) != 0) { sw_led1 = !sw_led1; } if((alert_number & ALERT_2) != 0) { sw_led2 = !sw_led2; } if((alert_number & ALERT_3) != 0) { sw_led3 = !sw_led3; } } void onCheckSignal1() { on_signal|=ON_SIGNAL_1; onBuzzer(); sw_led1 = SW_LED_ON; } void onCheckSignal2() { on_signal|=ON_SIGNAL_2; onBuzzer(); sw_led2 = SW_LED_ON; } void onCheckSignal3() { on_signal|=ON_SIGNAL_3; onBuzzer(); sw_led3 = SW_LED_ON; } void offCheckSignal1() { on_signal &= ~(ON_SIGNAL_1); offBuzzer(); sw_led1 = SW_LED_OFF; } void offCheckSignal2() { on_signal &= ~(ON_SIGNAL_2); offBuzzer(); sw_led1 = SW_LED_OFF; } void offCheckSignal3() { on_signal &= ~(ON_SIGNAL_3); offBuzzer(); sw_led1 = SW_LED_OFF; } void startAlert1() { alert_cnt=0; offBuzzer(); alert_number |= ALERT_1; sw_led1 = SW_LED_OFF; sw_led2 = SW_LED_OFF; sw_led3 = SW_LED_OFF; if(alert_number == ALERT_1) { AlertTimer.attach(alertCallback, ALERT_CYCLE_SEC); } } void stopAlert1() { sw_led1 = SW_LED_OFF; alert_number &= ~(ALERT_1); if(alert_number == ALERT_NON) { offBuzzer(); AlertTimer.detach(); } } void startAlert2() { alert_cnt=0; offBuzzer(); alert_number |= ALERT_2; sw_led1 = SW_LED_OFF; sw_led2 = SW_LED_OFF; sw_led3 = SW_LED_OFF; if(alert_number == ALERT_2) { AlertTimer.attach(alertCallback, ALERT_CYCLE_SEC); } } void stopAlert2() { sw_led2 = SW_LED_OFF; alert_number &= ~(ALERT_2); if(alert_number == ALERT_NON) { offBuzzer(); AlertTimer.detach(); } } void startAlert3() { alert_cnt=0; offBuzzer(); alert_number |= ALERT_3; sw_led1 = SW_LED_OFF; sw_led2 = SW_LED_OFF; sw_led3 = SW_LED_OFF; if(alert_number == ALERT_3) { AlertTimer.attach(alertCallback, ALERT_CYCLE_SEC); } } void stopAlert3() { sw_led3 = SW_LED_OFF; alert_number &= ~(ALERT_3); if(alert_number == ALERT_NON) { offBuzzer(); AlertTimer.detach(); } } int main() { receiveSize=0; sendSize=0; receiveComplete = INCOMPLETE; sendComplete = INCOMPLETE; rBuffIndex=0; sBuffIndex=0; myled = 1; sw_led1 = SW_LED_OFF; sw_led2 = SW_LED_OFF; offBuzzer(); alert_number=ALERT_NON; alert_cnt=0; check_connect=CONNECT_NON; on_signal=ON_SIGNAL_NON; intCnt = 0; intCnt2 = 0; intCnt3 = 0; sw1.mode(PullUp); sw1.fall(&push1); sw2.mode(PullUp); sw2.fall(&push2); uart.baud (19200); #ifdef MYDEBUG pc.baud (9600); #endif uart.attach(uartCB , Serial::RxIrq); #ifdef MYDEBUG pc.attach(pcCB , Serial::RxIrq); #endif while (true) { sleep(); //wait for interrupt if(alert == ALERT_START) { alert = ALERT_STOP; toggleBuzzer(); if((alert_number & ALERT_1) != 0) { sw_led1 = !sw_led1; } if((alert_number & ALERT_2) != 0) { sw_led2 = !sw_led2; } } if(receiveComplete == COMPLETE) { #ifdef MYDEBUG pc.putc('R'); pc.putc('V'); pc.putc(':'); for(rBuffIndex=0; rBuffIndex<receiveSize; ++rBuffIndex) { pc.putc(receiveBuff[rBuffIndex]); // ้€ไฟก } #endif if(receiveSize > 7) { if( (receiveBuff[3] == '5') && (receiveBuff[4] == '1') && (receiveBuff[5] == '7') && (receiveBuff[6] == '4') ) { startAlert1(); } else if( (receiveBuff[11] == '0') && // data:0001010010 :normal alert (receiveBuff[12] == '0') && (receiveBuff[14] == '0') && (receiveBuff[15] == '1') && (receiveBuff[17] == '0') && (receiveBuff[18] == '1') && (receiveBuff[20] == '0') && (receiveBuff[21] == '0') && (receiveBuff[23] == '1') && (receiveBuff[24] == '0') ) { startAlert1(); } else if( (receiveBuff[11] == '0') && // data:0101010010 :check connection success (receiveBuff[12] == '1') && (receiveBuff[14] == '0') && (receiveBuff[15] == '1') && (receiveBuff[17] == '0') && (receiveBuff[18] == '2') && (receiveBuff[20] == '0') && (receiveBuff[21] == '0') && (receiveBuff[23] == '1') && (receiveBuff[24] == '0') ) { check_connect &= ~(CONNECT_1); CheckConnectTimer.detach(); onCheckSignal1(); } else if( (receiveBuff[11] == '0') && // data:0102010010 :check connection success (receiveBuff[12] == '1') && (receiveBuff[14] == '0') && (receiveBuff[15] == '2') && (receiveBuff[17] == '0') && (receiveBuff[18] == '2') && (receiveBuff[20] == '0') && (receiveBuff[21] == '0') && (receiveBuff[23] == '1') && (receiveBuff[24] == '0') ) { check_connect &= ~(CONNECT_2); CheckConnectTimer.detach(); onCheckSignal2(); } else if( (receiveBuff[11] == '0') && // data:0103010010 :check connection success (receiveBuff[12] == '1') && (receiveBuff[14] == '0') && (receiveBuff[15] == '3') && (receiveBuff[17] == '0') && (receiveBuff[18] == '2') && (receiveBuff[20] == '0') && (receiveBuff[21] == '0') && (receiveBuff[23] == '1') && (receiveBuff[24] == '0') ) { check_connect &= ~(CONNECT_3); CheckConnectTimer.detach(); onCheckSignal3(); } else if( (receiveBuff[11] == '0') && // data:0010030101 (receiveBuff[12] == '0') && (receiveBuff[14] == '1') && (receiveBuff[15] == '0') && (receiveBuff[17] == '0') && (receiveBuff[18] == '3') && (receiveBuff[20] == '0') && (receiveBuff[21] == '1') && (receiveBuff[23] == '0') && (receiveBuff[24] == '1') ) { check_connect|=CONNECT_1; } else if( (receiveBuff[11] == '0') && // data:0010030102 (receiveBuff[12] == '0') && (receiveBuff[14] == '1') && (receiveBuff[15] == '0') && (receiveBuff[17] == '0') && (receiveBuff[18] == '3') && (receiveBuff[20] == '0') && (receiveBuff[21] == '1') && (receiveBuff[23] == '0') && (receiveBuff[24] == '2') ) { check_connect|=CONNECT_2; } else if( (receiveBuff[11] == '0') && // data:0010030103 (receiveBuff[12] == '0') && (receiveBuff[14] == '1') && (receiveBuff[15] == '0') && (receiveBuff[17] == '0') && (receiveBuff[18] == '3') && (receiveBuff[20] == '0') && (receiveBuff[21] == '1') && (receiveBuff[23] == '0') && (receiveBuff[24] == '3') ) { check_connect|=CONNECT_3; } } receiveComplete = INCOMPLETE; receiveSize = 0; } #ifdef MYDEBUG if(sendComplete == COMPLETE) { pc.putc('s'); pc.putc('d'); pc.putc(':'); for(sBuffIndex=0; sBuffIndex<sendSize; ++sBuffIndex) { pc.putc(sendBuff[sBuffIndex]); // ้€ไฟก } for(sBuffIndex=0; sBuffIndex<sendSize; ++sBuffIndex) { uart.putc(sendBuff[sBuffIndex]); // ้€ไฟก } sendComplete = INCOMPLETE; sendSize = 0; } #endif } }
15,820
5,851
/* * Copyright (c) 2021 Light Source Software, LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ #include <lse/TextSceneNode.h> #include <lse/Scene.h> #include <lse/yoga-ext.h> #include <lse/Style.h> #include <lse/CompositeContext.h> #include <lse/Log.h> #include <lse/Timer.h> #include <lse/Renderer.h> #include <lse/PixelConversion.h> namespace lse { TextSceneNode::TextSceneNode(Scene* scene) : SceneNode(scene) { YGNodeSetMeasureFunc(this->ygNode, SceneNode::YogaMeasureCallback); YGNodeSetNodeType(this->ygNode, YGNodeTypeText); } void TextSceneNode::OnStylePropertyChanged(StyleProperty property) { switch (property) { case StyleProperty::fontFamily: case StyleProperty::fontSize: case StyleProperty::fontStyle: case StyleProperty::fontWeight: case StyleProperty::lineHeight: case StyleProperty::maxLines: case StyleProperty::textOverflow: case StyleProperty::textTransform: this->MarkComputeStyleDirty(); break; case StyleProperty::textAlign: case StyleProperty::borderColor: // TODO: borderColor? case StyleProperty::color: case StyleProperty::filter: this->MarkCompositeDirty(); break; default: SceneNode::OnStylePropertyChanged(property); break; } } void TextSceneNode::OnFlexBoxLayoutChanged() { this->MarkCompositeDirty(); } void TextSceneNode::OnComputeStyle() { if (this->SetFont(this->style)) { this->block.Invalidate(); YGNodeMarkDirty(this->ygNode); } } YGSize TextSceneNode::OnMeasure(float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode) { if (widthMode == YGMeasureModeUndefined) { width = this->scene->GetWidth(); } if (heightMode == YGMeasureModeUndefined) { height = this->scene->GetHeight(); } this->block.Shape(this->text, this->fontFace, this->style, this->GetStyleContext(), width, height); return { this->block.WidthF(), this->block.HeightF() }; } void TextSceneNode::OnComposite(CompositeContext* ctx) { this->DrawBackground(ctx, StyleBackgroundClipBorderBox); this->DrawText(ctx); this->DrawBorder(ctx); } const std::string& TextSceneNode::GetText() const { return this->text; } void TextSceneNode::SetText(std::string&& text) { if (this->text != text) { this->text = std::move(text); this->block.Invalidate(); YGNodeMarkDirty(this->ygNode); } } bool TextSceneNode::SetFont(Style* style) { auto dirty{ false }; if (!style) { if (this->fontFace) { dirty = true; } this->ClearFontFaceResource(); return dirty; } auto findFontResult = this->scene->GetFontManager()->FindFont( style->GetString(StyleProperty::fontFamily), style->GetEnum<StyleFontStyle>(StyleProperty::fontStyle), style->GetEnum<StyleFontWeight>(StyleProperty::fontWeight)); if (this->fontFace == findFontResult) { return false; } // TODO: ResetFont() ? this->ClearFontFaceResource(); this->fontFace = findFontResult; if (!this->fontFace) { return true; } switch (this->fontFace->GetFontStatus()) { case FontStatusReady: dirty = true; break; case FontStatusLoading: this->fontFace->AddListener(this, [](Font* font, void* listener, FontStatus status) { auto self{static_cast<TextSceneNode*>(listener)}; if (status == FontStatusReady) { self->block.Invalidate(); YGNodeMarkDirty(self->ygNode); font->RemoveListener(listener); } else { self->ClearFontFaceResource(); } }); break; default: // TODO: clear? this->ClearFontFaceResource(); dirty = true; break; } return dirty; } void TextSceneNode::DrawText(CompositeContext* ctx) { auto box{YGNodeGetPaddingBox(this->ygNode)}; auto textStyle{Style::Or(this->style)}; if (this->block.IsEmpty()) { // if style width and height are set, measure is not used. if this is the situation, shape the text before paint. this->block.Shape(this->text, this->fontFace, textStyle, this->GetStyleContext(), box.width, box.height); } this->block.Paint(ctx->renderer); if (!this->block.IsReady()) { return; } Rect pos{ box.x + ctx->CurrentMatrix().GetTranslateX(), box.y + ctx->CurrentMatrix().GetTranslateY(), this->block.WidthF(), this->block.HeightF() }; switch (textStyle->GetEnum(StyleProperty::textAlign)) { case StyleTextAlignCenter: pos.x += ((box.width - pos.width) / 2.f); break; case StyleTextAlignRight: pos.x += (box.width - pos.width); break; default: break; } // TODO: clip auto textColor{ textStyle->GetColor(StyleProperty::color).value_or(ColorBlack) }; ctx->renderer->DrawImage( pos, this->block.GetTextureSourceRect(), this->block.GetTexture(), this->GetStyleContext()->ComputeFilter(textStyle, textColor, ctx->CurrentOpacity())); } void TextSceneNode::ClearFontFaceResource() { if (this->fontFace) { this->fontFace->RemoveListener(this); this->fontFace = nullptr; } } void TextSceneNode::OnDestroy() { this->ClearFontFaceResource(); this->block.Destroy(); } // TODO: temporary hack due to scene and renderer shutdown conflicts void TextSceneNode::OnDetach() { this->ClearFontFaceResource(); this->block.Destroy(); } } // namespace lse
5,877
1,880