hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
61fead47df29906cf3576128c4e49d0d3adf3215
840
cpp
C++
CEOI/2017/palindrome.cpp
nalinbhardwaj/olympiad
6b640d8cef2fa16fb4e9776f8416575519357edf
[ "MIT" ]
1
2018-12-14T07:51:26.000Z
2018-12-14T07:51:26.000Z
CEOI/2017/palindrome.cpp
nalinbhardwaj/olympiad
6b640d8cef2fa16fb4e9776f8416575519357edf
[ "MIT" ]
null
null
null
CEOI/2017/palindrome.cpp
nalinbhardwaj/olympiad
6b640d8cef2fa16fb4e9776f8416575519357edf
[ "MIT" ]
1
2019-06-23T10:34:19.000Z
2019-06-23T10:34:19.000Z
//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)); } }
14.482759
50
0.54881
nalinbhardwaj
11006e9f92d20522e33039acbfc19819486c5c76
3,433
cpp
C++
examples/3d/easyCamExample/src/ofApp.cpp
creatologist/openFrameworks0084
aa74f188f105b62fbcecb7baf2b41d56d97cf7bc
[ "MIT" ]
3
2017-12-27T23:02:50.000Z
2018-10-14T00:50:49.000Z
examples/3d/easyCamExample/src/ofApp.cpp
creatologist/openFrameworks0084
aa74f188f105b62fbcecb7baf2b41d56d97cf7bc
[ "MIT" ]
null
null
null
examples/3d/easyCamExample/src/ofApp.cpp
creatologist/openFrameworks0084
aa74f188f105b62fbcecb7baf2b41d56d97cf7bc
[ "MIT" ]
1
2020-02-28T20:39:20.000Z
2020-02-28T20:39:20.000Z
#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){ }
24.697842
179
0.499272
creatologist
11021a8038ae3cc9d22b5c7026aebcae6a20e663
21,155
hpp
C++
include/jet/Utilities.hpp
XanaduAI/jet
c74fd61c7caf821153b05ab9f9a783e779040161
[ "Apache-2.0" ]
29
2021-07-22T20:32:55.000Z
2022-03-28T20:36:03.000Z
include/jet/Utilities.hpp
XanaduAI/jet
c74fd61c7caf821153b05ab9f9a783e779040161
[ "Apache-2.0" ]
25
2021-07-22T21:05:20.000Z
2021-11-24T17:34:31.000Z
include/jet/Utilities.hpp
XanaduAI/jet
c74fd61c7caf821153b05ab9f9a783e779040161
[ "Apache-2.0" ]
7
2021-07-23T11:47:12.000Z
2022-03-23T07:12:39.000Z
#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
30.007092
80
0.623068
XanaduAI
1102642a3aa47a79509c1d3c1dc28d7df27dd909
76
hh
C++
MCDataProducts/inc/GenParticleCollection.hh
michaelmackenzie/Offline
57bcd11d499af77ed0619deeddace51ed2b0b097
[ "Apache-2.0" ]
null
null
null
MCDataProducts/inc/GenParticleCollection.hh
michaelmackenzie/Offline
57bcd11d499af77ed0619deeddace51ed2b0b097
[ "Apache-2.0" ]
26
2019-11-08T09:56:55.000Z
2020-09-09T17:25:33.000Z
MCDataProducts/inc/GenParticleCollection.hh
ryuwd/Offline
92957f111425910274df61dbcbd2bad76885f993
[ "Apache-2.0" ]
null
null
null
// redirection: FIXME! #include "Offline/MCDataProducts/inc/GenParticle.hh"
25.333333
52
0.789474
michaelmackenzie
11055fd55298017876da7d5cb3b5b4b77dcb6f37
229
cpp
C++
Codeforces Rating < 1300/A_Word_Capitalization.cpp
Ritu7683/Codeforces-A20J-Ladder
eb9d54c20e2ab4f5eba06379258cf932a9b2d003
[ "MIT" ]
1
2021-09-15T08:48:10.000Z
2021-09-15T08:48:10.000Z
Codeforces Rating < 1300/A_Word_Capitalization.cpp
Ritu7683/Codeforces-A20J-Ladder
eb9d54c20e2ab4f5eba06379258cf932a9b2d003
[ "MIT" ]
null
null
null
Codeforces Rating < 1300/A_Word_Capitalization.cpp
Ritu7683/Codeforces-A20J-Ladder
eb9d54c20e2ab4f5eba06379258cf932a9b2d003
[ "MIT" ]
null
null
null
#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; }
12.722222
29
0.497817
Ritu7683
110600e685f25e393ecd6089d3f42a871ad26bc2
7,659
cpp
C++
xlslib/src/xlslib/note.cpp
ferkulat/xlslib
c3c2e04e80e39a8262fd334a0e13b28ff1745c63
[ "BSD-2-Clause" ]
9
2015-05-29T10:22:26.000Z
2018-03-18T12:36:49.000Z
xlslib/src/xlslib/note.cpp
loulansuiye/xlslib
c3c2e04e80e39a8262fd334a0e13b28ff1745c63
[ "BSD-2-Clause" ]
null
null
null
xlslib/src/xlslib/note.cpp
loulansuiye/xlslib
c3c2e04e80e39a8262fd334a0e13b28ff1745c63
[ "BSD-2-Clause" ]
1
2021-07-03T00:46:01.000Z
2021-07-03T00:46:01.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 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); }
35.623256
147
0.658572
ferkulat
11071bf61c8f056dd6fb1cf526fb261697f7038c
2,242
cc
C++
Geometry/MTDNumberingBuilder/plugins/CmsMTDBuilder.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
Geometry/MTDNumberingBuilder/plugins/CmsMTDBuilder.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
Geometry/MTDNumberingBuilder/plugins/CmsMTDBuilder.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#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(); } } }
33.969697
132
0.720339
bisnupriyasahu
1107c31cce77f11fbb647436998ceacf4e25fb8f
54,434
cpp
C++
src/edcommon/model.cpp
GarethNelson/ares
fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e
[ "MIT" ]
null
null
null
src/edcommon/model.cpp
GarethNelson/ares
fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e
[ "MIT" ]
null
null
null
src/edcommon/model.cpp
GarethNelson/ares
fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e
[ "MIT" ]
null
null
null
/* 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
28.044307
119
0.665062
GarethNelson
11086346168afae2284634a663b83f4e9fc29531
7,930
cpp
C++
WDL/plush2/pl_read_3ds.cpp
hor-net/wdl-ol
4a88575f82c0c577b28fc3b27279456b12b187fe
[ "Zlib" ]
2
2017-12-05T04:18:55.000Z
2021-03-20T03:04:56.000Z
WDL/plush2/pl_read_3ds.cpp
Metabog/wdl-ol
bfe87d2c4297d003f2475dc22d460440e5e1b4fa
[ "Zlib" ]
null
null
null
WDL/plush2/pl_read_3ds.cpp
Metabog/wdl-ol
bfe87d2c4297d003f2475dc22d460440e5e1b4fa
[ "Zlib" ]
2
2017-04-24T12:45:33.000Z
2019-12-22T04:31:51.000Z
/****************************************************************************** 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; } } }
22.787356
80
0.583102
hor-net
1109568803479872ecba62b53e9492f3aae3671b
38,338
cpp
C++
src/common/information_schema.cpp
tisuama/BaikalDB
22e414eaac9dd6150f61976df6c735d6e51ea3f3
[ "Apache-2.0" ]
null
null
null
src/common/information_schema.cpp
tisuama/BaikalDB
22e414eaac9dd6150f61976df6c735d6e51ea3f3
[ "Apache-2.0" ]
null
null
null
src/common/information_schema.cpp
tisuama/BaikalDB
22e414eaac9dd6150f61976df6c735d6e51ea3f3
[ "Apache-2.0" ]
null
null
null
// 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
48.714104
141
0.547759
tisuama
110e0562d099679db9aaebb93c080a3f1cedebc5
10,152
cc
C++
src/Mapping.cc
MIRTK/VolumetricMapping
0c7e58204f8c278d887510b46d7ad0b96735f04f
[ "Apache-2.0" ]
1
2017-06-09T14:39:15.000Z
2017-06-09T14:39:15.000Z
src/Mapping.cc
MIRTK/VolumetricMapping
0c7e58204f8c278d887510b46d7ad0b96735f04f
[ "Apache-2.0" ]
1
2017-03-23T13:56:33.000Z
2017-03-23T17:19:22.000Z
src/Mapping.cc
MIRTK/Mapping
0c7e58204f8c278d887510b46d7ad0b96735f04f
[ "Apache-2.0" ]
2
2017-06-09T14:39:16.000Z
2019-09-25T09:08:03.000Z
/* * 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
28.923077
94
0.495764
MIRTK
1110c4184c0878954bb71f63e6e347e440e36cea
20,088
hpp
C++
libs/storage/include/nil/filecoin/storage/proofs/post/election/vanilla.hpp
NilFoundation/crypto3-fil-proofs
1fd78ad608278a1ed62fb29b0a077347b74a55f1
[ "MIT" ]
null
null
null
libs/storage/include/nil/filecoin/storage/proofs/post/election/vanilla.hpp
NilFoundation/crypto3-fil-proofs
1fd78ad608278a1ed62fb29b0a077347b74a55f1
[ "MIT" ]
4
2021-09-06T13:07:46.000Z
2021-11-16T12:38:09.000Z
libs/storage/include/nil/filecoin/storage/proofs/post/election/vanilla.hpp
NilFoundation/crypto3-fil-proofs
1fd78ad608278a1ed62fb29b0a077347b74a55f1
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------// // 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
53.425532
120
0.505625
NilFoundation
1112decafa844b641a6e71e23d12f88e42cf043d
4,027
cpp
C++
src/LoadedModel.cpp
sidmishraw/martian-cos
364ca3d875efab896a821faad43accdab74bd5d4
[ "BSD-3-Clause" ]
1
2018-05-20T21:27:12.000Z
2018-05-20T21:27:12.000Z
src/LoadedModel.cpp
sidmishraw/martian-cos
364ca3d875efab896a821faad43accdab74bd5d4
[ "BSD-3-Clause" ]
2
2018-05-24T01:03:36.000Z
2021-02-28T08:15:44.000Z
src/LoadedModel.cpp
sidmishraw/martian-cos
364ca3d875efab896a821faad43accdab74bd5d4
[ "BSD-3-Clause" ]
null
null
null
// // 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(); }
20.441624
94
0.735783
sidmishraw
1113a145ae73e5dd4080dc2629b8dde0ef79aa20
4,482
cc
C++
runtime/tests/test_buffer.cc
naoyam/physis
39ee5250a2d5baa545ca03e7c5c9aa9c81f1ab19
[ "BSD-3-Clause" ]
30
2015-01-27T02:45:34.000Z
2022-02-17T03:50:49.000Z
runtime/tests/test_buffer.cc
naoyam/physis
39ee5250a2d5baa545ca03e7c5c9aa9c81f1ab19
[ "BSD-3-Clause" ]
8
2015-01-02T02:10:04.000Z
2015-04-21T08:42:12.000Z
runtime/tests/test_buffer.cc
naoyam/physis
39ee5250a2d5baa545ca03e7c5c9aa9c81f1ab19
[ "BSD-3-Clause" ]
4
2015-12-16T10:18:31.000Z
2021-12-28T22:43:56.000Z
// 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(); }
23.465969
68
0.500669
naoyam
1113aebdf33f8740412e440635e3da92af2ee58e
281
cpp
C++
allMatuCommit/回文_2020040901027_20210920120011.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/回文_2020040901027_20210920120011.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/回文_2020040901027_20210920120011.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
#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; }
12.772727
24
0.405694
BachWV
11144c8848f85cbd6d24ce08a8c6ff9ed28ecb5e
673
cpp
C++
Deitel/Chapter02/exercises/2.24/ex_224.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter02/exercises/2.24/ex_224.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter02/exercises/2.24/ex_224.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
/* * ===================================================================================== * * 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; }
22.433333
88
0.356612
SebastianTirado
11146beceed78a107969a3394a9839683fe5efd9
5,303
cpp
C++
test/sources/tools/match/test-optimize_mask.cpp
Kartonagnick/tools-match
ec27ca94a031e04f072f8366bde2d567c29134c8
[ "MIT" ]
null
null
null
test/sources/tools/match/test-optimize_mask.cpp
Kartonagnick/tools-match
ec27ca94a031e04f072f8366bde2d567c29134c8
[ "MIT" ]
7
2021-02-05T20:45:04.000Z
2021-03-09T15:12:14.000Z
test/sources/tools/match/test-optimize_mask.cpp
Kartonagnick/tools-match
ec27ca94a031e04f072f8366bde2d567c29134c8
[ "MIT" ]
null
null
null
// [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
29.960452
80
0.443334
Kartonagnick
1115266ea6f1ad6946315dcfd49244e9cfe17af4
1,109
hpp
C++
controller.hpp
Greentwip/PuyoPuyo
cb76c4b5861e29765050675cde0185d15aa055e6
[ "MIT" ]
null
null
null
controller.hpp
Greentwip/PuyoPuyo
cb76c4b5861e29765050675cde0185d15aa055e6
[ "MIT" ]
null
null
null
controller.hpp
Greentwip/PuyoPuyo
cb76c4b5861e29765050675cde0185d15aa055e6
[ "MIT" ]
null
null
null
#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); } };
20.924528
59
0.693417
Greentwip
11160972c1639127f27bf491266449eb98ff1944
5,937
cxx
C++
Rendering/OpenGL2/vtkHiddenLineRemovalPass.cxx
keithroe/vtkoptix
c5bbfa0105552af3022811a7c81efec640fb810f
[ "BSD-3-Clause" ]
null
null
null
Rendering/OpenGL2/vtkHiddenLineRemovalPass.cxx
keithroe/vtkoptix
c5bbfa0105552af3022811a7c81efec640fb810f
[ "BSD-3-Clause" ]
null
null
null
Rendering/OpenGL2/vtkHiddenLineRemovalPass.cxx
keithroe/vtkoptix
c5bbfa0105552af3022811a7c81efec640fb810f
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= 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; }
32.442623
80
0.595419
keithroe
1117705173cdc73bec8975a071c6e4844bdb4793
2,773
cpp
C++
Labo09-Ordenamiento/main.cpp
LecJackS/Taller-Algoritmos-1-2019
cb0c1599abfce73bee090cf58b5dc4ca8d47cb0b
[ "MIT" ]
null
null
null
Labo09-Ordenamiento/main.cpp
LecJackS/Taller-Algoritmos-1-2019
cb0c1599abfce73bee090cf58b5dc4ca8d47cb0b
[ "MIT" ]
null
null
null
Labo09-Ordenamiento/main.cpp
LecJackS/Taller-Algoritmos-1-2019
cb0c1599abfce73bee090cf58b5dc4ca8d47cb0b
[ "MIT" ]
null
null
null
#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; }
31.873563
109
0.465921
LecJackS
111793c676ad7140d1e988a74ed4cf5ffcc48d82
734
cpp
C++
libs/proto/example/hello.cpp
zyiacas/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
11
2015-07-12T13:04:52.000Z
2021-05-30T23:23:46.000Z
libs/proto/example/hello.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
null
null
null
libs/proto/example/hello.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
3
2015-12-23T01:51:57.000Z
2019-08-25T04:58:32.000Z
//[ 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; } //]
26.214286
69
0.589918
zyiacas
1118270fde5eb9566d518af7e17fe45c6fa0ab32
752
cc
C++
test/extensions/wasm/test_data/asm2wasm_cpp.cc
brian-avery/envoy-1
61101255b67b70b89fe4b3dd229cecd047bd5620
[ "Apache-2.0" ]
null
null
null
test/extensions/wasm/test_data/asm2wasm_cpp.cc
brian-avery/envoy-1
61101255b67b70b89fe4b3dd229cecd047bd5620
[ "Apache-2.0" ]
null
null
null
test/extensions/wasm/test_data/asm2wasm_cpp.cc
brian-avery/envoy-1
61101255b67b70b89fe4b3dd229cecd047bd5620
[ "Apache-2.0" ]
1
2022-03-08T09:23:49.000Z
2022-03-08T09:23:49.000Z
// 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))); }
35.809524
98
0.668883
brian-avery
111b589bf119bbe67c7855522445a6c0bde32047
3,611
hpp
C++
src/dag/dag_block_manager.hpp
agrebin/taraxa-node
a594b01f52e727c8fc5dc87c9c325510c2a6f1cb
[ "MIT" ]
null
null
null
src/dag/dag_block_manager.hpp
agrebin/taraxa-node
a594b01f52e727c8fc5dc87c9c325510c2a6f1cb
[ "MIT" ]
7
2021-06-08T12:40:38.000Z
2021-06-16T12:11:15.000Z
src/dag/dag_block_manager.hpp
agrebin/taraxa-node
a594b01f52e727c8fc5dc87c9c325510c2a6f1cb
[ "MIT" ]
null
null
null
#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
41.505747
118
0.7635
agrebin
111cdeaa469629cd408bfcf3d07afb61a4311821
178
cpp
C++
Runic/Src/Runic/Scene/SceneManager.cpp
Swarmley/Runic-Engine
80a471728ae10e77e5370414ec45341a75df2469
[ "Apache-2.0" ]
null
null
null
Runic/Src/Runic/Scene/SceneManager.cpp
Swarmley/Runic-Engine
80a471728ae10e77e5370414ec45341a75df2469
[ "Apache-2.0" ]
null
null
null
Runic/Src/Runic/Scene/SceneManager.cpp
Swarmley/Runic-Engine
80a471728ae10e77e5370414ec45341a75df2469
[ "Apache-2.0" ]
null
null
null
#include "runicpch.h" #include "SceneManager.h" namespace Runic { Scope<SceneManager::SceneManagerData> SceneManager::s_Data = CreateScope<SceneManager::SceneManagerData>(); }
29.666667
108
0.786517
Swarmley
1120fe5c48d0ec4925a967b3fae35d5a8517ae09
8,496
cpp
C++
modules/simulator/src/VehicleDynamics/VehicleAckermann.cpp
SRai22/mvsim
0890889353c89ac0f1ad9bd6f700068ca22262f3
[ "BSD-3-Clause" ]
11
2020-07-18T03:16:25.000Z
2022-03-29T12:59:34.000Z
modules/simulator/src/VehicleDynamics/VehicleAckermann.cpp
SRai22/mvsim
0890889353c89ac0f1ad9bd6f700068ca22262f3
[ "BSD-3-Clause" ]
1
2022-01-21T07:56:43.000Z
2022-01-21T08:07:30.000Z
modules/simulator/src/VehicleDynamics/VehicleAckermann.cpp
SRai22/mvsim
0890889353c89ac0f1ad9bd6f700068ca22262f3
[ "BSD-3-Clause" ]
6
2020-06-17T02:34:28.000Z
2022-03-13T01:37:01.000Z
/*+-------------------------------------------------------------------------+ | 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; }
32.551724
108
0.660546
SRai22
11247378ff3ce23ff009136e2cb6c955e16446e2
1,126
hpp
C++
src/pbrrenderer2.hpp
jpbruyere/vke
cf965d29b9092ea6b56847028dc885b67b1603e0
[ "MIT" ]
1
2018-10-17T17:28:10.000Z
2018-10-17T17:28:10.000Z
src/pbrrenderer2.hpp
jpbruyere/vke
cf965d29b9092ea6b56847028dc885b67b1603e0
[ "MIT" ]
null
null
null
src/pbrrenderer2.hpp
jpbruyere/vke
cf965d29b9092ea6b56847028dc885b67b1603e0
[ "MIT" ]
1
2021-08-11T14:13:02.000Z
2021-08-11T14:13:02.000Z
#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); };
22.078431
86
0.676732
jpbruyere
1127332e487537822e4bbc0b99b5a872a57e23b8
3,723
cpp
C++
source/gameplay/PlayerProjectiles.cpp
Xett/gba-modern
8b74fcf78d49c156dc4ffa6c4adba8fd812004dd
[ "MIT" ]
null
null
null
source/gameplay/PlayerProjectiles.cpp
Xett/gba-modern
8b74fcf78d49c156dc4ffa6c4adba8fd812004dd
[ "MIT" ]
null
null
null
source/gameplay/PlayerProjectiles.cpp
Xett/gba-modern
8b74fcf78d49c156dc4ffa6c4adba8fd812004dd
[ "MIT" ]
1
2020-11-20T03:12:02.000Z
2020-11-20T03:12:02.000Z
//-------------------------------------------------------------------------------- // 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 }
37.606061
131
0.637658
Xett
1128adeb375e43db32f68460c232c4134508ccd6
2,817
hpp
C++
irohad/ordering/impl/on_demand_os_client_grpc.hpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
irohad/ordering/impl/on_demand_os_client_grpc.hpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
irohad/ordering/impl/on_demand_os_client_grpc.hpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
/** * 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
35.2125
80
0.676251
coderintherye
1128eef1ec4be5ec1817a87007c180758ea49b28
3,127
cpp
C++
lib/core/src/rodsError.cpp
aghsmith/irods
31d48a47a4942df688da94b30aa8a5b5210261bb
[ "BSD-3-Clause" ]
1
2022-03-08T13:00:56.000Z
2022-03-08T13:00:56.000Z
lib/core/src/rodsError.cpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
lib/core/src/rodsError.cpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
#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
22.496403
87
0.57819
aghsmith
112aff1d4d6f7bbdbb57fe6e5e141556be472d73
3,173
hpp
C++
include/armadillo_bits/op_sum_meat.hpp
ArashMassoudieh/GIFMod_
1fa9eda21fab870fc3baf56462f79eb800d5154f
[ "MIT" ]
8
2017-01-12T14:18:50.000Z
2021-02-18T14:44:33.000Z
include/armadillo_bits/op_sum_meat.hpp
ArashMassoudieh/GIFMod_
1fa9eda21fab870fc3baf56462f79eb800d5154f
[ "MIT" ]
1
2017-07-04T05:40:30.000Z
2017-07-04T05:43:37.000Z
include/armadillo_bits/op_sum_meat.hpp
ArashMassoudieh/GIFMod_
1fa9eda21fab870fc3baf56462f79eb800d5154f
[ "MIT" ]
6
2016-08-21T00:29:08.000Z
2022-01-09T08:41:33.000Z
// 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); } } } //! @}
19.114458
99
0.589663
ArashMassoudieh
112c2dc9f8f72e002a965ea65ec48db3c184fd8e
5,533
cpp
C++
clb/src/v20180317/model/LbRsTargets.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
clb/src/v20180317/model/LbRsTargets.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
clb/src/v20180317/model/LbRsTargets.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * 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; }
25.497696
139
0.663654
suluner
112c5818dcf4e4bda21a4cf79549cdbf05b2913a
1,439
cpp
C++
HackerRank/Problem Solving/Algorithms/GraphTheory/BreadthFirstSearch.cpp
AdityaChirravuri/CompetitiveProgramming
642550e8916b3f7939a1fdd52d10f5f8ae43f161
[ "MIT" ]
1
2021-07-13T01:49:25.000Z
2021-07-13T01:49:25.000Z
HackerRank/Problem Solving/Algorithms/GraphTheory/BreadthFirstSearch.cpp
AdityaChirravuri/CompetitiveProgramming
642550e8916b3f7939a1fdd52d10f5f8ae43f161
[ "MIT" ]
null
null
null
HackerRank/Problem Solving/Algorithms/GraphTheory/BreadthFirstSearch.cpp
AdityaChirravuri/CompetitiveProgramming
642550e8916b3f7939a1fdd52d10f5f8ae43f161
[ "MIT" ]
null
null
null
#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; }
17.765432
57
0.413482
AdityaChirravuri
112ed45777794d1ae5d574904f83d384da51ed65
2,990
hpp
C++
AirLib/include/vehicles/plane/UFRudder.hpp
artemopolus/AirSim-1
4a741e79c0197acf3cb6f3397bc55ea1d267f8c8
[ "MIT" ]
null
null
null
AirLib/include/vehicles/plane/UFRudder.hpp
artemopolus/AirSim-1
4a741e79c0197acf3cb6f3397bc55ea1d267f8c8
[ "MIT" ]
null
null
null
AirLib/include/vehicles/plane/UFRudder.hpp
artemopolus/AirSim-1
4a741e79c0197acf3cb6f3397bc55ea1d267f8c8
[ "MIT" ]
null
null
null
#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
33.595506
122
0.71204
artemopolus
113035645ab7998f7dc2089bb49985b608411cf1
463
cpp
C++
Codeforces/158A - Next Round.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/158A - Next Round.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/158A - Next Round.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#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; }
17.148148
54
0.464363
naimulcsx
1131b490ca517a46f9455044c237f9e0e64b8671
19,743
cpp
C++
dev/Code/Sandbox/Plugins/UiCanvasEditor/PropertiesContainer.cpp
Kezryk/lumberyard
d21172c26536133a4213873469a171f4f0c4280c
[ "AML" ]
1
2017-10-21T11:19:32.000Z
2017-10-21T11:19:32.000Z
dev/Code/Sandbox/Plugins/UiCanvasEditor/PropertiesContainer.cpp
Kezryk/lumberyard
d21172c26536133a4213873469a171f4f0c4280c
[ "AML" ]
null
null
null
dev/Code/Sandbox/Plugins/UiCanvasEditor/PropertiesContainer.cpp
Kezryk/lumberyard
d21172c26536133a4213873469a171f4f0c4280c
[ "AML" ]
null
null
null
/* * 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>
38.187621
169
0.634554
Kezryk
113289d7e964644ba652a33cf172d0d158897a3e
17,710
cpp
C++
Spades Game/Game/UI/LobbyFilterManager.cpp
jmasterx/StemwaterSpades
05e5d7c6d380d2f5986bd91269887f16c3e71962
[ "Unlicense" ]
6
2017-01-04T22:40:50.000Z
2019-11-24T15:37:46.000Z
Spades Game/Game/UI/LobbyFilterManager.cpp
jmasterx/StemwaterSpades
05e5d7c6d380d2f5986bd91269887f16c3e71962
[ "Unlicense" ]
1
2016-09-18T19:10:01.000Z
2017-08-04T23:53:38.000Z
Spades Game/Game/UI/LobbyFilterManager.cpp
jmasterx/StemwaterSpades
05e5d7c6d380d2f5986bd91269887f16c3e71962
[ "Unlicense" ]
2
2015-11-21T16:42:18.000Z
2019-04-21T20:41:39.000Z
#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; } } }
30.8
102
0.746132
jmasterx
1134279f867fa714499bf0c32591872d4f988d79
18,052
cc
C++
src/media/audio/drivers/aml-g12-tdm/audio-stream.cc
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
[ "BSD-2-Clause" ]
null
null
null
src/media/audio/drivers/aml-g12-tdm/audio-stream.cc
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
[ "BSD-2-Clause" ]
null
null
null
src/media/audio/drivers/aml-g12-tdm/audio-stream.cc
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
[ "BSD-2-Clause" ]
null
null
null
// 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");
33.742056
99
0.679315
EnderNightLord-ChromeBook
11375d1474b937d09f081169435e7038a8ecf073
11,688
cpp
C++
moon/core/network/socket.cpp
PM5616/moon
04fe49c498caa53acb1b6a9ded76839a6c465289
[ "MIT" ]
null
null
null
moon/core/network/socket.cpp
PM5616/moon
04fe49c498caa53acb1b6a9ded76839a6c465289
[ "MIT" ]
null
null
null
moon/core/network/socket.cpp
PM5616/moon
04fe49c498caa53acb1b6a9ded76839a6c465289
[ "MIT" ]
1
2019-09-09T21:25:15.000Z
2019-09-09T21:25:15.000Z
#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(); }); }
28.231884
187
0.548939
PM5616
113a22f0880d64de816b0cf42ffa0668639a02b9
1,710
hpp
C++
src/share/connected_devices/details/descriptions.hpp
egelwan/Karabiner-Elements
896439dd2130904275553282063dd7fe4852e1a8
[ "Unlicense" ]
5,422
2019-10-27T17:51:04.000Z
2022-03-31T15:45:41.000Z
src/share/connected_devices/details/descriptions.hpp
XXXalice/Karabiner-Elements
52f579cbf60251cf18915bd938eb4431360b763b
[ "Unlicense" ]
1,310
2019-10-28T04:57:24.000Z
2022-03-31T04:55:37.000Z
src/share/connected_devices/details/descriptions.hpp
XXXalice/Karabiner-Elements
52f579cbf60251cf18915bd938eb4431360b763b
[ "Unlicense" ]
282
2019-10-28T02:36:04.000Z
2022-03-19T06:18:54.000Z
#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
27.580645
124
0.634503
egelwan
113f4fd6d216825e4a30be9575443514be07c4cb
887
hpp
C++
include/RED4ext/Types/generated/anim/AnimNode_BlendSpace_InternalsBlendSpacePoint.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/anim/AnimNode_BlendSpace_InternalsBlendSpacePoint.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/anim/AnimNode_BlendSpace_InternalsBlendSpacePoint.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#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
27.71875
91
0.735062
Cyberpunk-Extended-Development-Team
114024e1b0915dfddf9bca872536bb96b808992a
1,719
cpp
C++
UVA/vol-100/10006.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
3
2017-05-12T14:45:37.000Z
2020-01-18T16:51:25.000Z
UVA/vol-100/10006.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
null
null
null
UVA/vol-100/10006.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
null
null
null
#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); } */
22.324675
99
0.528214
arash16
114271b5c47275bf0579b389fa1c3a5a0c384cfc
460
cpp
C++
BOJ_CPP/12789.cpp
tnsgh9603/BOJ_CPP
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
[ "MIT" ]
null
null
null
BOJ_CPP/12789.cpp
tnsgh9603/BOJ_CPP
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
[ "MIT" ]
null
null
null
BOJ_CPP/12789.cpp
tnsgh9603/BOJ_CPP
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
[ "MIT" ]
null
null
null
#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; }
20.909091
63
0.428261
tnsgh9603
1143e3c9a20da3c8c480e28247b909e41e87d942
618
cpp
C++
src/BucketSort.cpp
MarutTomasz/PAMSI_Projekt_2
e8a154babd328fb18f48304021af90d6d7a79480
[ "MIT" ]
null
null
null
src/BucketSort.cpp
MarutTomasz/PAMSI_Projekt_2
e8a154babd328fb18f48304021af90d6d7a79480
[ "MIT" ]
null
null
null
src/BucketSort.cpp
MarutTomasz/PAMSI_Projekt_2
e8a154babd328fb18f48304021af90d6d7a79480
[ "MIT" ]
null
null
null
#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 }
44.142857
95
0.68932
MarutTomasz
1143e5133ef4efc20855683f857ea2bfb104721d
17,704
cpp
C++
Source/ResourceAnimator.cpp
JellyBitStudios/JellyBitEngine
4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4
[ "MIT" ]
10
2019-02-05T07:57:21.000Z
2021-10-17T13:44:31.000Z
Source/ResourceAnimator.cpp
JellyBitStudios/JellyBitEngine
4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4
[ "MIT" ]
178
2019-02-26T17:29:08.000Z
2019-06-05T10:55:42.000Z
Source/ResourceAnimator.cpp
JellyBitStudios/JellyBitEngine
4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4
[ "MIT" ]
2
2020-02-27T18:57:27.000Z
2020-05-28T01:19:59.000Z
#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(); } }
23.859838
179
0.702666
JellyBitStudios
1146228624a8b8b9ab69bc02861e03c67580ec60
200
hpp
C++
Control_movement/chassis/Projects/RmBoardA/Src/IspImp.hpp
PhilosopheAM/21_Fall_project_gabbishSorting
15ef612d9e483ad72f9e37953875a7303f94b38e
[ "MIT" ]
1
2021-12-31T09:27:00.000Z
2021-12-31T09:27:00.000Z
Control_movement/chassis/Projects/RmBoardA/Src/IspImp.hpp
PhilosopheAM/21_Fall_project_gabbishSorting
15ef612d9e483ad72f9e37953875a7303f94b38e
[ "MIT" ]
null
null
null
Control_movement/chassis/Projects/RmBoardA/Src/IspImp.hpp
PhilosopheAM/21_Fall_project_gabbishSorting
15ef612d9e483ad72f9e37953875a7303f94b38e
[ "MIT" ]
1
2021-12-22T03:34:04.000Z
2021-12-22T03:34:04.000Z
#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
18.181818
42
0.78
PhilosopheAM
114680078d851d23f4ce09c036e0378d9c0da4e0
830
cpp
C++
VRDemoHelper/VRDemoHotKeyManager.cpp
sunzhuoshi/SteamVRDemoHelper
536280f1e5df5e4bdb85fca3460353e0f19cf43d
[ "MIT" ]
null
null
null
VRDemoHelper/VRDemoHotKeyManager.cpp
sunzhuoshi/SteamVRDemoHelper
536280f1e5df5e4bdb85fca3460353e0f19cf43d
[ "MIT" ]
null
null
null
VRDemoHelper/VRDemoHotKeyManager.cpp
sunzhuoshi/SteamVRDemoHelper
536280f1e5df5e4bdb85fca3460353e0f19cf43d
[ "MIT" ]
null
null
null
#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); }
24.411765
113
0.701205
sunzhuoshi
114847aae9ce44d97ea043bd5ae07da63ae2c1b7
2,961
cpp
C++
2/main.cpp
j00st/cpse2
f541d9097d1db064974d71f816cf49ecae30c6f8
[ "MIT" ]
null
null
null
2/main.cpp
j00st/cpse2
f541d9097d1db064974d71f816cf49ecae30c6f8
[ "MIT" ]
null
null
null
2/main.cpp
j00st/cpse2
f541d9097d1db064974d71f816cf49ecae30c6f8
[ "MIT" ]
null
null
null
#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; }
26.918182
120
0.61128
j00st
114a1391f6b8559b98560049e7c9e2fac7147cf0
5,737
hpp
C++
src/Players/MCTS/MCTS.hpp
ClubieDong/BoardGameAI
588506278f606fa6bef2864875bf8f78557ef03b
[ "MIT" ]
2
2021-05-26T07:17:24.000Z
2021-05-26T07:21:16.000Z
src/Players/MCTS/MCTS.hpp
ClubieDong/ChessAI
588506278f606fa6bef2864875bf8f78557ef03b
[ "MIT" ]
null
null
null
src/Players/MCTS/MCTS.hpp
ClubieDong/ChessAI
588506278f606fa6bef2864875bf8f78557ef03b
[ "MIT" ]
null
null
null
#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; } };
34.769697
117
0.495381
ClubieDong
114f7cd1d71a1928b7fdc9ee51b312e476ea714f
10,626
cpp
C++
test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe011/popframe011.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe011/popframe011.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe011/popframe011.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
/* * 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; } }
34.953947
123
0.641163
1690296356
1153397683add019ae00d8dfb3f32ab4f7e125b3
3,038
cpp
C++
src/system/boot/loader/RootFileSystem.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/system/boot/loader/RootFileSystem.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/system/boot/loader/RootFileSystem.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * 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; }
16.601093
74
0.691903
Kirishikesan
11540f3b5fc42fa35160a78cfafa58bc64951b83
480
cpp
C++
Phi Sieve.cpp
ArniRahman/Number-Theory
49ca663e8f425c4def53447fd9ad723b7096340a
[ "MIT" ]
null
null
null
Phi Sieve.cpp
ArniRahman/Number-Theory
49ca663e8f425c4def53447fd9ad723b7096340a
[ "MIT" ]
null
null
null
Phi Sieve.cpp
ArniRahman/Number-Theory
49ca663e8f425c4def53447fd9ad723b7096340a
[ "MIT" ]
null
null
null
#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; } }
12.307692
42
0.35625
ArniRahman
1156546512952871fafe93e4b5a42308322671df
3,346
cc
C++
tensorflow/compiler/tf2xla/kernels/arg_op.cc
DEVESHTARASIA/tensorflow
d3edb8c60ed4fd831d62833ed22f5c23486c561c
[ "Apache-2.0" ]
384
2017-02-21T18:38:04.000Z
2022-02-22T07:30:25.000Z
tensorflow/compiler/tf2xla/kernels/arg_op.cc
ChenAugustus/tensorflow
5828e285209ff8c3d1bef2e4bd7c55ca611080d5
[ "Apache-2.0" ]
15
2017-03-01T20:18:43.000Z
2020-05-07T10:33:51.000Z
tensorflow/compiler/tf2xla/kernels/arg_op.cc
ChenAugustus/tensorflow
5828e285209ff8c3d1bef2e4bd7c55ca611080d5
[ "Apache-2.0" ]
81
2017-02-21T19:31:19.000Z
2022-02-22T07:30:24.000Z
/* 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
35.221053
80
0.658398
DEVESHTARASIA
1157eb9c22c481f11eb5f67797fc66579ee45f6b
3,317
cpp
C++
cpp/open3d/core/linalg/Det.cpp
BlenderGamer/Open3D
8c6a7e74582fe09f3a2295933794bfc16026c21f
[ "MIT" ]
3,673
2019-04-06T05:35:43.000Z
2021-07-27T14:53:14.000Z
cpp/open3d/core/linalg/Det.cpp
BlenderGamer/Open3D
8c6a7e74582fe09f3a2295933794bfc16026c21f
[ "MIT" ]
2,904
2019-04-06T06:51:22.000Z
2021-07-27T13:49:54.000Z
cpp/open3d/core/linalg/Det.cpp
BlenderGamer/Open3D
8c6a7e74582fe09f3a2295933794bfc16026c21f
[ "MIT" ]
1,127
2019-04-06T09:39:17.000Z
2021-07-27T03:06:49.000Z
// ---------------------------------------------------------------------------- // - 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
40.950617
80
0.576726
BlenderGamer
115ba41d74147ea97c0af33b7b24739a62a5e7f1
4,957
cc
C++
SimMuon/MCTruth/src/RPCHitAssociator.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
13
2015-11-30T15:49:45.000Z
2022-02-08T16:11:30.000Z
SimMuon/MCTruth/src/RPCHitAssociator.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
640
2015-02-11T18:55:47.000Z
2022-03-31T14:12:23.000Z
SimMuon/MCTruth/src/RPCHitAssociator.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
51
2015-08-11T21:01:40.000Z
2022-03-30T07:31:34.000Z
#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; }
40.631148
119
0.675005
ckamtsikis
115c6d79cb96d32e949955a41ed115a65db3d833
8,637
cpp
C++
UnrealEngine-4.11.2-release/Engine/Source/Developer/Merge/Private/SMergeTreeView.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2016-10-01T21:35:52.000Z
2016-10-01T21:35:52.000Z
UnrealEngine-4.11.2-release/Engine/Source/Developer/Merge/Private/SMergeTreeView.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
null
null
null
UnrealEngine-4.11.2-release/Engine/Source/Developer/Merge/Private/SMergeTreeView.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2021-04-27T08:48:33.000Z
2021-04-27T08:48:33.000Z
// 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]; }
29.477816
209
0.734051
armroyce
115c80700797302f141aeb6437e57e6d14fd10f6
347
cpp
C++
cwiczenia2/cwi2zaddom1.cpp
baatochan/BasicsOfProgrammingCourse
f0ca00815c359a3e7be3255a3586c5d13d78038e
[ "Unlicense" ]
null
null
null
cwiczenia2/cwi2zaddom1.cpp
baatochan/BasicsOfProgrammingCourse
f0ca00815c359a3e7be3255a3586c5d13d78038e
[ "Unlicense" ]
null
null
null
cwiczenia2/cwi2zaddom1.cpp
baatochan/BasicsOfProgrammingCourse
f0ca00815c359a3e7be3255a3586c5d13d78038e
[ "Unlicense" ]
null
null
null
#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; }
15.772727
47
0.510086
baatochan
115d84c1a5bfedf18d8d57a2759c260166164eb3
4,375
cpp
C++
ui/src/efxpreviewarea.cpp
hawesy/qlcplus
1702f03144fe210611881f15424a535febae0c6a
[ "ECL-2.0", "Apache-2.0" ]
478
2015-01-20T14:51:17.000Z
2022-03-31T06:56:05.000Z
ui/src/efxpreviewarea.cpp
hjtappe/qlcplus
b5537fa11d419d148eca5cb1321ee98d3dc5047b
[ "ECL-2.0", "Apache-2.0" ]
711
2015-01-05T06:50:06.000Z
2022-03-06T20:31:07.000Z
ui/src/efxpreviewarea.cpp
hjtappe/qlcplus
b5537fa11d419d148eca5cb1321ee98d3dc5047b
[ "ECL-2.0", "Apache-2.0" ]
386
2015-01-07T15:36:59.000Z
2022-03-31T06:56:07.000Z
/* 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; }
24.717514
100
0.648229
hawesy
115ddb39f978e32f3184b239375600c8c208546f
2,514
cc
C++
seurat/geometry/quad_mesh_test.cc
Asteur/vrhelper
7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53
[ "Apache-2.0" ]
819
2018-05-04T20:43:55.000Z
2022-03-22T01:21:24.000Z
seurat/geometry/quad_mesh_test.cc
mebalzer/seurat
78c1293debdd2744cba11395024812f277f613f7
[ "Apache-2.0" ]
35
2018-05-05T03:50:16.000Z
2019-11-04T22:56:02.000Z
seurat/geometry/quad_mesh_test.cc
mebalzer/seurat
78c1293debdd2744cba11395024812f277f613f7
[ "Apache-2.0" ]
88
2018-05-04T20:53:42.000Z
2022-03-05T03:50:07.000Z
/* 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
32.649351
78
0.687749
Asteur
11618e2e68b188bf2607133d4de66fdbe614ed12
20,505
cpp
C++
src/xercesc/dom/deprecated/AttrImpl.cpp
allianz-pmichel/xerces-c-src_2_8_0
7e62f6c653944894a34ee41581e6d7d66e3387dd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/xercesc/dom/deprecated/AttrImpl.cpp
allianz-pmichel/xerces-c-src_2_8_0
7e62f6c653944894a34ee41581e6d7d66e3387dd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/xercesc/dom/deprecated/AttrImpl.cpp
allianz-pmichel/xerces-c-src_2_8_0
7e62f6c653944894a34ee41581e6d7d66e3387dd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * 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
29.588745
88
0.59566
allianz-pmichel
1161d81cd3096f71e6c3a73bc54a64a61792f5c1
2,216
cpp
C++
src/PID.cpp
Hamidreza3252/PID-Control-Project
3d0cdca5eee4a4faa95578f812fbd18ce8655eb4
[ "MIT" ]
null
null
null
src/PID.cpp
Hamidreza3252/PID-Control-Project
3d0cdca5eee4a4faa95578f812fbd18ce8655eb4
[ "MIT" ]
null
null
null
src/PID.cpp
Hamidreza3252/PID-Control-Project
3d0cdca5eee4a4faa95578f812fbd18ce8655eb4
[ "MIT" ]
null
null
null
#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_); } // --------------------------------------------------------------------------------------------------------------------
31.657143
122
0.409747
Hamidreza3252
1162339471b72855c29bf140b78f84b7dc63d811
3,997
cpp
C++
src/window.cpp
Samulus/raytracer
2cfce84af0190117f16dc054df1667bc8868b438
[ "MIT" ]
null
null
null
src/window.cpp
Samulus/raytracer
2cfce84af0190117f16dc054df1667bc8868b438
[ "MIT" ]
1
2019-09-02T20:55:06.000Z
2019-09-02T20:55:06.000Z
src/window.cpp
Samulus/raytracer
2cfce84af0190117f16dc054df1667bc8868b438
[ "MIT" ]
null
null
null
// // 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); }
35.061404
97
0.617713
Samulus
1162b0b99d357373a0a203e44e98a5d92306ef6d
2,356
cpp
C++
EU4toV2/Source/EU4World/Leader/EU4Leader.cpp
GregB76/EU4toVic2
0a8822101a36a16036fdc315e706d113d9231101
[ "MIT" ]
1
2020-04-22T03:09:51.000Z
2020-04-22T03:09:51.000Z
EU4toV2/Source/EU4World/Leader/EU4Leader.cpp
fessi1202/EU4toVic2
1f4cce609e495f8b4e00580a12ab4a29b304902f
[ "MIT" ]
null
null
null
EU4toV2/Source/EU4World/Leader/EU4Leader.cpp
fessi1202/EU4toVic2
1f4cce609e495f8b4e00580a12ab4a29b304902f
[ "MIT" ]
null
null
null
#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; }
32.722222
89
0.699491
GregB76
1162e73158b027001d8203ff72fcde43dca72208
2,885
cpp
C++
libcaf_core/src/tracing_data.cpp
dosuperuser/actor-framework
bee96d84bbc95414df5084b2d65f4886ba731558
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/src/tracing_data.cpp
dosuperuser/actor-framework
bee96d84bbc95414df5084b2d65f4886ba731558
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/src/tracing_data.cpp
dosuperuser/actor-framework
bee96d84bbc95414df5084b2d65f4886ba731558
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| 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
32.41573
80
0.49636
dosuperuser
1164162e0914988f2f4e527e41b1fd8f6e4230dd
18,587
cc
C++
third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
/* * 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
35.951644
88
0.719804
chromium
116526500659c13d6366b6db5a045c780a51a3a6
3,896
hpp
C++
samples/sampleslib/window.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
1
2018-03-01T01:05:25.000Z
2018-03-01T01:05:25.000Z
samples/sampleslib/window.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
null
null
null
samples/sampleslib/window.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
null
null
null
#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
29.074627
90
0.62808
YiJiangFengYun
11670232f86b94910304e9683dd1f2d7ebafda9d
229,759
cpp
C++
GBAemu/cpu/arm.cpp
robojan/EmuAll
0a589136df9fefbfa142e605e1d3a0c94f726bad
[ "Apache-2.0" ]
1
2021-03-04T03:52:39.000Z
2021-03-04T03:52:39.000Z
GBAemu/cpu/arm.cpp
robojan/EmuAll
0a589136df9fefbfa142e605e1d3a0c94f726bad
[ "Apache-2.0" ]
null
null
null
GBAemu/cpu/arm.cpp
robojan/EmuAll
0a589136df9fefbfa142e605e1d3a0c94f726bad
[ "Apache-2.0" ]
null
null
null
#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; } } }
32.419783
103
0.640841
robojan
1168a89c89cebf5be103047656ef6479312eb5ab
22,602
cpp
C++
unittests/Interpreter/InterpreterInfra.cpp
b0r3dd3v/souper
26fc1d3f59ee86885c0b073865b8c97130a9778d
[ "Apache-2.0" ]
1,758
2015-01-02T13:40:08.000Z
2022-03-30T17:24:53.000Z
unittests/Interpreter/InterpreterInfra.cpp
b0r3dd3v/souper
26fc1d3f59ee86885c0b073865b8c97130a9778d
[ "Apache-2.0" ]
556
2015-01-02T13:11:38.000Z
2022-03-01T20:55:11.000Z
unittests/Interpreter/InterpreterInfra.cpp
b0r3dd3v/souper
26fc1d3f59ee86885c0b073865b8c97130a9778d
[ "Apache-2.0" ]
144
2015-01-03T07:30:58.000Z
2022-03-08T07:41:08.000Z
// 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; }
30.834925
102
0.541545
b0r3dd3v
1168e453db2ad86a204d3f15c0361243ed0625f7
295
cpp
C++
src/rendering/records/SlideGpuRecord.cpp
halfmvsq/histolozee
c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5
[ "Apache-2.0" ]
null
null
null
src/rendering/records/SlideGpuRecord.cpp
halfmvsq/histolozee
c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5
[ "Apache-2.0" ]
null
null
null
src/rendering/records/SlideGpuRecord.cpp
halfmvsq/histolozee
c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5
[ "Apache-2.0" ]
null
null
null
#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; }
21.071429
68
0.732203
halfmvsq
1169ffcd851d833aae2dbddc3330975476a2a209
341
cpp
C++
src/HemeraGenerators/hemerageneratorsconfigureplugin.cpp
hemeraos/hemera-qt5-sdk
cb8c2a3fa692e5c3234bb9e1f1ae01b9e1d54771
[ "Apache-2.0" ]
null
null
null
src/HemeraGenerators/hemerageneratorsconfigureplugin.cpp
hemeraos/hemera-qt5-sdk
cb8c2a3fa692e5c3234bb9e1f1ae01b9e1d54771
[ "Apache-2.0" ]
null
null
null
src/HemeraGenerators/hemerageneratorsconfigureplugin.cpp
hemeraos/hemera-qt5-sdk
cb8c2a3fa692e5c3234bb9e1f1ae01b9e1d54771
[ "Apache-2.0" ]
1
2021-02-08T15:25:46.000Z
2021-02-08T15:25:46.000Z
/* * */ #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; } } }
12.178571
49
0.703812
hemeraos
116b40834155c6244b5bad09a34b0915491a81bc
145,952
cpp
C++
src/generator/x86_64/reg_alloc_multi.cpp
ERAP-SBT/ERAP-SBT
67cf885634ed9205650ee2353849d623d318e2d6
[ "MIT" ]
2
2022-03-28T07:43:02.000Z
2022-03-30T11:53:25.000Z
src/generator/x86_64/reg_alloc_multi.cpp
ERAP-SBT/ERAP-SBT
67cf885634ed9205650ee2353849d623d318e2d6
[ "MIT" ]
null
null
null
src/generator/x86_64/reg_alloc_multi.cpp
ERAP-SBT/ERAP-SBT
67cf885634ed9205650ee2353849d623d318e2d6
[ "MIT" ]
2
2022-03-30T10:39:04.000Z
2022-03-30T11:53:28.000Z
#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; }
46.128951
195
0.521274
ERAP-SBT
116c13a620794960c5b365297a95697cef1ac28a
5,905
cpp
C++
3dparty/taglib/tests/test_aiff.cpp
olanser/uteg
c8c79a8e8e5d185253b415e67f7b6d9e37114da3
[ "MIT" ]
3,066
2016-06-10T09:23:40.000Z
2022-03-31T11:01:01.000Z
3dparty/taglib/tests/test_aiff.cpp
olanser/uteg
c8c79a8e8e5d185253b415e67f7b6d9e37114da3
[ "MIT" ]
414
2016-09-20T20:26:05.000Z
2022-03-29T00:43:13.000Z
3dparty/taglib/tests/test_aiff.cpp
olanser/uteg
c8c79a8e8e5d185253b415e67f7b6d9e37114da3
[ "MIT" ]
310
2016-06-13T21:53:04.000Z
2022-03-18T14:36:38.000Z
/*************************************************************************** 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);
36.226994
98
0.598476
olanser
116f0d43144b6d728b73d8568444fff9379e5988
15,563
cpp
C++
library/bubble/bubble_border.cpp
topillar/PuTTY-ng
1f5bf26de0f42e03ef4f100fa879b16216d61abf
[ "MIT" ]
39
2019-06-22T12:25:54.000Z
2022-03-14T05:42:44.000Z
library/bubble/bubble_border.cpp
topillar/PuTTY-ng
1f5bf26de0f42e03ef4f100fa879b16216d61abf
[ "MIT" ]
5
2019-06-29T10:58:43.000Z
2020-09-04T08:44:09.000Z
library/bubble/bubble_border.cpp
topillar/PuTTY-ng
1f5bf26de0f42e03ef4f100fa879b16216d61abf
[ "MIT" ]
10
2019-08-07T06:08:23.000Z
2022-03-14T05:42:47.000Z
 #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); }
32.558577
86
0.586841
topillar
116f9457a86da21a7f2fab19654a4b143e44117b
2,654
cpp
C++
src/formats/pdb.cpp
danny305/ChargeFW2
c68fd06b9af244e5d8ed9172de17748e587bf46e
[ "MIT" ]
7
2020-05-19T15:14:15.000Z
2022-03-03T06:38:09.000Z
src/formats/pdb.cpp
danny305/ChargeFW2
c68fd06b9af244e5d8ed9172de17748e587bf46e
[ "MIT" ]
10
2021-03-04T21:38:49.000Z
2022-02-11T07:11:19.000Z
src/formats/pdb.cpp
danny305/ChargeFW2
c68fd06b9af244e5d8ed9172de17748e587bf46e
[ "MIT" ]
5
2021-03-05T00:42:41.000Z
2021-07-01T05:47:39.000Z
// // 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;
33.175
124
0.536549
danny305
117344447aed3b85948f68d21f921c79c258bb8a
470
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/align/detail/assume_aligned_gcc.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
ReactNativeFrontend/ios/Pods/boost/boost/align/detail/assume_aligned_gcc.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
ReactNativeFrontend/ios/Pods/boost/boost/align/detail/assume_aligned_gcc.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
/* 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
26.111111
68
0.804255
Harshitha91
1173cf80ee2459415a91ffc58c302cb3fea25c97
2,787
cpp
C++
src/plugins/intel_gpu/src/kernel_selector/core/actual_kernels/lstm/lstm_gemm_kernel_base.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/plugins/intel_gpu/src/kernel_selector/core/actual_kernels/lstm/lstm_gemm_kernel_base.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/plugins/intel_gpu/src/kernel_selector/core/actual_kernels/lstm/lstm_gemm_kernel_base.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// 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
40.391304
114
0.70183
kurylo
117415d2c124edfe1bb4c3aa3225bf45e54ad78c
6,760
cxx
C++
Modules/IO/RAW/test/itkRawImageIOTest5.cxx
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2021-11-29T14:41:43.000Z
2021-11-29T14:41:43.000Z
Modules/IO/RAW/test/itkRawImageIOTest5.cxx
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2017-08-18T19:28:52.000Z
2017-08-18T19:28:52.000Z
Modules/IO/RAW/test/itkRawImageIOTest5.cxx
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2017-08-18T19:07:39.000Z
2017-08-18T19:07:39.000Z
/*========================================================================= * * 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; }
21.666667
85
0.607249
floryst
1174ced20b24d1e950683308d42fd49b34695b06
418
cpp
C++
leetcode/01-Arrays_and_Strings/JD0101E-IsUnique/IsUnique_set.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
leetcode/01-Arrays_and_Strings/JD0101E-IsUnique/IsUnique_set.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
leetcode/01-Arrays_and_Strings/JD0101E-IsUnique/IsUnique_set.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
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; } };
22
63
0.380383
BinRay
1176a84637af5773c0babc8ec2b6f993371e3b41
15,820
cpp
C++
frdm_im920c_rcv_coide_kl25z/frdm_im920c_rcv/main.cpp
bigw00d/TrapChecker
9b36f7fef86928d196637ca958fadcacadb6cf50
[ "Apache-2.0" ]
null
null
null
frdm_im920c_rcv_coide_kl25z/frdm_im920c_rcv/main.cpp
bigw00d/TrapChecker
9b36f7fef86928d196637ca958fadcacadb6cf50
[ "Apache-2.0" ]
null
null
null
frdm_im920c_rcv_coide_kl25z/frdm_im920c_rcv/main.cpp
bigw00d/TrapChecker
9b36f7fef86928d196637ca958fadcacadb6cf50
[ "Apache-2.0" ]
null
null
null
#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 } }
26.27907
96
0.467826
bigw00d
1176b2596f2b6d1527e009db7ea27ca5cd96cc89
5,877
cc
C++
packages/@lse/core/addon/lse-core/lse/TextSceneNode.cc
lightsourceengine/LightSourceEngine
bc2d0cc08907f65a900d924d1a0ab19164171cb5
[ "Apache-2.0" ]
null
null
null
packages/@lse/core/addon/lse-core/lse/TextSceneNode.cc
lightsourceengine/LightSourceEngine
bc2d0cc08907f65a900d924d1a0ab19164171cb5
[ "Apache-2.0" ]
5
2020-07-23T01:09:07.000Z
2020-09-09T05:32:29.000Z
packages/@lse/core/addon/lse-core/lse/TextSceneNode.cc
lightsourceengine/LightSourceEngine
bc2d0cc08907f65a900d924d1a0ab19164171cb5
[ "Apache-2.0" ]
null
null
null
/* * 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
26.958716
118
0.68181
lightsourceengine
117a71339b9d75ad8aafa4b2881cb96e8be488c0
1,506
hpp
C++
include/poplibs_test/NonLinearity.hpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
95
2020-07-06T17:11:23.000Z
2022-03-12T14:42:28.000Z
include/poplibs_test/NonLinearity.hpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
null
null
null
include/poplibs_test/NonLinearity.hpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
14
2020-07-15T12:32:57.000Z
2022-01-26T14:58:45.000Z
// Copyright (c) 2017 Graphcore Ltd. All rights reserved. #ifndef poplibs_test_NonLinearity_hpp #define poplibs_test_NonLinearity_hpp #include "poplibs_support/Compiler.hpp" #include "poplibs_test/exceptions.hpp" #include "popnn/NonLinearity.hpp" #include <boost/multi_array.hpp> namespace poplibs_test { // input/output can be pointers to same memory void nonLinearity(popnn::NonLinearityType nonLinearityType, const double *inputData, double *outputData, std::size_t n); void nonLinearity(popnn::NonLinearityType nonLinearityType, boost::multi_array_ref<double, 2> array); void nonLinearity(popnn::NonLinearityType nonLinearityType, boost::multi_array<double, 4> &array); // For computing the gradient of non-linearity types SWISH and GELU // `activations` refers to the the input to the activation function rather than // the output. void bwdNonLinearity(popnn::NonLinearityType nonLinearityType, const double *activations, double *deltas, std::size_t n); void bwdNonLinearity(popnn::NonLinearityType nonLinearityType, const boost::multi_array<double, 4> &activations, boost::multi_array<double, 4> &deltas); void bwdNonLinearity(popnn::NonLinearityType nonLinearityType, const boost::multi_array<double, 2> &activations, boost::multi_array<double, 2> &deltas); } // End namespace poplibs_test. #endif // poplibs_test_NonLinearity_hpp
39.631579
79
0.720452
graphcore
117c39f8367eab1a403f37173443594510adc699
3,491
cpp
C++
src/util/MathUtil.cpp
castacks/wind_estimator
833ab9c52b44c90ab0486c72215c1ddefb0e7f98
[ "BSD-3-Clause" ]
8
2018-03-06T16:32:05.000Z
2021-07-20T14:56:35.000Z
src/util/MathUtil.cpp
wkyoun/wind_estimator
833ab9c52b44c90ab0486c72215c1ddefb0e7f98
[ "BSD-3-Clause" ]
null
null
null
src/util/MathUtil.cpp
wkyoun/wind_estimator
833ab9c52b44c90ab0486c72215c1ddefb0e7f98
[ "BSD-3-Clause" ]
4
2018-07-24T05:56:48.000Z
2021-03-28T02:14:24.000Z
/* * Copyright (c) 2018 Julian Soeren Lorenz, Carnegie Mellon University, 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. * 3. Neither the name of the copyright holder 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. * * END OF LICENSE * * Author: Julian Soeren Lorenz * Email: JulianLorenz@live.de * */ #include "MathUtil.h" namespace Util{ Matrix3d calcRotationMatrix(double qw, double qx, double qy, double qz){ // Sources: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles // https://arxiv.org/pdf/1708.08680.pdf // Note that the below matrix is transposed so it can be pre-multiplied Matrix3d R_g2f; R_g2f << qw*qw+qx*qx-qy*qy-qz*qz, 2*(qx*qy+qw*qz), 2*(qx*qz-qw*qy), 2*(qx*qy-qw*qz), qw*qw-qx*qx+qy*qy-qz*qz, 2*(qw*qx+qy*qz), 2*(qw*qy+qx*qz), 2*(qy*qz-qw*qx), qw*qw-qx*qx-qy*qy+qz*qz; return R_g2f; } Matrix3d calcRotationMatrix(Quaternion<double> q){ return calcRotationMatrix(q.w(),q.x(),q.y(),q.z()); } Matrix3d calcRotationMatrix(Vector4d q){ return calcRotationMatrix(q(0),q(1),q(2),q(3)); } Matrix3d calcRotationMatrix(double phi, double theta, double psi){ // Source: https://de.wikipedia.org/wiki/Eulersche_Winkel#Gier-Nick-Roll:_z.2C_y.E2.80.B2.2C_x.E2.80.B3-Konvention // Convention: Z Y' X'' Matrix3d R_g2f; const double c1 = std::cos(psi); //yaw const double c2 = std::cos(theta); //pitch const double c3 = std::cos(phi); //roll const double s1 = std::sin(psi); const double s2 = std::sin(theta); const double s3 = std::sin(phi); Matrix3d R_yaw, R_pitch, R_roll; R_yaw << c1, s1, 0, -s1, c1, 0, 0, 0, 1; R_pitch << c2, 0, -s2, 0, 1, 0, s2, 0, c2; R_roll << 1, 0, 0, 0, c3, s3, 0, -s3, c3; R_g2f = R_roll * R_pitch * R_yaw; /* Resulting matrix: R_g2f << c2*c1, c2*s1, -s2, s3*s2*c1-c3*s1, s3*s2*s1+c3*c1, s3*c2, c3*s2*c1+s3*s1, c3*s2*s1-s3*c1, c3*c2; */ return R_g2f; } }//end namespace
37.537634
118
0.672587
castacks
117eb1c55dd42e32b61a599b60b3a8c9c239adc5
2,850
cpp
C++
trunk/libs/angsys/source/value/boolean.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/angsys/source/value/boolean.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/angsys/source/value/boolean.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include <angsys.h> using namespace ang; #define MY_TYPE ang::variable<bool> #include "ang/inline/object_wrapper_specialization.inl" #undef MY_TYPE static collections::pair<castr_t, bool> s_boolean_parsing_map[] = { { "FALSE"_sv, false }, { "False"_sv, false }, { "HIGH"_sv, true }, { "High"_sv, true }, { "LOW"_sv, false }, { "Low"_sv, false }, { "NO"_sv, false }, { "No"_sv, false }, { "TRUE"_sv, true }, { "True"_sv, true }, { "YES"_sv, true }, { "Yes"_sv, true }, { "false"_sv, false }, { "high"_sv, true }, { "low"_sv, false }, { "no"_sv, false }, { "true"_sv, true }, { "yes"_sv, true }, }; value<bool> variable<bool>::parse(cstr_t cstr) { auto idx = algorithms::binary_search(cstr, collections::to_array(s_boolean_parsing_map)); if (idx >= algorithms::array_size(s_boolean_parsing_map)) return false; else return s_boolean_parsing_map[idx].value; } string variable<bool>::to_string(value<bool> val, text::text_format_t f_) { text::text_format_flags_t f; f.value = f_.format_flags(); switch (f.target) { case text::text_format::bool_: switch (f.case_) { case 2: switch (f.type) { case 1: return val.get() ? "YES"_r : "NO"_r; case 2: return val.get() ? "HIGH"_r : "LOW"_r; default: return val.get() ? "TRUE"_r : "FALSE"_r; } case 3: switch (f.type) { case 1: return val.get() ? "Yes"_r : "No"_r; case 2: return val.get() ? "High"_r : "Low"_r; default: return val.get() ? "True"_r : "False"_r; } default: switch (f.type) { case 1: return val.get() ? "yes"_r : "no"_r; case 2: return val.get() ? "high"_r : "low"_r; default: return val.get() ? "true"_r : "false"_r; } } case text::text_format::signed_: return variable<int>::to_string(val.get() ? 1 : 0, f_); case text::text_format::unsigned_: return variable<uint>::to_string(val.get() ? 1 : 0, f_); case text::text_format::float_: return variable<float>::to_string(val.get() ? 1.0f : 0.0f, f_); default: return val.get() ? "true"_r : "false"_r; } } variable<bool>::variable() { set(false); } variable<bool>::variable(bool const& val) { set(val); } variable<bool>::variable(value<bool> const& val) { set(val); } variable<bool>::variable(variable const* val) { set(val ? val->get() : false); } variable<bool>::~variable() { } string variable<bool>::to_string()const { return get() ? "true"_r : "false"_r; } string variable<bool>::to_string(text::text_format_t f)const { return ang::move(to_string(*this, f)); } rtti_t const& variable<bool>::value_type()const { return type_of<bool>(); } bool variable<bool>::set_value(rtti_t const& id, unknown_t val) { return false; } bool variable<bool>::get_value(rtti_t const& id, unknown_t val)const { return false; } variant variable<bool>::clone()const { return (ivariable*)new variable<bool>(get()); }
20.80292
90
0.641754
ChuyX3
11802b5c8fb08dfd814d4deb2a3d48d258bcdb8c
3,986
cpp
C++
src/CheckBox.cpp
MStr3am/sfui
64bdf89e229c1f4c3461c9d8e21e2a2d6e83c5c4
[ "BSD-3-Clause" ]
null
null
null
src/CheckBox.cpp
MStr3am/sfui
64bdf89e229c1f4c3461c9d8e21e2a2d6e83c5c4
[ "BSD-3-Clause" ]
null
null
null
src/CheckBox.cpp
MStr3am/sfui
64bdf89e229c1f4c3461c9d8e21e2a2d6e83c5c4
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009, Robin RUAUX 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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 <SFML/Graphics/RenderTarget.hpp> #include <SFUI/CheckBox.hpp> namespace sf { namespace ui { CheckBox::CheckBox(const Unicode::Text& caption) : Widget(), mChecked(false), mDecorator(), mCaption(caption), mCheckIcon() { SetDefaultStyle("BI_CheckBox"); LoadStyle(GetDefaultStyle()); Add(&mDecorator); Add(&mCaption); Add(&mCheckIcon); //mCheckIcon.AddMouseListener(this); AddMouseListener(this); } void CheckBox::SetChecked(bool checked) { mChecked = checked; LoadStyle((checked) ? GetDefaultStyle() + "_Checked" : GetDefaultStyle()); } bool CheckBox::IsChecked() const { return mChecked; } void CheckBox::OnMouseReleased(const Event::MouseButtonEvent& mouse) { if (mouse.Button == Mouse::Left) { if (mChecked) { mChecked = false; LoadStyle(GetDefaultStyle()); } else { mChecked = true; LoadStyle(GetDefaultStyle() + "_Checked"); } } } void CheckBox::LoadStyle(const std::string& nameStyle) { Widget::LoadStyle(nameStyle); mDecorator.LoadStyle(nameStyle + "->Background"); mCheckIcon.LoadStyle(nameStyle + "->Icon"); mCaption.LoadStyle(nameStyle + "->Label"); } void CheckBox::SetText(const Unicode::Text& text) { mCaption.SetText(text); } const Unicode::Text& CheckBox::GetText() const { return mCaption.GetText(); } void CheckBox::SetFont(const Font& font) { mCaption.SetFont(font); } const Font& CheckBox::GetFont() const { return mCaption.GetFont(); } void CheckBox::SetTextColor(const Color& color) { mCaption.SetColor(color); } const Color& CheckBox::GetTextColor() const { return mCaption.GetColor(); } } }
32.145161
87
0.585549
MStr3am
11817c4669ea4d00025ca7b88019be29e9d9b540
102
cc
C++
DQMServices/Core/test/DQMTestStandaloneBuildOfDQMStore.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
1
2021-01-04T10:25:39.000Z
2021-01-04T10:25:39.000Z
DQMServices/Core/test/DQMTestStandaloneBuildOfDQMStore.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
7
2016-07-17T02:34:54.000Z
2019-08-13T07:58:37.000Z
DQMServices/Core/test/DQMTestStandaloneBuildOfDQMStore.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
2
2019-09-27T08:33:22.000Z
2019-11-14T10:52:30.000Z
#define WITHOUT_CMS_FRAMEWORK 1 #include "DQMServices/Core/src/DQMStore.cc" int main() { return 0; }
20.4
43
0.754902
NTrevisani
1182aae321619cac6684da397f96b049b85f163c
1,953
cpp
C++
aslam_splines_python/src/QuadraticIntegralError.cpp
Curium-sg/aslam_splines
d2c8c69d28d2f742b1d96a6a4e43a5c5112497af
[ "BSD-3-Clause" ]
null
null
null
aslam_splines_python/src/QuadraticIntegralError.cpp
Curium-sg/aslam_splines
d2c8c69d28d2f742b1d96a6a4e43a5c5112497af
[ "BSD-3-Clause" ]
null
null
null
aslam_splines_python/src/QuadraticIntegralError.cpp
Curium-sg/aslam_splines
d2c8c69d28d2f742b1d96a6a4e43a5c5112497af
[ "BSD-3-Clause" ]
null
null
null
/* * QuadraticIntegralErrorTerm.cpp * * Created on: Dec 4, 2013 * Author: hannes */ #include <sstream> #include <boost/python.hpp> #include <numpy_eigen/boost_python_headers.hpp> #include <Eigen/Core> #include <aslam/backend/QuadraticIntegralError.hpp> using namespace boost::python; template <int dim, typename Expression = aslam::backend::VectorExpression<dim>> inline void addQuadraticIntegralExpressionErrorTerms(aslam::backend::OptimizationProblem & problem, double a, double b, int numberOfPoints, const object & expressionFactory, const Eigen::Matrix<double, dim, dim> & sqrtInvR){ using namespace aslam::backend::integration; struct ExpressionFactoryAdapter { ExpressionFactoryAdapter(const object & o) : o(o){} Expression operator()(double time) const { return extract<Expression>(o(time)); } private: const object & o; }; addQuadraticIntegralExpressionErrorTerms(problem, a, b, numberOfPoints, ExpressionFactoryAdapter(expressionFactory), sqrtInvR); } const char * BaseName = "addQuadraticIntegralExpressionErrorTermsToProblem"; template <int dimMax> void defAddQuadraticIntegralExpressionErrorTerms(){ std::stringstream s; s << BaseName << dimMax; boost::python::def( s.str().c_str(), &addQuadraticIntegralExpressionErrorTerms<dimMax>, boost::python::args("problem, timeA, timeB, nIntegrationPoints, expressionFactory, sqrtInvR") ); defAddQuadraticIntegralExpressionErrorTerms<dimMax -1>(); } template <> void defAddQuadraticIntegralExpressionErrorTerms<0>(){ } void exportAddQuadraticIntegralExpressionErrorTerms(){ defAddQuadraticIntegralExpressionErrorTerms<3>(); boost::python::def( "addQuadraticIntegralEuclideanExpressionErrorTermsToProblem", &addQuadraticIntegralExpressionErrorTerms<3, aslam::backend::EuclideanExpression>, boost::python::args("problem, timeA, timeB, nIntegrationPoints, expressionFactory, sqrtInvR") ); }
31.5
224
0.760881
Curium-sg
11837e97ba838a6c922e550da0425e2f476ad3b6
10,249
cc
C++
src/codegen.cc
TinkerEdgeR-Android/external_v8
7c9cad78aca05245a07529da3d689282cd554df9
[ "BSD-3-Clause" ]
27
2017-12-14T13:48:25.000Z
2020-12-31T15:46:55.000Z
src/codegen.cc
TinkerEdgeR-Android/external_v8
7c9cad78aca05245a07529da3d689282cd554df9
[ "BSD-3-Clause" ]
null
null
null
src/codegen.cc
TinkerEdgeR-Android/external_v8
7c9cad78aca05245a07529da3d689282cd554df9
[ "BSD-3-Clause" ]
3
2019-01-14T12:12:27.000Z
2019-06-07T09:47:00.000Z
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/codegen.h" #if defined(V8_OS_AIX) #include <fenv.h> // NOLINT(build/c++11) #endif #include <memory> #include "src/ast/prettyprinter.h" #include "src/bootstrapper.h" #include "src/compilation-info.h" #include "src/counters.h" #include "src/debug/debug.h" #include "src/eh-frame.h" #include "src/objects-inl.h" #include "src/runtime/runtime.h" namespace v8 { namespace internal { #if defined(V8_OS_WIN) double modulo(double x, double y) { // Workaround MS fmod bugs. ECMA-262 says: // dividend is finite and divisor is an infinity => result equals dividend // dividend is a zero and divisor is nonzero finite => result equals dividend if (!(std::isfinite(x) && (!std::isfinite(y) && !std::isnan(y))) && !(x == 0 && (y != 0 && std::isfinite(y)))) { x = fmod(x, y); } return x; } #else // POSIX double modulo(double x, double y) { #if defined(V8_OS_AIX) // AIX raises an underflow exception for (Number.MIN_VALUE % Number.MAX_VALUE) feclearexcept(FE_ALL_EXCEPT); double result = std::fmod(x, y); int exception = fetestexcept(FE_UNDERFLOW); return (exception ? x : result); #else return std::fmod(x, y); #endif } #endif // defined(V8_OS_WIN) #define UNARY_MATH_FUNCTION(name, generator) \ static UnaryMathFunctionWithIsolate fast_##name##_function = nullptr; \ double std_##name(double x, Isolate* isolate) { return std::name(x); } \ void init_fast_##name##_function(Isolate* isolate) { \ if (FLAG_fast_math) fast_##name##_function = generator(isolate); \ if (!fast_##name##_function) fast_##name##_function = std_##name; \ } \ void lazily_initialize_fast_##name(Isolate* isolate) { \ if (!fast_##name##_function) init_fast_##name##_function(isolate); \ } \ double fast_##name(double x, Isolate* isolate) { \ return (*fast_##name##_function)(x, isolate); \ } UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction) #undef UNARY_MATH_FUNCTION #define __ ACCESS_MASM(masm_) #ifdef DEBUG Comment::Comment(MacroAssembler* masm, const char* msg) : masm_(masm), msg_(msg) { __ RecordComment(msg); } Comment::~Comment() { if (msg_[0] == '[') __ RecordComment("]"); } #endif // DEBUG #undef __ void CodeGenerator::MakeCodePrologue(CompilationInfo* info, const char* kind) { bool print_ast = false; const char* ftype; if (info->isolate()->bootstrapper()->IsActive()) { print_ast = FLAG_print_builtin_ast; ftype = "builtin"; } else { print_ast = FLAG_print_ast; ftype = "user-defined"; } if (FLAG_trace_codegen || print_ast) { std::unique_ptr<char[]> name = info->GetDebugName(); PrintF("[generating %s code for %s function: %s]\n", kind, ftype, name.get()); } #ifdef DEBUG if (info->parse_info() && print_ast) { PrintF("--- AST ---\n%s\n", AstPrinter(info->isolate()).PrintProgram(info->literal())); } #endif // DEBUG } Handle<Code> CodeGenerator::MakeCodeEpilogue(MacroAssembler* masm, EhFrameWriter* eh_frame_writer, CompilationInfo* info, Handle<Object> self_reference) { Isolate* isolate = info->isolate(); // Allocate and install the code. CodeDesc desc; Code::Flags flags = info->code_flags(); bool is_crankshafted = Code::ExtractKindFromFlags(flags) == Code::OPTIMIZED_FUNCTION || info->IsStub(); masm->GetCode(&desc); if (eh_frame_writer) eh_frame_writer->GetEhFrame(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, flags, self_reference, false, is_crankshafted, info->prologue_offset(), info->is_debug() && !is_crankshafted); isolate->counters()->total_compiled_code_size()->Increment( code->instruction_size()); return code; } // Print function's source if it was not printed before. // Return a sequential id under which this function was printed. static int PrintFunctionSource(CompilationInfo* info, std::vector<Handle<SharedFunctionInfo>>* printed, int inlining_id, Handle<SharedFunctionInfo> shared) { // Outermost function has source id -1 and inlined functions take // source ids starting from 0. int source_id = -1; if (inlining_id != SourcePosition::kNotInlined) { for (unsigned i = 0; i < printed->size(); i++) { if (printed->at(i).is_identical_to(shared)) { return i; } } source_id = static_cast<int>(printed->size()); printed->push_back(shared); } Isolate* isolate = info->isolate(); if (!shared->script()->IsUndefined(isolate)) { Handle<Script> script(Script::cast(shared->script()), isolate); if (!script->source()->IsUndefined(isolate)) { CodeTracer::Scope tracing_scope(isolate->GetCodeTracer()); Object* source_name = script->name(); OFStream os(tracing_scope.file()); os << "--- FUNCTION SOURCE ("; if (source_name->IsString()) { os << String::cast(source_name)->ToCString().get() << ":"; } os << shared->DebugName()->ToCString().get() << ") id{"; os << info->optimization_id() << "," << source_id << "} start{"; os << shared->start_position() << "} ---\n"; { DisallowHeapAllocation no_allocation; int start = shared->start_position(); int len = shared->end_position() - start; String::SubStringRange source(String::cast(script->source()), start, len); for (const auto& c : source) { os << AsReversiblyEscapedUC16(c); } } os << "\n--- END ---\n"; } } return source_id; } // Print information for the given inlining: which function was inlined and // where the inlining occured. static void PrintInlinedFunctionInfo( CompilationInfo* info, int source_id, int inlining_id, const CompilationInfo::InlinedFunctionHolder& h) { CodeTracer::Scope tracing_scope(info->isolate()->GetCodeTracer()); OFStream os(tracing_scope.file()); os << "INLINE (" << h.shared_info->DebugName()->ToCString().get() << ") id{" << info->optimization_id() << "," << source_id << "} AS " << inlining_id << " AT "; const SourcePosition position = h.position.position; if (position.IsKnown()) { os << "<" << position.InliningId() << ":" << position.ScriptOffset() << ">"; } else { os << "<?>"; } os << std::endl; } // Print the source of all functions that participated in this optimizing // compilation. For inlined functions print source position of their inlining. static void DumpParticipatingSource(CompilationInfo* info) { AllowDeferredHandleDereference allow_deference_for_print_code; std::vector<Handle<SharedFunctionInfo>> printed; printed.reserve(info->inlined_functions().size()); PrintFunctionSource(info, &printed, SourcePosition::kNotInlined, info->shared_info()); const auto& inlined = info->inlined_functions(); for (unsigned id = 0; id < inlined.size(); id++) { const int source_id = PrintFunctionSource(info, &printed, id, inlined[id].shared_info); PrintInlinedFunctionInfo(info, source_id, id, inlined[id]); } } void CodeGenerator::PrintCode(Handle<Code> code, CompilationInfo* info) { if (FLAG_print_opt_source && info->IsOptimizing()) { DumpParticipatingSource(info); } #ifdef ENABLE_DISASSEMBLER AllowDeferredHandleDereference allow_deference_for_print_code; Isolate* isolate = info->isolate(); bool print_code = isolate->bootstrapper()->IsActive() ? FLAG_print_builtin_code : (FLAG_print_code || (info->IsStub() && FLAG_print_code_stubs) || (info->IsOptimizing() && FLAG_print_opt_code && info->shared_info()->PassesFilter(FLAG_print_opt_code_filter)) || (info->IsWasm() && FLAG_print_wasm_code)); if (print_code) { std::unique_ptr<char[]> debug_name = info->GetDebugName(); CodeTracer::Scope tracing_scope(info->isolate()->GetCodeTracer()); OFStream os(tracing_scope.file()); // Print the source code if available. bool print_source = info->parse_info() && (code->kind() == Code::OPTIMIZED_FUNCTION || code->kind() == Code::FUNCTION); if (print_source) { Handle<SharedFunctionInfo> shared = info->shared_info(); Handle<Script> script = info->script(); if (!script->IsUndefined(isolate) && !script->source()->IsUndefined(isolate)) { os << "--- Raw source ---\n"; StringCharacterStream stream(String::cast(script->source()), shared->start_position()); // fun->end_position() points to the last character in the stream. We // need to compensate by adding one to calculate the length. int source_len = shared->end_position() - shared->start_position() + 1; for (int i = 0; i < source_len; i++) { if (stream.HasMore()) { os << AsReversiblyEscapedUC16(stream.GetNext()); } } os << "\n\n"; } } if (info->IsOptimizing()) { if (FLAG_print_unopt_code && info->parse_info()) { os << "--- Unoptimized code ---\n"; info->closure()->shared()->code()->Disassemble(debug_name.get(), os); } os << "--- Optimized code ---\n" << "optimization_id = " << info->optimization_id() << "\n"; } else { os << "--- Code ---\n"; } if (print_source) { Handle<SharedFunctionInfo> shared = info->shared_info(); os << "source_position = " << shared->start_position() << "\n"; } code->Disassemble(debug_name.get(), os); os << "--- End code ---\n"; } #endif // ENABLE_DISASSEMBLER } } // namespace internal } // namespace v8
34.860544
80
0.612548
TinkerEdgeR-Android
1186c1da060ca7fce121b26d2ca885587ba746be
38,681
cpp
C++
src/energyplus/ForwardTranslator/ForwardTranslateAirConditionerVariableRefrigerantFlow.cpp
mehrdad-shokri/OpenStudio
1773b54ce1cb660818ac0114dd7eefae6639ca36
[ "blessing" ]
null
null
null
src/energyplus/ForwardTranslator/ForwardTranslateAirConditionerVariableRefrigerantFlow.cpp
mehrdad-shokri/OpenStudio
1773b54ce1cb660818ac0114dd7eefae6639ca36
[ "blessing" ]
null
null
null
src/energyplus/ForwardTranslator/ForwardTranslateAirConditionerVariableRefrigerantFlow.cpp
mehrdad-shokri/OpenStudio
1773b54ce1cb660818ac0114dd7eefae6639ca36
[ "blessing" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2020, Alliance for Sustainable Energy, LLC, and other contributors. 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. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "../ForwardTranslator.hpp" #include "../../model/Model.hpp" #include "../../model/Schedule.hpp" #include "../../model/Schedule_Impl.hpp" #include "../../model/Node.hpp" #include "../../model/Node_Impl.hpp" #include "../../model/PlantLoop.hpp" #include "../../model/PlantLoop_Impl.hpp" #include "../../model/ThermalZone.hpp" #include "../../model/ThermalZone_Impl.hpp" #include "../../model/AirConditionerVariableRefrigerantFlow.hpp" #include "../../model/AirConditionerVariableRefrigerantFlow_Impl.hpp" #include "../../model/ZoneHVACTerminalUnitVariableRefrigerantFlow.hpp" #include "../../model/ZoneHVACTerminalUnitVariableRefrigerantFlow_Impl.hpp" #include "../../model/Curve.hpp" #include "../../model/Curve_Impl.hpp" #include "../../utilities/core/Logger.hpp" #include "../../utilities/core/Assert.hpp" #include <utilities/idd/AirConditioner_VariableRefrigerantFlow_FieldEnums.hxx> #include <utilities/idd/ZoneTerminalUnitList_FieldEnums.hxx> #include "../../utilities/idd/IddEnums.hpp" #include <utilities/idd/IddEnums.hxx> #include "../../utilities/idf/IdfExtensibleGroup.hpp" using namespace openstudio::model; using namespace std; namespace openstudio { namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateAirConditionerVariableRefrigerantFlow( AirConditionerVariableRefrigerantFlow & modelObject ) { boost::optional<std::string> s; boost::optional<double> value; IdfObject idfObject(IddObjectType::AirConditioner_VariableRefrigerantFlow); m_idfObjects.push_back(idfObject); // Name s = modelObject.name(); if( s ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatPumpName,*s); } // AvailabilityScheduleName if( boost::optional<model::Schedule> schedule = modelObject.availabilitySchedule() ) { if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::AvailabilityScheduleName,_schedule->name().get()); } } // RatedTotalCoolingCapacity if( modelObject.isGrossRatedTotalCoolingCapacityAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::GrossRatedTotalCoolingCapacity,"Autosize"); } else if( (value = modelObject.grossRatedTotalCoolingCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::GrossRatedTotalCoolingCapacity,value.get()); } // RatedCoolingCOP if( (value = modelObject.grossRatedCoolingCOP()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::GrossRatedCoolingCOP,value.get()); } // MinimumOutdoorTemperatureinCoolingMode if( (value = modelObject.minimumOutdoorTemperatureinCoolingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumOutdoorTemperatureinCoolingMode,value.get()); } // MaximumOutdoorTemperatureinCoolingMode if( (value = modelObject.maximumOutdoorTemperatureinCoolingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorTemperatureinCoolingMode,value.get()); } // CoolingCapacityRatioModifierFunctionofLowTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.coolingCapacityRatioModifierFunctionofLowTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingCapacityRatioModifierFunctionofLowTemperatureCurveName,_curve->name().get()); } } // CoolingCapacityRatioBoundaryCurveName if( boost::optional<model::Curve> curve = modelObject.coolingCapacityRatioBoundaryCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingCapacityRatioBoundaryCurveName,_curve->name().get()); } } // CoolingCapacityRatioModifierFunctionofHighTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.coolingCapacityRatioModifierFunctionofHighTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingCapacityRatioModifierFunctionofHighTemperatureCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioModifierFunctionofLowTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioModifierFunctionofLowTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioModifierFunctionofLowTemperatureCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioBoundaryCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioBoundaryCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioBoundaryCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioModifierFunctionofHighTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioModifierFunctionofHighTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioModifierFunctionofHighTemperatureCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurveName,_curve->name().get()); } } // CoolingCombinationRatioCorrectionFactorCurveName if( boost::optional<model::Curve> curve = modelObject.coolingCombinationRatioCorrectionFactorCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingCombinationRatioCorrectionFactorCurveName,_curve->name().get()); } } // CoolingPartLoadFractionCorrelationCurveName if( boost::optional<model::Curve> curve = modelObject.coolingPartLoadFractionCorrelationCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingPartLoadFractionCorrelationCurveName,_curve->name().get()); } } // RatedTotalHeatingCapacity if( modelObject.isGrossRatedHeatingCapacityAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::GrossRatedHeatingCapacity,"Autosize"); } else if( (value = modelObject.grossRatedHeatingCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::GrossRatedHeatingCapacity,value.get()); } // RatedTotalHeatingCapacitySizingRatio if( (value = modelObject.ratedHeatingCapacitySizingRatio()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::RatedHeatingCapacitySizingRatio,value.get()); } // RatedHeatingCOP if( (value = modelObject.ratedHeatingCOP()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::GrossRatedHeatingCOP,value.get()); } // MinimumOutdoorTemperatureinHeatingMode if( (value = modelObject.minimumOutdoorTemperatureinHeatingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumOutdoorTemperatureinHeatingMode,value.get()); } // MaximumOutdoorTemperatureinHeatingMode if( (value = modelObject.maximumOutdoorTemperatureinHeatingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorTemperatureinHeatingMode,value.get()); } // HeatingCapacityRatioModifierFunctionofLowTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.heatingCapacityRatioModifierFunctionofLowTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingCapacityRatioModifierFunctionofLowTemperatureCurveName,_curve->name().get()); } } // HeatingCapacityRatioBoundaryCurveName if( boost::optional<model::Curve> curve = modelObject.heatingCapacityRatioBoundaryCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingCapacityRatioBoundaryCurveName,_curve->name().get()); } } // HeatingCapacityRatioModifierFunctionofHighTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.heatingCapacityRatioModifierFunctionofHighTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingCapacityRatioModifierFunctionofHighTemperatureCurveName,_curve->name().get()); } } // HeatingEnergyInputRatioModifierFunctionofLowTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioModifierFunctionofLowTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioModifierFunctionofLowTemperatureCurveName,_curve->name().get()); } } // HeatingEnergyInputRatioBoundaryCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioBoundaryCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioBoundaryCurveName,_curve->name().get()); } } // HeatingEnergyInputRatioModifierFunctionofHighTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioModifierFunctionofHighTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioModifierFunctionofHighTemperatureCurveName,_curve->name().get()); } } // HeatingPerformanceCurveOutdoorTemperatureType if( (s = modelObject.heatingPerformanceCurveOutdoorTemperatureType()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingPerformanceCurveOutdoorTemperatureType,s.get()); } // HeatingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurveName,_curve->name().get()); } } // HeatingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurveName,_curve->name().get()); } } // HeatingCombinationRatioCorrectionFactorCurveName if( boost::optional<model::Curve> curve = modelObject.heatingCombinationRatioCorrectionFactorCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingCombinationRatioCorrectionFactorCurveName,_curve->name().get()); } } // HeatingPartLoadFractionCorrelationCurveName if( boost::optional<model::Curve> curve = modelObject.heatingPartLoadFractionCorrelationCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingPartLoadFractionCorrelationCurveName,_curve->name().get()); } } // MinimumHeatPumpPartLoadRatio if( (value = modelObject.minimumHeatPumpPartLoadRatio()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumHeatPumpPartLoadRatio,value.get()); } // ZoneNameforMasterThermostatLocation if( boost::optional<model::ThermalZone> zone = modelObject.zoneforMasterThermostatLocation() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::ZoneNameforMasterThermostatLocation,zone->name().get()); } // MasterThermostatPriorityControlType if( (s = modelObject.masterThermostatPriorityControlType()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::MasterThermostatPriorityControlType,s.get()); } // ThermostatPriorityScheduleName if( boost::optional<model::Schedule> schedule = modelObject.thermostatPrioritySchedule() ) { if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::ThermostatPriorityScheduleName,_schedule->name().get()); } } // HeatPumpWasteHeatRecovery if( modelObject.heatPumpWasteHeatRecovery() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatPumpWasteHeatRecovery,"Yes"); } else { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatPumpWasteHeatRecovery,"No"); } // EquivalentPipingLengthusedforPipingCorrectionFactorinCoolingMode if( (value = modelObject.equivalentPipingLengthusedforPipingCorrectionFactorinCoolingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EquivalentPipingLengthusedforPipingCorrectionFactorinCoolingMode,value.get()); } // VerticalHeightusedforPipingCorrectionFactor if( (value = modelObject.verticalHeightusedforPipingCorrectionFactor()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::VerticalHeightusedforPipingCorrectionFactor,value.get()); } // PipingCorrectionFactorforLengthinCoolingModeCurveName if( boost::optional<model::Curve> curve = modelObject.pipingCorrectionFactorforLengthinCoolingModeCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::PipingCorrectionFactorforLengthinCoolingModeCurveName,_curve->name().get()); } } // PipingCorrectionFactorforHeightinCoolingModeCoefficient if( (value = modelObject.pipingCorrectionFactorforHeightinCoolingModeCoefficient()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::PipingCorrectionFactorforHeightinCoolingModeCoefficient,value.get()); } // EquivalentPipingLengthusedforPipingCorrectionFactorinHeatingMode if( (value = modelObject.equivalentPipingLengthusedforPipingCorrectionFactorinHeatingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EquivalentPipingLengthusedforPipingCorrectionFactorinHeatingMode,value.get()); } // PipingCorrectionFactorforLengthinHeatingModeCurveName if( boost::optional<model::Curve> curve = modelObject.pipingCorrectionFactorforLengthinHeatingModeCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::PipingCorrectionFactorforLengthinHeatingModeCurveName,_curve->name().get()); } } // PipingCorrectionFactorforHeightinHeatingModeCoefficient if( (value = modelObject.pipingCorrectionFactorforHeightinHeatingModeCoefficient()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::PipingCorrectionFactorforHeightinHeatingModeCoefficient,value.get()); } // CrankcaseHeaterPowerperCompressor if( (value = modelObject.crankcaseHeaterPowerperCompressor()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::CrankcaseHeaterPowerperCompressor,value.get()); } // NumberofCompressors { int number = modelObject.numberofCompressors(); idfObject.setUnsigned(AirConditioner_VariableRefrigerantFlowFields::NumberofCompressors,(unsigned)number); } // RatioofCompressorSizetoTotalCompressorCapacity if( (value = modelObject.ratioofCompressorSizetoTotalCompressorCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::RatioofCompressorSizetoTotalCompressorCapacity,value.get()); } // MaximumOutdoorDrybulbTemperatureforCrankcaseHeater if( (value = modelObject.maximumOutdoorDrybulbTemperatureforCrankcaseHeater()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorDryBulbTemperatureforCrankcaseHeater,value.get()); } // DefrostStrategy if( (s = modelObject.defrostStrategy()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::DefrostStrategy,s.get()); } // DefrostControl if( (s = modelObject.defrostControl()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::DefrostControl,s.get()); } // DefrostEnergyInputRatioModifierFunctionofTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.defrostEnergyInputRatioModifierFunctionofTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::DefrostEnergyInputRatioModifierFunctionofTemperatureCurveName,_curve->name().get()); } } // DefrostTimePeriodFraction if( (value = modelObject.defrostTimePeriodFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::DefrostTimePeriodFraction,value.get()); } // ResistiveDefrostHeaterCapacity if( modelObject.isResistiveDefrostHeaterCapacityAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::ResistiveDefrostHeaterCapacity,"Autosize"); } else if( (value = modelObject.resistiveDefrostHeaterCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::ResistiveDefrostHeaterCapacity,value.get()); } // MaximumOutdoorDrybulbTemperatureforDefrostOperation if( (value = modelObject.maximumOutdoorDrybulbTemperatureforDefrostOperation()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorDrybulbTemperatureforDefrostOperation,value.get()); } // Condenser Type // It was decided that the "smart" logic shouldn't be in the model itself. // So now, we do two things: // * If condenserType is set, respect that, but issue Errors if it's wrong // * If condenserType is not set, we default it (default is done in the model actually) // * If VRF connected to a PlantLoop => WaterCooled, else "AirCooled" ("EvaporativelyCooled" is less common and will be reserved for people who // know what they are doing and are hardsetting it) std::string condenserType = modelObject.condenserType(); if (modelObject.isCondenserTypeDefaulted()) { // We log an Info anyways, might be useful if (openstudio::istringEqual(condenserType, "EvaporativelyCooled")) { LOG(Info, modelObject.briefDescription() << " is connected to a PlantLoop, defaulting condenserType to 'WaterCooled'."); } else { LOG(Info, modelObject.briefDescription() << " is not connected to a PlantLoop, defaulting condenserType to 'AirCooled'."); } } else { boost::optional<PlantLoop> _plant = modelObject.plantLoop(); if ( (openstudio::istringEqual(condenserType, "AirCooled") || openstudio::istringEqual(condenserType, "EvaporativelyCooled")) && _plant.is_initialized()) { LOG(Error, modelObject.briefDescription() << " has an hardcoded condenserType '" << condenserType << "' while it is connected to a PlantLoop."); } else if( openstudio::istringEqual(condenserType, "WaterCooled") && !_plant.is_initialized()) { LOG(Error, modelObject.briefDescription() << " has an hardcoded condenserType '" << condenserType << "' while it is NOT connected to a PlantLoop."); } } idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CondenserType, condenserType); // CondenserInletNodeName if( boost::optional<ModelObject> mo = modelObject.inletModelObject() ) { if( boost::optional<Node> node = mo->optionalCast<Node>() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CondenserInletNodeName,node->name().get()); } } // CondenserOutletNodeName if( boost::optional<ModelObject> mo = modelObject.outletModelObject() ) { if( boost::optional<Node> node = mo->optionalCast<Node>() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CondenserOutletNodeName,node->name().get()); } } // WaterCondenserVolumeFlowRate if( modelObject.isWaterCondenserVolumeFlowRateAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::WaterCondenserVolumeFlowRate,"Autosize"); } else if( (value = modelObject.waterCondenserVolumeFlowRate()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::WaterCondenserVolumeFlowRate,value.get()); } // EvaporativeCondenserEffectiveness if( (value = modelObject.evaporativeCondenserEffectiveness()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserEffectiveness,value.get()); } // EvaporativeCondenserAirFlowRate if( modelObject.isEvaporativeCondenserAirFlowRateAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserAirFlowRate,"Autosize"); } else if( (value = modelObject.evaporativeCondenserAirFlowRate()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserAirFlowRate,value.get()); } // EvaporativeCondenserPumpRatedPowerConsumption if( modelObject.isEvaporativeCondenserPumpRatedPowerConsumptionAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserPumpRatedPowerConsumption,"Autosize"); } else if( ( value = modelObject.evaporativeCondenserPumpRatedPowerConsumption()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserPumpRatedPowerConsumption,value.get()); } // BasinHeaterCapacity if( (value = modelObject.basinHeaterCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterCapacity,value.get()); } // BasinHeaterSetpointTemperature if( (value = modelObject.basinHeaterSetpointTemperature()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterSetpointTemperature,value.get()); } // BasinHeaterOperatingScheduleName if( boost::optional<model::Schedule> schedule = modelObject.basinHeaterOperatingSchedule() ) { if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterOperatingScheduleName,_schedule->name().get()); } } // FuelType if( (s = modelObject.fuelType()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::FuelType,s.get()); } // MinimumOutdoorTemperatureinHeatRecoveryMode if( (value = modelObject.minimumOutdoorTemperatureinHeatRecoveryMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumOutdoorTemperatureinHeatRecoveryMode,value.get()); } // MaximumOutdoorTemperatureinHeatRecoveryMode if( (value = modelObject.maximumOutdoorTemperatureinHeatingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorTemperatureinHeatRecoveryMode,value.get()); } // HeatRecoveryCoolingCapacityModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryCoolingCapacityModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingCapacityModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryCoolingCapacityFraction if( (value = modelObject.initialHeatRecoveryCoolingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryCoolingCapacityFraction,value.get()); } // HeatRecoveryCoolingCapacityTimeConstant if( (value = modelObject.heatRecoveryCoolingCapacityTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingCapacityTimeConstant,value.get()); } // HeatRecoveryCoolingEnergyModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryCoolingEnergyModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingEnergyModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryCoolingEnergyFraction if( (value = modelObject.initialHeatRecoveryCoolingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryCoolingEnergyFraction,value.get()); } // HeatRecoveryCoolingEnergyTimeConstant if( (value = modelObject.heatRecoveryCoolingEnergyTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingEnergyTimeConstant,value.get()); } // HeatRecoveryHeatingCapacityModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryHeatingCapacityModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingCapacityModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryHeatingCapacityFraction if( (value = modelObject.initialHeatRecoveryHeatingCapacityFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryHeatingCapacityFraction,value.get()); } // HeatRecoveryHeatingCapacityTimeConstant if( (value = modelObject.heatRecoveryHeatingCapacityTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingCapacityTimeConstant,value.get()); } // HeatRecoveryHeatingEnergyModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryHeatingEnergyModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingEnergyModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryHeatingEnergyFraction if( (value = modelObject.initialHeatRecoveryHeatingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryHeatingEnergyFraction,value.get()); } // HeatRecoveryHeatingEnergyTimeConstant if( (value = modelObject.heatRecoveryHeatingEnergyTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingEnergyTimeConstant,value.get()); } // Terminal Unit List IdfObject _zoneTerminalUnitList(IddObjectType::ZoneTerminalUnitList); std::string terminalUnitListName = modelObject.name().get() + " Terminal List"; _zoneTerminalUnitList.setString(ZoneTerminalUnitListFields::ZoneTerminalUnitListName,terminalUnitListName); idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::ZoneTerminalUnitListName,terminalUnitListName); m_idfObjects.push_back(_zoneTerminalUnitList); std::vector<ZoneHVACTerminalUnitVariableRefrigerantFlow> terminals = modelObject.terminals(); for( auto & terminal : terminals ) { boost::optional<IdfObject> _terminal = translateAndMapModelObject(terminal); OS_ASSERT(_terminal); IdfExtensibleGroup eg = _zoneTerminalUnitList.pushExtensibleGroup(); eg.setString(ZoneTerminalUnitListExtensibleFields::ZoneTerminalUnitName,_terminal->name().get()); } // WaterCondenserVolumeFlowRate if( modelObject.isWaterCondenserVolumeFlowRateAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::WaterCondenserVolumeFlowRate,"Autosize"); } else if( (value = modelObject.waterCondenserVolumeFlowRate()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::WaterCondenserVolumeFlowRate,value.get()); } // EvaporativeCondenserEffectiveness if( (value = modelObject.evaporativeCondenserEffectiveness()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserEffectiveness,value.get()); } // EvaporativeCondenserAirFlowRate if( modelObject.isEvaporativeCondenserAirFlowRateAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserAirFlowRate,"Autosize"); } else if( (value = modelObject.evaporativeCondenserAirFlowRate()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserAirFlowRate,value.get()); } // EvaporativeCondenserPumpRatedPowerConsumption if( modelObject.isEvaporativeCondenserPumpRatedPowerConsumptionAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserPumpRatedPowerConsumption,"Autosize"); } else if( (value = modelObject.evaporativeCondenserPumpRatedPowerConsumption()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserPumpRatedPowerConsumption,value.get()); } // BasinHeaterCapacity if( (value = modelObject.basinHeaterCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterCapacity,value.get()); } // BasinHeaterSetpointTemperature if( (value = modelObject.basinHeaterSetpointTemperature()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterSetpointTemperature,value.get()); } // BasinHeaterOperatingScheduleName if( boost::optional<model::Schedule> schedule = modelObject.basinHeaterOperatingSchedule() ) { if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterOperatingScheduleName,_schedule->name().get()); } } // FuelType if( (s = modelObject.fuelType()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::FuelType,s.get()); } // MinimumOutdoorTemperatureinHeatRecoveryMode if( (value = modelObject.minimumOutdoorTemperatureinHeatRecoveryMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumOutdoorTemperatureinHeatRecoveryMode,value.get()); } // MaximumOutdoorTemperatureinHeatRecoveryMode if( (value = modelObject.maximumOutdoorTemperatureinHeatRecoveryMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorTemperatureinHeatRecoveryMode,value.get()); } // HeatRecoveryCoolingCapacityModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryCoolingCapacityModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingCapacityModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryCoolingCapacityFraction if( (value = modelObject.initialHeatRecoveryCoolingCapacityFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryCoolingCapacityFraction,value.get()); } // HeatRecoveryCoolingCapacityTimeConstant if( (value = modelObject.heatRecoveryCoolingCapacityTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingCapacityTimeConstant,value.get()); } // HeatRecoveryCoolingEnergyModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryCoolingEnergyModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingEnergyModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryCoolingEnergyFraction if( (value = modelObject.initialHeatRecoveryCoolingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryCoolingEnergyFraction,value.get()); } // HeatRecoveryCoolingEnergyTimeConstant if( (value = modelObject.heatRecoveryCoolingEnergyTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingEnergyTimeConstant,value.get()); } // HeatRecoveryHeatingCapacityModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryHeatingCapacityModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingCapacityModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryHeatingCapacityFraction if( (value = modelObject.initialHeatRecoveryHeatingCapacityFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryHeatingCapacityFraction,value.get()); } // HeatRecoveryHeatingCapacityTimeConstant if( (value = modelObject.heatRecoveryHeatingCapacityTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingCapacityTimeConstant,value.get()); } // HeatRecoveryHeatingEnergyModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryHeatingEnergyModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingEnergyModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryHeatingEnergyFraction if( (value = modelObject.initialHeatRecoveryHeatingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryHeatingEnergyFraction,value.get()); } // HeatRecoveryHeatingEnergyTimeConstant if( (value = modelObject.heatRecoveryHeatingEnergyTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingEnergyTimeConstant,value.get()); } return idfObject; } } // energyplus } // openstudio
39.309959
162
0.784132
mehrdad-shokri
1188967c68e1fe9048a3f5f1a97d44ee8d18c56d
4,196
cpp
C++
exotations/task_maps/task_map/src/Point2Line.cpp
LongfeiProjects/exotica
206b296edf9bf3b653ca3984b1449151ca17d374
[ "BSD-3-Clause" ]
1
2019-04-12T20:26:59.000Z
2019-04-12T20:26:59.000Z
exotations/task_maps/task_map/src/Point2Line.cpp
LongfeiProjects/exotica
206b296edf9bf3b653ca3984b1449151ca17d374
[ "BSD-3-Clause" ]
null
null
null
exotations/task_maps/task_map/src/Point2Line.cpp
LongfeiProjects/exotica
206b296edf9bf3b653ca3984b1449151ca17d374
[ "BSD-3-Clause" ]
null
null
null
/* * Author: Christian Rauch * * Copyright (c) 2018, University Of Edinburgh * 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 nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "task_map/Point2Line.hpp" REGISTER_TASKMAP_TYPE("Point2Line", exotica::Point2Line); namespace exotica { Eigen::Vector3d Point2Line::distance(const Eigen::Vector3d &point, const Eigen::Vector3d &line, const bool infinite, const bool dbg) { // http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html // let: // s: start of line // e: end of line // p: point // then the point on vector v = e-s that is closest to p is vp = s + t*(e-s) with // t = ((s-p)*(e-s)) / (|e-s|^2) (* denotes the dot product) // the line starts at the origin of BaseOffset, hence s=0, v='line', vp=t*'line' double t = (-point).dot(line) / line.norm(); if (dbg) HIGHLIGHT_NAMED("P2L", "t " << t); if (!infinite) { // clip to to range [0,1] t = std::min(std::max(0.0, t), 1.0); if (dbg) HIGHLIGHT_NAMED("P2L", "|t| " << t); } // vector from point 'p' to point 'vp' on line const Eigen::Vector3d dv = (t * line) - point; if (dbg) HIGHLIGHT_NAMED("P2L", "dv " << dv.transpose()); return dv; } Point2Line::Point2Line() {} void Point2Line::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if (phi.rows() != Kinematics[0].Phi.rows()) throw_named("Wrong size of phi!"); for (int i = 0; i < Kinematics[0].Phi.rows(); i++) { phi(i) = distance(Eigen::Map<const Eigen::Vector3d>(Kinematics[0].Phi(i).p.data), line, infinite, debug_).norm(); } } void Point2Line::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if (phi.rows() != Kinematics[0].Phi.rows()) throw_named("Wrong size of phi!"); if (J.rows() != Kinematics[0].J.rows() || J.cols() != Kinematics[0].J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics[0].J(0).data.cols()); for (int i = 0; i < Kinematics[0].Phi.rows(); i++) { // direction from point to line const Eigen::Vector3d dv = distance(Eigen::Map<const Eigen::Vector3d>(Kinematics[0].Phi(i).p.data), line, infinite, debug_); phi(i) = dv.norm(); for (int j = 0; j < J.cols(); j++) { J(i, j) = -dv.dot(Eigen::Map<const Eigen::Vector3d>(Kinematics[0].J[i].getColumn(j).vel.data)) / dv.norm(); } } } void Point2Line::Instantiate(Point2LineInitializer &init) { line = init.EndPoint.head<3>() - boost::any_cast<Eigen::VectorXd>(init.EndEffector[0].getProperty("BaseOffset")).head<3>(); infinite = init.infinite; } int Point2Line::taskSpaceDim() { return Kinematics[0].Phi.rows(); } } // namespace exotica
40.346154
157
0.664919
LongfeiProjects
118c65525d22b302d8badb189bc39e171ea277d6
4,784
cpp
C++
world.cpp
rob05c/cppmud
2fc4cda4373d273fab49dd23975e278fa39ca28d
[ "MIT" ]
null
null
null
world.cpp
rob05c/cppmud
2fc4cda4373d273fab49dd23975e278fa39ca28d
[ "MIT" ]
null
null
null
world.cpp
rob05c/cppmud
2fc4cda4373d273fab49dd23975e278fa39ca28d
[ "MIT" ]
null
null
null
#include <atomic> #include <algorithm> #include <thread> #include <chrono> #include "world.hpp" #include "util.hpp" #include "player.hpp" #include "dir.hpp" #include "room.hpp" #include "object.hpp" World::World() { this->self = std::shared_ptr<World>(this); this->startActorThread(); } World::~World() { this->destructing = true; this->actorThread.join(); this->nextID = 1; // start at 1, so any default-initialized ids are never valid. } ID World::NextID() { return this->nextID.fetch_add(1, std::memory_order_relaxed); // TODO verify order } void World::AddRoom(std::shared_ptr<Room> r) { this->rooms[r->ID] = r; this->room_links[r->ID] = std::map<Direction, RoomID>(); } void World::AddPlayer(std::shared_ptr<Player> player, RoomID room_id) { this->players[player->ID] = player; this->name_players[player->Name] = player->ID; this->SetPlayerRoom(player->ID, room_id); } void World::AddObject(std::shared_ptr<Object> obj, PlayerID player_id) { this->objects[obj->ID] = obj; // TODO handle player not existing. Handle errors everywhere. Go has ruined me. std::shared_ptr<Player> player = this->GetPlayer(player_id); player->Objects[obj->ID] = obj; obj->LocationID.Player = player_id; obj->LocationType = ObjectLocationPlayer; } // LinkRooms links the two rooms in both direction, where the Direction is from room0 to room1. // TODO add a special function for one-way paths. void World::LinkRooms(RoomID room0, RoomID room1, Direction dir) { this->room_links[room0][dir] = room1; this->room_links[room1][reverse_direction(dir)] = room0; } void World::SetPlayerRoom(PlayerID playerID, RoomID newRoomID) { const auto oldPlayerRoomID = this->player_rooms.find(playerID); if(oldPlayerRoomID != this->player_rooms.end()) { auto playerSet = this->room_players.find(oldPlayerRoomID->second); playerSet->second.erase(playerID); // TODO check and error if world.room_players[room] doesn't exist (should never happen) } this->player_rooms[playerID] = newRoomID; this->room_players[newRoomID].insert(playerID); } void World::SetObjectRoom(ObjectID object_id, RoomID new_room_id) { std::shared_ptr<Object> obj = this->objects[object_id]; switch(obj->LocationType) { case ObjectLocationRoom: { RoomID old_room_id = obj->LocationID.Room; std::shared_ptr<Room> old_room(this->rooms[old_room_id]); old_room->Objects.erase(object_id); break; } case ObjectLocationPlayer: { PlayerID player_id = obj->LocationID.Player; std::shared_ptr<Player> player = this->players[player_id]; player->Objects.erase(object_id); break; } default: { // TODO handle error; should never happen return; } } std::shared_ptr<Room> room = this->rooms[new_room_id]; room->Objects[object_id] = obj; obj->LocationType = ObjectLocationRoom; obj->LocationID.Room = new_room_id; // TODO print the move to players in previous and new room } void World::startActorThread() { // TODO change to something lighter weight than an OS thread // TBB? Microthread? Poll? Something else? this->actorThread = std::thread([=]() { for(;;) { if(this->destructing) { return; } for(auto it = this->objects.begin(), end = this->objects.end(); it != end; ++it) { std::shared_ptr<Object> obj = it->second; if(obj->Actor_ == nullptr) { continue; } obj->Actor_->Do(this->GetShared(), obj->ID); } std::this_thread::sleep_for(std::chrono::milliseconds(this->ActorThreadIntervalMS)); } }); } // GetPlayer returns the player with the given ID. // If the ID doesn't exist, returns NULL. std::shared_ptr<Player> World::GetPlayer(PlayerID v) { return this->players[v]; } // GetRoom returns the room with the given ID. // If the ID doesn't exist, returns NULL. std::shared_ptr<Room> World::GetRoom(RoomID v) { return this->rooms[v]; } // GetObject returns the object with the given ID. // If the ID doesn't exist, returns NULL. std::shared_ptr<Object> World::GetObject(ObjectID v) { return this->objects[v]; } // Returns the room the given player is in. RoomID World::GetPlayerRoom(PlayerID v) { // TODO change to return a bool? If a room didn't exist, it would be a subtle bug bug // But, players should always be in a room, right? return this->player_rooms[v]; } std::map<Direction, RoomID> World::GetRoomLinks(RoomID v) { // TODO change to return a bool? If a room didn't exist, it would be a very subtle bug return this->room_links[v]; } PlayerID World::GetPlayerByName(std::string name) { // TODO change to return a bool? If a player didn't exist, it would be a very subtle bug return this->name_players[name]; } std::shared_ptr<World> World::GetShared() { return self; } LockedWorld::LockedWorld(LockableWorld w) { w.m->lock(); this->w = w.w; this->l = w; } LockedWorld::~LockedWorld() { l.m->unlock(); }
29.170732
124
0.709448
rob05c
118e303a8acf839dfd2e6f6b61cd81966dc92ebd
3,695
hpp
C++
Adobe/Illustrator/plugin/Illustrator2019SDK/illustratorapi/illustrator/AIContract.hpp
MingboPeng/rhino.inside
9fdb1cf1c72e8f16e2e75509c48d22b15e61bef5
[ "MIT" ]
317
2018-08-23T19:43:37.000Z
2022-03-12T04:22:20.000Z
Adobe/Illustrator/plugin/Illustrator2019SDK/illustratorapi/illustrator/AIContract.hpp
hiroyainage/rhino.inside
d4bc5d212a3e7492cc0dd18af541232c24bf9117
[ "MIT" ]
90
2018-10-23T17:11:15.000Z
2022-03-12T12:47:39.000Z
Adobe/Illustrator/plugin/Illustrator2019SDK/illustratorapi/illustrator/AIContract.hpp
hiroyainage/rhino.inside
d4bc5d212a3e7492cc0dd18af541232c24bf9117
[ "MIT" ]
153
2018-09-12T02:16:55.000Z
2022-03-30T04:30:52.000Z
/************************************************************************* * * ADOBE CONFIDENTIAL * * Copyright 2017 Adobe * * All Rights Reserved. * * NOTICE: Adobe permits you to use, modify, and distribute this file in * accordance with the terms of the Adobe license agreement accompanying * it. If you have received this file from a source other than Adobe, * then your use, modification, or distribution of it requires the prior * written permission of Adobe. * **************************************************************************/ #pragma once #include "AITypes.h" #include "AIAssert.hpp" #include "IAILiteralString.h" /** Usage: struct Widget { ai::int32 id = -1; bool processed = false; std::string name; }; std::unique_ptr<Widget> CreateWidget(); void ProcessWidget() { auto widget1 = CreateWidget(); auto widget2 = CreateWidget(); ai::Expects(widget1 != nullptr); // Throws by default ai::Expects(widget2 != nullptr, "Widget should not be NULL"); // Throws with custom message ai::Expects(widget1->id != -1, "Wrong widget id", ai::ContractPolicy::kAssert); // Only Assert ai::Expects(!widget1->name.empty(), "Wrong widget name", ai::ContractPolicy::kAssert); // Only Assert // ... // ... ai::Ensures(widget1->processed == true, "Widget should be processed", ai::ContractPolicy::kAssertAndThrow); // Assert and Throw ai::Ensures(widget2->processed == true, ai::ContractPolicy::kAssertAndThrow); // Assert and Throw } */ namespace ai { namespace Contract { constexpr ai::LiteralString kDefaultPreconditionMsg {"Failed Precondition"}; constexpr ai::LiteralString kDefaultPostconditionMsg {"Failed Postcondition"}; /** Exception class for Contract violation */ struct Violation : public ai::LogicError { explicit Violation(const char* message) : ai::LogicError(kBadParameterErr, message) { } }; /** Contract policy types */ struct AssertPolicy {}; struct ThrowPolicy {}; struct AssertAndThrowPolicy {}; /** Contract verification */ template <typename T> /* Assert */ inline void Check(T condition, const char* msg, AssertPolicy) { AIMsgAssert(condition, msg); } template <typename T> /* Throw */ inline void Check(T condition, const char* msg, ThrowPolicy) { if (!condition) { throw Violation{msg}; } } template <typename T> /* Assert and Throw */ inline void Check(T condition, const char* msg, AssertAndThrowPolicy) { if (!condition) { AIMsgAssert(false, msg); throw Violation{msg}; } } } // namespace Contract namespace ContractPolicy { // Instances of the Contract policy types constexpr Contract::AssertPolicy kAssert {}; constexpr Contract::ThrowPolicy kThrow {}; constexpr Contract::AssertAndThrowPolicy kAssertAndThrow {}; } // namespace ContractPolicy template <typename T, typename Policy = Contract::ThrowPolicy> inline void Expects(T condition, const char* msg = Contract::kDefaultPreconditionMsg, Policy policy = ContractPolicy::kThrow) { Contract::Check(condition, msg, policy); } template <typename T, typename Policy> inline void Expects(T condition, Policy policy) { Contract::Check(condition, Contract::kDefaultPreconditionMsg, policy); } template <typename T, typename Policy = Contract::ThrowPolicy> inline void Ensures(T condition, const char* msg = Contract::kDefaultPostconditionMsg, Policy policy = ContractPolicy::kThrow) { Contract::Check(condition, msg, policy); } template <typename T, typename Policy> inline void Ensures(T condition, Policy policy) { Contract::Check(condition, Contract::kDefaultPostconditionMsg, policy); } } // namespace ai
25.659722
129
0.679567
MingboPeng
119170a78d4fabfeffcc1bb49d5b6ccb9568f99b
6,579
hpp
C++
libs/EXTERNAL/libtatum/libtatum/tatum/tags/TimingTag.hpp
brycejh/vtr-verilog-to-routing
f61da5eb2d4e008728a01def827d55a0e9f285d0
[ "MIT" ]
682
2015-07-10T00:39:26.000Z
2022-03-30T05:24:53.000Z
libs/EXTERNAL/libtatum/libtatum/tatum/tags/TimingTag.hpp
brycejh/vtr-verilog-to-routing
f61da5eb2d4e008728a01def827d55a0e9f285d0
[ "MIT" ]
1,399
2015-07-24T22:09:09.000Z
2022-03-29T06:22:48.000Z
libs/EXTERNAL/libtatum/libtatum/tatum/tags/TimingTag.hpp
brycejh/vtr-verilog-to-routing
f61da5eb2d4e008728a01def827d55a0e9f285d0
[ "MIT" ]
311
2015-07-09T13:59:48.000Z
2022-03-28T00:15:20.000Z
#pragma once #include <iosfwd> #include <limits> #include "tatum/Time.hpp" #include "tatum/TimingGraphFwd.hpp" namespace tatum { enum class TagType : unsigned char { CLOCK_LAUNCH, CLOCK_CAPTURE, DATA_ARRIVAL, DATA_REQUIRED, SLACK, UNKOWN }; class TimingTag; std::ostream& operator<<(std::ostream& os, TagType type); bool is_const_gen_tag(const TimingTag& tag); /** * The 'TimingTag' class represents an individual timing tag: the information associated * with a node's arrival/required times. * * * This primarily includes the actual arrival and required time, but also * auxillary metadata such as the clock domain, and launching node. * * The clock domain in particular is used to tag arrival/required times from different * clock domains at a single node. This enables us to perform only a single graph traversal * and still analyze mulitple clocks. * * NOTE: Timing analyzers usually operate on the collection of tags at a particular node. * This is modelled by the separate 'TimingTags' class. */ class TimingTag { public: //Static //Returns a tag suitable for use at a constant generator, during //setup analysis. // ///In particular it's domains are left invalid (i.e. wildcards), //and it's arrival time set to -inf (so it will be maxed out by //any non-constant tag) static TimingTag CONST_GEN_TAG_SETUP() { return TimingTag(Time(-std::numeric_limits<float>::infinity()), DomainId::INVALID(), DomainId::INVALID(), NodeId::INVALID(), TagType::DATA_ARRIVAL); } //Returns a tag suitable for use at a constant generator, during //hold analysis. // ///In particular it's domains are left invalid (i.e. wildcards), //and it's arrival time set to +inf (so it will be minned out by //any non-constant tag) static TimingTag CONST_GEN_TAG_HOLD() { return TimingTag(Time(+std::numeric_limits<float>::infinity()), DomainId::INVALID(), DomainId::INVALID(), NodeId::INVALID(), TagType::DATA_ARRIVAL); } public: //Constructors TimingTag(); ///\param arr_time_val The tagged arrival time ///\param req_time_val The tagged required time ///\param launch_domain The clock domain the tag was launched from ///\param capture_domain The clock domain the tag was captured on ///\param node The origin node's id (e.g. source/sink that originally launched/required this tag) TimingTag(const Time& time_val, DomainId launch_domain, DomainId capture_domain, NodeId node, TagType type); ///\param arr_time_val The tagged arrival time ///\param req_time_val The tagged required time ///\param base_tag The tag from which to copy auxilary meta-data (e.g. domain, launch node) TimingTag(const Time& time_val, NodeId origin, const TimingTag& base_tag); public: //Accessors ///\returns This tag's arrival time const Time& time() const { return time_; } ///\returns This tag's launching clock domain DomainId launch_clock_domain() const { return launch_clock_domain_; } DomainId capture_clock_domain() const { return capture_clock_domain_; } ///\returns This tag's launching node's id NodeId origin_node() const { return origin_node_; } TagType type() const { return type_; } public: //Utility friend bool operator==(const TimingTag& lhs, const TimingTag& rhs); friend bool operator!=(const TimingTag& lhs, const TimingTag& rhs); public: //Mutators ///\param new_time The new value set as the tag's time void set_time(const Time& new_time) { time_ = new_time; } ///\param new_clock_domain The new value set as the tag's source clock domain void set_launch_clock_domain(const DomainId new_clock_domain) { launch_clock_domain_ = new_clock_domain; } ///\param new_clock_domain The new value set as the tag's capture clock domain void set_capture_clock_domain(const DomainId new_clock_domain) { capture_clock_domain_ = new_clock_domain; } ///\param new_launch_node The new value set as the tag's launching node void set_origin_node(const NodeId new_origin_node) { origin_node_ = new_origin_node; } void set_type(const TagType new_type) { type_ = new_type; } /* * Modification operations * For the following the passed in time is maxed/minned with the * respective arr/req time. If the value of this tag is updated * the meta-data (domain, launch node etc) are copied from the * base tag */ ///Updates the tag's arrival time if new_arr_time is larger than the current arrival time. ///If the arrival time is updated, meta-data is also updated from base_tag ///\param new_arr_time The arrival time to compare against ///\param base_tag The tag from which meta-data is copied ///\returns true if the tag is modified, false otherwise bool max(const Time& new_time, const NodeId origin, const TimingTag& base_tag); ///Updates the tag's arrival time if new_arr_time is smaller than the current arrival time. ///If the arrival time is updated, meta-data is also updated from base_tag ///\param new_arr_time The arrival time to compare against ///\param base_tag The tag from which meta-data is copied ///\returns true if the tag is modified, false otherwise bool min(const Time& new_time, const NodeId origin, const TimingTag& base_tag); private: bool update(const Time& new_time, const NodeId origin, const TimingTag& base_tag); /* * Data */ Time time_; //Required time NodeId origin_node_; //Node which launched this arr/req time DomainId launch_clock_domain_; //Clock domain for arr/req times DomainId capture_clock_domain_; //Clock domain for arr/req times TagType type_; }; //For comparing the values of two timing tags struct TimingTagValueComp { bool operator()(const tatum::TimingTag& lhs, const tatum::TimingTag& rhs) { return lhs.time().value() < rhs.time().value(); } }; } //namepsace //Implementation #include "TimingTag.inl"
40.611111
116
0.655115
brycejh
1192580c35b8ba8a70cae37da2a7adeb26e3a1d5
510
hpp
C++
include/mppic/optimization/MotionModel.hpp
SteveMacenski/mppic
539d78a41777afba0d9a2195b6076a9167ed27a2
[ "MIT" ]
null
null
null
include/mppic/optimization/MotionModel.hpp
SteveMacenski/mppic
539d78a41777afba0d9a2195b6076a9167ed27a2
[ "MIT" ]
null
null
null
include/mppic/optimization/MotionModel.hpp
SteveMacenski/mppic
539d78a41777afba0d9a2195b6076a9167ed27a2
[ "MIT" ]
1
2022-03-27T01:44:43.000Z
2022-03-27T01:44:43.000Z
#pragma once #include <cstdint> #include <string> #include <unordered_map> namespace mppi::optimization { enum class MotionModel : uint8_t { Omni, DiffDrive, Carlike }; inline bool isHolonomic(MotionModel motion_model) { return (motion_model == MotionModel::Omni) ? true : false; } const inline std::unordered_map<std::string, MotionModel> MOTION_MODEL_NAMES_MAP = { {"diff", MotionModel::DiffDrive}, {"carlike", MotionModel::Carlike}, {"omni", MotionModel::Omni}}; } // namespace mppi::optimization
25.5
100
0.739216
SteveMacenski
119387e8f1d5c691234c6638eb5bca63a2f902c4
2,178
hpp
C++
src/engine/systems/physics_system/physics_system.hpp
Jean-LouisH/Omnia
e637746839801eb73707d10e3243d4a430dfea78
[ "MIT" ]
null
null
null
src/engine/systems/physics_system/physics_system.hpp
Jean-LouisH/Omnia
e637746839801eb73707d10e3243d4a430dfea78
[ "MIT" ]
null
null
null
src/engine/systems/physics_system/physics_system.hpp
Jean-LouisH/Omnia
e637746839801eb73707d10e3243d4a430dfea78
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2020 Jean-Louis Haywood // // 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. #pragma once #include "application/scene/scene.hpp" #include "system.hpp" namespace Omnia { /* Processes Components related to time and classical mechanics physics simulations. */ class PhysicsSystem : public System { public: ~PhysicsSystem(); void setMsPerComputeUpdate(uint32_t msPerComputeUpdate); virtual void initialize() override; void process(std::shared_ptr<Scene> scene) override; virtual void deinitialize() override; void onComputeEnd(std::shared_ptr<Scene> scene); private: float secondsPerComputeUpdate = 0.008; void updateTimers(std::shared_ptr<SceneTree> scene); void displace(std::shared_ptr<SceneTree> scene); void gravitate(std::shared_ptr<SceneTree> scene); void decelerate(std::shared_ptr<SceneTree> scene); void applyForces(std::shared_ptr<SceneTree> scene); void detectCollisions(std::shared_ptr<SceneTree> scene); void handleCollisions(std::shared_ptr<SceneTree> scene); void displaceEntityTree(std::shared_ptr<SceneTree> sceneTree, EntityID entityID, glm::vec3 value); }; }
39.6
100
0.76584
Jean-LouisH
1194ed9c749b1158dee62afbb44c4cd53c101ef0
17,312
cc
C++
media/cast/logging/encoding_event_subscriber_unittest.cc
halton/chromium-crosswalk
bfcca582b723b9535907f0b410b920ef99911b70
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/cast/logging/encoding_event_subscriber_unittest.cc
halton/chromium-crosswalk
bfcca582b723b9535907f0b410b920ef99911b70
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/cast/logging/encoding_event_subscriber_unittest.cc
halton/chromium-crosswalk
bfcca582b723b9535907f0b410b920ef99911b70
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/test/simple_test_tick_clock.h" #include "base/time/tick_clock.h" #include "media/cast/cast_environment.h" #include "media/cast/logging/encoding_event_subscriber.h" #include "media/cast/logging/logging_defines.h" #include "media/cast/test/fake_single_thread_task_runner.h" #include "testing/gtest/include/gtest/gtest.h" using media::cast::proto::AggregatedFrameEvent; using media::cast::proto::AggregatedPacketEvent; using media::cast::proto::BasePacketEvent; namespace media { namespace cast { class EncodingEventSubscriberTest : public ::testing::Test { protected: EncodingEventSubscriberTest() : testing_clock_(new base::SimpleTestTickClock()), task_runner_(new test::FakeSingleThreadTaskRunner(testing_clock_)), cast_environment_(new CastEnvironment( scoped_ptr<base::TickClock>(testing_clock_).Pass(), task_runner_, task_runner_, task_runner_, task_runner_, task_runner_, task_runner_, GetLoggingConfigWithRawEventsAndStatsEnabled())) {} void Init(EventMediaType event_media_type) { DCHECK(!event_subscriber_); event_subscriber_.reset(new EncodingEventSubscriber(event_media_type, 10)); cast_environment_->Logging()->AddRawEventSubscriber( event_subscriber_.get()); } virtual ~EncodingEventSubscriberTest() { if (event_subscriber_) { cast_environment_->Logging()->RemoveRawEventSubscriber( event_subscriber_.get()); } } base::SimpleTestTickClock* testing_clock_; // Owned by CastEnvironment. scoped_refptr<test::FakeSingleThreadTaskRunner> task_runner_; scoped_refptr<CastEnvironment> cast_environment_; scoped_ptr<EncodingEventSubscriber> event_subscriber_; }; TEST_F(EncodingEventSubscriberTest, FrameEventTruncating) { Init(VIDEO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); // Entry with RTP timestamp 0 should get dropped. for (int i = 0; i < 11; i++) { cast_environment_->Logging()->InsertFrameEvent(now, kVideoFrameCaptured, i * 100, /*frame_id*/ 0); cast_environment_->Logging()->InsertFrameEvent(now, kVideoFrameDecoded, i * 100, /*frame_id*/ 0); } FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(10u, frame_events.size()); EXPECT_EQ(100u, frame_events.begin()->first); EXPECT_EQ(1000u, frame_events.rbegin()->first); } TEST_F(EncodingEventSubscriberTest, PacketEventTruncating) { Init(AUDIO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); // Entry with RTP timestamp 0 should get dropped. for (int i = 0; i < 11; i++) { cast_environment_->Logging()->InsertPacketEvent(now, kAudioPacketReceived, /*rtp_timestamp*/ i * 100, /*frame_id*/ 0, /*packet_id*/ i, /*max_packet_id*/ 10, /*size*/ 123); } PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(10u, packet_events.size()); EXPECT_EQ(100u, packet_events.begin()->first); EXPECT_EQ(1000u, packet_events.rbegin()->first); } TEST_F(EncodingEventSubscriberTest, EventFiltering) { Init(VIDEO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; cast_environment_->Logging()->InsertFrameEvent(now, kVideoFrameDecoded, rtp_timestamp, /*frame_id*/ 0); // This is an AUDIO_EVENT and shouldn't be processed by the subscriber. cast_environment_->Logging()->InsertFrameEvent(now, kAudioFrameDecoded, rtp_timestamp, /*frame_id*/ 0); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); FrameEventMap::iterator frame_it = frame_events.find(rtp_timestamp); ASSERT_TRUE(frame_it != frame_events.end()); linked_ptr<AggregatedFrameEvent> frame_event = frame_it->second; ASSERT_EQ(1, frame_event->event_type_size()); EXPECT_EQ(media::cast::proto::VIDEO_FRAME_DECODED, frame_event->event_type(0)); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); EXPECT_TRUE(packet_events.empty()); } TEST_F(EncodingEventSubscriberTest, FrameEvent) { Init(VIDEO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; cast_environment_->Logging()->InsertFrameEvent(now, kVideoFrameDecoded, rtp_timestamp, /*frame_id*/ 0); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(1u, frame_events.size()); FrameEventMap::iterator it = frame_events.find(rtp_timestamp); ASSERT_TRUE(it != frame_events.end()); linked_ptr<AggregatedFrameEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->event_type_size()); EXPECT_EQ(media::cast::proto::VIDEO_FRAME_DECODED, event->event_type(0)); ASSERT_EQ(1, event->event_timestamp_micros_size()); EXPECT_EQ(now.ToInternalValue(), event->event_timestamp_micros(0)); EXPECT_EQ(0, event->encoded_frame_size()); EXPECT_EQ(0, event->delay_millis()); event_subscriber_->GetFrameEventsAndReset(&frame_events); EXPECT_TRUE(frame_events.empty()); } TEST_F(EncodingEventSubscriberTest, FrameEventDelay) { Init(AUDIO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int delay_ms = 100; cast_environment_->Logging()->InsertFrameEventWithDelay( now, kAudioPlayoutDelay, rtp_timestamp, /*frame_id*/ 0, base::TimeDelta::FromMilliseconds(delay_ms)); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(1u, frame_events.size()); FrameEventMap::iterator it = frame_events.find(rtp_timestamp); ASSERT_TRUE(it != frame_events.end()); linked_ptr<AggregatedFrameEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->event_type_size()); EXPECT_EQ(media::cast::proto::AUDIO_PLAYOUT_DELAY, event->event_type(0)); ASSERT_EQ(1, event->event_timestamp_micros_size()); EXPECT_EQ(now.ToInternalValue(), event->event_timestamp_micros(0)); EXPECT_EQ(0, event->encoded_frame_size()); EXPECT_EQ(100, event->delay_millis()); } TEST_F(EncodingEventSubscriberTest, FrameEventSize) { Init(VIDEO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int size = 123; cast_environment_->Logging()->InsertFrameEventWithSize( now, kVideoFrameEncoded, rtp_timestamp, /*frame_id*/ 0, size); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(1u, frame_events.size()); FrameEventMap::iterator it = frame_events.find(rtp_timestamp); ASSERT_TRUE(it != frame_events.end()); linked_ptr<AggregatedFrameEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->event_type_size()); EXPECT_EQ(media::cast::proto::VIDEO_FRAME_ENCODED, event->event_type(0)); ASSERT_EQ(1, event->event_timestamp_micros_size()); EXPECT_EQ(now.ToInternalValue(), event->event_timestamp_micros(0)); EXPECT_EQ(size, event->encoded_frame_size()); EXPECT_EQ(0, event->delay_millis()); } TEST_F(EncodingEventSubscriberTest, MultipleFrameEvents) { Init(AUDIO_EVENT); RtpTimestamp rtp_timestamp1 = 100; RtpTimestamp rtp_timestamp2 = 200; base::TimeTicks now1(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertFrameEventWithDelay( now1, kAudioPlayoutDelay, rtp_timestamp1, /*frame_id*/ 0, /*delay*/ base::TimeDelta::FromMilliseconds(100)); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now2(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertFrameEventWithSize( now2, kAudioFrameEncoded, rtp_timestamp2, /*frame_id*/ 0, /*size*/ 123); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now3(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertFrameEvent( now3, kAudioFrameDecoded, rtp_timestamp1, /*frame_id*/ 0); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(2u, frame_events.size()); FrameEventMap::iterator it = frame_events.find(100); ASSERT_TRUE(it != frame_events.end()); linked_ptr<AggregatedFrameEvent> event = it->second; EXPECT_EQ(rtp_timestamp1, event->rtp_timestamp()); ASSERT_EQ(2, event->event_type_size()); EXPECT_EQ(media::cast::proto::AUDIO_PLAYOUT_DELAY, event->event_type(0)); EXPECT_EQ(media::cast::proto::AUDIO_FRAME_DECODED, event->event_type(1)); ASSERT_EQ(2, event->event_timestamp_micros_size()); EXPECT_EQ(now1.ToInternalValue(), event->event_timestamp_micros(0)); EXPECT_EQ(now3.ToInternalValue(), event->event_timestamp_micros(1)); it = frame_events.find(200); ASSERT_TRUE(it != frame_events.end()); event = it->second; EXPECT_EQ(rtp_timestamp2, event->rtp_timestamp()); ASSERT_EQ(1, event->event_type_size()); EXPECT_EQ(media::cast::proto::AUDIO_FRAME_ENCODED, event->event_type(0)); ASSERT_EQ(1, event->event_timestamp_micros_size()); EXPECT_EQ(now2.ToInternalValue(), event->event_timestamp_micros(0)); } TEST_F(EncodingEventSubscriberTest, PacketEvent) { Init(AUDIO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int packet_id = 2; int size = 100; cast_environment_->Logging()->InsertPacketEvent( now, kAudioPacketReceived, rtp_timestamp, /*frame_id*/ 0, packet_id, /*max_packet_id*/ 10, size); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(1u, packet_events.size()); PacketEventMap::iterator it = packet_events.find(rtp_timestamp); ASSERT_TRUE(it != packet_events.end()); linked_ptr<AggregatedPacketEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->base_packet_event_size()); const BasePacketEvent& base_event = event->base_packet_event(0); EXPECT_EQ(packet_id, base_event.packet_id()); ASSERT_EQ(1, base_event.event_type_size()); EXPECT_EQ(media::cast::proto::AUDIO_PACKET_RECEIVED, base_event.event_type(0)); ASSERT_EQ(1, base_event.event_timestamp_micros_size()); EXPECT_EQ(now.ToInternalValue(), base_event.event_timestamp_micros(0)); event_subscriber_->GetPacketEventsAndReset(&packet_events); EXPECT_TRUE(packet_events.empty()); } TEST_F(EncodingEventSubscriberTest, MultiplePacketEventsForPacket) { Init(OTHER_EVENT); base::TimeTicks now1(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int packet_id = 2; int size = 100; cast_environment_->Logging()->InsertPacketEvent( now1, kPacketSentToPacer, rtp_timestamp, /*frame_id*/ 0, packet_id, /*max_packet_id*/ 10, size); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now2(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertPacketEvent( now2, kPacketSentToNetwork, rtp_timestamp, /*frame_id*/ 0, packet_id, /*max_packet_id*/ 10, size); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(1u, packet_events.size()); PacketEventMap::iterator it = packet_events.find(rtp_timestamp); ASSERT_TRUE(it != packet_events.end()); linked_ptr<AggregatedPacketEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->base_packet_event_size()); const BasePacketEvent& base_event = event->base_packet_event(0); EXPECT_EQ(packet_id, base_event.packet_id()); ASSERT_EQ(2, base_event.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_SENT_TO_PACER, base_event.event_type(0)); EXPECT_EQ(media::cast::proto::PACKET_SENT_TO_NETWORK, base_event.event_type(1)); ASSERT_EQ(2, base_event.event_timestamp_micros_size()); EXPECT_EQ(now1.ToInternalValue(), base_event.event_timestamp_micros(0)); EXPECT_EQ(now2.ToInternalValue(), base_event.event_timestamp_micros(1)); } TEST_F(EncodingEventSubscriberTest, MultiplePacketEventsForFrame) { Init(OTHER_EVENT); base::TimeTicks now1(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int packet_id_1 = 2; int packet_id_2 = 3; int size = 100; cast_environment_->Logging()->InsertPacketEvent( now1, kPacketSentToPacer, rtp_timestamp, /*frame_id*/ 0, packet_id_1, /*max_packet_id*/ 10, size); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now2(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertPacketEvent( now2, kPacketRetransmitted, rtp_timestamp, /*frame_id*/ 0, packet_id_2, /*max_packet_id*/ 10, size); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(1u, packet_events.size()); PacketEventMap::iterator it = packet_events.find(rtp_timestamp); ASSERT_TRUE(it != packet_events.end()); linked_ptr<AggregatedPacketEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(2, event->base_packet_event_size()); const BasePacketEvent& base_event = event->base_packet_event(0); EXPECT_EQ(packet_id_1, base_event.packet_id()); ASSERT_EQ(1, base_event.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_SENT_TO_PACER, base_event.event_type(0)); ASSERT_EQ(1, base_event.event_timestamp_micros_size()); EXPECT_EQ(now1.ToInternalValue(), base_event.event_timestamp_micros(0)); const BasePacketEvent& base_event_2 = event->base_packet_event(1); EXPECT_EQ(packet_id_2, base_event_2.packet_id()); ASSERT_EQ(1, base_event_2.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_RETRANSMITTED, base_event_2.event_type(0)); ASSERT_EQ(1, base_event_2.event_timestamp_micros_size()); EXPECT_EQ(now2.ToInternalValue(), base_event_2.event_timestamp_micros(0)); } TEST_F(EncodingEventSubscriberTest, MultiplePacketEvents) { Init(OTHER_EVENT); base::TimeTicks now1(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp_1 = 100; RtpTimestamp rtp_timestamp_2 = 200; int packet_id_1 = 2; int packet_id_2 = 3; int size = 100; cast_environment_->Logging()->InsertPacketEvent( now1, kPacketSentToPacer, rtp_timestamp_1, /*frame_id*/ 0, packet_id_1, /*max_packet_id*/ 10, size); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now2(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertPacketEvent( now2, kPacketRetransmitted, rtp_timestamp_2, /*frame_id*/ 0, packet_id_2, /*max_packet_id*/ 10, size); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(2u, packet_events.size()); PacketEventMap::iterator it = packet_events.find(rtp_timestamp_1); ASSERT_TRUE(it != packet_events.end()); linked_ptr<AggregatedPacketEvent> event = it->second; EXPECT_EQ(rtp_timestamp_1, event->rtp_timestamp()); ASSERT_EQ(1, event->base_packet_event_size()); const BasePacketEvent& base_event = event->base_packet_event(0); EXPECT_EQ(packet_id_1, base_event.packet_id()); ASSERT_EQ(1, base_event.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_SENT_TO_PACER, base_event.event_type(0)); ASSERT_EQ(1, base_event.event_timestamp_micros_size()); EXPECT_EQ(now1.ToInternalValue(), base_event.event_timestamp_micros(0)); it = packet_events.find(rtp_timestamp_2); ASSERT_TRUE(it != packet_events.end()); event = it->second; EXPECT_EQ(rtp_timestamp_2, event->rtp_timestamp()); ASSERT_EQ(1, event->base_packet_event_size()); const BasePacketEvent& base_event_2 = event->base_packet_event(0); EXPECT_EQ(packet_id_2, base_event_2.packet_id()); ASSERT_EQ(1, base_event_2.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_RETRANSMITTED, base_event_2.event_type(0)); ASSERT_EQ(1, base_event_2.event_timestamp_micros_size()); EXPECT_EQ(now2.ToInternalValue(), base_event_2.event_timestamp_micros(0)); } } // namespace cast } // namespace media
37.390929
80
0.71049
halton
11984da9a63001080bc3f57fde1a71f2b22afd32
10,216
cc
C++
util/mach/composite_mach_message_server_test.cc
hunter-packages/crashpad
3583c50a6575857abcf140f6ea3b8d11390205b3
[ "Apache-2.0" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
util/mach/composite_mach_message_server_test.cc
hunter-packages/crashpad
3583c50a6575857abcf140f6ea3b8d11390205b3
[ "Apache-2.0" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
util/mach/composite_mach_message_server_test.cc
hunter-packages/crashpad
3583c50a6575857abcf140f6ea3b8d11390205b3
[ "Apache-2.0" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2014 The Crashpad 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 "util/mach/composite_mach_message_server.h" #include <sys/types.h> #include "base/strings/stringprintf.h" #include "gtest/gtest.h" #include "test/gtest_death_check.h" #include "util/mach/mach_message.h" namespace crashpad { namespace test { namespace { TEST(CompositeMachMessageServer, Empty) { CompositeMachMessageServer server; EXPECT_TRUE(server.MachMessageServerRequestIDs().empty()); mach_msg_empty_rcv_t request = {}; EXPECT_EQ(sizeof(request.header), server.MachMessageServerRequestSize()); mig_reply_error_t reply = {}; EXPECT_EQ(sizeof(reply), server.MachMessageServerReplySize()); bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(MIG_BAD_ID, reply.RetCode); } class TestMachMessageHandler : public MachMessageServer::Interface { public: TestMachMessageHandler() : MachMessageServer::Interface(), request_ids_(), request_size_(0), reply_size_(0), return_code_(KERN_FAILURE), return_value_(false), destroy_complex_request_(false) { } ~TestMachMessageHandler() { } void SetReturnCodes(bool return_value, kern_return_t return_code, bool destroy_complex_request) { return_value_ = return_value; return_code_ = return_code; destroy_complex_request_ = destroy_complex_request; } void AddRequestID(mach_msg_id_t request_id) { request_ids_.insert(request_id); } void SetRequestSize(mach_msg_size_t request_size) { request_size_ = request_size; } void SetReplySize(mach_msg_size_t reply_size) { reply_size_ = reply_size; } // MachMessageServer::Interface: bool MachMessageServerFunction(const mach_msg_header_t* in, mach_msg_header_t* out, bool* destroy_complex_request) override { EXPECT_NE(request_ids_.end(), request_ids_.find(in->msgh_id)); *destroy_complex_request = destroy_complex_request_; PrepareMIGReplyFromRequest(in, out); SetMIGReplyError(out, return_code_); return return_value_; } std::set<mach_msg_id_t> MachMessageServerRequestIDs() override { return request_ids_; } mach_msg_size_t MachMessageServerRequestSize() override { return request_size_; } mach_msg_size_t MachMessageServerReplySize() override { return reply_size_; } private: std::set<mach_msg_id_t> request_ids_; mach_msg_size_t request_size_; mach_msg_size_t reply_size_; kern_return_t return_code_; bool return_value_; bool destroy_complex_request_; DISALLOW_COPY_AND_ASSIGN(TestMachMessageHandler); }; TEST(CompositeMachMessageServer, HandlerDoesNotHandle) { TestMachMessageHandler handler; CompositeMachMessageServer server; server.AddHandler(&handler); EXPECT_TRUE(server.MachMessageServerRequestIDs().empty()); mach_msg_empty_rcv_t request = {}; EXPECT_EQ(sizeof(request.header), server.MachMessageServerRequestSize()); mig_reply_error_t reply = {}; EXPECT_EQ(sizeof(reply), server.MachMessageServerReplySize()); bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(MIG_BAD_ID, reply.RetCode); EXPECT_FALSE(destroy_complex_request); } TEST(CompositeMachMessageServer, OneHandler) { const mach_msg_id_t kRequestID = 100; const mach_msg_size_t kRequestSize = 256; const mach_msg_size_t kReplySize = 128; const kern_return_t kReturnCode = KERN_SUCCESS; TestMachMessageHandler handler; handler.AddRequestID(kRequestID); handler.SetRequestSize(kRequestSize); handler.SetReplySize(kReplySize); handler.SetReturnCodes(true, kReturnCode, true); CompositeMachMessageServer server; // The chosen request and reply sizes must be larger than the defaults for // that portion fo the test to be valid. EXPECT_GT(kRequestSize, server.MachMessageServerRequestSize()); EXPECT_GT(kReplySize, server.MachMessageServerReplySize()); server.AddHandler(&handler); std::set<mach_msg_id_t> expect_request_ids; expect_request_ids.insert(kRequestID); EXPECT_EQ(expect_request_ids, server.MachMessageServerRequestIDs()); EXPECT_EQ(kRequestSize, server.MachMessageServerRequestSize()); EXPECT_EQ(kReplySize, server.MachMessageServerReplySize()); mach_msg_empty_rcv_t request = {}; mig_reply_error_t reply = {}; // Send a message with an unknown request ID. request.header.msgh_id = 0; bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(MIG_BAD_ID, reply.RetCode); EXPECT_FALSE(destroy_complex_request); // Send a message with a known request ID. request.header.msgh_id = kRequestID; EXPECT_TRUE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(kReturnCode, reply.RetCode); EXPECT_TRUE(destroy_complex_request); } TEST(CompositeMachMessageServer, ThreeHandlers) { const mach_msg_id_t kRequestIDs0[] = {5}; const kern_return_t kReturnCode0 = KERN_SUCCESS; const mach_msg_id_t kRequestIDs1[] = {4, 7}; const kern_return_t kReturnCode1 = KERN_PROTECTION_FAILURE; const mach_msg_id_t kRequestIDs2[] = {10, 0, 20}; const mach_msg_size_t kRequestSize2 = 6144; const mach_msg_size_t kReplySize2 = 16384; const kern_return_t kReturnCode2 = KERN_NOT_RECEIVER; TestMachMessageHandler handlers[3]; std::set<mach_msg_id_t> expect_request_ids; for (size_t index = 0; index < arraysize(kRequestIDs0); ++index) { const mach_msg_id_t request_id = kRequestIDs0[index]; handlers[0].AddRequestID(request_id); expect_request_ids.insert(request_id); } handlers[0].SetRequestSize(sizeof(mach_msg_header_t)); handlers[0].SetReplySize(sizeof(mig_reply_error_t)); handlers[0].SetReturnCodes(true, kReturnCode0, false); for (size_t index = 0; index < arraysize(kRequestIDs1); ++index) { const mach_msg_id_t request_id = kRequestIDs1[index]; handlers[1].AddRequestID(request_id); expect_request_ids.insert(request_id); } handlers[1].SetRequestSize(100); handlers[1].SetReplySize(200); handlers[1].SetReturnCodes(false, kReturnCode1, true); for (size_t index = 0; index < arraysize(kRequestIDs2); ++index) { const mach_msg_id_t request_id = kRequestIDs2[index]; handlers[2].AddRequestID(request_id); expect_request_ids.insert(request_id); } handlers[2].SetRequestSize(kRequestSize2); handlers[2].SetReplySize(kReplySize2); handlers[2].SetReturnCodes(true, kReturnCode2, true); CompositeMachMessageServer server; // The chosen request and reply sizes must be larger than the defaults for // that portion fo the test to be valid. EXPECT_GT(kRequestSize2, server.MachMessageServerRequestSize()); EXPECT_GT(kReplySize2, server.MachMessageServerReplySize()); server.AddHandler(&handlers[0]); server.AddHandler(&handlers[1]); server.AddHandler(&handlers[2]); EXPECT_EQ(expect_request_ids, server.MachMessageServerRequestIDs()); EXPECT_EQ(kRequestSize2, server.MachMessageServerRequestSize()); EXPECT_EQ(kReplySize2, server.MachMessageServerReplySize()); mach_msg_empty_rcv_t request = {}; mig_reply_error_t reply = {}; // Send a message with an unknown request ID. request.header.msgh_id = 100; bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(MIG_BAD_ID, reply.RetCode); EXPECT_FALSE(destroy_complex_request); // Send messages with known request IDs. for (size_t index = 0; index < arraysize(kRequestIDs0); ++index) { request.header.msgh_id = kRequestIDs0[index]; SCOPED_TRACE(base::StringPrintf( "handler 0, index %zu, id %d", index, request.header.msgh_id)); EXPECT_TRUE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(kReturnCode0, reply.RetCode); EXPECT_FALSE(destroy_complex_request); } for (size_t index = 0; index < arraysize(kRequestIDs1); ++index) { request.header.msgh_id = kRequestIDs1[index]; SCOPED_TRACE(base::StringPrintf( "handler 1, index %zu, id %d", index, request.header.msgh_id)); EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(kReturnCode1, reply.RetCode); EXPECT_TRUE(destroy_complex_request); } for (size_t index = 0; index < arraysize(kRequestIDs2); ++index) { request.header.msgh_id = kRequestIDs2[index]; SCOPED_TRACE(base::StringPrintf( "handler 2, index %zu, id %d", index, request.header.msgh_id)); EXPECT_TRUE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(kReturnCode2, reply.RetCode); EXPECT_TRUE(destroy_complex_request); } } // CompositeMachMessageServer can’t deal with two handlers that want to handle // the same request ID. TEST(CompositeMachMessageServerDeathTest, DuplicateRequestID) { const mach_msg_id_t kRequestID = 400; TestMachMessageHandler handlers[2]; handlers[0].AddRequestID(kRequestID); handlers[1].AddRequestID(kRequestID); CompositeMachMessageServer server; server.AddHandler(&handlers[0]); EXPECT_DEATH_CHECK(server.AddHandler(&handlers[1]), "duplicate request ID"); } } // namespace } // namespace test } // namespace crashpad
33.276873
78
0.751958
hunter-packages
11993fdb5fee80caf71360a53ddb1ebff02481d3
3,888
hpp
C++
src/mapping/had_map/lanelet2_map_provider/include/lanelet2_map_provider/lanelet2_map_provider_node.hpp
jiangtaojiang/AutowareAuto
579bd5cec65859779d215c28c468b06de809749b
[ "Apache-2.0" ]
4
2020-12-04T00:38:42.000Z
2022-02-24T05:48:58.000Z
src/mapping/had_map/lanelet2_map_provider/include/lanelet2_map_provider/lanelet2_map_provider_node.hpp
jiangtaojiang/AutowareAuto
579bd5cec65859779d215c28c468b06de809749b
[ "Apache-2.0" ]
null
null
null
src/mapping/had_map/lanelet2_map_provider/include/lanelet2_map_provider/lanelet2_map_provider_node.hpp
jiangtaojiang/AutowareAuto
579bd5cec65859779d215c28c468b06de809749b
[ "Apache-2.0" ]
1
2020-12-04T00:38:56.000Z
2020-12-04T00:38:56.000Z
// Copyright 2020 The Autoware Foundation // // 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. /// \copyright Copyright 2020 The Autoware Foundation /// \file /// \brief This file defines the lanelet2_map_provider_node class. #ifndef LANELET2_MAP_PROVIDER__LANELET2_MAP_PROVIDER_NODE_HPP_ #define LANELET2_MAP_PROVIDER__LANELET2_MAP_PROVIDER_NODE_HPP_ #include <rclcpp/rclcpp.hpp> #include <lanelet2_map_provider/lanelet2_map_provider.hpp> #include <common/types.hpp> #include <string> #include <memory> #include "autoware_auto_msgs/srv/had_map_service.hpp" #include "autoware_auto_msgs/msg/had_map_bin.hpp" using autoware::common::types::float64_t; using autoware::common::types::bool8_t; namespace autoware { namespace lanelet2_map_provider { /// \class Lanelet2MapProviderNode /// \brief ROS 2 Node for semantic map provider using lanelet2 map format. /// Node loads a lanelet2 OSM format map using the class Lanelet2MapProvider /// and then runs a service for supplying other /// nodes map information according to their requests. Requests are defined by /// a sequences of requested primitives as well as geometric bounds on requested map /// data class LANELET2_MAP_PROVIDER_PUBLIC Lanelet2MapProviderNode : public rclcpp::Node { public: /// \brief default constructor, starts driver /// *breaks docs test - no node_nmae generated by automatic package generator /// -- param[in] node_name name of the node for rclcpp internals /// \throw runtime error if failed to start threads or configure driver explicit Lanelet2MapProviderNode(const rclcpp::NodeOptions & options); /// \brief load_map loads the osm map data while projecting into the coordinate /// system defined by the map origin void load_map(); /// \brief Initialisation of the node Create the map provider object from the given map filename, /// and set up the service call handler for the node void init(); /// \brief Handles the node service requests /// \param request Service request message for map data specifying map content and geom. bounds /// \param response Service repsone to request, containing a sub-set of map data /// but nethertheless containing a complete and valid lanelet2 map void handle_request( std::shared_ptr<autoware_auto_msgs::srv::HADMapService_Request> request, std::shared_ptr<autoware_auto_msgs::srv::HADMapService_Response> response); private: /// If the origin not defined by parameters, get the transform describing /// the map origin (earth->map transform, set by the pcd /// map provider). Geocentric lanelet2 coordinates can then be projected intro the map frame. /// Must be recieved before the node can call the map provider constructor, and start the /// service handler void get_map_origin(); float64_t m_origin_lat; /// map orgin in latitude, longitude and elevatopm float64_t m_origin_lon; float64_t m_origin_ele; bool8_t m_origin_set; bool8_t m_verbose; ///< whether to use verbose output or not. std::string m_map_filename; std::unique_ptr<Lanelet2MapProvider> m_map_provider; rclcpp::Service<autoware_auto_msgs::srv::HADMapService>::SharedPtr m_map_service; geometry_msgs::msg::TransformStamped m_earth_to_map; /// map origin in ECEF ENU transform }; } // namespace lanelet2_map_provider } // namespace autoware #endif // LANELET2_MAP_PROVIDER__LANELET2_MAP_PROVIDER_NODE_HPP_
40.5
99
0.773405
jiangtaojiang
119a8990fd825c7102acd6c0e0c1397ebc5bd533
4,118
cpp
C++
import/tests/gamma_by_eye.cpp
HosokawaKenchi/PsychlopsJS
3209442e6dbda57dbdf5e0ed6ffefc55972fb8fb
[ "MIT" ]
null
null
null
import/tests/gamma_by_eye.cpp
HosokawaKenchi/PsychlopsJS
3209442e6dbda57dbdf5e0ed6ffefc55972fb8fb
[ "MIT" ]
3
2020-06-06T04:16:06.000Z
2020-07-24T07:36:06.000Z
import/tests/gamma_by_eye.cpp
psychlopsdev/PsychlopsJS
3209442e6dbda57dbdf5e0ed6ffefc55972fb8fb
[ "MIT" ]
1
2018-12-17T04:59:11.000Z
2018-12-17T04:59:11.000Z
#include <psychlops.h> using namespace Psychlops; double estimated_gamma = 0; double gamma_step = 8.0; var estimate_gamma = function(colorlevel) { estimated_gamma = 0; gamma_step = 8.0; while (0.0001<gamma_step) { while (0<pow(colorlevel, estimated_gamma) - 0.5) { estimated_gamma += gamma_step; } estimated_gamma -= gamma_step; gamma_step /= 2.0; } estimated_gamma += gamma_step; return estimated_gamma; }; void psychlops_main() { //// 1 Declaration // declare default window and variables for its parameters double CANVAS_FRAMENUM; int CANVAS_REFRESHRATE; Canvas cnvs(Canvas::fullscreen); Widgets::Theme::setLightTheme(); Interval rng; double Gr, Gb, Gg; double measured_r = 0.5, measured_g = 0.5, measured_b = 0.5; Widgets::Dial dial_r, dial_g, dial_b; dial_r.set(200, 60).centering().shift(-300, 200); dial_g.set(200, 60).centering().shift(0, 200); dial_b.set(200, 60).centering().shift(300, 200); dial_r.link(measured_r, "Red", 0 <= rng < 0.99, 1.0 / 8, 0.5); dial_g.link(measured_g, "Green", 0 <= rng < 0.99, 1.0 / 8, 0.5); dial_b.link(measured_b, "Blue", 0 <= rng < 0.99, 1.0 / 8, 0.5); Widgets::Button endbutton, switchbutton; endbutton.set(L"キャンセル", 48); endbutton.centering().shift(cnvs.getWidth()*0.4, cnvs.getHeight()*0.4); switchbutton.set(L" 次へ ", 48); switchbutton.centering(cnvs.getHcenter(), dial_g.getBottom() + 200); //// 2 Initialization // Set initial values for local variables CANVAS_REFRESHRATE = cnvs.getRefreshRate(); CANVAS_FRAMENUM = 0; //// 3 Drawing Psychlops::Rectangle center_rect(100, 100); Image grads[3]; Color grads_color[3]; grads_color[0] = Color(1, 0, 0); grads_color[1] = Color(0, 1, 0); grads_color[2] = Color(0, 0, 1); for (int i = 0; i < 3; i++) { grads[i].set(200, 200); for (int y = 0; y < 200; y++) { for (int x = 0; x < 200; x++) { grads[i].pix(x, y, y % 2 == 0 ? grads_color[i] : Color::black); } } grads[i].cache(); grads[i].centering().shift(-300 + i * 300, 0); } int endflag = 0; Mouse::show(); Psychlops::Letters instruction1(L"それぞれの図形の下のスライダーを調整し、"); Psychlops::Letters instruction2(L"中心の四角とその周りの明るさをできるだけ近づけてください。"); instruction1.centering().shift(0, -300); instruction2.centering().shift(0, -300 + Psychlops.Font.default_font.size * 1.1); Figures::ShaderGabor gbr; gbr.setSigma(200); gbr.centering(); bool calibrating = true; int frames = 0; Psychlops::Color::setGammaValue(1.0, 1.0, 1.0); // [begin loop] while (endflag < 1) { frames++; if (calibrating) { cnvs.clear(); dial_r.draw(); dial_g.draw(); dial_b.draw(); if (dial_r.changed()) { Gr = estimate_gamma(measured_r); } if (dial_g.changed()) { Gg = estimate_gamma(measured_g); } if (dial_b.changed()) { Gb = estimate_gamma(measured_b); } if (endflag == 0) { for (int i = 0; i < 3; i++) { grads[i].shift(0, (frames % 2) * 2 - 1).draw(); } } else if (endflag == 1) { for (int i = 0; i < 3; i++) { grads[i].draw(); } } center_rect.centering().shift(-300 + 0 * 300, 0); center_rect.draw(Color(measured_r, 0.0, 0.0)); center_rect.centering().shift(-300 + 1 * 300, 0); center_rect.draw(Color(0.0, measured_g, 0.0)); center_rect.centering().shift(-300 + 2 * 300, 0); center_rect.draw(Color(0.0, 0.0, measured_b)); instruction1.draw(Color::white); instruction2.draw(Color::white); endbutton.draw(); if (endbutton.pushed()) { endflag = 4; } switchbutton.draw(); if (switchbutton.pushed()) { endflag += 1; calibrating = false; frames = 0; measured_r = 0.5; measured_g = 0.5; measured_b = 0.5; } } else { cnvs.clear(); if (frames > 30) { calibrating = true; frames = 0; } } cnvs.flip(); CANVAS_FRAMENUM++; } // [end loop] AppInfo::localSettings["GammaR"] = Gr; AppInfo::localSettings["GammaG"] = Gg; AppInfo::localSettings["GammaB"] = Gb; AppInfo::saveLocalSettings(); //alert("Estimated Gamma:\r\nR: "+Gr+"\r\nG: "+Gg+"\r\nB:"+Gb); }
27.453333
84
0.616076
HosokawaKenchi
119bba808d980f24e8481af7cc3ba34361c67faa
12,513
cpp
C++
tf2_src/utils/vmpi/iphelpers.cpp
d3fc0n6/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/utils/vmpi/iphelpers.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/utils/vmpi/iphelpers.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #pragma warning (disable:4127) #include <winsock2.h> #include <ws2tcpip.h> #pragma warning (default:4127) #include "iphelpers.h" #include "basetypes.h" #include <assert.h> #include "utllinkedlist.h" #include "utlvector.h" #include "tier1/strtools.h" // This automatically calls WSAStartup for the app at startup. class CIPStarter { public: CIPStarter() { WSADATA wsaData; WSAStartup( WINSOCK_VERSION, &wsaData ); } }; static CIPStarter g_Starter; unsigned long SampleMilliseconds() { CCycleCount cnt; cnt.Sample(); return cnt.GetMilliseconds(); } // ------------------------------------------------------------------------------------------ // // CChunkWalker. // ------------------------------------------------------------------------------------------ // CChunkWalker::CChunkWalker( void const * const *pChunks, const int *pChunkLengths, int nChunks ) { m_TotalLength = 0; for ( int i=0; i < nChunks; i++ ) m_TotalLength += pChunkLengths[i]; m_iCurChunk = 0; m_iCurChunkPos = 0; m_pChunks = pChunks; m_pChunkLengths = pChunkLengths; m_nChunks = nChunks; } int CChunkWalker::GetTotalLength() const { return m_TotalLength; } void CChunkWalker::CopyTo( void *pOut, int nBytes ) { unsigned char *pOutPos = (unsigned char*)pOut; int nBytesLeft = nBytes; while ( nBytesLeft > 0 ) { int toCopy = nBytesLeft; int curChunkLen = m_pChunkLengths[m_iCurChunk]; int amtLeft = curChunkLen - m_iCurChunkPos; if ( nBytesLeft > amtLeft ) { toCopy = amtLeft; } unsigned char *pCurChunkData = (unsigned char*)m_pChunks[m_iCurChunk]; memcpy( pOutPos, &pCurChunkData[m_iCurChunkPos], toCopy ); nBytesLeft -= toCopy; pOutPos += toCopy; // Slide up to the next chunk if we're done with the one we're on. m_iCurChunkPos += toCopy; assert( m_iCurChunkPos <= curChunkLen ); if ( m_iCurChunkPos == curChunkLen ) { ++m_iCurChunk; m_iCurChunkPos = 0; if ( m_iCurChunk == m_nChunks ) { assert( nBytesLeft == 0 ); } } } } // ------------------------------------------------------------------------------------------ // // CWaitTimer // ------------------------------------------------------------------------------------------ // bool g_bForceWaitTimers = false; CWaitTimer::CWaitTimer( double flSeconds ) { m_StartTime = SampleMilliseconds(); m_WaitMS = (unsigned long)( flSeconds * 1000.0 ); } bool CWaitTimer::ShouldKeepWaiting() { if ( m_WaitMS == 0 ) { return false; } else { return ( SampleMilliseconds() - m_StartTime ) <= m_WaitMS || g_bForceWaitTimers; } } // ------------------------------------------------------------------------------------------ // // CIPAddr. // ------------------------------------------------------------------------------------------ // CIPAddr::CIPAddr() { Init( 0, 0, 0, 0, 0 ); } CIPAddr::CIPAddr( const int inputIP[4], const int inputPort ) { Init( inputIP[0], inputIP[1], inputIP[2], inputIP[3], inputPort ); } CIPAddr::CIPAddr( int ip0, int ip1, int ip2, int ip3, int ipPort ) { Init( ip0, ip1, ip2, ip3, ipPort ); } void CIPAddr::Init( int ip0, int ip1, int ip2, int ip3, int ipPort ) { ip[0] = (unsigned char)ip0; ip[1] = (unsigned char)ip1; ip[2] = (unsigned char)ip2; ip[3] = (unsigned char)ip3; port = (unsigned short)ipPort; } bool CIPAddr::operator==( const CIPAddr &o ) const { return ip[0] == o.ip[0] && ip[1] == o.ip[1] && ip[2] == o.ip[2] && ip[3] == o.ip[3] && port == o.port; } bool CIPAddr::operator!=( const CIPAddr &o ) const { return !( *this == o ); } void CIPAddr::SetupLocal( int inPort ) { ip[0] = 0x7f; ip[1] = 0; ip[2] = 0; ip[3] = 1; port = inPort; } // ------------------------------------------------------------------------------------------ // // Static helpers. // ------------------------------------------------------------------------------------------ // static double IP_FloatTime() { CCycleCount cnt; cnt.Sample(); return cnt.GetSeconds(); } TIMEVAL SetupTimeVal( double flTimeout ) { TIMEVAL timeVal; timeVal.tv_sec = (long)flTimeout; timeVal.tv_usec = (long)( (flTimeout - (long)flTimeout) * 1000.0 ); return timeVal; } // Convert a CIPAddr to a sockaddr_in. void IPAddrToInAddr( const CIPAddr *pIn, in_addr *pOut ) { u_char *p = (u_char*)pOut; p[0] = pIn->ip[0]; p[1] = pIn->ip[1]; p[2] = pIn->ip[2]; p[3] = pIn->ip[3]; } // Convert a CIPAddr to a sockaddr_in. void IPAddrToSockAddr( const CIPAddr *pIn, struct sockaddr_in *pOut ) { memset( pOut, 0, sizeof(*pOut) ); pOut->sin_family = AF_INET; pOut->sin_port = htons( pIn->port ); IPAddrToInAddr( pIn, &pOut->sin_addr ); } // Convert a CIPAddr to a sockaddr_in. void SockAddrToIPAddr( const struct sockaddr_in *pIn, CIPAddr *pOut ) { const u_char *p = (const u_char*)&pIn->sin_addr; pOut->ip[0] = p[0]; pOut->ip[1] = p[1]; pOut->ip[2] = p[2]; pOut->ip[3] = p[3]; pOut->port = ntohs( pIn->sin_port ); } class CIPSocket : public ISocket { public: CIPSocket() { m_Socket = INVALID_SOCKET; m_bSetupToBroadcast = false; } virtual ~CIPSocket() { Term(); } // ISocket implementation. public: virtual void Release() { delete this; } virtual bool CreateSocket() { // Clear any old socket we had around. Term(); // Create a socket to send and receive through. SOCKET sock = socket( AF_INET, SOCK_DGRAM, IPPROTO_IP ); if ( sock == INVALID_SOCKET ) { Assert( false ); return false; } // Nonblocking please.. int status; DWORD val = 1; status = ioctlsocket( sock, FIONBIO, &val ); if ( status != 0 ) { assert( false ); closesocket( sock ); return false; } m_Socket = sock; return true; } // Called after we have a socket. virtual bool BindPart2( const CIPAddr *pAddr ) { Assert( m_Socket != INVALID_SOCKET ); // bind to it! sockaddr_in addr; IPAddrToSockAddr( pAddr, &addr ); int status = bind( m_Socket, (sockaddr*)&addr, sizeof(addr) ); if ( status == 0 ) { return true; } else { Term(); return false; } } virtual bool Bind( const CIPAddr *pAddr ) { if ( !CreateSocket() ) return false; return BindPart2( pAddr ); } virtual bool BindToAny( const unsigned short port ) { // (INADDR_ANY) CIPAddr addr; addr.ip[0] = addr.ip[1] = addr.ip[2] = addr.ip[3] = 0; addr.port = port; return Bind( &addr ); } virtual bool ListenToMulticastStream( const CIPAddr &addr, const CIPAddr &localInterface ) { ip_mreq mr; IPAddrToInAddr( &addr, &mr.imr_multiaddr ); IPAddrToInAddr( &localInterface, &mr.imr_interface ); // This helps a lot if the stream is sending really fast. int rcvBuf = 1024*1024*2; setsockopt( m_Socket, SOL_SOCKET, SO_RCVBUF, (char*)&rcvBuf, sizeof( rcvBuf ) ); if ( setsockopt( m_Socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mr, sizeof( mr ) ) == 0 ) { // Remember this so we do IP_DEL_MEMBERSHIP on shutdown. m_bMulticastGroupMembership = true; m_MulticastGroupMREQ = mr; return true; } else { return false; } } virtual bool Broadcast( const void *pData, const int len, const unsigned short port ) { assert( m_Socket != INVALID_SOCKET ); // Make sure we're setup to broadcast. if ( !m_bSetupToBroadcast ) { BOOL bBroadcast = true; if ( setsockopt( m_Socket, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof( bBroadcast ) ) != 0 ) { assert( false ); return false; } m_bSetupToBroadcast = true; } CIPAddr addr; addr.ip[0] = addr.ip[1] = addr.ip[2] = addr.ip[3] = 0xFF; addr.port = port; return SendTo( &addr, pData, len ); } virtual bool SendTo( const CIPAddr *pAddr, const void *pData, const int len ) { return SendChunksTo( pAddr, &pData, &len, 1 ); } virtual bool SendChunksTo( const CIPAddr *pAddr, void const * const *pChunks, const int *pChunkLengths, int nChunks ) { WSABUF bufs[32]; if ( nChunks > 32 ) { Error( "CIPSocket::SendChunksTo: too many chunks (%d).", nChunks ); } int nTotalBytes = 0; for ( int i=0; i < nChunks; i++ ) { bufs[i].len = pChunkLengths[i]; bufs[i].buf = (char*)pChunks[i]; nTotalBytes += pChunkLengths[i]; } assert( m_Socket != INVALID_SOCKET ); // Translate the address. sockaddr_in addr; IPAddrToSockAddr( pAddr, &addr ); DWORD dwNumBytesSent = 0; DWORD ret = WSASendTo( m_Socket, bufs, nChunks, &dwNumBytesSent, 0, (sockaddr*)&addr, sizeof( addr ), NULL, NULL ); return ret == 0 && (int)dwNumBytesSent == nTotalBytes; } virtual int RecvFrom( void *pData, int maxDataLen, CIPAddr *pFrom ) { assert( m_Socket != INVALID_SOCKET ); fd_set readSet; readSet.fd_count = 1; readSet.fd_array[0] = m_Socket; TIMEVAL timeVal = SetupTimeVal( 0 ); // See if it has a packet waiting. int status = select( 0, &readSet, NULL, NULL, &timeVal ); if ( status == 0 || status == SOCKET_ERROR ) return -1; // Get the data. sockaddr_in sender; int fromSize = sizeof( sockaddr_in ); status = recvfrom( m_Socket, (char*)pData, maxDataLen, 0, (struct sockaddr*)&sender, &fromSize ); if ( status == 0 || status == SOCKET_ERROR ) { return -1; } else { if ( pFrom ) { SockAddrToIPAddr( &sender, pFrom ); } m_flLastRecvTime = IP_FloatTime(); return status; } } virtual double GetRecvTimeout() { return IP_FloatTime() - m_flLastRecvTime; } private: void Term() { if ( m_Socket != INVALID_SOCKET ) { if ( m_bMulticastGroupMembership ) { // Undo our multicast group membership. setsockopt( m_Socket, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&m_MulticastGroupMREQ, sizeof( m_MulticastGroupMREQ ) ); } closesocket( m_Socket ); m_Socket = INVALID_SOCKET; } m_bSetupToBroadcast = false; m_bMulticastGroupMembership = false; } private: SOCKET m_Socket; bool m_bMulticastGroupMembership; // Did we join a multicast group? ip_mreq m_MulticastGroupMREQ; bool m_bSetupToBroadcast; double m_flLastRecvTime; bool m_bListenSocket; }; ISocket* CreateIPSocket() { return new CIPSocket; } ISocket* CreateMulticastListenSocket( const CIPAddr &addr, const CIPAddr &localInterface ) { CIPSocket *pSocket = new CIPSocket; CIPAddr bindAddr = localInterface; bindAddr.port = addr.port; if ( pSocket->Bind( &bindAddr ) && pSocket->ListenToMulticastStream( addr, localInterface ) ) { return pSocket; } else { pSocket->Release(); return NULL; } } bool ConvertStringToIPAddr( const char *pStr, CIPAddr *pOut ) { char ipStr[512]; const char *pColon = strchr( pStr, ':' ); if ( pColon ) { int toCopy = pColon - pStr; if ( toCopy < 2 || toCopy > sizeof(ipStr)-1 ) { assert( false ); return false; } memcpy( ipStr, pStr, toCopy ); ipStr[toCopy] = 0; pOut->port = (unsigned short)atoi( pColon+1 ); } else { strncpy( ipStr, pStr, sizeof( ipStr ) ); ipStr[ sizeof(ipStr)-1 ] = 0; } if ( ipStr[0] >= '0' && ipStr[0] <= '9' ) { // It's numbers. int ip[4]; sscanf( ipStr, "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3] ); pOut->ip[0] = (unsigned char)ip[0]; pOut->ip[1] = (unsigned char)ip[1]; pOut->ip[2] = (unsigned char)ip[2]; pOut->ip[3] = (unsigned char)ip[3]; } else { // It's a text string. struct hostent *pHost = gethostbyname( ipStr ); if( !pHost ) return false; pOut->ip[0] = pHost->h_addr_list[0][0]; pOut->ip[1] = pHost->h_addr_list[0][1]; pOut->ip[2] = pHost->h_addr_list[0][2]; pOut->ip[3] = pHost->h_addr_list[0][3]; } return true; } bool ConvertIPAddrToString( const CIPAddr *pIn, char *pOut, int outLen ) { in_addr addr; addr.S_un.S_un_b.s_b1 = pIn->ip[0]; addr.S_un.S_un_b.s_b2 = pIn->ip[1]; addr.S_un.S_un_b.s_b3 = pIn->ip[2]; addr.S_un.S_un_b.s_b4 = pIn->ip[3]; HOSTENT *pEnt = gethostbyaddr( (char*)&addr, sizeof( addr ), AF_INET ); if ( pEnt ) { Q_strncpy( pOut, pEnt->h_name, outLen ); return true; } else { return false; } } void IP_GetLastErrorString( char *pStr, int maxLen ) { char *lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); Q_strncpy( pStr, lpMsgBuf, maxLen ); LocalFree( lpMsgBuf ); }
20.479542
121
0.603293
d3fc0n6
119e4894c0332b263e6a3f84dc6b052b9f35d03b
756
hh
C++
inc/EFiberMutex.hh
jjzhang166/CxxFiber
fb9a8744425725441d27016ee3707fc7c235f65d
[ "Apache-2.0" ]
14
2016-12-13T08:23:17.000Z
2020-03-29T23:28:46.000Z
inc/EFiberMutex.hh
jjzhang166/CxxFiber
fb9a8744425725441d27016ee3707fc7c235f65d
[ "Apache-2.0" ]
null
null
null
inc/EFiberMutex.hh
jjzhang166/CxxFiber
fb9a8744425725441d27016ee3707fc7c235f65d
[ "Apache-2.0" ]
8
2017-02-09T09:56:20.000Z
2019-02-19T07:22:11.000Z
/* * EFiberMutex.hh * * Created on: 2016-5-9 * Author: cxxjava@163.com */ #ifndef EFIBERMUTEX_HH_ #define EFIBERMUTEX_HH_ #include "./EFiberBlocker.hh" namespace efc { namespace eco { /** * Mutex for fiber. */ class EFiberMutex: public ELock { public: virtual ~EFiberMutex(); EFiberMutex(); virtual void lock(); virtual void lockInterruptibly() THROWS(EUnsupportedOperationException); virtual boolean tryLock(); virtual boolean tryLock(llong time, ETimeUnit* unit=ETimeUnit::MILLISECONDS); virtual void unlock(); virtual ECondition* newCondition() THROWS(EUnsupportedOperationException); virtual boolean isLocked(); private: EFiberBlocker blocker; }; } /* namespace eco */ } /* namespace efc */ #endif /* EFIBERMUTEX_HH_ */
18.439024
78
0.72619
jjzhang166
119f554b83b2acb1d35c3604cc5a915b905ffc4b
4,799
hpp
C++
include/slate_api/lapack/lascl.hpp
rileyjmurray/tlapack
640dc35a2eb0748b3c094efda8187a9e0b6a5762
[ "BSD-3-Clause" ]
null
null
null
include/slate_api/lapack/lascl.hpp
rileyjmurray/tlapack
640dc35a2eb0748b3c094efda8187a9e0b6a5762
[ "BSD-3-Clause" ]
null
null
null
include/slate_api/lapack/lascl.hpp
rileyjmurray/tlapack
640dc35a2eb0748b3c094efda8187a9e0b6a5762
[ "BSD-3-Clause" ]
null
null
null
/// @file lascl.hpp Multiplies a matrix by a scalar. /// @author Weslley S Pereira, University of Colorado Denver, USA // // Copyright (c) 2012-2021, University of Colorado Denver. All rights reserved. // // This file is part of <T>LAPACK. // <T>LAPACK is free software: you can redistribute it and/or modify it under // the terms of the BSD 3-Clause license. See the accompanying LICENSE file. #ifndef __SLATE_LASCL_HH__ #define __SLATE_LASCL_HH__ #include "lapack/types.hpp" #include "lapack/lascl.hpp" namespace lapack { /** @brief Multiplies a matrix A by the real scalar a/b. * * Multiplication of a matrix A by scalar a/b is done without over/underflow as long as the final * result $a A/b$ does not over/underflow. The parameter type specifies that * A may be full, upper triangular, lower triangular, upper Hessenberg, or banded. * * @return 0 if success. * @return -i if the ith argument is invalid. * * @param[in] type Specifies the type of matrix A. * * MatrixType::General: * A is a full matrix. * MatrixType::Lower: * A is a lower triangular matrix. * MatrixType::Upper: * A is an upper triangular matrix. * MatrixType::Hessenberg: * A is an upper Hessenberg matrix. * MatrixType::LowerBand: * A is a symmetric band matrix with lower bandwidth kl and upper bandwidth ku * and with the only the lower half stored. * MatrixType::UpperBand: * A is a symmetric band matrix with lower bandwidth kl and upper bandwidth ku * and with the only the upper half stored. * MatrixType::Band: * A is a band matrix with lower bandwidth kl and upper bandwidth ku. * * @param[in] kl The lower bandwidth of A, used only for banded matrix types B, Q and Z. * @param[in] ku The upper bandwidth of A, used only for banded matrix types B, Q and Z. * @param[in] b The denominator of the scalar a/b. * @param[in] a The numerator of the scalar a/b. * @param[in] m The number of rows of the matrix A. m>=0 * @param[in] n The number of columns of the matrix A. n>=0 * @param[in,out] A Pointer to the matrix A [in/out]. * @param[in] lda The column length of the matrix A. * * @ingroup auxiliary */ template< typename T > int lascl( lapack::MatrixType matrixtype, idx_t kl, idx_t ku, const real_type<T>& b, const real_type<T>& a, idx_t m, idx_t n, T* A, idx_t lda ) { using blas::internal::colmajor_matrix; using std::max; // check arguments lapack_error_if( (matrixtype != MatrixType::General) && (matrixtype != MatrixType::Lower) && (matrixtype != MatrixType::Upper) && (matrixtype != MatrixType::Hessenberg), -1 ); lapack_error_if( ( (matrixtype == MatrixType::LowerBand) || (matrixtype == MatrixType::UpperBand) || (matrixtype == MatrixType::Band) ) && ( (kl < 0) || (kl > max(m-1, idx_t(0))) ), -2 ); lapack_error_if( ( (matrixtype == MatrixType::LowerBand) || (matrixtype == MatrixType::UpperBand) || (matrixtype == MatrixType::Band) ) && ( (ku < 0) || (ku > max(n-1, idx_t(0))) ), -3 ); lapack_error_if( ( (matrixtype == MatrixType::LowerBand) || (matrixtype == MatrixType::UpperBand) ) && ( kl != ku ), -3 ); lapack_error_if( m < 0, -6 ); lapack_error_if( (lda < m) && ( (matrixtype == MatrixType::General) || (matrixtype == MatrixType::Lower) || (matrixtype == MatrixType::Upper) || (matrixtype == MatrixType::Hessenberg) ), -9 ); lapack_error_if( (matrixtype == MatrixType::LowerBand) && (lda < kl + 1), -9); lapack_error_if( (matrixtype == MatrixType::UpperBand) && (lda < ku + 1), -9); lapack_error_if( (matrixtype == MatrixType::Band) && (lda < 2 * kl + ku + 1), -9); // Matrix views auto _A = colmajor_matrix<T>( A, m, n, lda ); if (matrixtype == MatrixType::General) return lascl( general_matrix, b, a, _A ); else if (matrixtype == MatrixType::Lower) return lascl( lower_triangle, b, a, _A ); else if (matrixtype == MatrixType::Upper) return lascl( upper_triangle, b, a, _A ); else if (matrixtype == MatrixType::Hessenberg) return lascl( hessenberg_matrix, b, a, _A ); else if (matrixtype == MatrixType::LowerBand) return lascl( symmetric_lowerband_t{kl}, b, a, _A ); else if (matrixtype == MatrixType::UpperBand) return lascl( symmetric_upperband_t{ku}, b, a, _A ); else if (matrixtype == MatrixType::Band) return lascl( band_matrix_t{kl,ku}, b, a, _A ); return 0; } } #endif // __LASCL_HH__
37.492188
97
0.613461
rileyjmurray