blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cd595372c4ba722ace7b1c09cb1680fc7b72f487 | 7866cf16724c0e90d45ab5fb97448a6b865b82b3 | /cpp/samchon/library/StringUtil.hpp | b8dbd3387edac6424ba43fb18407a18b9afa78df | [
"BSD-3-Clause"
] | permissive | samchon/framework | 652d8077e6fc355538fd96b08cf2a13d421fae58 | bdfaad460e3e8edce72f0dd5168aad2cf68c839d | refs/heads/master | 2021-01-23T09:01:37.452889 | 2020-01-18T09:06:52 | 2020-01-18T09:06:52 | 39,832,985 | 95 | 39 | BSD-3-Clause | 2018-02-09T01:18:49 | 2015-07-28T12:38:14 | C++ | UTF-8 | C++ | false | false | 22,230 | hpp | #pragma once
#include <string>
#include <iostream>
#include <sstream>
#include <samchon/WeakString.hpp>
#include <samchon/IndexPair.hpp>
#include <samchon/library/Math.hpp>
namespace samchon
{
namespace library
{
/**
* @brief Utility class for string
*
* @details
* <p> StringUtil is an utility class providing lots of static methods for std::string. </p>
*
* <p> There are two methods to strength std::string to have addictional uility methods like trim and split.
* The way of first is to make std::string class inheriting from std::string.
* The second is to make StringUtil class having static methods. </p>
*
* <p> But those methods have problems. std::string class violates standard and StringUtil class violates
* principle of Object-Oriented Design. For the present, I've made the StringUtil class, but if you
* have a good opinion about the issue, please write your opinion on my github. </p>
*
* @image html cpp/subset/library_string.png
* @image latex cpp/subset/library_string.png
*
* @see library::WeakString
* @see samchon::library
* @author Jeongho Nam <http://samchon.org>
*/
class StringUtil
{
public:
/* ----------------------------------------------------------------------
SUBSTITUTE
---------------------------------------------------------------------- */
/**
* @brief Substitutes "{n}" tokens within the specified string with the respective arguments passed in.
*
* @param format The string to make substitutions in.\n
* This string can contain special tokens of the form {n}, where n is a zero based index,
* that will be replaced with the additional parameters found at that index if specified
* @param val Target value to substitute the minimum {n} tokens
* @param args Additional parameters that can be substituted in the str parameter at each {n} location,
* where n is an integer (zero based) index value into the varadics of values specified.
* @return New string with all of the {n} tokens replaced with the respective arguments specified.
*/
template <typename T, typename ... _Args>
static auto substitute(const std::string &format,
const T& val, const _Args& ... args) -> std::string
{
std::string &res = _substitute(format, val);
return StringUtil::substitute(res, args...);
};
template <typename T> static auto substitute(const std::string &format, const T& val) -> std::string
{
return _substitute(format, val);
};
/**
* @brief Substitutes "{n}" tokens within the specified sql-string with the respective arguments passed in.\n
* @warning substituteSQL creates the dynamic sql-statement.\n
* Not recommended when the dynamic sql-statement is not only for procedure.
*
* @param format The string to make substitutions in.\n
* This string can contain special tokens of the form {n}, where n is a zero based index,
* that will be replaced with the additional parameters found at that index if specified
* @param val Target value to substitute the minimum {n} tokens
* @param args Additional parameters that can be substituted in the str parameter at each {n} location,
* where n is an integer (zero based) index value into the varadics of values specified.
* @return New sql-string with all of the {n} tokens replaced with the respective arguments specified.
*/
template <typename T, typename ... _Args >
static auto substituteSQL(const std::string &format,
const T& value, const _Args& ... args) -> std::string
{
std::string &res = _substituteSQL(format, value);
return StringUtil::substituteSQL(res, args...);
};
template <typename T> static auto substituteSQL(const std::string &format, const T& value) -> std::string
{
return _substituteSQL(format, value);
};
protected:
template <typename T> static auto _substitute(const std::string &format, const T& value) -> std::string
{
std::vector<std::string> &parenthesisArray = betweens(format, { (char)'{' }, { (char)'}' });
std::vector<long> vec;
for (auto it = parenthesisArray.begin(); it != parenthesisArray.end(); it++)
if (isNumeric(*it) == true)
vec.push_back(stoi(*it));
size_t index = (size_t)Math::minimum(vec).getValue();
//replaceAll
std::string &to = toString(value);
return replaceAll(format, "{" + std::to_string(index) + "}", to);
};
template <typename T> static auto _substituteSQL(const std::string &format, const T& value) -> std::string
{
std::vector<std::string> &parenthesisArray = betweens(format, "{", "}");
std::vector<long> vec;
for (auto it = parenthesisArray.begin(); it != parenthesisArray.end(); it++)
if (isNumeric(*it) == true)
vec.push_back(stoi(*it));
size_t index = (size_t)Math::minimum(vec).getValue();
//replaceAll
std::string &to = toSQL(value);
return replaceAll(format, "{" + std::to_string(index) + "}", to);
};
/* ----------------------------------------------------------------------
SUBSTITUTE -> TO_STRING
---------------------------------------------------------------------- */
template <typename T>
static auto toString(const T &val) -> std::string
{
return std::to_string(val);
};
template<> static auto toString(const std::string &str) -> std::string
{
return str;
};
template<> static auto toString(const WeakString &str) -> std::string
{
return str.str();
};
static auto toString(const char *ptr) -> std::string
{
return ptr;
};
template <typename T>
static auto toSQL(const T &val) -> std::string
{
if (val == INT_MIN)
return "NULL";
return std::to_string(val);
};
template<> static auto toSQL(const bool &flag) -> std::string
{
return std::to_string(flag);
};
template<> static auto toSQL(const char &val) -> std::string
{
return toSQL(std::string({ val }));
};
template<> static auto toSQL(const std::string &str) -> std::string
{
return toSQL(WeakString(str));
};
template<> static auto toSQL(const WeakString &wstr) -> std::string
{
if (wstr.empty() == true)
return "NULL";
else
{
if (wstr.find("'") != std::string::npos)
return "'" + wstr.replaceAll("'", "''") + "'";
else
return "'" + wstr.str() + "'";
}
};
static auto toSQL(const char *ptr) -> std::string
{
return toSQL(std::string(ptr));
};
public:
/* ----------------------------------------------------------------------
NUMBER-FORMAT
IN MONETARY UNIT, ADD DELIMETER ','
COLOR-FORMAT
POSITIVE NUMBER IS RED,
NEGATIVE NUMBER IS BLUE
ZERO IS BLACK
---------------------------------------------------------------------- */
/**
* @brief Returns wheter the std::string represents Number or not\n
*
* @param str Target std::string to check
* @return Whether the std::string can be converted to Number or not
*/
static auto isNumeric(const std::string &str) -> bool
{
try
{
stoi(str);
//stod( replaceAll(str, ",", "") );
}
catch (const std::exception &)
{
return false;
}
catch (...)
{
return false;
}
return true;
};
/**
* @brief Number std::string to Number having ',' symbols
*
* @param str Target std::string you want to convert to Number
* @return Number from std::string
*/
static auto toNumber(const std::string &str) -> double
{
std::string &numStr = replaceAll(str, ",", "");
return stod(numStr);
};
/**
* @brief
*
* @details
* Returns a string converted from the number rounded off from specified precision with "," symbols
* ex) numberFormat(17151.339, 2) => 17,151.34
*
* @param val A number wants to convert to string
* @param precision Target precision of roundoff
* @return A string representing the number with roundoff and "," symbols
*/
static auto numberFormat(double val, int precision = 2) -> std::string
{
std::string str;
// FIRST, DO ROUND-OFF
val = round(val * pow(10, precision));
val = val / pow(10, precision);
// SEPERATE NUMBERS
bool is_negative = (val < 0);
unsigned long long natural = (unsigned long long)abs(val);
double fraction = abs(val) - (unsigned long long)abs(val);
// NATURAL NUMBER
if (natural == 0)
str = "0";
else
{
// NOT ZERO
size_t cipher_count = (size_t)log10(natural) + 1;
for (size_t i = 0; i <= cipher_count; i++)
{
size_t cipher = natural % (size_t)pow(10, i + 1);
cipher = (size_t)(cipher / pow(10, i));
if (i == cipher_count && cipher == 0)
continue;
// IS MULTIPLIER OF 3
if (i > 0 && i % 3 == 0)
str = "," + str;
// PUSH FRONT TO THE STRING
str = std::to_string(cipher) + str;
}
}
// NEGATIVE SIGN
if (is_negative == true)
str = "-" + str;
// ADD FRACTION
if (precision > 0 && fraction != 0)
{
fraction = (double)(unsigned long long)round(fraction * pow(10, precision));
size_t zeros = precision - (size_t)log10(fraction) - 1;
str += "." + std::string(zeros, '0') + std::to_string((unsigned long long)fraction);
}
return str;
};
/**
* @brief
* Returns a percentage string converted from the number rounded off from specified precision with "," symbols\n
* ex) percentFormat(11.3391, 1) => 1,133.9%
*
* @warning Do not multiply by 100 to the value representing percent
* @param val A number wants to convert to percentage string
* @param precision Target precision of roundoff
*/
static auto percentFormat(double val, int precision = 2) -> std::string
{
if (val == INT_MIN)
return "";
return numberFormat(val * 100, precision) + "%";
};
/**
* @brief
* Returns a string converted from the number rounded off from specified precision with "," symbols and color tag\n
* ex) numberFormat(17151.339, 2) => <font color='red'>17,151.34</font>
*
* @details
* Which color would be chosen
* \li Number is positive, color is RED
* \li Number is zero (0), color is BLACK
* \li Number is negative, color is BLUE
*
* @param val A number wants to convert to colored string
* @param precision Target precision of roundoff
* @return A colored string representing the number with roundoff and "," symbols
*/
static auto colorNumberFormat(double value, int precision = 2, double delimiter = 0.0) -> std::string
{
std::string color;
if (value > delimiter) color = "red";
else if (value == delimiter) color = "black";
else color = "blue";
return substitute
(
"<font color='{1}'>{2}</font>",
color,
numberFormat(value, precision)
);
};
/**
* @brief Returns a percentage string converted from the number rounded off from specified precision with "," symbols\n
* ex) percentFormat(11.3391, 1) => 1,133.9%
*
* @warning Do not multiply by 100 to the value representing percent
* @param val A number wants to convert to percentage string
* @param precision Target precision of roundoff
*/
static auto colorPercentFormat(double value, int precision = 2, double delimiter = 0.0) -> std::string
{
std::string color;
if (value > delimiter) color = "red";
else if (value == delimiter) color = "black";
else color = "blue";
return substitute
(
"<font color='{1}'>{2}</font>",
color,
percentFormat(value, precision)
);
};
/* ----------------------------------------------------------------------
TRIM -> WITH LTRIM & RTRIM
IT'S RIGHT, THE TRIM OF ORACLE
---------------------------------------------------------------------- */
/**
* @brief Removes all designated characters from the beginning and end of the specified string
*
* @param str The string should be trimmed
* @param delims Designated character(s)
* @return Updated string where designated characters was removed from the beginning and end
*/
static auto trim(const std::string &val, const std::vector<std::string> &delims) -> std::string
{
return WeakString(val).trim(delims).str();
};
/**
* @brief Removes all designated characters from the beginning of the specified string
*
* @param str The string should be trimmed
* @param delims Designated character(s)
* @return Updated string where designated characters was removed from the beginning
*/
static auto ltrim(const std::string &val, const std::vector<std::string> &delims) -> std::string
{
return WeakString(val).ltrim(delims).str();
};
/**
* @brief Removes all designated characters from the end of the specified string
*
* @param str The string should be trimmed
* @param delims Designated character(s)
* @return Updated string where designated characters was removed from the end
*/
static auto rtrim(const std::string &val, const std::vector<std::string> &delims) -> std::string
{
return WeakString(val).rtrim(delims).str();
};
static auto trim(const std::string &str) -> std::string
{
return WeakString(str).trim().str();
};
static auto ltrim(const std::string &str) -> std::string
{
return WeakString(str).ltrim().str();
};
static auto rtrim(const std::string &str) -> std::string
{
return WeakString(str).rtrim().str();
};
static auto trim(const std::string &str, const std::string &delim) -> std::string
{
return WeakString(str).trim(delim).str();
};
static auto ltrim(const std::string &str, const std::string &delim) -> std::string
{
return WeakString(str).ltrim(delim).str();
};
static auto rtrim(const std::string &str, const std::string &delim) -> std::string
{
return WeakString(str).rtrim(delim).str();
};
/* ----------------------------------------------------------------------
EXTRACTORS
---------------------------------------------------------------------- */
/**
* @brief Finds first occurence in string
*
* @details
* Finds first occurence position of each delim in the string after startIndex
* and returns the minimum position of them\n
* \n
* If startIndex is not specified, then starts from 0.\n
* If failed to find any substring, returns -1 (std::string::npos)
*
* @param str Target string to find
* @param delims The substrings of target(str) which to find
* @param startIndex Specified starting index of find. Default is 0
* @return pair\<size_t := position, string := matched substring\>
*/
static auto finds(const std::string &str,
const std::vector<std::string> &delims, size_t startIndex = 0) -> IndexPair<std::string>
{
IndexPair<WeakString> &iPair = WeakString(str).finds(delims, startIndex);
return { iPair.get_index(), iPair.getValue().str() };
};
/**
* @brief Finds last occurence in string
*
* @details
* Finds last occurence position of each delim in the string before endIndex
* and returns the maximum position of them\n
* \n
* If index is not specified, then starts str.size() - 1\n
* If failed to find any substring, returns -1 (std::string::npos)
*
* @param str Target string to find
* @param delims The substrings of target(str) which to find
* @param endIndex Specified starting index of find. Default is str.size() - 1
* @return pair\<size_t := position, string := matched substring\>
*/
static auto rfinds(const std::string &str,
const std::vector<std::string> &delims, size_t endIndex = SIZE_MAX) -> IndexPair<std::string>
{
IndexPair<WeakString> &iPair = WeakString(str).rfinds(delims, endIndex);
return { iPair.get_index(), iPair.getValue().str() };
};
/**
* @brief Generates a substring
*
* @details
* Extracts a string consisting of the character specified by startIndex and all characters up to endIndex - 1
* If endIndex is not specified, string::size() will be used instead.\n
* If endIndex is greater than startIndex, then those will be swapped
*
* @param str Target string to be applied substring
* @param startIndex Index of the first character.\n
* If startIndex is greater than endIndex, those will be swapped
* @param endIndex Index of the last character - 1.\n
If not specified, then string::size() will be used instead
* @return Extracted string by specified index(es)
*/
static auto substring(const std::string &str,
size_t startIndex, size_t endIndex = SIZE_MAX) -> std::string
{
return WeakString(str).substring(startIndex, endIndex).str();
};
/**
* @brief Generate a substring.
*
* @details
* <p> Extracts a substring consisting of the characters from specified start to end
* It's same with str.substring( ? = (str.find(start) + start.size()), str.find(end, ?) ) </p>
*
* <p> ex) between("ABCD[EFGH]IJK", "[", "]") => "EFGH" </p>
*
* \li If start is not specified, extracts from begin of the string to end.
* \li If end is not specified, extracts from start to end of the string.
* \li If start and end are all omitted, returns str, itself.
*
* @param str Target string to be applied between
* @param start A string for separating substring at the front
* @param end A string for separating substring at the end
*
* @return substring by specified terms
*/
static auto between(const std::string &str,
const std::string &start = "", const std::string &end = "") -> std::string
{
return WeakString(str).between(start, end).str();
};
//TAB
/**
* @brief Adds tab(\t) character to first position of each line
*
* @param str Target str to add tabs
* @param n The size of tab to be added for each line
* @return A string added multiple tabs
*/
static auto addTab(const std::string &str, size_t n = 1) -> std::string
{
std::vector<std::string> &lines = split(str, "\n");
std::string val;
std::string tab;
size_t i;
val.reserve(val.size() + lines.size());
tab.reserve(n);
for (i = 0; i < n; i++)
tab += "\t";
for (i = 0; i < lines.size(); i++)
val.append(tab + lines[i] + ((i == lines.size() - 1) ? "" : "\n"));
return val;
};
//MULTIPLE STRINGS
/**
* @brief Generates substrings
* @details Splits a string into an array of substrings by dividing the specified delimiter
*
* @param str Target string to split
* @param delim The pattern that specifies where to split this string
* @return An array of substrings
*/
static auto split(const std::string &str, const std::string &delim) -> std::vector<std::string>
{
std::vector<WeakString> &arr = WeakString(str).split(delim);
std::vector<std::string> resArray(arr.size());
for (size_t i = 0; i < arr.size(); i++)
resArray[i] = move(arr[i].str());
return resArray;
};
/**
* @brief Generates substrings
*
* @details
* <p> Splits a string into an array of substrings dividing by specified delimeters of start and end.
* It's the array of substrings adjusted the between. </p>
*
* \li If startStr is omitted, it's same with the split by endStr not having last item
* \li If endStr is omitted, it's same with the split by startStr not having first item
* \li If startStr and endStar are all omitted, returns {str}
*
* @param str Target string to split by between
* @param start A string for separating substring at the front.
* If omitted, it's same with split(end) not having last item
* @param end A string for separating substring at the end.
* If omitted, it's same with split(start) not having first item
* @return An array of substrings
*/
static auto betweens
(
const std::string &str,
const std::string &start = "", const std::string &end = ""
) -> std::vector<std::string>
{
std::vector<WeakString> &arr = WeakString(str).betweens(start, end);
std::vector<std::string> resArray(arr.size());
for (size_t i = 0; i < arr.size(); i++)
resArray[i] = move(arr[i].str());
return resArray;
};
/* ----------------------------------------------------------------------
REPLACERS
---------------------------------------------------------------------- */
//ALPHABET-CONVERSION
/**
* @brief Returns a string that all uppercase characters are converted to lowercase.
*
* @param str Target string to convert uppercase to lowercase
* @return A string converted to lowercase
*/
static auto toLowerCase(const std::string &str) -> std::string
{
return WeakString(str).toLowerCase();
};
/**
* Returns a string all lowercase characters are converted to uppercase\n
*
* @param str Target string to convert lowercase to uppercase
* @return A string converted to uppercase
*/
static auto yoUpperCase(const std::string &str) -> std::string
{
return WeakString(str).yoUpperCase();
};
/**
* @brief Returns a string specified word is replaced
*
* @param str Target string to replace
* @param before Specific word you want to be replaced
* @param after Specific word you want to replace
* @return A string specified word is replaced
*/
static auto replaceAll
(
const std::string &str,
const std::string &before, const std::string &after
) -> std::string
{
return WeakString(str).replaceAll(before, after);
};
/**
* @brief Returns a string specified words are replaced
*
* @param str Target string to replace
* @param pairs A specific word's pairs you want to replace and to be replaced
* @return A string specified words are replaced
*/
static auto replaceAll(const std::string &str,
const std::vector<std::pair<std::string, std::string>> &pairs) -> std::string
{
return WeakString(str).replaceAll(pairs);
};
/**
* @brief Replace all HTML spaces to a literal space.
*
* @param str Target string to replace.
*/
static auto removeHTMLSpaces(const std::string &str) -> std::string
{
std::vector<std::pair<std::string, std::string>> pairs =
{
{ " ", " " },
{ "\t", " " },
{ " ", " " }
};
return replaceAll(str, pairs);
};
};
};
}; | [
"samchon@samchon.org"
] | samchon@samchon.org |
53b789a022a759f23f56cdcad97f91dd85f9a31c | 204c5937cdea475f5c3dafde6d770a74ae9b8919 | /ACM contest/2015多校/4/06.cpp | 6cef04d8354d93369ec41e5f172a789ab05b8914 | [] | no_license | mlz000/Algorithms | ad2c35e4441bcbdad61203489888b83627024b7e | 495eb701d4ec6b317816786ad5b38681fbea1001 | refs/heads/master | 2023-01-04T03:50:02.673937 | 2023-01-02T22:46:20 | 2023-01-02T22:46:20 | 101,135,823 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 610 | cpp | #include <bits/stdc++.h>//construction
using namespace std;
#define pb push_back
typedef long long LL;
const int N = 30;
int a[N][N];
int main() {
int T;
LL k;
scanf("%d", &T);
while (T--) {
memset(a, 0, sizeof(a));
puts("28 21");
for (int i = 1; i <= 8; ++i)
for (int j = 1; j <= 8; ++j)
a[i][j] = 1;
for (int i = 9; i <= 27; ++i) a[i][i + 1] = 1;
scanf("%I64d", &k);
for (int i = 1; i <= 20; ++i, k /= 8)
for (int j = 1; j <= k % 8; ++j)
a[j][8 + i] = 1;
for (int i = 1; i <= 28; ++i) {
for (int j = 1; j <= 28; ++j) printf("%d", a[i][j]);
puts("");
}
}
return 0;
}
| [
"njumlz@gmail.com"
] | njumlz@gmail.com |
cfb7b53d63c4935bda131d45ea7602c930d8c311 | ccaf43320529059e43365b518fbfe7fa56a2a272 | /이동하기.cpp | 0d241b1b560da540ef35f01dd07ef211321189fa | [] | no_license | minsoonss/BOJ-Algospot | c02aeacfb1fa02909a3fb9a4c8ad1bc109325565 | bc3ead24d06e5632f5598b4772451875f026d4c5 | refs/heads/master | 2020-12-03T15:40:59.262840 | 2016-08-26T07:16:26 | 2016-08-26T07:16:26 | 66,530,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 394 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
int d[1001][1001];
int main(){
int n,m,i,j;
cin >> n >> m;
for(i = 1; i <= n; i++){
for(j = 1; j <= m; j++){
cin >> d[i][j];
if(i == 0 && j > 0)d[i][j] += d[i][j-1];
else if(j == 0 && i > 0)d[i][j] += d[i-1][j];
else{
d[i][j]+=max(d[i-1][j-1],max(d[i-1][j],d[i][j-1]));
}
}
}
cout << d[n][m];
} | [
"wp024302@gmail.com"
] | wp024302@gmail.com |
9dcd2658a2e7ed1e90eec791899226b4bbc592fa | 71a0a5bffa4bfd8ed0b398c79f09c48705a2ae27 | /smart_feeder/smart_feeder.ino | f791c1ca605105c83a140636c8a472393f076eaa | [] | no_license | ariyanki/esp8266 | 4eaad9b9b73e68c37805624044335305acd83ee3 | e4b3fed4b79cec27f529327ad8bfe304d6554eb0 | refs/heads/master | 2023-02-13T07:39:06.047761 | 2021-01-03T10:07:32 | 2021-01-03T10:07:32 | 273,612,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,849 | ino | // Load Wi-Fi library
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <EEPROM.h>
#include <ArduinoOTA.h>
Servo servo;
int servoFrom = 0;
int servoTo = 0;
// #### Network Configuration ####
// Access Point network credentials
const char* hostname = "pakanikan1";
const char* ap_ssid = "pakanikan1";
const char* ap_password = "esp826612345";
bool wifiConnected = false;
// Set web server port number to 80
ESP8266WebServer server(80);
// #### NTP Configuration ####
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
String months[12]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "id.pool.ntp.org", (7*3600));
// #### Time ####
unsigned long timeNow = 0;
unsigned long timeLast = 0;
int startingHour = 0;
int seconds = 0;
int minutes = 0;
int hours = startingHour;
String currentDate = "";
String currentDay = "";
// #### Timer Configuration ####
#define TIMER_LIMIT 24 // for 24 times setting, each time 9 char *24
String timer[TIMER_LIMIT];
// #### EEPROM to store Data ####
// character length setting
int singleLength = 1;
int ssidLength = 32;
int pwdLength = 32;
int ipLength=15;
int timeLength=9*TIMER_LIMIT;
// Address Position setting
int ssidAddr = 0;
int pwdAddr = ssidAddr+ssidLength;
int ipAddr = pwdAddr+pwdLength;
int ipSubnetAddr = ipAddr+ipLength;
int ipGatewayAddr = ipSubnetAddr+ipLength;
int ipDNSAddr = ipGatewayAddr+ipLength;
int gpioAddr = ipDNSAddr+ipLength;
int servoWriteFromAddr = gpioAddr+singleLength;
int servoWriteToAddr = servoWriteFromAddr+singleLength;
int timeAddr = servoWriteToAddr+singleLength;
int eepromSize=timeAddr+timeLength;
void eeprom_write(String buffer, int addr, int length) {
String curVal = eeprom_read(addr, length);
// Check before write to minimize eeprom write operation
if(curVal!=buffer){
int bufferLength = buffer.length();
EEPROM.begin(eepromSize);
delay(10);
for (int L = addr; L < addr+bufferLength; ++L) {
EEPROM.write(L, buffer[L-addr]);
}
//set empty
for (int L = addr+bufferLength; L < addr+length; ++L) {
EEPROM.write(L, 255);
}
EEPROM.commit();
}
}
String eeprom_read(int addr, int length) {
EEPROM.begin(eepromSize);
String buffer="";
delay(10);
for (int L = addr; L < addr+length; ++L){
if (isAscii(EEPROM.read(L)))
buffer += char(EEPROM.read(L));
}
return buffer;
}
void eeprom_write_single(int value, int addr) {
int curVal = eeprom_read_single(addr);
// Check before write to minimize eeprom write operation
if(curVal!=value){
EEPROM.begin(eepromSize);
EEPROM.write(addr, value);
EEPROM.commit();
}
}
int eeprom_read_single(int addr) {
EEPROM.begin(eepromSize);
return EEPROM.read(addr);
}
// #### HTTP Configuration ####
String logStr = "";
String headerHtml = "<!DOCTYPE html><html>"
"<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
"<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\" integrity=\"sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu\" crossorigin=\"anonymous\">"
"<link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\">"
"<style>"
"html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}"
"body {margin:0px}"
".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;"
"text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}"
".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}"
".button2 {background-color: #77878A;border-radius: 15px; display: inline-grid;text-decoration: none;}"
".header {background-color: black; color: white;padding: 20px;margin: 0px; margin-bottom: 20px;}"
".switch {position: relative; display: inline-block; width: 120px; height: 68px} "
".switch input {display: none}"
".slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 34px}"
".slider:before {position: absolute; content: \"\"; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 68px}"
"input:checked+.slider {background-color: #2196F3}"
"input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}"
"</style></head>";
String footerHtml = "<script src=\"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\" integrity=\"sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd\" crossorigin=\"anonymous\"></script>"
"<html>";
String redirectToRootHtml = "<!DOCTYPE html><html>"
"<head><script>window.location.href = \"/\";</script></head>"
"<body></body></html>";
String savedNotifHtml = headerHtml + "<body><br/><br/>"
"<p>Your configuration has been saved, if you are sure with your configuration then please restart your device</p>"
"<p><a href=\"#\"><button class=\"button button2\" onclick=\"restart()\"><i class=\"fas fa-redo\"></i> Restart</button></a></p>"
"<p><a href=\"/\"><button class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Back to home</button></a></p>"
"<script>"
"function restart(element) {"
"var xhr = new XMLHttpRequest();"
"xhr.open(\"GET\", \"/restart\", true);"
"xhr.send();"
"}"
"</script>"
"</body>"+footerHtml;
void handleRoot() {
String htmlRes = headerHtml + "<body><h1 class=\"header\">Smart Feeder</h1>"
"<h3 style=\"margin-bottom: 20px;\">"+currentDay+", "+currentDate+" "+hours+":"+minutes+":"+seconds+"</h3><hr>"
"<p>"+logStr+"</p>"
"<p><button class=\"button button2\" onclick=\"testFeed()\">Feeding Test</button></p>"
"<p>To make this timer work, please make sure your wifi connected to the internet to get time from NTP Server.</p>"
"<p>If the datetime above correct then your wifi configuration is correct.</p>"
"<p style=\"margin-top: 40px;\"><a href=\"/settings\"><button class=\"button button2\"><i class=\"fas fa-cogs\"></i> Settings</button></a></p>"
"<script>function testFeed() {"
"var xhr = new XMLHttpRequest();"
"xhr.open(\"GET\", \"/feeding\", true);"
"xhr.send();"
"}"
"</script>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleSettings() {
String htmlRes = headerHtml + "<body><h1 class=\"header\">Settings</h1>"
"<h3 style=\"margin-bottom: 20px;\">"+currentDay+", "+currentDate+" "+hours+":"+minutes+":"+seconds+"</h3><hr>"
"<p><a href=\"/wificonfig\"><button class=\"button button2\"><i class=\"fas fa-wifi\"></i> Wifi Config</button></a></p>"
"<p><a href=\"/servoconfig\"><button class=\"button button2\"><i class=\"fas fa-plug\"></i> Servo Config</button></a></p>"
"<p><a href=\"/timerconfig\"><button class=\"button button2\"><i class=\"fas fa-clock\"></i> Timer Config</button></a></p>"
"<p><a href=\"#\"><button class=\"button button2\" onclick=\"synctime()\"><i class=\"fas fa-clock\"></i> Sync Time</button></a></p>"
"<p><a href=\"#\"><button class=\"button button2\" onclick=\"restart()\"><i class=\"fas fa-redo\"></i> Restart</button></a></p>"
"<p><a href=\"/\"><button class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Back to home</button></a></p>"
"<p></p>"
"<script>"
"function restart(element) {"
"var xhr = new XMLHttpRequest();"
"xhr.open(\"GET\", \"/restart\", true);"
"xhr.send();"
"}"
"function synctime(element) {"
"var xhr = new XMLHttpRequest();"
"xhr.open(\"GET\", \"/synctime\", true);"
"xhr.send();"
"}"
"</script>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleFeeding() {
servoWrite();
server.send(200, "text/plain", "OK");
}
void handleWifiConfigForm() {
String ssid = eeprom_read(ssidAddr, ssidLength);
String password = eeprom_read(pwdAddr, pwdLength);
String strIp = eeprom_read(ipAddr, ipLength);
String strSubnet = eeprom_read(ipSubnetAddr, ipLength);
String strGateway = eeprom_read(ipGatewayAddr, ipLength);
String strDNS = eeprom_read(ipDNSAddr, ipLength);
String htmlRes = headerHtml + "<body><h1 class=\"header\">Wifi Config</h1>"
"<form method=post action=\"/savewificonfig\" style=\"margin: 20px\">"
"<p><b>SSID</b><br/><input type=text class=\"form-control\" name=ssid id=ssid value=\""+ssid+"\"><br/>(max 32 character)</p>"
"<p><b>Password</b><br/><input type=text class=\"form-control\" name=password id=password value=\""+password+"\"><br/>(max 32 character)</p>"
"<p>Manual Setting IP<br/>(leave empty if you want to use DHCP)</p>"
"<p><b>IP Address</b><br/><input type=text class=\"form-control\" name=ip id=ip value=\""+strIp+"\"></p>"
"<p><b>Subnet</b><br/><input type=text class=\"form-control\" name=subnet id=subnet value=\""+strSubnet+"\"></p>"
"<p><b>Gateway</b><br/><input type=text class=\"form-control\" name=gateway id=gateway value=\""+strGateway+"\"></p>"
"<p><b>DNS</b><br/><input type=text class=\"form-control\" name=dns id=dns value=\""+strDNS+"\"></p>"
"<p><button type=submit value=Save class=\"button button2\"><i class=\"fas fa-save\"></i> Save</button> <button type=\"button\" onclick=\"window.location.href = '/';\" class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Cancel</button></p>"
"</form>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleSaveWifiConfigForm() {
eeprom_write(server.arg("ssid"), ssidAddr,ssidLength);
eeprom_write(server.arg("password"), pwdAddr,pwdLength);
eeprom_write(server.arg("ip"), ipAddr,ipLength);
eeprom_write(server.arg("subnet"), ipSubnetAddr,ipLength);
eeprom_write(server.arg("gateway"), ipGatewayAddr,ipLength);
eeprom_write(server.arg("dns"), ipDNSAddr,ipLength);
server.send(200, "text/html", savedNotifHtml);
}
void handleServoConfigForm() {
String strGPIO = String(eeprom_read_single(gpioAddr));
String strWriteFrom = String(eeprom_read_single(servoWriteFromAddr));
String strWriteTo = String(eeprom_read_single(servoWriteToAddr));
String htmlRes = headerHtml + "<body><h1 class=\"header\">Servo Config</h1>"
"<form method=post action=\"/saveservoconfig\" style=\"margin: 20px\">"
"<p><b>GPIO Number</b></br><input type=text class=\"form-control\" name=gpio id=gpio value=\""+strGPIO+"\"></p>"
"<p><b>Write From</b></br><input type=text class=\"form-control\" name=write_from id=write_from value=\""+strWriteFrom+"\"></p>"
"<p><b>Write To</b></br><input type=text class=\"form-control\" name=write_to id=write_to value=\""+strWriteTo+"\"></p>"
"<p><button type=submit value=Save class=\"button button2\"><i class=\"fas fa-save\"></i> Save</button> <button type=\"button\" onclick=\"window.location.href = '/';\" class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Cancel</button></p>"
"</form>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleSaveServoConfigForm() {
eeprom_write_single(server.arg("gpio").toInt(), gpioAddr);
eeprom_write_single(server.arg("write_from").toInt(), servoWriteFromAddr);
eeprom_write_single (server.arg("write_to").toInt(), servoWriteToAddr);
server.send(200, "text/html", savedNotifHtml);
}
void handleTimerConfigForm() {
String strTimer = eeprom_read(timeAddr, timeLength);
String htmlRes = headerHtml + "<body><h1 class=\"header\">Timer Config</h1>"
"<form method=post action=\"/savetimerconfig\" style=\"margin: 20px\">"
"<p>Format hour:minute:second without \"0\"<br/>"
"For multiple time input with \";\" delimitier<br/>"
"To save memory it has limit "+String(TIMER_LIMIT)+" times setting maximum<br/>"
"<b>Example:</b> 1:30:0;6:8:0;18:7:12</p>"
"<p><b>Timer</b></br><input type=text class=\"form-control\" name=timer id=timer value=\""+strTimer+"\"></p>"
"<p><button type=submit value=Save class=\"button button2\"><i class=\"fas fa-save\"></i> Save</button> <button type=\"button\" onclick=\"window.location.href = '/';\" class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Cancel</button></p>"
"</form>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleSaveTimerConfigForm() {
eeprom_write(server.arg("timer"), timeAddr,timeLength);
readTimer();
server.send(200, "text/html", redirectToRootHtml);
}
void handleRestart() {
ESP.restart();
}
void handleSyncTime() {
syncTime();
}
void servoWrite() {
// Total delay must be more than 1000 milisecond when using timer
servo.write(servoTo);
delay(500);
servo.write(servoFrom);
delay(2000);
}
void connectToWifi(){
// GET Wifi Config from EEPROM
String ssid = eeprom_read(ssidAddr, ssidLength);
Serial.println("EEPROM "+String(eepromSize)+" Config:");
Serial.println(ssid);
if(ssid.length()>0){
String password = eeprom_read(pwdAddr, pwdLength);
Serial.println(password);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
int i = 0;
while (WiFi.status() != WL_CONNECTED) {
i++;
if(i>20) break;
delay(500);
Serial.print(".");
}
if(i>20) {
Serial.println("WiFi not connected. Please use \""+String(ap_ssid)+"\" AP to config");
}else{
//Set Static IP
String strIp = eeprom_read(ipAddr, ipLength);
Serial.println(strIp);
IPAddress local_IP;
if(local_IP.fromString(strIp)){
Serial.println("IP Parsed");
String strSubnet = eeprom_read(ipSubnetAddr, ipLength);
String strGateway = eeprom_read(ipGatewayAddr, ipLength);
String strDNS = eeprom_read(ipDNSAddr, ipLength);
Serial.println(strSubnet);
Serial.println(strGateway);
Serial.println(strDNS);
IPAddress gateway;
IPAddress subnet;
IPAddress dns;
if(gateway.fromString(strSubnet)){
Serial.println("Gateway Parsed");
}
if(subnet.fromString(strGateway)){
Serial.println("Subnet Parsed");
}
if(dns.fromString(strDNS)){
Serial.println("DNS Parsed");
}
if (!WiFi.config(local_IP, dns, gateway, subnet)) {
Serial.println("STA Failed to configure");
}
}
Serial.println("WiFi connected.");
//Set hostname
if (!MDNS.begin(hostname)) {
Serial.println("Error setting up MDNS responder!");
}
wifiConnected = true;
timeClient.begin();
syncTime();
}
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
}
void readTimer(){
// GET timer for EEPROM
String strTime = eeprom_read(timeAddr, timeLength);
int f = 0, r=0;
for (int i=0; i < strTime.length(); i++)
{
if(strTime.charAt(i) == ';')
{
timer[f] = strTime.substring(r, i);
r=(i+1);
f++;
}
}
}
void syncTime(){
if (wifiConnected){
timeClient.update();
seconds = timeClient.getSeconds();
minutes = timeClient.getMinutes();
hours = timeClient.getHours();
timeLast = millis();
unsigned long epochTime = timeClient.getEpochTime();
struct tm *ptm = gmtime ((time_t *)&epochTime);
int monthDay = ptm->tm_mday;
int currentMonth = ptm->tm_mon+1;
String currentMonthName = months[currentMonth-1];
int currentYear = ptm->tm_year+1900;
currentDay = String(daysOfTheWeek[timeClient.getDay()]);
currentDate = String(monthDay) + " " + String(currentMonthName) + " " + String(currentYear);
}
}
void updateTime(){
timeNow = millis();
if (timeNow >= timeLast+1000){
timeLast=timeNow;
seconds = seconds + 1;
if (seconds == 60) {
seconds = 0;
minutes = minutes + 1;
}
if (minutes == 60){
minutes = 0;
hours = hours + 1;
}
if (hours == 24){
hours = 0;
}
}
}
void setup() {
Serial.begin(115200);
delay(100);
// Initialize servo pin
servo.attach(eeprom_read_single(gpioAddr));
servoFrom = eeprom_read_single(servoWriteFromAddr);
servoTo = eeprom_read_single(servoWriteToAddr);
servo.write(servoFrom);
// Initialize Access Point
WiFi.softAP(ap_ssid, ap_password);
Serial.print("visit: \n");
Serial.println(WiFi.softAPIP());
connectToWifi();
readTimer();
// start web server
server.on("/", handleRoot);
server.on("/settings", handleSettings);
server.on("/feeding", handleFeeding);
server.on("/wificonfig", handleWifiConfigForm);
server.on("/savewificonfig", HTTP_POST, handleSaveWifiConfigForm);
server.on("/servoconfig", handleServoConfigForm);
server.on("/saveservoconfig", HTTP_POST, handleSaveServoConfigForm);
server.on("/timerconfig", handleTimerConfigForm);
server.on("/savetimerconfig", HTTP_POST, handleSaveTimerConfigForm);
server.on("/restart", HTTP_GET, handleRestart);
server.on("/synctime", HTTP_GET, handleSyncTime);
server.begin();
ArduinoOTA.onStart([]() {
Serial.println("Start");
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
}
long lastMilis = 0;
void loop(){
server.handleClient();
updateTime();
ArduinoOTA.handle();
// execute in second
if (millis() >= lastMilis+1000){
lastMilis=millis();
if (seconds == 30 and !wifiConnected){
connectToWifi();
}
// Execute Timer
String checkTime = String(hours)+":"+String(minutes)+":"+String(seconds);
for (int i=0;i<TIMER_LIMIT;i++){
if (timer[i] == checkTime) {
servoWrite();
}
}
}
}
| [
"ariyanki.bahtiar@gmail.com"
] | ariyanki.bahtiar@gmail.com |
0971f829aa2cb6d969f9e717835a159ffc76f084 | b8a69a6f1c2996fdc3de3ad1b22a1208849277f6 | /leftRotation.cpp | 7794deb21bb94c6c550d2a3876328eb4c07c2119 | [] | no_license | bjeevana94/HackerRank | bc8601be9e76df5862141668de053a1d035788d9 | 34c68d1083e003943ea91246d6412f9b1b402192 | refs/heads/master | 2021-01-11T20:16:01.641946 | 2017-06-13T09:08:16 | 2017-06-13T09:08:16 | 79,077,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 972 | cpp | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
vector<int> array_left_rotation(vector<int> a, int n, int k) {
for (int i = 0; i < k; i++){
a.push_back(a[0]);
a.erase(a.begin() + 0);
}
return a;
}
int main(){
int n;
int k;
cin >> n >> k;
vector<int> a(n);
for(int a_i = 0;a_i < n;a_i++){
cin >> a[a_i];
}
vector<int> output = array_left_rotation(a, n, k);
for(int i = 0; i < n;i++)
cout << output[i] << " ";
cout << endl;
return 0;
}
| [
"noreply@github.com"
] | bjeevana94.noreply@github.com |
18069a82cad06a7e80c04792ca4830e5e87fe9f9 | 8763ca36fd606b2337dcef06c844673f710ac533 | /BSTNode.cpp | 2ac780311eafeec11c78acff0d22cec4af546933 | [] | no_license | espadatiburon/menuBST_CPP | 529e416824416beb10df932dab5d873a5bc4b983 | 8a0d271a2408c36183fdb5877863035e5e65ff65 | refs/heads/master | 2020-03-21T01:57:37.648421 | 2018-06-20T02:48:55 | 2018-06-20T02:48:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,987 | cpp | #ifndef BSTNODE_CPP
#define BSTNODE_CPP
#include "BSTNode.h"
namespace cs20 {
template <class Object>
BSTNode<Object>::BSTNode( const Object& theElement,
BSTNode<Object> * theLeftSide,
BSTNode<Object> * theRightSide,
int theSize) {
element = theElement;
rightSide = theRightSide;
leftSide = theLeftSide;
sz = theSize;
}
template <class Object>
int BSTNode<Object>::size( BSTNode<Object> * node ) {
if (node == nullptr )
return( 0 );
else
return( 1 + size( node->rightSide ) + size( node->leftSide ) );
}
template <class Object>
int BSTNode<Object>::height( BSTNode<Object> * node ) {
if (node == nullptr )
return( -1 );
else
return( 1 + max( height( node->leftSide ), height( node->rightSide ) ) );
}
template <class Object>
BSTNode<Object> * BSTNode<Object>::duplicate( ) const {
BSTNode<Object> * newNode = new BSTNode<Object>( element );
if (rightSide != nullptr) {
newNode->rightSide = rightSide->duplicate();
}
if (leftSide != nullptr) {
newNode->leftSide = leftSide->duplicate();
}
newNode->sz = sz;
return( newNode );
}
template <class Object>
std::ostream& BSTNode<Object>::printBSTNode( std::ostream& outs ) const {
Object o = element;
outs << o << " ";
if (leftSide != nullptr)
leftSide->printBSTNode( outs );
else
outs << "LSNULLPTR ";
if (rightSide != nullptr)
rightSide->printBSTNode( outs );
else
outs << "RSNULLPTR ";
outs << std::endl;
return( outs );
}
template <class Object>
int BSTNode<Object>::max( int a, int b ) {
int result = a;
if (b > a)
result = b;
return( result );
}
template <class Object>
const Object& BSTNode<Object>::getElement() const {
return( element );
}
template <class Object>
BSTNode<Object>* BSTNode<Object>::getLeftSide() const {
return( leftSide );
}
template <class Object>
BSTNode<Object>* BSTNode<Object>::getRightSide() const {
return( rightSide );
}
}
#endif | [
"noreply@github.com"
] | espadatiburon.noreply@github.com |
d9d54298286227c10bef0dc7ba0b8aed62a4359a | bac649c895da8043ddb346a98ae1ae56a8d96a31 | /Codes/Light OJ/1053 - Higher Math/HigherMath.cpp | c7b1aee9bdaba100cd378292a8eee8dbe8a393b4 | [] | no_license | raihanthecooldude/ACM | f3d376554df7b744f771bbf559ab9e28e37a25cb | 4c4c6e5de49670abbd9976daf2ae723520874aea | refs/heads/master | 2021-07-02T00:46:57.203310 | 2019-05-27T17:59:37 | 2019-05-27T17:59:37 | 139,543,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | cpp | #include<bits/stdc++.h>
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
#define pi 3.1415927
#define MOD 1000000007
#define MAX 100005
#define UMAX 9223372036854775807
#define MAXARRAY 2000002
#define ll long long
#define nl '\n'
#define xx first
#define yy second
#define pb push_back
#define ss stringstream
int main()
{
int t, caseno=1;
cin>>t;
while(caseno<=t)
{
int a, b, c;
cin>>a>>b>>c;
if(((a*a)+(b*b)==(c*c)) || ((a*a)+(c*c)==(b*b)) || ((c*c)+(b*b)==(a*a)))
{
cout<<"Case "<<caseno<<": yes"<<endl;
}
else
{
cout<<"Case "<<caseno<<": no"<<endl;
}
caseno++;
}
return 0;
}
| [
"raihanthecooldude@gmail.com"
] | raihanthecooldude@gmail.com |
f89bc743c3b956d4a2b8bc2764230d6ca0cfd4fa | 492976adfdf031252c85de91a185bfd625738a0c | /src/Game/AI/AI/aiCastleLynelBattle.h | ff1ec332e671195a3d4d1e953a6d905629f7963b | [] | no_license | zeldaret/botw | 50ccb72c6d3969c0b067168f6f9124665a7f7590 | fd527f92164b8efdb746cffcf23c4f033fbffa76 | refs/heads/master | 2023-07-21T13:12:24.107437 | 2023-07-01T20:29:40 | 2023-07-01T20:29:40 | 288,736,599 | 1,350 | 117 | null | 2023-09-03T14:45:38 | 2020-08-19T13:16:30 | C++ | UTF-8 | C++ | false | false | 530 | h | #pragma once
#include "Game/AI/AI/aiLynelBattle.h"
#include "KingSystem/ActorSystem/actAiAi.h"
namespace uking::ai {
class CastleLynelBattle : public LynelBattle {
SEAD_RTTI_OVERRIDE(CastleLynelBattle, LynelBattle)
public:
explicit CastleLynelBattle(const InitArg& arg);
~CastleLynelBattle() override;
bool init_(sead::Heap* heap) override;
void enter_(ksys::act::ai::InlineParamPack* params) override;
void leave_() override;
void loadParams_() override;
protected:
};
} // namespace uking::ai
| [
"leo@leolam.fr"
] | leo@leolam.fr |
8e01190e73cb3a74e5910323e5f7f4266331ac79 | 14e00a226015c07522cc99b70fbcee5a2a8747d7 | /lab1/catkin_ws/src/libclfsm/src/FSMSuspensibleMachine.cc | 0ce38fce2989d1de85d6c9c76e394c36b86b53c0 | [
"Apache-2.0"
] | permissive | Joshua-Mitchell/robotics | 031fa1033bda465b813c40633da57886c3446a2c | 3f60f72bfaf9de4e2d65c7baac0dd57ee2d556b8 | refs/heads/master | 2020-04-27T13:01:25.073103 | 2019-03-10T14:49:08 | 2019-03-10T14:49:08 | 174,352,695 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,806 | cc | /*
* FSMSuspensibleMachine.cc
*
* Created by René Hexel on 24/09/11.
* Copyright (c) 2011-2014 Rene Hexel.
* 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. All advertising materials mentioning features or use of this
* software must display the following acknowledgement:
*
* This product includes software developed by Rene Hexel.
*
* 4. Neither the name of the author nor the names of 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.
*
* -----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or
* modify it under the above terms or under the terms of the GNU
* General Public License as published by the Free Software Foundation;
* either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see http://www.gnu.org/licenses/
* or write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "FSMSuspensibleMachine.h"
#include "FSMState.h"
using namespace FSM;
SuspensibleMachine::~SuspensibleMachine()
{
if (_deleteSuspendState && _suspendState)
delete _suspendState;
}
void SuspensibleMachine::setSuspendState(State *s, bool del)
{
if (_deleteSuspendState && _suspendState)
delete _suspendState;
_suspendState = s;
_deleteSuspendState = del;
}
void SuspensibleMachine::suspend()
{
using namespace std;
if (!_suspendState)
{
_suspendState = new State(-1, "Suspended");
if (!_suspendState)
throw "Unable to create dynamic suspend state";
_deleteSuspendState = true;
}
if (currentState() != _suspendState)
{
_resumeState = currentState();
setPreviousState(_resumeState);
if (debugSuspends)
cerr << "Suspend " << id() << ": " << previousState()->name() << " -> " << currentState()->name() << endl;
}
else if (debugSuspends > 1)
cerr << "Suspend " << id() << ": " << previousState()->name() << " -> " << currentState()->name() << " (re-suspend)" << endl;
setCurrentState(_suspendState);
}
void SuspensibleMachine::resume()
{
using namespace std;
State *curr = currentState();
/*
* only do anything if suspended
*/
if (curr != _suspendState)
{
if (debugSuspends > 1)
cerr << "Resume " << id() << ": " << currentState()->name() << " -> " << currentState()->name() << " (re-resume)" << endl;
return;
}
State *prev = _resumeState;
if (!prev || prev == _suspendState) prev = states()[0];
setPreviousState(curr);
setCurrentState(prev);
if (debugSuspends)
cerr << "Resume " << id() << ": " << curr->name() << " -> " << prev->name() << (prev == states()[0] ? " (initial)" : "") << endl;
}
| [
"joshua.mitchell4@griffithuni.edu.au"
] | joshua.mitchell4@griffithuni.edu.au |
5cb77790949fc5e25e6199110586b10ebe64a4f8 | 6278552a2faaef9534f8a599dae881063fe12cf5 | /src/main.cpp | 0385189adb3e5e823e71df088315f7b751cc9371 | [] | no_license | SyedAzizEnam/MPC-Controller | 0fc8eafc9888bc48ad3ceca367910c02a22d2d31 | 7698677f7f1c8d00e00be7fdfadb598b7603aa1c | refs/heads/master | 2020-06-16T18:27:04.724289 | 2017-07-30T20:31:00 | 2017-07-30T20:31:00 | 94,153,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,247 | cpp | #include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "MPC.h"
#include "json.hpp"
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.rfind("}]");
if (found_null != string::npos) {
return "";
} else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
// Evaluate a polynomial.
double polyeval(Eigen::VectorXd coeffs, double x) {
double result = 0.0;
for (int i = 0; i < coeffs.size(); i++) {
result += coeffs[i] * pow(x, i);
}
return result;
}
// Fit a polynomial.
// Adapted from
// https://github.com/JuliaMath/Polynomials.jl/blob/master/src/Polynomials.jl#L676-L716
Eigen::VectorXd polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals,
int order) {
assert(xvals.size() == yvals.size());
assert(order >= 1 && order <= xvals.size() - 1);
Eigen::MatrixXd A(xvals.size(), order + 1);
for (int i = 0; i < xvals.size(); i++) {
A(i, 0) = 1.0;
}
for (int j = 0; j < xvals.size(); j++) {
for (int i = 0; i < order; i++) {
A(j, i + 1) = A(j, i) * xvals(j);
}
}
auto Q = A.householderQr();
auto result = Q.solve(yvals);
return result;
}
int main() {
uWS::Hub h;
// MPC is initialized here!
MPC mpc;
h.onMessage([&mpc](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,
uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
string sdata = string(data).substr(0, length);
cout << sdata << endl;
if (sdata.size() > 2 && sdata[0] == '4' && sdata[1] == '2') {
string s = hasData(sdata);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
vector<double> ptsx = j[1]["ptsx"];
vector<double> ptsy = j[1]["ptsy"];
double px = j[1]["x"];
double py = j[1]["y"];
double psi = j[1]["psi"];
double v = j[1]["speed"];
// Transform ptsx and ptsy to car's reference
for (int i = 0; i< ptsx.size(); i++)
{
//translate
double t_x = ptsx[i] - px;
double t_y = ptsy[i] - py;
//rotate
ptsx[i] = t_x * cos(-psi) - t_y * sin(-psi);
ptsy[i] = t_x * sin(-psi) + t_y * cos(-psi);
}
//convert std::vector to Eigen::VectorXd
double* ptr_x = &ptsx[0];
Eigen::Map<Eigen::VectorXd> ptsx_v(ptr_x, ptsx.size());
double* ptr_y = &ptsy[0];
Eigen::Map<Eigen::VectorXd> ptsy_v(ptr_y, ptsy.size());
Eigen::VectorXd coeffs = polyfit(ptsx_v, ptsy_v, 3);
double cte = polyeval(coeffs, 0);
// simplified since px = py = psi = 0
double epsi = -atan(coeffs[1]);
Eigen::VectorXd state(6);
state << 0.0, 0.0, 0.0, v, cte, epsi;
double Lf = 2.67;
vector<double> mpc_results = mpc.Solve(state, coeffs);
double steer_value = mpc_results[0]/(deg2rad(25)*Lf);
double throttle_value = mpc_results[1];
json msgJson;
// NOTE: Remember to divide by deg2rad(25) before you send the steering value back.
// Otherwise the values will be in between [-deg2rad(25), deg2rad(25] instead of [-1, 1].
msgJson["steering_angle"] = steer_value;
msgJson["throttle"] = throttle_value;
//Display the MPC predicted trajectory
vector<double> mpc_x_vals;
vector<double> mpc_y_vals;
for (int i = 2; i < mpc_results.size(); i++)
{
if (i%2 == 0) {
mpc_x_vals.push_back(mpc_results[i]);
}
else {
mpc_y_vals.push_back(mpc_results[i]);
}
}
//.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system
// the points in the simulator are connected by a Green line
msgJson["mpc_x"] = mpc_x_vals;
msgJson["mpc_y"] = mpc_y_vals;
//Display the waypoints/reference line
vector<double> next_x_vals;
vector<double> next_y_vals;
double poly_inc = 2.5;
int num_points = 25;
for (int i = 0; i< num_points; i++)
{
next_x_vals.push_back(poly_inc*i);
next_y_vals.push_back(polyeval(coeffs, poly_inc*i));
}
//.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system
// the points in the simulator are connected by a Yellow line
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
std::cout << msg << std::endl;
// Latency
// The purpose is to mimic real driving conditions where
// the car does actuate the commands instantly.
//
// Feel free to play around with this value but should be to drive
// around the track with 100ms latency.
//
// NOTE: REMEMBER TO SET THIS TO 100 MILLISECONDS BEFORE
// SUBMITTING.
this_thread::sleep_for(chrono::milliseconds(100));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the
// program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,
size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1) {
res->end(s.data(), s.length());
} else {
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
| [
"azizenam@gmail.com"
] | azizenam@gmail.com |
f17a18611b4aafb084acbedfb8133a625c2f4030 | 5506803b1e48b519a748510fac5be2047319a333 | /example/oglplus/025_reflected_torus.cpp | 8975c29e862fd514d99c66424a8b9bcf671b8782 | [
"BSL-1.0"
] | permissive | James-Z/oglplus | dc5ed546094c891aeabffcba2db45cfc78e08ef9 | a43867907d5d132ba253178232e8852f51c83e6b | refs/heads/master | 2020-05-29T11:08:14.386144 | 2014-02-13T18:33:03 | 2014-02-13T18:33:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,882 | cpp | /**
* @example oglplus/025_reflected_torus.cpp
* @brief Shows how to draw a torus reflected in a horizontal plane
*
* @oglplus_screenshot{025_reflected_torus}
*
* Copyright 2008-2013 Matus Chochlik. 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)
*
* @oglplus_example_uses_cxx11{FUNCTION_TEMPLATE_DEFAULT_ARGS}
*
* @oglplus_example_uses_gl{GL_VERSION_3_3}
* @oglplus_example_uses_gl{GL_ARB_separate_shader_objects;GL_EXT_direct_state_access}
*/
#include <oglplus/gl.hpp>
#include <oglplus/all.hpp>
#include <oglplus/opt/smart_enums.hpp>
#include <oglplus/shapes/twisted_torus.hpp>
#include <cmath>
#include "example.hpp"
namespace oglplus {
class ReflectionExample : public Example
{
private:
// the torus vertex attribute builder
shapes::TwistedTorus make_torus;
// here will be stored the indices used by the drawing instructions
shapes::TwistedTorus::IndexArray torus_indices;
// the instructions for drawing the torus
shapes::DrawingInstructions torus_instr;
// wrapper around the current OpenGL context
Context gl;
// Vertex shaders for the normally rendered and the reflected objects
VertexShader vs_norm;
VertexShader vs_refl;
// Geometry shader for the reflected objects
GeometryShader gs_refl;
// Fragment shader
FragmentShader fs;
// Programs
Program prog_norm;
Program prog_refl;
// A vertex array object for the torus
VertexArray torus;
// A vertex array object for the reflective plane
VertexArray plane;
// VBOs for the torus' vertices and normals
Buffer torus_verts, torus_normals;
// VBOs for the plane's vertices and normals
Buffer plane_verts, plane_normals;
public:
ReflectionExample(void)
: torus_indices(make_torus.Indices())
, torus_instr(make_torus.Instructions())
, vs_norm(ObjectDesc("Vertex-Normal"))
, vs_refl(ObjectDesc("Vertex-Reflection"))
, gs_refl(ObjectDesc("Geometry-Reflection"))
{
namespace se = oglplus::smart_enums;
// Set the normal object vertex shader source
vs_norm.Source(
"#version 330\n"
"in vec4 Position;"
"in vec3 Normal;"
"out vec3 geomColor;"
"out vec3 geomNormal;"
"out vec3 geomLight;"
"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
"uniform vec3 LightPos;"
"void main(void)"
"{"
" gl_Position = ModelMatrix * Position;"
" geomColor = Normal;"
" geomNormal = mat3(ModelMatrix)*Normal;"
" geomLight = LightPos-gl_Position.xyz;"
" gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
"}"
);
// compile it
vs_norm.Compile();
// Set the reflected object vertex shader source
// which just passes data to the geometry shader
vs_refl.Source(
"#version 330\n"
"in vec4 Position;"
"in vec3 Normal;"
"out vec3 vertNormal;"
"void main(void)"
"{"
" gl_Position = Position;"
" vertNormal = Normal;"
"}"
);
// compile it
vs_refl.Compile();
// Set the reflected object geometry shader source
// This shader creates a reflection matrix that
// relies on the fact that the reflection is going
// to be done by the y-plane
gs_refl.Source(
"#version 330\n"
"layout(triangles) in;"
"layout(triangle_strip, max_vertices = 6) out;"
"in vec3 vertNormal[];"
"uniform mat4 ProjectionMatrix;"
"uniform mat4 CameraMatrix;"
"uniform mat4 ModelMatrix;"
"out vec3 geomColor;"
"out vec3 geomNormal;"
"out vec3 geomLight;"
"uniform vec3 LightPos;"
"mat4 ReflectionMatrix = mat4("
" 1.0, 0.0, 0.0, 0.0,"
" 0.0,-1.0, 0.0, 0.0,"
" 0.0, 0.0, 1.0, 0.0,"
" 0.0, 0.0, 0.0, 1.0 "
");"
"void main(void)"
"{"
" for(int v=0; v!=gl_in.length(); ++v)"
" {"
" vec4 Position = gl_in[v].gl_Position;"
" gl_Position = ModelMatrix * Position;"
" geomColor = vertNormal[v];"
" geomNormal = mat3(ModelMatrix)*vertNormal[v];"
" geomLight = LightPos - gl_Position.xyz;"
" gl_Position = "
" ProjectionMatrix *"
" CameraMatrix *"
" ReflectionMatrix *"
" gl_Position;"
" EmitVertex();"
" }"
" EndPrimitive();"
"}"
);
// compile it
gs_refl.Compile();
// set the fragment shader source
fs.Source(
"#version 330\n"
"in vec3 geomColor;"
"in vec3 geomNormal;"
"in vec3 geomLight;"
"out vec4 fragColor;"
"void main(void)"
"{"
" float l = length(geomLight);"
" float d = l > 0.0 ? dot("
" geomNormal, "
" normalize(geomLight)"
" ) / l : 0.0;"
" float i = 0.2 + max(d, 0.0) * 2.0;"
" fragColor = vec4(abs(geomNormal)*i, 1.0);"
"}"
);
// compile it
fs.Compile();
// attach the shaders to the normal rendering program
prog_norm.AttachShader(vs_norm);
prog_norm.AttachShader(fs);
// link it
prog_norm.Link();
// attach the shaders to the reflection rendering program
prog_refl.AttachShader(vs_refl);
prog_refl.AttachShader(gs_refl);
prog_refl.AttachShader(fs);
// link it
prog_refl.Link();
// bind the VAO for the torus
torus.Bind();
// bind the VBO for the torus vertices
torus_verts.Bind(se::Array());
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.Positions(data);
// upload the data
Buffer::Data(se::Array(), data);
// setup the vertex attribs array for the vertices
typedef VertexAttribArray VAA;
VertexAttribSlot
loc_norm = VAA::GetLocation(prog_norm, "Position"),
loc_refl = VAA::GetLocation(prog_refl, "Position");
assert(loc_norm == loc_refl);
VertexAttribArray attr(loc_norm);
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VBO for the torus normals
torus_normals.Bind(se::Array());
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.Normals(data);
// upload the data
Buffer::Data(se::Array(), data);
// setup the vertex attribs array for the normals
typedef VertexAttribArray VAA;
VertexAttribSlot
loc_norm = VAA::GetLocation(prog_norm, "Normal"),
loc_refl = VAA::GetLocation(prog_refl, "Normal");
assert(loc_norm == loc_refl);
VertexAttribArray attr(loc_norm);
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VAO for the plane
plane.Bind();
// bind the VBO for the plane vertices
plane_verts.Bind(se::Array());
{
GLfloat data[4*3] = {
-2.0f, 0.0f, 2.0f,
-2.0f, 0.0f, -2.0f,
2.0f, 0.0f, 2.0f,
2.0f, 0.0f, -2.0f
};
// upload the data
Buffer::Data(se::Array(), 4*3, data);
// setup the vertex attribs array for the vertices
prog_norm.Use();
VertexAttribArray attr(prog_norm, "Position");
attr.Setup<Vec3f>();
attr.Enable();
}
// bind the VBO for the torus normals
plane_normals.Bind(se::Array());
{
GLfloat data[4*3] = {
-0.1f, 1.0f, 0.1f,
-0.1f, 1.0f, -0.1f,
0.1f, 1.0f, 0.1f,
0.1f, 1.0f, -0.1f
};
// upload the data
Buffer::Data(se::Array(), 4*3, data);
// setup the vertex attribs array for the normals
prog_norm.Use();
VertexAttribArray attr(prog_norm, "Normal");
attr.Setup<Vec3f>();
attr.Enable();
}
VertexArray::Unbind();
Vec3f lightPos(2.0f, 2.0f, 3.0f);
prog_norm.Use();
SetUniform(prog_norm, "LightPos", lightPos);
prog_refl.Use();
SetUniform(prog_refl, "LightPos", lightPos);
//
gl.ClearColor(0.2f, 0.2f, 0.2f, 0.0f);
gl.ClearDepth(1.0f);
gl.ClearStencil(0);
}
void Reshape(GLuint width, GLuint height)
{
gl.Viewport(width, height);
Mat4f projection = CamMatrixf::PerspectiveX(
Degrees(65),
double(width)/height,
1, 40
);
SetProgramUniform(prog_norm, "ProjectionMatrix", projection);
SetProgramUniform(prog_refl, "ProjectionMatrix", projection);
}
void Render(double time)
{
namespace se = oglplus::smart_enums;
gl.Clear().ColorBuffer().DepthBuffer().StencilBuffer();
// make the camera matrix orbiting around the origin
// at radius of 3.5 with elevation between 15 and 90 degrees
Mat4f camera = CamMatrixf::Orbiting(
Vec3f(),
6.5,
Degrees(time * 135),
Degrees(15 + (-SineWave(0.25+time/12.5)+1.0)*0.5*75)
);
ModelMatrixf model = ModelMatrixf::Translation(0.0f, 1.5f, 0.0);
ModelMatrixf identity;
//
SetProgramUniform(prog_norm, "CameraMatrix", camera);
SetProgramUniform(prog_refl, "CameraMatrix", camera);
// draw the plane into the stencil buffer
prog_norm.Use();
gl.Disable(se::Blend());
gl.Disable(se::DepthTest());
gl.Enable(se::StencilTest());
gl.ColorMask(false, false, false, false);
gl.StencilFunc(se::Always(), 1, 1);
gl.StencilOp(se::Keep(), se::Keep(), se::Replace());
Uniform<Mat4f> model_matrix_norm(prog_norm, "ModelMatrix");
model_matrix_norm.Set(identity);
plane.Bind();
gl.DrawArrays(se::TriangleStrip(), 0, 4);
gl.ColorMask(true, true, true, true);
gl.Enable(se::DepthTest());
gl.StencilFunc(se::Equal(), 1, 1);
gl.StencilOp(se::Keep(), se::Keep(), se::Keep());
// draw the torus using the reflection program
prog_refl.Use();
Uniform<Mat4f>(prog_refl, "ModelMatrix").Set(model);
torus.Bind();
torus_instr.Draw(torus_indices);
gl.Disable(se::StencilTest());
prog_norm.Use();
// draw the torus using the normal object program
model_matrix_norm.Set(model);
torus_instr.Draw(torus_indices);
// blend-in the plane
gl.Enable(se::Blend());
gl.BlendEquation(se::Max());
model_matrix_norm.Set(identity);
plane.Bind();
gl.DrawArrays(se::TriangleStrip(), 0, 4);
}
bool Continue(double time)
{
return time < 30.0;
}
};
void setupExample(ExampleParams& /*params*/){ }
std::unique_ptr<ExampleThread> makeExampleThread(
Example& /*example*/,
unsigned /*thread_id*/,
const ExampleParams& /*params*/
){ return std::unique_ptr<ExampleThread>(); }
std::unique_ptr<Example> makeExample(const ExampleParams& /*params*/)
{
return std::unique_ptr<Example>(new ReflectionExample);
}
} // namespace oglplus
| [
"chochlik@gmail.com"
] | chochlik@gmail.com |
81dd136780df0d5f3dcc385ddea4e2835b9f9987 | ed2f89fc0bfb136cbbd5a49733b7e46aadfdc0fd | /_MODEL_FOLDERS_/lightSpheres/lightSpheres_INIT.cpp | 29a55535f2e6ed7de43b3eec94cbe66cd6f8c94e | [] | no_license | marcclintdion/a7_3D_CUBE | 40975879cf0840286ad1c37d80f906db581e60c4 | 1ba081bf93485523221da32038cad718a1f823ea | refs/heads/master | 2021-01-20T12:00:32.550585 | 2015-09-19T03:25:14 | 2015-09-19T03:25:14 | 42,757,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,026 | cpp | #ifdef __APPLE__
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#endif
//===============================================================================================
lightSpheres_SHADER = glCreateProgram();
//---------------------------------------------------------------------
const GLchar *vertexSource_lightSpheres =
" #define highp \n"
" uniform highp vec4 light_POSITION_01; \n"
" uniform mat4 mvpMatrix; \n"
" uniform mat4 mvMatrix; \n"
" uniform mat4 lightMatrix; \n"
" attribute vec4 position; \n"
" attribute vec2 texture; \n"
" varying highp vec4 lightPosition_PASS; \n"
//-------------------------------------------
" uniform mat4 textureMatrix; \n"
" varying highp vec4 shadowTexcoord; \n"
" highp vec4 TEMP_shadowTexcoord; \n"
" uniform highp vec4 offset; \n"
//-------------------------------------------
" varying highp vec2 varTexcoord; \n"
//-----------------------------------------------------------------------------------------------------------------
" varying highp vec3 vertex_pos; \n"
//-----------------------------------------------------------------------------------------------------------------
" void main() \n"
" { \n"
//---------------------------------------------------------------------------------------------------------
" TEMP_shadowTexcoord = textureMatrix * mvpMatrix * position; \n"
" shadowTexcoord = TEMP_shadowTexcoord + offset; \n"
//---------------------------------------------------------------------------------------------------------
" lightPosition_PASS = normalize(lightMatrix * light_POSITION_01); \n"
" varTexcoord = texture; \n"
" gl_Position = mvpMatrix * position; \n"
" }\n";
//#################################################################################################################################
//#################################################################################################################################
//#################################################################################################################################
//#################################################################################################################################
//---------------------------------------------------------------------
lightSpheres_SHADER_VERTEX = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(lightSpheres_SHADER_VERTEX, 1, &vertexSource_lightSpheres, NULL);
glCompileShader(lightSpheres_SHADER_VERTEX);
//---------------------------------------------------------------------
const GLchar *fragmentSource_lightSpheres =
" #ifdef GL_ES \n"
" #else \n"
" #define highp \n"
" #endif \n"
" uniform sampler2DShadow ShadowTexture; \n"
" varying highp vec4 shadowTexcoord; \n"
" highp vec4 shadow; \n"
//--------------------------------------------
" uniform sampler2D Texture1; \n"
" uniform sampler2D NormalMap; \n"
//--------------------------------------------
" uniform highp float constantAttenuation; \n"
//--------------------------------------------
" varying highp vec4 lightPosition_PASS; \n"
" varying highp vec2 varTexcoord; \n"
//--------------------------------------------
" highp float NdotL2; \n"
" highp vec3 normal_2; \n"
" highp vec3 NormalTex; \n"
//-----------------------------------
" void main() \n"
" { \n"
//--------------------------------------------------------------------------------------------------
" vec4 shadowCoordinateWdivide = shadowTexcoord / shadowTexcoord.w; \n"
" shadowCoordinateWdivide.z += constantAttenuation; \n"
" float distanceFromLight = shadow2DProj(ShadowTexture, shadowTexcoord).r; \n"
" float shadow = 1.0; \n"
" if (shadowTexcoord.w > 0.0) \n"
" shadow = distanceFromLight < shadowCoordinateWdivide.z ? 0.3 : 1.0 ; \n"
//--------------------------------------------------------------------------------------------------
" NormalTex = texture2D(NormalMap, varTexcoord.xy).xyz; \n"
" NormalTex = (NormalTex - 0.5); \n"
" normal_2 = normalize(NormalTex); \n"
" NdotL2 = max(dot(normal_2, lightPosition_PASS.xyz), 0.0); \n"
//-----------------------------------------------------------------------------------------------------------------------------
" gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0) ; \n"
" }\n";
//---------------------------------------------------------------------
lightSpheres_SHADER_FRAGMENT = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(lightSpheres_SHADER_FRAGMENT, 1, &fragmentSource_lightSpheres, NULL);
glCompileShader(lightSpheres_SHADER_FRAGMENT);
//------------------------------------------------
glAttachShader(lightSpheres_SHADER, lightSpheres_SHADER_VERTEX);
glAttachShader(lightSpheres_SHADER, lightSpheres_SHADER_FRAGMENT);
//------------------------------------------------
glBindAttribLocation(lightSpheres_SHADER, 0, "position");
glBindAttribLocation(lightSpheres_SHADER, 1, "normal");
glBindAttribLocation(lightSpheres_SHADER, 2, "tangent");
glBindAttribLocation(lightSpheres_SHADER, 3, "texture");
//------------------------------------------------
glLinkProgram(lightSpheres_SHADER);
//------------------------------------------------
#ifdef __APPLE__
glDetachShader(lightSpheres_SHADER, lightSpheres_SHADER_VERTEX);
glDetachShader(lightSpheres_SHADER, lightSpheres_SHADER_FRAGMENT);
#endif
//------------------------------------------------
glDeleteShader(lightSpheres_SHADER_VERTEX);
glDeleteShader(lightSpheres_SHADER_FRAGMENT);
//---------------------------------------------------------------------------------------------------------------------------
UNIFORM_MODELVIEWPROJ_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "mvpMatrix");
UNIFORM_MODELVIEW_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "mvMatrix");
UNIFORM_LIGHT_MATRIX_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "lightMatrix");
UNIFORM_textureMatrix_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "textureMatrix");
UNIFORM_INVERSEMATRIX_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "inverseMatrix");
UNIFORM_offset_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "offset");
//-------------------------------------
UNIFORM_LIGHT_POSITION_01_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "light_POSITION_01");
UNIFORM_SHININESS_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "shininess");
//-------------------------------------
UNIFORM_QUADRATIC_ATTENUATION_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "quadraticAttenuation");
UNIFORM_LINEAR_ATTENUATION_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "linearAttenuation");
UNIFORM_CONSTANT_ATTENUATION_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "constantAttenuation");
//-------------------------------------
UNIFORM_TEXTURE_SHADOW_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "ShadowTexture");
UNIFORM_TEXTURE_DOT3_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "NormalMap");
UNIFORM_TEXTURE_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "Texture1");
//---------------------------------------------------------------------------------------------------------------------------
/*
#ifdef __APPLE__
filePathName = [[NSBundle mainBundle] pathForResource:@"lightSpheres_DOT3" ofType:@"bmp"];
image = imgLoadImage([filePathName cStringUsingEncoding:NSASCIIStringEncoding]);
glGenTextures(1, &lightSpheres_NORMALMAP);
glBindTexture(GL_TEXTURE_2D, lightSpheres_NORMALMAP);
ConfigureAndLoadTexture(image->data, image->width, image->height );
imgDestroyImage(image);
//---------------------
filePathName = [[NSBundle mainBundle] pathForResource:@"lightSpheres" ofType:@"png"];
image = imgLoadImage([filePathName cStringUsingEncoding:NSASCIIStringEncoding]);
glGenTextures(1, &lightSpheres_TEXTUREMAP);
glBindTexture(GL_TEXTURE_2D, lightSpheres_TEXTUREMAP);
ConfigureAndLoadTexture(image->data, image->width, image->height );
imgDestroyImage(image);
#endif
//------------------------------------------------------------------------------------------
#ifdef WIN32
loadTexture("_MODEL_FOLDERS_/lightSpheres/lightSpheres_DOT3.bmp", lightSpheres_NORMALMAP);
loadTexture("_MODEL_FOLDERS_/lightSpheres/lightSpheres.png", lightSpheres_TEXTUREMAP);
#endif
*/
//--------------------------------------------------------------------------------------------------------------------
#include "lightSpheres.cpp"
glGenBuffers(1, &lightSpheres_VBO);
glBindBuffer(GL_ARRAY_BUFFER, lightSpheres_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(lightSpheres), lightSpheres, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//--------------------------------------------------------------------------------------------------------------------
#include "lightSpheres_INDICES.cpp"
glGenBuffers(1, &lightSpheres_INDEX_VBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lightSpheres_INDEX_VBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(lightSpheres_INDICES), lightSpheres_INDICES, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//====================================================================================================================
glGenFramebuffers(1, &geometryLightPass_fboId);
glGenTextures(1, &geometryLightPass_TEXTURE);
glBindTexture(GL_TEXTURE_2D, geometryLightPass_TEXTURE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)viewWidth / resize_LIGHTS_FBO, (GLsizei)viewHeight / resize_LIGHTS_FBO, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glBindFramebuffer(GL_FRAMEBUFFER, geometryLightPass_fboId);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, geometryLightPass_TEXTURE, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//=======================================================================================================================
srand(time(0));
//float randomVelocity[] = {0.0, 0.0, 0.0};
//float randomGravity = 0.0;
for(int i = 0; i < numberOfGeometryLights; i++)
{
lightSpheres_POSITION_ARRAY[i][0] = ((rand()% 10) - 5) *1.1;
lightSpheres_POSITION_ARRAY[i][1] = ((rand()% 10) - 5) *1.1;
lightSpheres_POSITION_ARRAY[i][2] = ((rand()% 10) - 5) *1.1;
//--------------------------------------------------------------------
lightSpheres_VELOCITY_ARRAY[i][0] = ((rand()% 10) - 5) *.002;
lightSpheres_VELOCITY_ARRAY[i][1] = ((rand()% 10) - 5) *.002;
lightSpheres_VELOCITY_ARRAY[i][2] = ((rand()% 10) - 5) *.002;
//--------------------------------------------------------------------
lightSpheres_ROTATION_ARRAY[i][0] = ((rand()% 10) - 5) *.002;
lightSpheres_ROTATION_ARRAY[i][1] = ((rand()% 10) - 5) *.002;
lightSpheres_ROTATION_ARRAY[i][2] = ((rand()% 10) - 5) *.002;
lightSpheres_ROTATION_ARRAY[i][3] = ((rand()% 10) - 5) *.002;
//--------------------------------------------------------------------
lightSpheres_SCALE_ARRAY[i][0] = ((rand()% 10) - 5) *0.4;
lightSpheres_SCALE_ARRAY[i][1] = lightSpheres_SCALE_ARRAY[i][0];
lightSpheres_SCALE_ARRAY[i][2] = lightSpheres_SCALE_ARRAY[i][0];
//--------------------------------------------------------------------
}
//#####################################################################################################################
| [
"marcclintdion@Marcs-iMac.local"
] | marcclintdion@Marcs-iMac.local |
ac865118a1b6695a7f0ed7325e8024b41396cdef | 7d36d9de8ddcf9cc6890ee985d8d515ed67411f6 | /include/user_factors.h | 7949ab2a02466b67a050b7182d9a0be7a1d9de69 | [] | no_license | Calm-wy/monodepth_localization | 0002098f563664e9bf8f45577764643dbf4f5c55 | 8192faf6a6467920a440a41d159bcfb7c3a14e98 | refs/heads/master | 2020-06-17T05:51:06.682349 | 2019-05-24T02:05:02 | 2019-05-24T02:05:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,271 | h | /**
* @file slam_factors.h
* @brief User defined factors
*
*/
#include <isam/isam.h>
#include "user_nodes.h"
// NOTE: When you add a new factor, modify gparser.cpp/h to enable proper graph loading
// Unfortunately, currently no loading from native isam is supported.
#pragma once
namespace Eigen {
typedef Matrix<double, 1, 1> Matrix1d;
}
namespace isam {
class Sonar3d {
public:
static const int dim = 3;
static const char* name() {
return "Sonar2d";
}
private:
Pose2d m_pose;
};
class Plane3d_Factor : public FactorT<Plane3d> {
Plane3d_Node* _plane;
public:
Plane3d_Factor (Plane3d_Node *plane,
const Plane3d& measure, const Noise& noise)
: FactorT<Plane3d> ("Plane3d_Factor", Plane3d::dim, noise, measure),
_plane (plane) {
_nodes.resize(1);
_nodes[0] = plane;
}
void initialize () {
if (!_plane->initialized ()) {
Plane3d predict (_measure);
_plane->init (predict);
}
}
Eigen::VectorXd basic_error (Selector s = ESTIMATE) const {
const Plane3d& plane = _plane->value (s);
Eigen::Vector3d err = plane.vector () - _measure.vector ();
return err;
}
private:
};
class Pose3d_Plane3d_Factor : public FactorT<Plane3d> {
Pose3d_Node* _pose;
Plane3d_Node* _plane;
public:
Pose3d_Plane3d_Factor (Pose3d_Node *pose, Plane3d_Node *plane,
const Plane3d& measure, const Noise& noise)
: FactorT<Plane3d> ("Pose3d_Plane3d_Factor", Plane3d::dim, noise, measure),
_pose (pose),
_plane (plane) {
_nodes.resize(2);
_nodes[0] = pose;
_nodes[1] = plane;
}
void initialize () {
require(_pose->initialized (),
"Pose3d_Plane3d_Factor requires pose to be initialized");
if (!_plane->initialized ()) {
Pose3d pose = _pose->value ();
Plane3d predict (_measure.oplus (pose));
/* std::cout << "measure: " << std::endl; */
/* std::cout << _measure << std::endl; */
/* std::cout << "pose: " << std::endl; */
/* std::cout << pose << std::endl; */
/* std::cout << "predict: " << std::endl; */
/* std::cout << predict << std::endl; */
_plane->init (predict);
}
}
Eigen::VectorXd basic_error (Selector s = ESTIMATE) const {
const Pose3d& thisPose = _pose->value (s);
const Plane3d& plane = _plane->value (s);
Plane3d predict = plane.ominus (thisPose);
Eigen::Vector3d err = predict.vector () - _measure.vector ();
return err;
}
private:
};
/* Pose i and pose j observe two planar patches, k and l respectively, that are
* coplanar */
class Piecewise_Planar_Factor : public Factor {
Pose3d_Node *_posei;
Pose3d_Node *_posej;
Plane3d_Node *_planek;
Plane3d_Node *_planel;
public:
Piecewise_Planar_Factor (Pose3d_Node* posei, Pose3d_Node* posej,
Plane3d_Node* planek, Plane3d_Node* planel,
const Noise& noise,
Anchor3d_Node *anchor1=NULL, Anchor3d_Node *anchor2=NULL)
: Factor ("Piecewise_Planar_Factor", Plane3d::dim, noise),
_posei (posei),
_posej (posej),
_planek (planek),
_planel (planel) {
require((anchor1==NULL && anchor2==NULL) || (anchor1!=NULL && anchor2!=NULL),
"slam3d: Piecewise_Planar_Factor requires either 0 or 2 anchor nodes");
if (anchor1) {
_nodes.resize(6);
_nodes[4] = anchor1;
_nodes[5] = anchor2;
} else {
_nodes.resize(4);
}
_nodes[0] = posei;
_nodes[1] = posej;
_nodes[2] = planek;
_nodes[3] = planel;
}
void initialize () {
if (_nodes.size () == 4) {
require (_posei->initialized () && _posej->initialized () &&
_planek->initialized () && _planel->initialized (),
"Piecewise_Planar_Factor requires both poses and both planes to be initialized");
}
else if (_nodes.size () == 6) {
require (_posei->initialized () && _posej->initialized () &&
_planek->initialized () && _planel->initialized () &&
_nodes[4]->initialized () && _nodes[5]->initialized (),
"Piecewise_Planar_Factor requires both poses, both planes, and both anchors to be initialized");
}
}
Eigen::VectorXd basic_error (Selector s = ESTIMATE) const {
Vector3d err;
if (_nodes.size () == 4) {
/* std::cout << std::endl; */
const Pose3d& posei = _posei->value (s);
const Pose3d& posej = _posej->value (s);
const Plane3d& planek = _planek->value (s);
const Plane3d& planel = _planel->value (s);
#ifdef NON_GLOBAL_PLANES
Plane3d planeik = planek;
Plane3d planejl = planel;
#else
/* return planek.vector () - planel.vector (); */
Plane3d planeik = planek.ominus (posei);
/* Plane3d planeil = planel.ominus (posei); */
Plane3d planejl = planel.ominus (posej);
#endif
Pose3d poseji = posei.ominus (posej);
/* std::cout << "CHECK" << std::endl; */
Plane3d planejlPred = planeik.oplus (poseji);
/* std::cout << "DONE" << std::endl; */
err = planejl.vector () - planejlPred.vector ();
/* const Pose3d& posei = _posei->value (s); */
/* const Pose3d& posej = _posej->value (s); */
/* const Plane3d& planek = _planek->value (s); */
/* const Plane3d& planel = _planel->value (s); */
/* /\* Plane3d planeik = planek.oplus (posei); *\/ */
/* /\* Plane3d planeil = planel.oplus (posei); *\/ */
/* /\* err = planeik.vector () - planeil.vector (); *\/ */
/* /\* err = planek.vector () - planel.vector (); *\/ */
/* Plane3d planeik = planek.ominus (posei); */
/* Plane3d planejl = planel.ominus (posej); */
/* /\* std::cout << "plane ik: " << std::endl; *\/ */
/* /\* std::cout << planeik << std::endl; *\/ */
/* /\* std::cout << "plane k: " << std::endl; *\/ */
/* /\* std::cout << planek << std::endl; *\/ */
/* /\* std::cout << "plane l: " << std::endl; *\/ */
/* /\* std::cout << planel << std::endl; *\/ */
/* /\* std::cout << "plane ik: " << std::endl; *\/ */
/* /\* std::cout << planeik << std::endl; *\/ */
/* /\* std::cout << "plane jl: " << std::endl; *\/ */
/* /\* std::cout << planejl << std::endl; *\/ */
/* Pose3d poseij = posej.ominus (posei); */
/* Plane3d planejlPred = planeik.ominus (poseij); */
/* err = planejlPred.vector () - planejl.vector (); */
/* /\* std::cout << "plane jl pred: " << std::endl; *\/ */
/* /\* std::cout << planejlPred << std::endl; *\/ */
/* std::cout << std::endl; */
/* std::cout << posei << std::endl; */
/* std::cout << posej << std::endl; */
/* std::cout << poseij << std::endl; */
/* std::cout << planejl << std::endl; */
/* std::cout << planelPred << std::endl; */
/* std::cout << err << std::endl; */
/* std::cout << "------------------------------" << std::endl; */
}
else if (_nodes.size () == 6) {
/* std::cout << std::endl; */
const Pose3d& a1 = dynamic_cast<Pose3d_Node*>(_nodes[4])->value(s);
const Pose3d& a2 = dynamic_cast<Pose3d_Node*>(_nodes[5])->value(s);
Pose3d a1Inv = Pose3d (a1.oTw ());
Pose3d a2Inv = Pose3d (a2.oTw ());
const Pose3d& posei = _posei->value (s);
const Pose3d& posej = _posej->value (s);
const Plane3d& planek = _planek->value (s);
const Plane3d& planel = _planel->value (s);
#ifdef GLOBAL_PLANES
Plane3d planeik = planek.oplus (a1);
Plane3d planejl = planel.oplus (a2);
#else
/* return planek.vector () - planel.vector (); */
Plane3d planeik = planek.ominus (a1Inv).ominus (a1.oplus (posei));
/* Plane3d planeil = planel.ominus (posei); */
Plane3d planejl = planel.ominus (a2Inv).ominus (a2.oplus (posej));
#endif
Pose3d poseji = a1.oplus (posei).ominus (a2.oplus (posej));
/* std::cout << "CHECK" << std::endl; */
Plane3d planejlPred = planeik.oplus (poseji);
/* std::cout << "DONE" << std::endl; */
err = planejl.vector () - planejlPred.vector ();
}
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " " << " " << noise_to_string(_noise);
}
};
// A 2d constraint between sonar frames
class Sonar2d_Factor : public FactorT<Pose2d> {
const Pose3d_Node* _pose1;
const Pose3d_Node* _pose2;
Pose3d _sonar_frame1;
Pose3d _sonar_frame2;
public:
/**
* Constructor.
* @param pose1 The pose from which the measurement starts.
* @param pose2 The pose to which the measurement extends.
* @param measure The relative measurement from pose1 to pose2 (pose2 in pose1's frame).
* @param noise The 3x3 square root information matrix (upper triangular).
* @sonar_frame1 the transformation from pose1 to the sonar frame.
* @sonar_frame2 the transfomration from pose2 to the sonar frame.
*/
Sonar2d_Factor(Pose3d_Node* pose1, Pose3d_Node* pose2,
const Pose2d& measure, const Noise& noise,
Pose3d sonar_frame1, Pose3d sonar_frame2)
: FactorT<Pose2d>("Sonar2d_Factor", 3, noise, measure),
_pose1(pose1),
_pose2(pose2),
_sonar_frame1(sonar_frame1),
_sonar_frame2(sonar_frame2)
{
_nodes.resize(2);
_nodes[0] = pose1;
_nodes[1] = pose2;
}
void initialize() {
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// @todo add predicted sonar transformation
// @todo add sonar transformation from vehicle body
const Pose3d& p1 = _pose1->value(s);
const Pose3d& p2 = _pose2->value(s);
Pose3d predicted = (p2.oplus(_sonar_frame2)).ominus(p1.oplus(_sonar_frame1));
Eigen::VectorXd p(3);
p << predicted.x(), predicted.y(), predicted.yaw(); // Predicted
Eigen::VectorXd err(3);
err << p(0)-_measure.x(), p(1)-_measure.y(), p(2)-_measure.t();
err(2) = standardRad(err(2));
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " " << _measure << " " << noise_to_string(_noise) << " " << _sonar_frame1 << " " << _sonar_frame2;
}
};
// xyz factor
class Pose3d_xyz_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector3d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 3x3 square root information matrix (upper triangular).
*/
Pose3d_xyz_Factor(Pose3d_Node* pose, const Eigen::Vector3d& pose_partial, const Noise& noise)
: Factor("Pose3d_xyz_Factor", 3, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(3);
err << pose.x() - _pose_partial(0), pose.y() - _pose_partial(1), pose.z() - _pose_partial(2);
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ", " << _pose_partial(2) << ") " << noise_to_string(_noise);
}
};
// xyh factor
class Pose3d_xyh_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector3d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 3x3 square root information matrix (upper triangular).
*/
Pose3d_xyh_Factor(Pose3d_Node* pose, const Eigen::Vector3d& pose_partial, const Noise& noise)
: Factor("Pose3d_xyh_Factor", 3, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(3);
err << pose.x() - _pose_partial(0), pose.y() - _pose_partial(1), pose.yaw() - _pose_partial(2);
err(2) = standardRad(err(2));
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ", " << _pose_partial(2) << ") " << noise_to_string(_noise);
}
};
// h factor
class Pose3d_h_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Matrix1d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 1x1 square root information matrix (upper triangular).
*/
Pose3d_h_Factor(Pose3d_Node* pose, const Eigen::Matrix1d& pose_partial, const Noise& noise)
: Factor("Pose3d_h_Factor", 1, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(1);
err << pose.yaw() - _pose_partial(0);
err(0) = standardRad(err(0));
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ") " << noise_to_string(_noise);
}
};
// z factor
class Pose3d_z_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Matrix1d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 1x1 square root information matrix (upper triangular).
*/
Pose3d_z_Factor(Pose3d_Node* pose, const Eigen::Matrix1d& pose_partial, const Noise& noise)
: Factor("Pose3d_z_Factor", 1, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(1);
err << pose.z() - _pose_partial(0);
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ") " << noise_to_string(_noise);
}
};
// rp factor
class Pose3d_rp_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector2d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 2x2 square root information matrix (upper triangular).
*/
Pose3d_rp_Factor(Pose3d_Node* pose, const Eigen::Vector2d& pose_partial, const Noise& noise)
: Factor("Pose3d_rp_Factor", 2, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(2);
err << pose.roll() - _pose_partial(0), pose.pitch() - _pose_partial(1);
err(0) = standardRad(err(0));
err(1) = standardRad(err(1));
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ") " << noise_to_string(_noise);
}
};
// xy factor
class Pose3d_xy_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector2d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 2x2 square root information matrix (upper triangular).
*/
Pose3d_xy_Factor(Pose3d_Node* pose, const Eigen::Vector2d& pose_partial, const Noise& noise)
: Factor("Pose3d_xy_Factor", 2, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(2);
err << pose.x() - _pose_partial(0), pose.y() - _pose_partial(1);
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ") " << noise_to_string(_noise);
}
};
class Pose3d_MaxMix_xy_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector2d _pose_partial;
Noise _noise1;
Noise _noise2;
double _w1;
double _w2;
Eigen::Matrix2d _L1;
Eigen::Matrix2d _L2;
double _c1;
double _c2;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 2x2 square root information matrix (upper triangular).
*/
Pose3d_MaxMix_xy_Factor(Pose3d_Node* pose, const Eigen::Vector2d& pose_partial, const Noise& noise1, const Noise& noise2, double w1, double w2)
: Factor("Pose3d_MaxMix_xy_Factor", 2, Information(Eigen::Matrix2d::Identity())),
_pose(pose), _pose_partial(pose_partial), _noise1(noise1), _noise2(noise2), _w1(w1), _w2(w2)
{
_nodes.resize(1);
_nodes[0] = pose;
_L1 = _noise1.sqrtinf().transpose() * _noise1.sqrtinf();
_L2 = _noise1.sqrtinf().transpose() * _noise2.sqrtinf();
_c1 = _w1/(2.0*M_PI*sqrt(1.0/_L1.determinant()));
_c2 = _w2/(2.0*M_PI*sqrt(1.0/_L2.determinant()));
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(2);
err << pose.x() - _pose_partial(0), pose.y() - _pose_partial(1);
double d1 = (err.transpose()*_L1*err);
double p1 = _c1 * exp (-0.5*d1);
double d2 = (err.transpose()*_L2*err);
double p2 = _c2 * exp (-0.5*d2);
if (p1 > p2) {
return _noise1.sqrtinf() * err;
} else {
return _noise2.sqrtinf() * err;
}
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ") ";
out << _w1 << " " << noise_to_string(_noise1);
out << _w2 << " " << noise_to_string(_noise1);
}
};
/**
* This class is for the plane measurement
* @author Hyunchul Roh (rohs_@kaist.ac.kr)
*/
class Wall3d_Wall3d_Factor : public FactorT<Point3d> {
Pose3d_Node* _pose1;
Pose3d_Node* _pose2;
public:
Wall3d_Wall3d_Factor(Pose3d_Node* pose1, Pose3d_Node* pose2, const Point3d& measure, const Noise& noise, Wall3d *wall1, Wall3d *wall2,
Anchor3d_Node *anchor1 = NULL, Anchor3d_Node *anchor2 = NULL)
: FactorT<Point3d>("Wall3d_Wall3d_Factor", 3, noise, measure), _pose1(pose1), _pose2(pose2) {
require((wall1 == NULL && wall2 == NULL) || (wall1 != NULL && wall2 != NULL),
"slam3d: Wall3d_Wall3d_Factor requires either 0 or 2 wall");
require((anchor1 == NULL && anchor2 == NULL) || (anchor1 != NULL && anchor2 != NULL),
"slam3d: Wall3d_Wall3d_Factor requires either 0 or 2 anchor nodes");
if (anchor1) {
_nodes.resize(4);
_nodes[2] = anchor1;
_nodes[3] = anchor2;
}
else {
_nodes.resize(2);
}
_nodes[0] = pose1;
_nodes[1] = pose2;
_wall1 = wall1;
_wall2 = wall2;
}
void initialize() {
if (_nodes.size() == 2) {
require(_nodes[0]->initialized() && _nodes[1]->initialized(), "Plane3d_Plane3d_Factor: both nodes have to be initialized");
}
else if (_nodes.size() == 4) {
require(_nodes[0]->initialized() && _nodes[1]->initialized() && _nodes[2]->initialized() && _nodes[3]->initialized(), "Plane3d_Plane3d_Factor: both nodes and both anchors have to be initialized");
}
}
Eigen::VectorXd basic_error(Selector s = ESTIMATE) const {
const Pose3d& p1 = _pose1->value(s);
const Pose3d& p2 = _pose2->value(s);
Pose3d p21;
p21 = p1.ominus(p2);
Plane3d plane1 = _wall1->normal();
Plane3d plane2 = _wall2->normal();
Plane3d plane2_cvt_to_plane1 = plane2.ominus(p21);
double dot_product = (plane2_cvt_to_plane1.x()*plane1.x() + plane2_cvt_to_plane1.y()*plane1.y() + plane2_cvt_to_plane1.z()*plane1.z()) / (plane2_cvt_to_plane1.d()*plane1.d());
double err_angle = 1.0 - fabs(dot_product);
Point3d wall2_cvt_to_wall1 = _wall2->ptxfer(p21);
//double err_d1 = (plane1.x() * wall2_cvt_to_wall1.x() + plane1.y() * wall2_cvt_to_wall1.y() + plane1.z() * wall2_cvt_to_wall1.z() + _wall1->d()) / sqrt(plane1.x()*plane1.x() + plane1.y()*plane1.y() + plane1.z()*plane1.z());
double tmpd = -(plane2_cvt_to_plane1.x() * wall2_cvt_to_wall1.x() + plane2_cvt_to_plane1.y() * wall2_cvt_to_wall1.y() + plane2_cvt_to_plane1.z() * wall2_cvt_to_wall1.z());
double err_d2 = (plane2_cvt_to_plane1.x() * _wall1->cx() + plane2_cvt_to_plane1.y() * _wall1->cy() + plane2_cvt_to_plane1.z() * _wall1->cz() + tmpd) / sqrt(plane2_cvt_to_plane1.x()*plane2_cvt_to_plane1.x() + plane2_cvt_to_plane1.y()*plane2_cvt_to_plane1.y() + plane2_cvt_to_plane1.z()*plane2_cvt_to_plane1.z());
//printf("%2.3f %2.3f %2.3f\n", err_angle, err_d1, err_d2);
Eigen::VectorXd err(3);// = predicted_plane.vector() - _measure.vector();
err(0) = standardRad(err_angle);
err(1) = 0;// abs(err_d1);
err(2) = fabs(err_d2);
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " " << _measure << " " << noise_to_string(_noise);
}
private:
Wall3d* _wall1;
Wall3d* _wall2;
};
} // namespace isam
| [
"youngji.brigid.kim@gmail.com"
] | youngji.brigid.kim@gmail.com |
f1aefb530612b66eb0bf6dbf1f17bc073d75cad7 | b2c2de30aec8f6cd84162f9fdf3ab23614b6d963 | /opencv/sources/modules/core/test/test_rand.cpp | 9cb683aa55220d714b8b46a32b3ed069f3830cb2 | [
"BSD-3-Clause"
] | permissive | ASeoighe/5thYearProject | aeaecde5eb289bcc09f570cb8815fcda2b2367a6 | 772aff2b30f04261691171a1039c417c386785c4 | refs/heads/master | 2021-09-14T11:41:11.701841 | 2018-04-24T22:30:41 | 2018-04-24T22:30:41 | 112,224,159 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,981 | cpp | #include "test_precomp.hpp"
using namespace cv;
using namespace std;
class Core_RandTest : public cvtest::BaseTest
{
public:
Core_RandTest();
protected:
void run(int);
bool check_pdf(const Mat& hist, double scale, int dist_type,
double& refval, double& realval);
};
Core_RandTest::Core_RandTest()
{
}
static double chi2_p95(int n)
{
static float chi2_tab95[] = {
3.841f, 5.991f, 7.815f, 9.488f, 11.07f, 12.59f, 14.07f, 15.51f,
16.92f, 18.31f, 19.68f, 21.03f, 21.03f, 22.36f, 23.69f, 25.00f,
26.30f, 27.59f, 28.87f, 30.14f, 31.41f, 32.67f, 33.92f, 35.17f,
36.42f, 37.65f, 38.89f, 40.11f, 41.34f, 42.56f, 43.77f };
static const double xp = 1.64;
CV_Assert(n >= 1);
if( n <= 30 )
return chi2_tab95[n-1];
return n + sqrt((double)2*n)*xp + 0.6666666666666*(xp*xp - 1);
}
bool Core_RandTest::check_pdf(const Mat& hist, double scale,
int dist_type, double& refval, double& realval)
{
Mat hist0(hist.size(), CV_32F);
const int* H = (const int*)hist.data;
float* H0 = ((float*)hist0.data);
int i, hsz = hist.cols;
double sum = 0;
for( i = 0; i < hsz; i++ )
sum += H[i];
CV_Assert( fabs(1./sum - scale) < FLT_EPSILON );
if( dist_type == CV_RAND_UNI )
{
float scale0 = (float)(1./hsz);
for( i = 0; i < hsz; i++ )
H0[i] = scale0;
}
else
{
double sum2 = 0, r = (hsz-1.)/2;
double alpha = 2*sqrt(2.)/r, beta = -alpha*r;
for( i = 0; i < hsz; i++ )
{
double x = i*alpha + beta;
H0[i] = (float)exp(-x*x);
sum2 += H0[i];
}
sum2 = 1./sum2;
for( i = 0; i < hsz; i++ )
H0[i] = (float)(H0[i]*sum2);
}
double chi2 = 0;
for( i = 0; i < hsz; i++ )
{
double a = H0[i];
double b = H[i]*scale;
if( a > DBL_EPSILON )
chi2 += (a - b)*(a - b)/(a + b);
}
realval = chi2;
double chi2_pval = chi2_p95(hsz - 1 - (dist_type == CV_RAND_NORMAL ? 2 : 0));
refval = chi2_pval*0.01;
return realval <= refval;
}
void Core_RandTest::run( int )
{
static int _ranges[][2] =
{{ 0, 256 }, { -128, 128 }, { 0, 65536 }, { -32768, 32768 },
{ -1000000, 1000000 }, { -1000, 1000 }, { -1000, 1000 }};
const int MAX_SDIM = 10;
const int N = 2000000;
const int maxSlice = 1000;
const int MAX_HIST_SIZE = 1000;
int progress = 0;
RNG& rng = ts->get_rng();
RNG tested_rng = theRNG();
test_case_count = 200;
for( int idx = 0; idx < test_case_count; idx++ )
{
progress = update_progress( progress, idx, test_case_count, 0 );
ts->update_context( this, idx, false );
int depth = cvtest::randInt(rng) % (CV_64F+1);
int c, cn = (cvtest::randInt(rng) % 4) + 1;
int type = CV_MAKETYPE(depth, cn);
int dist_type = cvtest::randInt(rng) % (CV_RAND_NORMAL+1);
int i, k, SZ = N/cn;
Scalar A, B;
double eps = 1.e-4;
if (depth == CV_64F)
eps = 1.e-7;
bool do_sphere_test = dist_type == CV_RAND_UNI;
Mat arr[2], hist[4];
int W[] = {0,0,0,0};
arr[0].create(1, SZ, type);
arr[1].create(1, SZ, type);
bool fast_algo = dist_type == CV_RAND_UNI && depth < CV_32F;
for( c = 0; c < cn; c++ )
{
int a, b, hsz;
if( dist_type == CV_RAND_UNI )
{
a = (int)(cvtest::randInt(rng) % (_ranges[depth][1] -
_ranges[depth][0])) + _ranges[depth][0];
do
{
b = (int)(cvtest::randInt(rng) % (_ranges[depth][1] -
_ranges[depth][0])) + _ranges[depth][0];
}
while( abs(a-b) <= 1 );
if( a > b )
std::swap(a, b);
unsigned r = (unsigned)(b - a);
fast_algo = fast_algo && r <= 256 && (r & (r-1)) == 0;
hsz = min((unsigned)(b - a), (unsigned)MAX_HIST_SIZE);
do_sphere_test = do_sphere_test && b - a >= 100;
}
else
{
int vrange = _ranges[depth][1] - _ranges[depth][0];
int meanrange = vrange/16;
int mindiv = MAX(vrange/20, 5);
int maxdiv = MIN(vrange/8, 10000);
a = cvtest::randInt(rng) % meanrange - meanrange/2 +
(_ranges[depth][0] + _ranges[depth][1])/2;
b = cvtest::randInt(rng) % (maxdiv - mindiv) + mindiv;
hsz = min((unsigned)b*9, (unsigned)MAX_HIST_SIZE);
}
A[c] = a;
B[c] = b;
hist[c].create(1, hsz, CV_32S);
}
cv::RNG saved_rng = tested_rng;
int maxk = fast_algo ? 0 : 1;
for( k = 0; k <= maxk; k++ )
{
tested_rng = saved_rng;
int sz = 0, dsz = 0, slice;
for( slice = 0; slice < maxSlice; slice++, sz += dsz )
{
dsz = slice+1 < maxSlice ? (int)(cvtest::randInt(rng) % (SZ - sz + 1)) : SZ - sz;
Mat aslice = arr[k].colRange(sz, sz + dsz);
tested_rng.fill(aslice, dist_type, A, B);
}
}
if( maxk >= 1 && norm(arr[0], arr[1], NORM_INF) > eps)
{
ts->printf( cvtest::TS::LOG, "RNG output depends on the array lengths (some generated numbers get lost?)" );
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
for( c = 0; c < cn; c++ )
{
const uchar* data = arr[0].data;
int* H = hist[c].ptr<int>();
int HSZ = hist[c].cols;
double minVal = dist_type == CV_RAND_UNI ? A[c] : A[c] - B[c]*4;
double maxVal = dist_type == CV_RAND_UNI ? B[c] : A[c] + B[c]*4;
double scale = HSZ/(maxVal - minVal);
double delta = -minVal*scale;
hist[c] = Scalar::all(0);
for( i = c; i < SZ*cn; i += cn )
{
double val = depth == CV_8U ? ((const uchar*)data)[i] :
depth == CV_8S ? ((const schar*)data)[i] :
depth == CV_16U ? ((const ushort*)data)[i] :
depth == CV_16S ? ((const short*)data)[i] :
depth == CV_32S ? ((const int*)data)[i] :
depth == CV_32F ? ((const float*)data)[i] :
((const double*)data)[i];
int ival = cvFloor(val*scale + delta);
if( (unsigned)ival < (unsigned)HSZ )
{
H[ival]++;
W[c]++;
}
else if( dist_type == CV_RAND_UNI )
{
if( (minVal <= val && val < maxVal) || (depth >= CV_32F && val == maxVal) )
{
H[ival < 0 ? 0 : HSZ-1]++;
W[c]++;
}
else
{
putchar('^');
}
}
}
if( dist_type == CV_RAND_UNI && W[c] != SZ )
{
ts->printf( cvtest::TS::LOG, "Uniform RNG gave values out of the range [%g,%g) on channel %d/%d\n",
A[c], B[c], c, cn);
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
if( dist_type == CV_RAND_NORMAL && W[c] < SZ*.90)
{
ts->printf( cvtest::TS::LOG, "Normal RNG gave too many values out of the range (%g+4*%g,%g+4*%g) on channel %d/%d\n",
A[c], B[c], A[c], B[c], c, cn);
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
double refval = 0, realval = 0;
if( !check_pdf(hist[c], 1./W[c], dist_type, refval, realval) )
{
ts->printf( cvtest::TS::LOG, "RNG failed Chi-square test "
"(got %g vs probable maximum %g) on channel %d/%d\n",
realval, refval, c, cn);
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
}
// Monte-Carlo test. Compute volume of SDIM-dimensional sphere
// inscribed in [-1,1]^SDIM cube.
if( do_sphere_test )
{
int SDIM = cvtest::randInt(rng) % (MAX_SDIM-1) + 2;
int N0 = (SZ*cn/SDIM), n = 0;
double r2 = 0;
const uchar* data = arr[0].data;
double scale[4], delta[4];
for( c = 0; c < cn; c++ )
{
scale[c] = 2./(B[c] - A[c]);
delta[c] = -A[c]*scale[c] - 1;
}
for( i = k = c = 0; i <= SZ*cn - SDIM; i++, k++, c++ )
{
double val = depth == CV_8U ? ((const uchar*)data)[i] :
depth == CV_8S ? ((const schar*)data)[i] :
depth == CV_16U ? ((const ushort*)data)[i] :
depth == CV_16S ? ((const short*)data)[i] :
depth == CV_32S ? ((const int*)data)[i] :
depth == CV_32F ? ((const float*)data)[i] : ((const double*)data)[i];
c &= c < cn ? -1 : 0;
val = val*scale[c] + delta[c];
r2 += val*val;
if( k == SDIM-1 )
{
n += r2 <= 1;
r2 = 0;
k = -1;
}
}
double V = ((double)n/N0)*(1 << SDIM);
// the theoretically computed volume
int sdim = SDIM % 2;
double V0 = sdim + 1;
for( sdim += 2; sdim <= SDIM; sdim += 2 )
V0 *= 2*CV_PI/sdim;
if( fabs(V - V0) > 0.3*fabs(V0) )
{
ts->printf( cvtest::TS::LOG, "RNG failed %d-dim sphere volume test (got %g instead of %g)\n",
SDIM, V, V0);
ts->printf( cvtest::TS::LOG, "depth = %d, N0 = %d\n", depth, N0);
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
}
}
}
TEST(Core_Rand, quality) { Core_RandTest test; test.safe_run(); }
class Core_RandRangeTest : public cvtest::BaseTest
{
public:
Core_RandRangeTest() {}
~Core_RandRangeTest() {}
protected:
void run(int)
{
Mat a(Size(1280, 720), CV_8U, Scalar(20));
Mat af(Size(1280, 720), CV_32F, Scalar(20));
theRNG().fill(a, RNG::UNIFORM, -DBL_MAX, DBL_MAX);
theRNG().fill(af, RNG::UNIFORM, -DBL_MAX, DBL_MAX);
int n0 = 0, n255 = 0, nx = 0;
int nfmin = 0, nfmax = 0, nfx = 0;
for( int i = 0; i < a.rows; i++ )
for( int j = 0; j < a.cols; j++ )
{
int v = a.at<uchar>(i,j);
double vf = af.at<float>(i,j);
if( v == 0 ) n0++;
else if( v == 255 ) n255++;
else nx++;
if( vf < FLT_MAX*-0.999f ) nfmin++;
else if( vf > FLT_MAX*0.999f ) nfmax++;
else nfx++;
}
CV_Assert( n0 > nx*2 && n255 > nx*2 );
CV_Assert( nfmin > nfx*2 && nfmax > nfx*2 );
}
};
TEST(Core_Rand, range) { Core_RandRangeTest test; test.safe_run(); }
TEST(Core_RNG_MT19937, regression)
{
cv::RNG_MT19937 rng;
int actual[61] = {0, };
const size_t length = (sizeof(actual) / sizeof(actual[0]));
for (int i = 0; i < 10000; ++i )
{
actual[(unsigned)(rng.next() ^ i) % length]++;
}
int expected[length] = {
177, 158, 180, 177, 160, 179, 143, 162,
177, 144, 170, 174, 165, 168, 168, 156,
177, 157, 159, 169, 177, 182, 166, 154,
144, 180, 168, 152, 170, 187, 160, 145,
139, 164, 157, 179, 148, 183, 159, 160,
196, 184, 149, 142, 162, 148, 163, 152,
168, 173, 160, 181, 172, 181, 155, 153,
158, 171, 138, 150, 150 };
for (size_t i = 0; i < length; ++i)
{
ASSERT_EQ(expected[i], actual[i]);
}
}
<<<<<<< HEAD
=======
TEST(Core_Rand, Regression_Stack_Corruption)
{
int bufsz = 128; //enough for 14 doubles
AutoBuffer<uchar> buffer(bufsz);
size_t offset = 0;
cv::Mat_<cv::Point2d> x(2, 3, (cv::Point2d*)(buffer+offset)); offset += x.total()*x.elemSize();
double& param1 = *(double*)(buffer+offset); offset += sizeof(double);
double& param2 = *(double*)(buffer+offset); offset += sizeof(double);
param1 = -9; param2 = 2;
cv::theRNG().fill(x, cv::RNG::NORMAL, param1, param2);
ASSERT_EQ(param1, -9);
ASSERT_EQ(param2, 2);
}
>>>>>>> 4a5a6cfc1ba26f73cbd6c6fcaf561ca6dbced81d
| [
"aaronjoyce2@gmail.com"
] | aaronjoyce2@gmail.com |
c9d26134f06df057c4562147e7f77b12181b5645 | 5e59fe8bcdd12a2d375a58dbb719e1db395c7d16 | /mruby-sys/vendor/emscripten/system/lib/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_emscripten.cc | 610770704cedb4491bec1144c87ba0a11154a9bd | [
"NCSA",
"MIT",
"MPL-2.0"
] | permissive | ifyouseewendy/artichoke | 4ec7f34dcd644bd1156ac54b87953eb070c22cd0 | 6f569cbb0273a468cbe49f4c60144bf189cfb7a0 | refs/heads/master | 2020-07-05T20:53:41.334690 | 2020-03-19T22:07:12 | 2020-03-20T01:41:30 | 202,770,950 | 1 | 0 | MIT | 2019-08-16T17:23:33 | 2019-08-16T17:23:32 | null | UTF-8 | C++ | false | false | 1,332 | cc | //===-- sanitizer_stacktrace_emscripten.cc --------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
//
// Implementation of fast stack unwinding for Emscripten.
//===----------------------------------------------------------------------===//
#ifdef __EMSCRIPTEN__
#include "sanitizer_common.h"
#include "sanitizer_stacktrace.h"
namespace __sanitizer {
extern "C" {
uptr emscripten_stack_snapshot();
uptr emscripten_return_address(int level);
u32 emscripten_stack_unwind_buffer(uptr pc, uptr *buffer, u32 depth);
}
uptr StackTrace::GetCurrentPc() {
return emscripten_stack_snapshot();
}
void BufferedStackTrace::FastUnwindStack(uptr pc, uptr bp, uptr stack_top,
uptr stack_bottom, u32 max_depth) {
bool saw_pc = false;
max_depth = Min(max_depth, kStackTraceMax);
size = emscripten_stack_unwind_buffer(pc, trace_buffer, max_depth);
trace_buffer[0] = pc;
size = Max(size, 1U);
}
} // namespace __sanitizer
#endif // __EMSCRIPTEN__
| [
"rjl@hyperbo.la"
] | rjl@hyperbo.la |
64234dca87cdc115173958f640c332b8c24b619e | d09092dbe69c66e916d8dd76d677bc20776806fe | /.libs/puno_automatic_generated/inc/types/com/sun/star/awt/XMouseListener.hpp | c3495449258d432c60d891692743ec31b235eb65 | [] | no_license | GXhua/puno | 026859fcbc7a509aa34ee857a3e64e99a4568020 | e2f8e7d645efbde5132b588678a04f70f1ae2e00 | refs/heads/master | 2020-03-22T07:35:46.570037 | 2018-07-11T02:19:26 | 2018-07-11T02:19:26 | 139,710,567 | 0 | 0 | null | 2018-07-04T11:03:58 | 2018-07-04T11:03:58 | null | UTF-8 | C++ | false | false | 1,513 | hpp | #ifndef INCLUDED_COM_SUN_STAR_AWT_XMOUSELISTENER_HPP
#define INCLUDED_COM_SUN_STAR_AWT_XMOUSELISTENER_HPP
#include "sal/config.h"
#include "com/sun/star/awt/XMouseListener.hdl"
#include "com/sun/star/awt/MouseEvent.hpp"
#include "com/sun/star/lang/XEventListener.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Type.hxx"
#include "cppu/unotype.hxx"
namespace com { namespace sun { namespace star { namespace awt {
inline ::css::uno::Type const & cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::css::awt::XMouseListener const *) {
static typelib_TypeDescriptionReference * the_type = 0;
if ( !the_type )
{
typelib_TypeDescriptionReference * aSuperTypes[1];
aSuperTypes[0] = ::cppu::UnoType< const ::css::uno::Reference< ::css::lang::XEventListener > >::get().getTypeLibType();
typelib_static_mi_interface_type_init( &the_type, "com.sun.star.awt.XMouseListener", 1, aSuperTypes );
}
return * reinterpret_cast< ::css::uno::Type * >( &the_type );
}
} } } }
SAL_DEPRECATED("use cppu::UnoType") inline ::css::uno::Type const & SAL_CALL getCppuType(SAL_UNUSED_PARAMETER ::css::uno::Reference< ::css::awt::XMouseListener > const *) {
return ::cppu::UnoType< ::css::uno::Reference< ::css::awt::XMouseListener > >::get();
}
::css::uno::Type const & ::css::awt::XMouseListener::static_type(SAL_UNUSED_PARAMETER void *) {
return ::cppu::UnoType< ::css::awt::XMouseListener >::get();
}
#endif // INCLUDED_COM_SUN_STAR_AWT_XMOUSELISTENER_HPP
| [
"guoxinhua@10.10.12.142"
] | guoxinhua@10.10.12.142 |
1f7ec6eb173e5aa4aeac2048080cdbd639d5296b | 4a7f31f146b1397455887c7e7ed30cdd5982b2bd | /includes/strategy/create.hpp | 6975326c8e416e7f2b1e74cb378cc919dec749f0 | [] | no_license | Disabled77/metaprogramming | 5ac73c2b4bc5e7034a16fcec133a1cdca2ae1ed2 | 010c9ae991b5bea98d5168fd3eddb93c0a7f6164 | refs/heads/master | 2020-03-29T05:58:43.258986 | 2017-06-29T13:19:22 | 2017-06-29T13:19:22 | 94,656,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | hpp | #pragma once
namespace strategy {
template<class T>
struct NewCreate{
template<class... Args>
static T* create(Args... args){
return new T { args... };
}
};
template<class T>
struct MallocCreate{
template<class... Args>
static T* create(Args... args){
T* object = reinterpret_cast<T*>(malloc(sizeof(T)));
new (object) T { args... };
return object;
}
};
template<class T>
struct PrototypCreate{
PrototypCreate(T* (functionPrototype)(T) = nullptr):
functionPrototype_ { functionPrototype }
{}
void setPrototype(T* (functionPrototype)(T)){
functionPrototype_ = functionPrototype;
}
template<class... Args>
T* create(T value) const {
T* variable = functionPrototype_(value);
return variable;
}
T* (*functionPrototype_)(T);
};
} // namespace strategy
| [
"dmitry.belous89@gmail.com"
] | dmitry.belous89@gmail.com |
32d907a959be20b0a7f350d9f9f48cd127c5b872 | 005f6e37941b66536f6719a7bb94ab4d3d7cf418 | /src/prx_packages/manipulation/simulation/plants/simple_planning_manipulator.hpp | cf0d19db06161c1d56bbe2efd93e3f80d4a464a5 | [] | no_license | warehouse-picking-automation-challenges/ru_pracsys | c56b9a873218fefb91658e08b74c4a1bc7e16628 | 786ce2e3e0d70d01c951028a90c117a0f23d0804 | refs/heads/master | 2021-05-31T05:52:33.396310 | 2016-02-07T22:34:39 | 2016-02-07T22:34:39 | 39,845,771 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,801 | hpp | ///**
// * @file simple_planning_manipulator.hpp
// *
// * @copyright Software License Agreement (BSD License)
// * Copyright (c) 2013, Rutgers the State University of New Jersey, New Brunswick
// * All Rights Reserved.
// * For a full description see the file named LICENSE.
// *
// * Authors: Andrew Dobson, Andrew Kimmel, Athanasios Krontiris, Zakary Littlefield, Kostas Bekris
// *
// * Email: pracsys@googlegroups.com
// */
//
//#pragma once
//
//#ifndef PRX_SIMPLE_PLANNING_MANIPULATOR_PLANT_HPP
//#define PRX_SIMPLE_PLANNING_MANIPULATOR_PLANT_HPP
//
//#include "prx/utilities/definitions/defs.hpp"
//#include "simple_manipulator.hpp"
//
//namespace prx
//{
// namespace packages
// {
// namespace manipulation
// {
//
// class simple_planning_manipulator_plant_t : public simple_manipulator_plant_t
// {
//
// public:
//
// simple_planning_manipulator_plant_t();
//
// virtual ~simple_planning_manipulator_plant_t();
//
// virtual void init(const util::parameter_reader_t * reader, const util::parameter_reader_t* template_reader = NULL);
//
// void propagate(const double simulation_step);
//
// virtual void update_phys_configs(util::config_list_t& configs) const;
//
// virtual void get_effectors_name(std::vector<std::string>& names) const;
//
// virtual bool is_grasping() const;
//
// virtual void get_end_effector_position(std::vector<double>& pos);
//
// virtual void IK_solver(util::config_t& effector_config, std::vector<double>& state_vec);
//
// /** @copydoc plant_t::steering_function(const state_t*, const state_t*, plan_t&)*/
// void steering_function(const sim::state_t* start, const sim::state_t* goal, sim::plan_t& result_plan);
//
// /** @copydoc plant_t::append_contingency(plan_t&, double)*/
// void append_contingency(sim::plan_t& result_plan, double duration);
//
// protected:
//
// /** Indexer for state variable : X */
// const static unsigned VAR_X;
//
// /** Indexer for state variable : Y */
// const static unsigned VAR_Y;
//
// /** Indexer for state variable : Z */
// const static unsigned VAR_Z;
//
// /** Indexer for state variable : THETA X */
// const static unsigned VAR_TX;
//
// /** Indexer for state variable : THETA Y */
// const static unsigned VAR_TY;
//
// /** Indexer for state variable : THETA Z */
// const static unsigned VAR_TZ;
//
// /** Indexer for grasping control variable G */
// const static unsigned VAR_G;
//
// /** Internal state & control memory */
// double _x;
// double _y;
// double _z;
// double _tx;
// double _ty;
// double _tz;
// double _g;
//
// double _cx;
// double _cy;
// double _cz;
// double _ctx;
// double _cty;
// double _ctz;
// double _cg;
//
// mutable util::config_t end_effector_config;
// util::config_t *end_effector_relative_config;
// util::config_t *rside_config;
// util::config_t *lside_config;
// util::config_t *rfinger_config;
// util::config_t *lfinger_config;
// std::string right_finger_name;
// std::string left_finger_name;
// std::string right_side_name;
// std::string left_side_name;
// double effector_distance;
// double side_x;
// double side_y;
// double finger_y;
// double side_grasp_y;
// double finger_grasp_y;
// double max_grasp;
// double end_effector_position;
// double prev_g;
//
// util::vector_t tmp_pos;
// std::vector<double> tmp_state;
// mutable util::quaternion_t tmp_orient;
// util::config_t tmp_config;
//
// /**
// * The maximum distance for the plant in a simulation step.
// * @brief The maximum distance for the plant in a simulation step.
// */
// double max_step;
//
// /**
// * The step for a specific distance.
// * @brief The step for a specific distance.
// */
// double interpolation_step;
//
// /**
// * The total cover before change control.
// * @brief The total cover before change control.
// */
// double dist;
//
// /**
// * A flag for the next step.
// * @brief A flag for the next step.
// */
// bool reset;
//
// /**
// * To copy the initial state before the interpolation.
// * @brief To copy the initial state before the interpolation.
// */
// sim::state_t* initial_state;
//
// /**
// * To copy the plant's state into to do interpolation and copying and such.
// * @brief To copy the plant's state into to do interpolation and copying and such.
// */
// sim::state_t* state;
//
// /**
// * Used to check if the rigid body is actually making progress.
// * @brief Used to check if the rigid body is actually making progress.
// */
// sim::state_t* hold_state;
//
// /**
// * Holds the state from the last propagation.
// * @brief Holds the state from the last propagation.
// */
// sim::state_t* prior_state;
//
// /**
// * The previously used control by the system.
// * @brief The previously used control by the system.
// */
// sim::control_t* prior_control;
//
// /**
// * To copy the plant's control into in order to do equivalence checking.
// * @brief To copy the plant's control into in order to do equivalence checking.
// */
// sim::control_t* control;
//
// };
// }
// }
//}
//
//#endif | [
"kostas.bekris@cs.rutgers.edu"
] | kostas.bekris@cs.rutgers.edu |
5f281b56ca2a8fea8425a2da4aecbc23a01262b6 | d7fe5077a5694265c4bab15b7acbc8a4424ddd89 | /naive/src/Analysis/NoPredBlocks.cpp | 53309420f754752b92a1003d6f3468476e136741 | [] | no_license | fengjixuchui/acsac17wip | 56cfcea51e30d36f2f5fe5b0ef511ba2ae4ce83f | 5b93e78b96978977a485149c32594d85b1ae329d | refs/heads/master | 2023-03-16T19:33:31.606714 | 2020-11-02T16:29:10 | 2020-11-02T16:29:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,580 | cpp | #include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
#include "NoPredBlocks.h"
void
NoPredBlocks::getAnalysisUsage(AnalysisUsage &AU) const
{
AU.setPreservesCFG();
}
bool
NoPredBlocks::runOnModule(Module &M)
{
unsigned long long total_blocks = 0;
unsigned long long blocks_without_predecessors = 0;
unsigned long long blocks_without_successors = 0;
unsigned long long island_blocks = 0;
for (Function &F : M) {
bool entryBlock = true;
for (BasicBlock &B : F) {
++total_blocks;
bool hasSuccessor = false;
if (succ_begin(&B) != succ_begin(&B)) {
hasSuccessor = true;
} else {
++blocks_without_successors;
}
bool hasPredecessor = false;
if (pred_begin(&B) != pred_end(&B)) {
hasPredecessor = true;
} else {
++blocks_without_predecessors;
}
if (hasSuccessor == false && hasPredecessor == false) {
if (entryBlock == false) {
++island_blocks;
}
}
entryBlock = false;
}
}
errs() << "Total blocks: " << total_blocks << "\n";
errs() << "Island blocks: " << island_blocks << "\n";
errs() << "Blocks w/o preds: " << blocks_without_predecessors << "\n";
errs() << "Blocks w/o successors: " << blocks_without_successors << "\n";
return true;
}
char NoPredBlocks::ID = 0;
static RegisterPass<NoPredBlocks> XX("no-pred-blocks", "");
| [
"areiter@veracode.com"
] | areiter@veracode.com |
d4ff8968b5b5f272fd0da6da4fe70202a45b3096 | fa59cfedc5f57e881679fb0b5046da8c911229ca | /9465 스티커.cpp | 75007d318d104fd8d516d62b1630b47e91af4021 | [] | no_license | ju214425/algorithm | e2862df2c55490b97aefffaec99bb449a9db7e1f | db6d96eda3272a7faddaf11fdd02534d6231eafc | refs/heads/master | 2023-07-02T21:32:53.718629 | 2023-06-25T06:04:57 | 2023-06-25T06:04:57 | 193,701,850 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,731 | cpp | // #include <iostream>
// using namespace std;
// int max(int num1, int num2){
// return num1 > num2 ? num1 : num2;
// }
// int main(){
// int numberOfTests;
// cin >> numberOfTests;
// int answerArr[numberOfTests + 1];
// for(int i = 1 ; i <= numberOfTests ; i++){
// int length;
// cin >> length;
// int arr[length + 1][2];
// int dp[length + 1];
// int temp = 0;
// for(int j = 0 ; j < 2 ; j++){
// for(int k = 1 ; k <= length ; k++){
// cin >> arr[k][j];
// }
// }
// dp[0] = 0;
// dp[1] = max(arr[1][0], arr[1][1]);
// dp[2] = max(arr[1][0] + arr[2][1], arr[1][1] + arr[2][0]);
// for(int j = 3 ; j <= length ; j++){
// int cur = max(arr[j][0], arr[j][1]);
// int check = 0;
// if(dp[j-1] == dp[j-2] + arr[j-1][0]){
// check = arr[j][1];
// }
// else{
// check = arr[j][0];
// }
// dp[j] = max(dp[j-2] + cur, dp[j-1] + check);
// }
// answerArr[i] = dp[length];
// }
// for(int i = 1 ; i <= numberOfTests ; i++){
// cout << answerArr[i] << endl;
// }
// return 0;
// }
#include <cstdio>
#include <algorithm>
using namespace std;
int arr[100005][2];
int dp[100005][2];
int main(){
int t, answer;
scanf("%d", &t);
for(int i = 0 ; i < t ; i++){
int n;
scanf("%d", &n);
for(int j = 0 ; j < n ; j++){
scanf("%d", &arr[j][0]);
}
for(int j = 0 ; j < n ; j++){
scanf("%d", &arr[j][1]);
}
dp[0][0] = arr[0][0];
dp[0][1] = arr[0][1];
dp[1][0] = arr[0][1] + arr[1][0];
dp[1][1] = arr[0][0] + arr[1][1];
for(int j = 2 ; j < n ; j++){
dp[j][0] = arr[j][0] + max(dp[j-1][1], dp[j-2][1]);
dp[j][1] = arr[j][1] + max(dp[j-1][0], dp[j-2][0]);
}
answer = max(dp[n-1][0], dp[n-1][1]);
printf("%d\n", answer);
}
} | [
"2016025841@hanyang.ac.kr"
] | 2016025841@hanyang.ac.kr |
4e6625fd121ed1977df0ad294158bbcfa9e13427 | f198391333b9ca636b35a98b62d822fb53f8b95d | /LANServer/LANServer.ino | 94bdccecf6c95d9d9c944c95cbc9ab22957400f7 | [] | no_license | Rezenter/LANOven | 518a0aa49464308e5eb7e4c32e2a874916ed4f25 | ec3958a41022efa35c5ae0fecadebcc6594cd8ba | refs/heads/master | 2021-01-11T00:45:44.841647 | 2016-10-10T08:57:46 | 2016-10-10T08:57:46 | 70,469,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,168 | ino | #include <UIPEthernet.h>
EthernetServer server = EthernetServer(1);//port
EthernetClient client;
bool alreadyConnected = false;
void setup()
{
pinMode(A0, INPUT);
pinMode(A1, INPUT);
pinMode(A2, INPUT);
pinMode(A3, INPUT);
uint8_t mac[6] = {0x00,0x01,0x02,0x03,0x04,0x05};
IPAddress myIP(172,16,13,21);
Ethernet.begin(mac,myIP);
server.begin();
}
void loop()
{
client = server.available();
if(client.connected()){
if (client.available() > 0) {
parse();
}
}
}
void parse(){
String in;
char tmp;
while(client.available() > 0){
tmp = client.read();
in += tmp;
}
if(in.substring(0, in.length()-1).equals("request")){
int input[4] = {analogRead(A0), analogRead(A1),
analogRead(A2), analogRead(A3)};
client.println("analog data:");
client.print("voltage = ");
client.println(input[0]);
client.print("current = ");
client.println(input[1]);
client.print("reference = ");
client.println(input[2]);
client.print("ground = ");
client.println(input[3]);
client.print("milliseconds since powerup = ");
client.println(millis());
client.println("end");
}
}
| [
"noreply@github.com"
] | Rezenter.noreply@github.com |
0a5682a2d63acfb8051b3aac6eda419494723205 | d970f0f7275b7fb13bf315de797d5e38a06aa655 | /include/sico/frames/object_local.hpp | 4bfc9ec3d3ab56847a51a14888ea3565280f819b | [
"MIT"
] | permissive | fjacomme/sico | d5e4ece8a8600990135873900fd9cf4eada910f1 | 501b8f08313e4394ac8585167b74374e2ae3da09 | refs/heads/master | 2023-01-10T22:21:25.653182 | 2020-11-10T13:45:01 | 2020-11-10T13:45:01 | 264,876,122 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,616 | hpp | #pragma once
#include "sico/conversions/enu_local.hpp"
#include "sico/conversions/local_local.hpp"
#include "sico/frames/local_tangent.hpp"
#include "sico/types/orientations.hpp"
namespace sico {
/// Local Frame for an object positioned in an ENU frame
class frame_object {
protected:
frame_enu frame;
quat_enu quat;
public:
frame_object(pos_lla const& ref, ori_enu const& ori)
: frame(ref)
, quat(ori)
{
}
void set_ref(pos_lla const& ref, ori_enu const& ori)
{
frame.set_ref(ref);
quat = quat_enu(ori);
}
pos_local to_local(pos_lla const& p) const { return to_local(frame.to_enu(p)); }
pos_lla to_lla(pos_local const& p) const { return frame.to_lla(to_enu(p)); }
pos_local to_local(pos_enu const& p) const { return sico::to_local(p, quat); }
pos_enu to_enu(pos_local const& p) const { return sico::to_enu(p, quat); }
};
/// Local frame for an object on another object
class frame_child_object {
protected:
pos_local ref;
quat_local quat;
public:
frame_child_object(pos_local const& child_pos, ori_local const& ori)
: ref(child_pos)
, quat(ori)
{
}
void set_ref(pos_local const& child_pos, ori_local const& ori)
{
ref = child_pos;
quat = quat_local(ori);
}
pos_local to_child(pos_local const& p) const { return sico::to_child(ref, quat, p); }
pos_local to_parent(pos_local const& p) const { return sico::to_parent(ref, quat, p); }
};
} // namespace sico
//
// Simulation-Coordinates library
// Author F.Jacomme
// MIT Licensed
// | [
"florian@jacomme.fr"
] | florian@jacomme.fr |
bba78b98f6f8c58529862ea61b6201339bece2d1 | 4e68b2d90fbcf829435514ae3631c75b5ba2e438 | /src/yb/util/algorithm_util.h | aaa7fdecfb5bb1b5cbeba1dc269cacd4b3bb8bc2 | [
"OpenSSL",
"Apache-2.0",
"BSD-3-Clause",
"CC0-1.0",
"Unlicense",
"bzip2-1.0.6",
"dtoa",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | bhrgv-bolla/yugabyte-db | b4b2c22d76b0503e1f96d1279b858800ae138119 | 7b12cce17745647e1870f7f7b44a9a71068ceecd | refs/heads/master | 2020-03-11T20:50:05.257512 | 2018-04-19T06:56:16 | 2018-04-19T10:39:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | h | // Copyright (c) YugaByte, Inc.
//
// 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.
//
#ifndef YB_UTIL_ALGORITHM_UTIL_H
#define YB_UTIL_ALGORITHM_UTIL_H
#include <algorithm>
#include "yb/util/enums.h"
namespace yb {
enum class SortOrder : uint8_t {
kAscending = 0,
kDescending
};
template<typename Iterator, typename Functor>
void SortByKey(Iterator begin,
Iterator end,
const Functor& f,
SortOrder sort_order = SortOrder::kAscending) {
using Value = typename Iterator::value_type;
const bool invert_order = sort_order == SortOrder::kDescending;
std::sort(begin, end, [invert_order, &f](const Value& a, const Value& b){
return f(a) < f(b) != invert_order;
});
}
}; // namespace yb
#endif // YB_UTIL_ALGORITHM_UTIL_H
| [
"mbautin@users.noreply.github.com"
] | mbautin@users.noreply.github.com |
d1ce39cc84771ff1a302fc27ee3523c8d97d47d0 | a0320ceb1fb8d62cef8729b9c7245a25543398b1 | /Queues/slidingWindowMax.cpp | b38a489db4739ab49783a325c22777115a857339 | [] | no_license | Utkal97/Data-Structures-and-Algorithms | d558d847b8651fb0f6bd89026cca6d900f496fe2 | 6eca25b8ec71a118cda35c85d150ef6ae01b3243 | refs/heads/master | 2022-04-13T10:32:34.909651 | 2020-04-04T12:04:00 | 2020-04-04T12:04:00 | 247,907,610 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 917 | cpp | #include<bits/stdc++.h>
#include "DoubleEndedQueue.h"
using namespace std;
vector<int> slidingWindow(int A[], int len, int window_size) {
DoubleEndedQueue q;
for(int ind=0;ind<window_size;ind++) {
while(!q.empty() && A[ind] >= A[q.back()])
int popped = q.pop_back();
q.push_back(ind);
}
vector<int> answer;
answer.push_back(A[q.front()]);
for(int ind=window_size; ind<len; ind++) {
while(!q.empty() && ind-q.front() >= window_size)
q.pop_front();
while(!q.empty() && A[ind]>=A[q.back()])
q.pop_back();
q.push_back(ind);
answer.push_back(A[q.front()]);
}
return answer;
}
int main() {
int input[8] = {1,3,-1,-3,5,3,6,7};
int k = 3;
vector<int> ans = slidingWindow(input, 8, k);
for(int i=0; i<ans.size(); i++) {
cout<<ans[i]<<" ";
}
cout<<endl;
return 0;
} | [
"utkal.s15@iiits.in"
] | utkal.s15@iiits.in |
7b2ae70b2d51805efb79e23a08bad42f317de492 | c7ebab4f0bb325fddd99e2e6952241e6d5177faf | /Buffer.cpp | 71800e3bd44133ec88cb9c7e770712955754ef38 | [] | no_license | zhuqiweigit/mymuduo | d1cd19a4a10ad7c2d2d327dafa3a6c9379d8c76a | 31701d4b72cf29051bf721ea1d720535b048b39c | refs/heads/main | 2023-03-08T03:49:18.547494 | 2021-02-26T12:51:39 | 2021-02-26T12:51:39 | 342,574,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | cpp | #include "Buffer.h"
#include <errno.h>
#include <sys/uio.h>
#include <unistd.h>
/**
* 维护了一个vector<char>Buffer, 和两个读写的int Index,使用int而非指针或迭代器,是因为vector的迭代器失效问题
*
* Buffer的布局: 0-----8---------------readIndex--------------writeIndex-----------------size-----capacity
* 空白头部 读过后的空闲区 待读数据 可写的空白区
*
* append函数:往buffer写入数据,写之前先检查可写空白区间够不够,如果不够,就使用makeSpace扩容。
*
* makeSpace:先检查【读后的空白区 + 可写的空白区】是否够写
* 不够:直接扩容,假设需要写入n字节,则扩容至 writeIndex + n
* 够:把待读数据挪动到开头,把空白区合并即可
*
* 注:我们使用的容量,应该看size,而非capacity。
*/
size_t Buffer::readFd(int fd, int* saveErrno){
char extrabuf[65536] = {0};
struct iovec vec[2];
const size_t writable = writeableBytes();
vec[0].iov_base = beginWrite();
vec[0].iov_len = writable;
vec[1].iov_base = extrabuf;
vec[1].iov_len = sizeof extrabuf;
const int iovcnt = writable < sizeof(extrabuf) ? 2 : 1;
const size_t n = ::readv(fd, vec, iovcnt);
if(n < 0){
*saveErrno = errno;
}else if(n <= writable){
writeIndex_ += n;
}else{
writeIndex_ = buffer_.size();
append(extrabuf, n - writable);
}
return n;
}
size_t Buffer::writeFd(int fd, int* saveErrno){
size_t n = ::write(fd, peek(), readableBytes());
if(n < 0){
*saveErrno = errno;
}
return n;
} | [
"XXX@xx.com"
] | XXX@xx.com |
c81101c7bcbb78273876a76b1be5dba551b25a7f | cb796fe6cdd2b58782cd5bbd6b7bd29d4ea6a298 | /f1000/doc/fwsdk/IQA_LIB_uBlaze_rev1_5/include/hxx/ADC1_CH13.hxx | 8e11b0d2e4dc9c333947d90c46e33aa7565b76f6 | [] | no_license | IQAnalog/iqa_external | b0098d5102d8d7b462993fce081544bd2db00e52 | 13e2c782699f962fb19de9987933cbef66b47ce1 | refs/heads/master | 2023-03-23T13:46:16.550707 | 2021-03-24T18:03:22 | 2021-03-24T18:03:22 | 350,906,829 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,857 | hxx | //*******************************************************************************
// __ __ *
// / \/ \ *
// \ \ *
// I Q - A N A L O G *
// \ \ IQ-Analog Corp *
// \__/\__/ www.iqanalog.com *
// *
//------------------------------------------------------------------------------*
// *
// Copyright (C) 2018-2019 IQ-Analog Corp. All rights reserved. *
// *
//------------------------------------------------------------------------------*
// IQ-Analog CONFIDENTIAL *
//------------------------------------------------------------------------------*
// *
// This file is released with "Government Purpose Rights" as defined *
// in DFARS SUBPART 227.71, clause 252.227-7013. *
// *
//*******************************************************************************
// Generated by RMM 3.3
// IQ-Analog Corp. 2013-2018.
#ifndef __ADC1_CH13_HXX__
#define __ADC1_CH13_HXX__
#define ADC1_CH13_TDC_LUT00 (REG_ADC1_CH13+0x0)
#define ADC1_CH13_TDC_LUT01 (REG_ADC1_CH13+0x4)
#define ADC1_CH13_TDC_LUT02 (REG_ADC1_CH13+0x8)
#define ADC1_CH13_TDC_LUT03 (REG_ADC1_CH13+0xc)
#define ADC1_CH13_TDC_LUT04 (REG_ADC1_CH13+0x10)
#define ADC1_CH13_TDC_LUT05 (REG_ADC1_CH13+0x14)
#define ADC1_CH13_TDC_LUT06 (REG_ADC1_CH13+0x18)
#define ADC1_CH13_TDC_LUT07 (REG_ADC1_CH13+0x1c)
#define ADC1_CH13_TDC_LUT08 (REG_ADC1_CH13+0x20)
#define ADC1_CH13_TDC_BUS_ACCESS (REG_ADC1_CH13+0x24)
#define ADC1_CH13_TDC_OFFSET_AND_GAIN (REG_ADC1_CH13+0x28)
#define ADC1_CH13_TDC_TI_CAL (REG_ADC1_CH13+0x2c)
#define ADC1_CH13_TDC_MISC (REG_ADC1_CH13+0x30)
#define ADC1_CH13_TDC_CAL (REG_ADC1_CH13+0x34)
#define ADC1_CH13_TDC_DITHER (REG_ADC1_CH13+0x38)
#define ADC1_CH13_TDC_BIT_WEIGHTS0 (REG_ADC1_CH13+0x3c)
#define ADC1_CH13_TDC_BIT_WEIGHTS1 (REG_ADC1_CH13+0x40)
#define ADC1_CH13_TDC_STATUS (REG_ADC1_CH13+0x44)
#endif /* __ADC1_CH13_HXX__ */
| [
"rudyl@iqanalog.com"
] | rudyl@iqanalog.com |
738e66fc4c9d586f015fa82e0b35213033daead3 | 9cf25c7877689dda2918a9c8f3a07b16f3549d9d | /Engine/Audio/AudioSystem.h | 49c8618800933de69f04b3eedddbbd78d3023c92 | [] | no_license | spo0kyman/GAT150 | e6b9befcde1eb3124e562884e94e5cb5727b3356 | ced74e960215ce5b0265636062195cda3e5ff9db | refs/heads/master | 2022-12-10T19:00:32.010359 | 2020-09-02T01:33:57 | 2020-09-02T01:33:57 | 284,793,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | h | #pragma once
#include "Core/System.h"
#include "fmod.hpp"
namespace nc {
class AudioSystem : public System {
public:
virtual bool Startup() override;
virtual void Shutdown() override;
virtual void Update() override;
friend class Sound;
protected:
FMOD::System* m_system{ nullptr };
};
} | [
"61479588+spo0kyman@users.noreply.github.com"
] | 61479588+spo0kyman@users.noreply.github.com |
eca14227b5f94317f3910073e25394fc21122137 | 0a7c02bd90d575c2238cc25340cc670515452b05 | /data/dlopen/lib.cc | cbbe083de86d0ba3aec96826453a1fa906664b18 | [] | no_license | 010ric/inMemory_DBSystem_course | 181df3633b2bd24158e92b6bbaefef47777df45d | ced3d8ed10ecd46e347021544650a57481067c2e | refs/heads/main | 2023-01-14T03:51:54.829329 | 2020-11-21T10:47:44 | 2020-11-21T10:47:44 | 314,787,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45 | cc | extern "C" int foo(int x) { return x * 2; }
| [
"mturic@inovex.de"
] | mturic@inovex.de |
d2d465366486abacf468cc9740266a07717f3043 | 1c1b09bba3a951df1b9dd24debc1d2b840477b89 | /FIT2096_Assignment2b_WillStojic/Player.cpp | 9ff1553e68656cef72b74bc39e4d442e041b1aca | [] | no_license | WillStojic/FIT2096_Assignment2b | 8e0e73dd98d808edefec526f5c5201cea46e40ce | 10f86d919d6cf44d318effaf1cef588b4f27f8a2 | refs/heads/master | 2020-03-17T00:37:11.510144 | 2018-05-28T19:06:30 | 2018-05-28T19:06:30 | 133,123,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,096 | cpp | #include "Player.h"
#include "MathsHelper.h"
Player::Player(InputController* input)
: PhysicsObject(Vector3(MathsHelper::RandomRange(1, 48), 0, MathsHelper::RandomRange(1, 48)))
{
m_input = input;
// The player is much stronger than any monster on the board
m_health = 200.0f;
m_gems = 0;
//starting ammo
m_ammo = 8;
m_score = 0;
m_monstersDefeated = 0;
//amount of frames before the player can fire another bullet.
m_fireRate = 15;
//movement attributes
m_moveSpeed = 5.0f;
m_jumpStrength = 0.3f;
//player has no mesh, therefore bounds are manually set, mesh is kept relatively thin, so the player can dodge bullets more easily
m_boundingBox = new CBoundingBox(m_position + Vector3(-0.15f, 0.0f, -0.15f), m_position + Vector3(0.15f, 1.8f, 0.15f));
}
Player::~Player() {}
void Player::Update(float timestep, FirstPersonCamera* &camera, BulletFactory* &bulletFactory)
{
m_position = Vector3::Lerp(m_position, m_targetPosition, timestep * m_moveSpeed);
//disables player input, if health is below 0
if (m_health <= 0)
{
//player falls on their back when dead.
camera->SetPosition(m_position + Vector3(0.0f, 0.3f, 0.0f));
}
else
{
//attaches camera to player
camera->SetPosition(m_position + Vector3(0.0f, 1.6f, 0.0f));
//save on function calls by intialising local variables
float m_heading = camera->GetHeading();
float m_pitch = camera->GetPitch();
// Accumulate change in mouse position
m_heading += m_input->GetMouseDeltaX() * camera->GetRotationSpeed() * timestep;
m_pitch += m_input->GetMouseDeltaY() * camera->GetRotationSpeed() * timestep;
// Limit how far the player can look down and up
m_pitch = MathsHelper::Clamp(m_pitch, ToRadians(-80.0f), ToRadians(80.0f));
camera->SetHeading(m_heading);
camera->SetPitch(m_pitch);
// Wrap heading and pitch up in a matrix so we can transform our look at vector
// Heading is controlled by MouseX (horizontal movement) but it is a rotation around Y
// Pitch controlled by MouseY (vertical movement) but it is a rotation around X
Matrix heading = Matrix::CreateRotationY(m_heading);
Matrix pitch = Matrix::CreateRotationX(m_pitch);
// Transform a world right vector from world space into local space
Vector3 localRight = Vector3::TransformNormal(Vector3(1, 0, 0), heading);
// Essentially our local forward vector but always parallel with the ground
// Remember a cross product gives us a vector perpendicular to the two input vectors
Vector3 localForwardXZ = localRight.Cross(Vector3(0, 1, 0));
// We're going to need this a lot. Store it locally here to save on our function calls
Vector3 currentPos = camera->GetPosition();
Vector3 translation = m_position;
//moves the player's position
if (m_input->GetKeyHold('W'))
{
translation += localForwardXZ;
}
if (m_input->GetKeyHold('S'))
{
translation -= localForwardXZ;
}
if (m_input->GetKeyHold('A'))
{
translation -= localRight;
}
if (m_input->GetKeyHold('D'))
{
translation += localRight;
}
if (m_input->GetKeyHold(VK_SHIFT))
{
m_moveSpeed = 10;
}
else
m_moveSpeed = 5;
if (m_input->GetKeyDown(VK_SPACE) && m_position.y < 0.1)
{
this->Jump(m_jumpStrength);
}
m_targetPosition = translation;
// Combine pitch and heading into one matrix for convenience
Matrix lookAtRotation = pitch * heading;
// Transform a world forward vector into local space (take pitch and heading into account)
Vector3 lookAt = Vector3::TransformNormal(Vector3(0, 0, 1), lookAtRotation);
m_headOffPoint = (lookAt * 10) + currentPos;
//handles shooting input
++m_shootTicker;
if (m_input->GetMouseDown(0) && m_shootTicker > m_fireRate && m_ammo != 0)
{
//creates bullet trajectory
Vector3 aim = lookAt * 50;
aim += currentPos;
Vector3 offset = Vector3::TransformNormal(Vector3(0, 0, 0.5), lookAtRotation) + currentPos;
//spawns bullet
bulletFactory->InitialiseBullet(offset, aim, BulletType::PLAYER);
//reduces ammo after each shot
--m_ammo;
//resets shoot ticker, thus meaning the player will have to wait a set amount of frames to shoot again
m_shootTicker = 0;
}
// At this point, our look-at vector is still relative to the origin
// Add our position to it so it originates from the camera and points slightly in front of it
// Remember the look-at vector needs to describe a point in the world relative to the origin
lookAt += currentPos;
//orient player's y rotation to camera
m_rotY = lookAt.y;
// Use parent's mutators so isDirty flags get flipped
camera->SetLookAt(lookAt);
camera->SetPosition(currentPos);
m_boundingBox->SetMin(m_position + Vector3(-0.05f, 1.1f, -0.05f));
m_boundingBox->SetMax(m_position + Vector3(0.05f, 1.8f, 0.05f));
PhysicsObject::Update(timestep);
}
}
//simple adjustment to player variable once item is collided with.
void Player::PickupItem(ItemType itemType)
{
if (itemType == ItemType::HEALTH)
m_health += 10;
else if (itemType == ItemType::AMMO)
m_ammo += 4;
else if (itemType == ItemType::GEM)
{
++m_gems;
m_score += 40;
}
}
| [
"wsto0001@student.monash.edu"
] | wsto0001@student.monash.edu |
1d960042dd25ff02d954baeb89b66b4040bd25e6 | fc74816e1cfbef9f3a15f3955bfe608b2605c44b | /count.cpp | 073b09c00ae768cf8805564d6d4b93b9073c7c8e | [] | no_license | marklance/work | 5e90b5a7808228269e526516a152912bc7b1afdd | ff089d1644e5f99175b7828903b9047996935843 | refs/heads/master | 2021-04-28T09:17:27.555380 | 2018-06-03T15:52:41 | 2018-06-03T15:52:41 | 121,955,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 673 | cpp | #include <iostream>
#include <fstream>
#include <cstdlib>
int main(int argc, char * argv[])
{
using namespace std;
if (argc == 1)
{
cerr << "Usage: " << argv[0] << " filename[s]\n";
exit(EXIT_FAILURE);
}
ifstream fin;
long count;
long total = 0;
char ch;
for (int file = 1; file < argc; file++)
{
fin.open(argv[file]);
if (!fin.is_open())
{
cerr << "Could not open " << argv[file] << endl;
fin.clear();
continue;
}
count = 0;
while (fin.get(ch))
count++;
cout << count << " characters in " << argv[file] << endl;
total += count;
fin.clear();
fin.close();
}
cout << total << " characters in all file\n";
return 0;
}
| [
"2927295165@qq.com"
] | 2927295165@qq.com |
b8523ef664f336fbafe38f036dc8317fc6b50dca | d5dd043940702693d9308670d00d1b179f33e874 | /MIXKEY_NEW_CODE/Adafruit-GFX-Library-master/Adafruit_GFX.h | 5c1b92dc763b8fe8aa42be38e29ddb7adf25f341 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | OasysLab/MIXKEY_NEW_CODE_NBIoT_3G | 520dc2f087cfddaa021f30723425b356c4c02cd1 | 82f1b79f034ab4389e3b7d6829b0cda1ac035181 | refs/heads/master | 2020-03-23T12:00:19.337505 | 2018-07-19T05:58:52 | 2018-07-19T05:58:52 | 141,531,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,006 | h | #ifndef _ADAFRUIT_GFX_H
#define _ADAFRUIT_GFX_H
#if ARDUINO >= 100
#include "Arduino.h"
#include "Print.h"
#else
#include "WProgram.h"
#endif
#include "gfxfont.h"
class Adafruit_GFX : public Print {
public:
Adafruit_GFX(int16_t w, int16_t h); // Constructor
// This MUST be defined by the subclass:
virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0;
// These MAY be overridden by the subclass to provide device-specific
// optimized code. Otherwise 'generic' versions are used.
virtual void
drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color),
drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color),
drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color),
drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color),
fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color),
fillScreen(uint16_t color),
invertDisplay(boolean i);
// These exist only with Adafruit_GFX (no subclass overrides)
void
drawConnectedLogo(),
drawLogo(),
drawConnectLogo(),
drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color),
drawCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername,
uint16_t color),
fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color),
fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername,
int16_t delta, uint16_t color),
drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1,
int16_t x2, int16_t y2, uint16_t color),
fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1,
int16_t x2, int16_t y2, uint16_t color),
drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h,
int16_t radius, uint16_t color),
fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h,
int16_t radius, uint16_t color),
drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color),
drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color, uint16_t bg),
drawBitmap(int16_t x, int16_t y, uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color),
drawBitmap(int16_t x, int16_t y, uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color, uint16_t bg),
drawXBitmap(int16_t x, int16_t y, const uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color),
drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color,
uint16_t bg, uint8_t size),
setCursor(int16_t x, int16_t y),
setTextColor(uint16_t c),
setTextColor(uint16_t c, uint16_t bg),
setTextSize(uint8_t s),
setTextWrap(boolean w),
setRotation(uint8_t r),
cp437(boolean x=true),
setFont(const GFXfont *f = NULL),
getTextBounds(char *string, int16_t x, int16_t y,
int16_t *x1, int16_t *y1, uint16_t *w, uint16_t *h),
getTextBounds(const __FlashStringHelper *s, int16_t x, int16_t y,
int16_t *x1, int16_t *y1, uint16_t *w, uint16_t *h);
#if ARDUINO >= 100
virtual size_t write(uint8_t);
#else
virtual void write(uint8_t);
#endif
int16_t height(void) const;
int16_t width(void) const;
uint8_t getRotation(void) const;
// get current cursor position (get rotation safe maximum values, using: width() for x, height() for y)
int16_t getCursorX(void) const;
int16_t getCursorY(void) const;
protected:
const int16_t
WIDTH, HEIGHT; // This is the 'raw' display w/h - never changes
int16_t
_width, _height, // Display w/h as modified by current rotation
cursor_x, cursor_y;
uint16_t
textcolor, textbgcolor;
uint8_t
textsize,
rotation;
boolean
wrap, // If set, 'wrap' text at right edge of display
_cp437; // If set, use correct CP437 charset (default is off)
GFXfont
*gfxFont;
};
class Adafruit_GFX_Button {
public:
Adafruit_GFX_Button(void);
void initButton(Adafruit_GFX *gfx, int16_t x, int16_t y,
uint8_t w, uint8_t h, uint16_t outline, uint16_t fill,
uint16_t textcolor, char *label, uint8_t textsize);
void drawButton(boolean inverted = false);
boolean contains(int16_t x, int16_t y);
void press(boolean p);
boolean isPressed();
boolean justPressed();
boolean justReleased();
private:
Adafruit_GFX *_gfx;
int16_t _x, _y;
uint16_t _w, _h;
uint8_t _textsize;
uint16_t _outlinecolor, _fillcolor, _textcolor;
char _label[10];
boolean currstate, laststate;
};
class GFXcanvas1 : public Adafruit_GFX {
public:
GFXcanvas1(uint16_t w, uint16_t h);
~GFXcanvas1(void);
void drawPixel(int16_t x, int16_t y, uint16_t color),
fillScreen(uint16_t color);
uint8_t *getBuffer(void);
private:
uint8_t *buffer;
};
class GFXcanvas16 : public Adafruit_GFX {
GFXcanvas16(uint16_t w, uint16_t h);
~GFXcanvas16(void);
void drawPixel(int16_t x, int16_t y, uint16_t color),
fillScreen(uint16_t color);
uint16_t *getBuffer(void);
private:
uint16_t *buffer;
};
#endif // _ADAFRUIT_GFX_H
| [
"qqlinebotapi@gmail.com"
] | qqlinebotapi@gmail.com |
3ba96dd105aa816b78d5d5f37bd4479f1106ab2d | 375c093f555bddd1ce10e80530dba9119cc24306 | /BOJ/20361.cpp | 1ff903190b2cffd779ebfa73eebabbd48b0fa611 | [] | no_license | Seojeonguk/Algorithm_practice | e8c2add155a1341087e4c528f5346c8711525f96 | b29a1a7421edf2a9968229822dcbdc5a7926e2f5 | refs/heads/master | 2023-08-25T11:40:40.076347 | 2023-08-25T09:07:45 | 2023-08-25T09:07:45 | 154,248,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | #ifdef _DEBUG
#include "bits_stdc++.h"
#else
#include "bits/stdc++.h"
#endif
#pragma warning(disable:4996)
using namespace std;
int n, x, k,a,b;
int main() {
#ifdef _CONSOLE
freopen("sample.txt", "r", stdin);
#endif
scanf("%d %d %d", &n, &x, &k);
for (int i = 0; i < k; i++) {
scanf("%d %d", &a, &b);
if (a == x) x = b;
else if (b == x) x = a;
}
printf("%d\n", x);
} | [
"uk7880@naver.com"
] | uk7880@naver.com |
804c2545f58436e1df2eaca999344c6c3eb7344e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_308_collectd-5.6.3.cpp | 59bef3734378a6afdb92c73c674bdf8dab83f14a | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 963 | cpp | static void aggregate(gauge_t *sum_by_state) /* {{{ */
{
for (size_t state = 0; state < COLLECTD_CPU_STATE_MAX; state++)
sum_by_state[state] = NAN;
for (size_t cpu_num = 0; cpu_num < global_cpu_num; cpu_num++) {
cpu_state_t *this_cpu_states = get_cpu_state(cpu_num, 0);
this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate = NAN;
for (size_t state = 0; state < COLLECTD_CPU_STATE_ACTIVE; state++) {
if (!this_cpu_states[state].has_value)
continue;
RATE_ADD(sum_by_state[state], this_cpu_states[state].rate);
if (state != COLLECTD_CPU_STATE_IDLE)
RATE_ADD(this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate,
this_cpu_states[state].rate);
}
if (!isnan(this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate))
this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].has_value = 1;
RATE_ADD(sum_by_state[COLLECTD_CPU_STATE_ACTIVE],
this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate);
}
} | [
"993273596@qq.com"
] | 993273596@qq.com |
1e2eab60eaa70114bb684e4ee635db610d8af8a5 | 391dede5cf715071d5fac9ac376d26c3b4edf040 | /linux/my_application.cc | 83d3efea9d28fd5e5102f095dd9f54cf29a81926 | [] | no_license | Vritika21/intertwined | 5fa0450fd9632f83b8722fcb25c2a1fefd9586f6 | d22dbd787fcc5a8543f56f9e79cd7894fd1c76fc | refs/heads/master | 2023-04-06T22:49:55.002306 | 2021-04-08T21:50:23 | 2021-04-08T21:50:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,654 | cc | #include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen *screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar *header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "intertwined");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
}
else {
gtk_window_set_title(window, "intertwined");
}
gtk_window_set_default_size(window, 1280, 720);
gtk_widget_show(GTK_WIDGET(window));
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application, gchar ***arguments, int *exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GObject::dispose.
static void my_application_dispose(GObject *object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID,
nullptr));
}
| [
"madhurmaurya365@gmail.com"
] | madhurmaurya365@gmail.com |
de80a75a3b3eeadd4f3649dc92f5e2357c4e9e17 | a3634de7800ae5fe8e68532d7c3a7570b9c61c5b | /codechef/JUNE17PRMQ2.cpp | 7baaa3cebf4b6cb9faedcb6066d9c87412c279a0 | [] | no_license | MayankChaturvedi/competitive-coding | a737a2a36b8aa7aea1193f2db4b32b081f78e2ba | 9e9bd21de669c7b7bd29a262b29965ecc80ad621 | refs/heads/master | 2020-03-18T01:39:29.447631 | 2018-02-19T15:04:32 | 2018-02-19T15:04:32 | 134,152,930 | 0 | 1 | null | 2018-05-20T13:27:35 | 2018-05-20T13:27:34 | null | UTF-8 | C++ | false | false | 3,533 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;
inline void fastRead_int(long long &x)
{ register int c = getchar_unlocked();
x = 0;
int neg = 0;
for(; ((c<48 || c>57) && c != '-'); c = getchar_unlocked());
if(c=='-')
{ neg = 1;
c = getchar_unlocked();
}
for(; c>47 && c<58 ; c = getchar_unlocked())
{ x = (x<<1) + (x<<3) + c - 48;
}
}
const int MAXN=1e5+2, MAXIND=4*MAXN;
vector<int> Segtree[MAXIND]; //Array and Segtree will follow 0-based and 1-based indexing respectively.
vector<int> Array[MAXN];
int primes[168]={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,
223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509,
521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853,
857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997};
//initializes Segtree from Array.
void initialize(int node, int b, int e, int N)
{ if (b == e)
Segtree[node] = Array[b];
else
{ //compute the values in the left and right subtrees
initialize(2*node, b, (b+e)/2, N);
initialize(2*node + 1, (b+e)/2 + 1, e, N);
Segtree[node].resize(Segtree[2*node].size() + Segtree[2*node +1].size());
merge(Segtree[2*node].begin(), Segtree[2*node].end(), Segtree[2*node +1].begin(), Segtree[2*node +1].end(), Segtree[node].begin());
sort(Segtree[node].begin(), Segtree[node].end());
}
//printf("%d ",node);
//for(int i : Segtree[node])
//printf("%d ",i);
//printf("\n");
}
int query(int node, int b, int e, int i, int j, int X, int Y)
{
int p1, p2;
//if the current interval doesn't intersect
//the query interval return -1
if (i > e || j < b)
return -1;
//if the current interval is included in
//the query interval return Segtree[node]
if (b >= i && e <= j)
{ auto lowerlimit= lower_bound(Segtree[node].begin(), Segtree[node].end(), X);
auto upperlimit= upper_bound(Segtree[node].begin(), Segtree[node].end(), Y);
return upperlimit-lowerlimit;
}
p1 = query(2*node, b, (b+e)/2, i, j, X, Y);
p2 = query(2*node + 1, (b+e)/2 + 1, e, i, j, X, Y);
if (p1 == -1)
return p2;
if (p2 == -1)
return p1;
return p1 + p2;
}
int main()
{ long long N;
fastRead_int(N);
long long a[N];
for(int i=0; i<N; i++)
fastRead_int(a[i]);
long long Q;
fastRead_int(Q);
for(int i=0; i<N; i++)
{ long long temp=a[i];
for(int j=0; j<168 && temp>1; j++)
{ while(temp % primes[j] == 0)
{ Array[i].push_back(primes[j]);
temp/=primes[j];
}
}
if(temp>1)
{ Array[i].push_back(temp);
}
}
initialize(1, 0, N-1, N);
while(Q--) //For each query, we search for L to R on all of the 168 segment trees.
{ long long L, R, X, Y;
fastRead_int(L);
fastRead_int(R);
fastRead_int(X);
fastRead_int(Y);
L--; R--;
long long que=query(1, 0, N-1, L, R, X, Y);
printf("%lld\n",que);
}
return 0;
}
| [
"f20160006@goa.bits-pilani.ac.in"
] | f20160006@goa.bits-pilani.ac.in |
879d107ab1cc6c6cb7b4f9a64cc2a4bb8007e470 | e5c0b38c9cc0c0e6155c9d626e299c7b03affd1e | /trunk/Code/Engine/Graphics/StaticMeshes/StaticMesh.cpp | 8e9bb78979af5033d8a1d660a0c4d21c5a8405d0 | [] | no_license | BGCX261/zombigame-svn-to-git | 4e5ec3ade52da3937e2b7d395424c40939657743 | aa9fb16789f1721557085deae123771f5aefc4dd | refs/heads/master | 2020-05-26T21:56:40.088036 | 2015-08-25T15:33:27 | 2015-08-25T15:33:27 | 41,597,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,893 | cpp | #include "StaticMesh.h"
#include "RenderManager.h"
#include "Texture/Texture.h"
#include "Vertex/VertexType.h"
#include "Vertex/IndexedVertex.h"
#include "Core.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "Texture/TextureManager.h"
#include "Shaders/EffectManager.h"
#include "Shaders/EffectTechnique.h"
#include "Exceptions/Exception.h"
#if defined( _DEBUG )
#include "Memory/MemLeaks.h"
#endif // defined( _DEBUG )
using namespace std;
#define _HEADER 0xFF77
#define _FOOTER 0x77FF
CStaticMesh::CStaticMesh()
: m_TechniqueName("")
, m_FileName("")
, m_NumVertexs(0)
, m_NumFaces(0)
, m_Textures(NULL)
, m_Techniques(NULL)
, m_RVs(NULL)
, m_VertexBufferPhysX(0)
, m_IndexBufferPhysX(0)
, m_pV3fSelfIlluminationColor(0)
{
}
CStaticMesh::~CStaticMesh()
{
CHECKED_DELETE(m_pV3fSelfIlluminationColor)
m_Techniques.clear();
m_Textures.clear();
Release();
}
bool CStaticMesh::Load(const std::string &FileName)
{
m_FileName = FileName;
ifstream l_File(m_FileName.c_str(), ios::in|ios::binary);
if(l_File.is_open())
{
unsigned short l_Header = 0;
unsigned short l_CantMateriales = 0;
//unsigned short l_CantIndices = 0;
unsigned short l_VertexType = 0;
unsigned short l_CountTextures = 0;
unsigned short l_CantVertices = 0;
unsigned short l_IndexCount = 0;
unsigned short l_Footer = 0;
std::vector<unsigned short> l_vVertexTypes;
//Lectura del Header
l_File.read((char *)&l_Header, sizeof(unsigned short));
if(l_Header != _HEADER)
{
LOGGER->AddNewLog(ELL_WARNING, "CStaticMesh::Load Encabezado incorrecto al leer el archivo '%'",m_FileName);
l_File.close();
return false;
}
//Cantidad de materiales
l_File.read((char *)&l_CantMateriales, sizeof(unsigned short));
std::string l_TechniqueName;
//ciclo para cada material
for(int j = 0; j < l_CantMateriales; j++)
{
//Lectura del Vertex Type
l_File.read((char *)&l_VertexType, sizeof(unsigned short));
//se verifica si tiene alpha_test
if (l_VertexType & ALPHA_TEST)
{
l_VertexType = l_VertexType ^ ALPHA_TEST;
l_TechniqueName=CORE->GetEffectManager()->GetTechniqueEffectNameByVertexDefault(l_VertexType);
if (m_pV3fSelfIlluminationColor != NULL)
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_SI_AT"));
}
else
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_AT"));
}
}
else if(l_VertexType & ALPHA_BLEND)
{
l_VertexType = l_VertexType ^ ALPHA_BLEND;
l_TechniqueName=CORE->GetEffectManager()->GetTechniqueEffectNameByVertexDefault(l_VertexType);
if (m_pV3fSelfIlluminationColor != NULL)
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_SI_AB"));
}
else
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_AB"));
}
}
else // en los otros casos en los que no hay transparencias
{
l_TechniqueName = CORE->GetEffectManager()->GetTechniqueEffectNameByVertexDefault(l_VertexType);
if (m_pV3fSelfIlluminationColor != NULL)
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_SI"));
}
else
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName));
}
}
l_vVertexTypes.push_back(l_VertexType);
//Cantidad de texturas
l_File.read((char *)&l_CountTextures, sizeof(unsigned short));
//Lectura de materiales. Se leen "l_CountTextures" materiales.
m_Textures.push_back(std::vector<CTexture *>());
for(int i = 0; i < l_CountTextures; i++)
{
//Path Size
unsigned short l_pathSize = 0;
l_File.read((char *)&l_pathSize, sizeof(unsigned short));
//Reading Path
char * l_pathMaterial = new char[l_pathSize+1];
int temp = sizeof(l_pathMaterial);
l_File.read(l_pathMaterial, sizeof(char) * (l_pathSize+1));
//Carga la textura y la introduce en su vector
CTexture *l_Texture=CORE->GetTextureManager()->GetTexture(l_pathMaterial);
m_Textures[j].push_back(l_Texture);
CHECKED_DELETE_ARRAY(l_pathMaterial);
}
}//fin de ciclo para cada material
//l_File.read((char *)&l_CantIndices, sizeof(unsigned short));
for(int j = 0; j < l_CantMateriales; j++)
{
l_File.read((char *)&l_CantVertices, sizeof(unsigned short));
int l_Size=0;
l_VertexType = l_vVertexTypes.at(j);
if(l_VertexType == TNORMAL_TEXTURE1_VERTEX::GetVertexType())
{
l_Size=sizeof(TNORMAL_TEXTURE1_VERTEX);
}
else if(l_VertexType == TNORMAL_TEXTURE2_VERTEX::GetVertexType())
{
l_Size=sizeof(TNORMAL_TEXTURE2_VERTEX);
}
else if(l_VertexType == TNORMAL_COLORED_VERTEX::GetVertexType())
{
l_Size=sizeof(TNORMAL_COLORED_VERTEX);
}
else if(l_VertexType == TNORMAL_TANGENT_BINORMAL_TEXTURED::GetVertexType())
{
l_Size=sizeof(TNORMAL_TANGENT_BINORMAL_TEXTURED);
}
else if(l_VertexType == TNORMAL_TANGENT_BINORMAL_TEXTURED2::GetVertexType())
{
l_Size=sizeof(TNORMAL_TANGENT_BINORMAL_TEXTURED2);
}
char *l_Vtxs=new char[l_Size*l_CantVertices];
l_File.read((char *)&l_Vtxs[0],l_Size*l_CantVertices);
l_File.read((char *)&l_IndexCount, sizeof(unsigned short));
unsigned short *l_Indxs = new unsigned short[l_IndexCount];
l_File.read((char *)&l_Indxs[0],sizeof(unsigned short)*l_IndexCount);
CRenderableVertexs * l_RV;
//-----------------------------------
if(l_VertexType == TNORMAL_TEXTURE1_VERTEX::GetVertexType())
{
l_RV = new CIndexedVertex<TNORMAL_TEXTURE1_VERTEX>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
else if(l_VertexType == TNORMAL_TEXTURE2_VERTEX::GetVertexType())
{
l_RV = new CIndexedVertex<TNORMAL_TEXTURE2_VERTEX>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
else if(l_VertexType == TNORMAL_COLORED_VERTEX::GetVertexType())
{
l_RV = new CIndexedVertex<TNORMAL_COLORED_VERTEX>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
else if(l_VertexType == TNORMAL_TANGENT_BINORMAL_TEXTURED::GetVertexType())
{
//calcular en el vertex buffer las tangenciales y binormales
CalcTangentsAndBinormals(l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount, sizeof(TNORMAL_TANGENT_BINORMAL_TEXTURED), 0, 12, 28, 44, 60);
TNORMAL_TANGENT_BINORMAL_TEXTURED *l_HackVtxs=(TNORMAL_TANGENT_BINORMAL_TEXTURED *)&l_Vtxs[0];
Vect3f l_Min, l_Max;
for(int b=0;b<l_CantVertices;++b)
{
if(b==0)
{
l_Min=Vect3f(l_HackVtxs[b].x,l_HackVtxs[b].y,l_HackVtxs[b].z);
l_Max=Vect3f(l_HackVtxs[b].x,l_HackVtxs[b].y,l_HackVtxs[b].z);
}
if(l_HackVtxs[b].x<l_Min.x)
l_Min.x=l_HackVtxs[b].x;
if(l_HackVtxs[b].y<l_Min.y)
l_Min.y=l_HackVtxs[b].y;
if(l_HackVtxs[b].z<l_Min.z)
l_Min.z=l_HackVtxs[b].z;
if(l_HackVtxs[b].x>l_Max.x)
l_Max.x=l_HackVtxs[b].x;
if(l_HackVtxs[b].y>l_Max.y)
l_Max.y=l_HackVtxs[b].y;
if(l_HackVtxs[b].z>l_Max.z)
l_Max.z=l_HackVtxs[b].z;
}
l_RV = new CIndexedVertex<TNORMAL_TANGENT_BINORMAL_TEXTURED>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
else if(l_VertexType == TNORMAL_TANGENT_BINORMAL_TEXTURED2::GetVertexType())
{
//calcular en el vertex buffer las tangenciales y binormales
CalcTangentsAndBinormals(l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount, sizeof(TNORMAL_TANGENT_BINORMAL_TEXTURED2), 0, 12, 28, 44, 60);
l_RV = new CIndexedVertex<TNORMAL_TANGENT_BINORMAL_TEXTURED2>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
//CRenderableVertexs *l_RV = new CIndexedVertex<TNORMAL_COLORED_TEXTURE1_VERTEX>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
this->m_NumVertexs = l_IndexCount;
this->m_NumFaces = l_IndexCount / 3;
m_RVs.push_back(l_RV);
//-----------------------------------
//Prueba PhysX
for(int i = 0; i < l_CantVertices; i++)
{
D3DXVECTOR3 *v1=(D3DXVECTOR3 *) &l_Vtxs[i*l_Size];
m_VertexBufferPhysX.push_back(Vect3f(v1->x,v1->y,v1->z));
}
uint32 l_Index;
for(int i = 0; i < l_IndexCount; i++)
{
l_Index = (uint32) l_Indxs[i];
m_IndexBufferPhysX.push_back(l_Index);
}
//-----------------------------------
CHECKED_DELETE_ARRAY(l_Vtxs);
CHECKED_DELETE_ARRAY(l_Indxs);
}
l_File.read((char *)&l_Footer, sizeof(unsigned short));
if(l_Footer != _FOOTER)
{
LOGGER->AddNewLog(ELL_ERROR, "CStaticMesh::Load->Pie de archivo incorrecto al leer el archivo '%s'",m_FileName.c_str());
l_File.close();
return false;
}
l_File.close();
}
else
{
std::string msg_error = "CStaticMesh::Load->Error al abrir el archivo. El archivo no existe: ";
msg_error.append(m_FileName.c_str());
LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str());
//throw CException(__FILE__, __LINE__, msg_error);
return false;
}
return true;
}
bool CStaticMesh::ReLoad()
{
Release();
return Load(m_FileName);
}
void CStaticMesh::Render(CRenderManager *RM) const
{
vector<CRenderableVertexs*>::const_iterator l_Iter = this->m_RVs.begin();
for(int i=0;l_Iter != m_RVs.end();++i, ++l_Iter)
{
for(size_t j=0;j<m_Textures[i].size();++j)
{
m_Textures[i][j]->Activate(j);
}
CEffectTechnique *l_Technique=CORE->GetEffectManager()->GetStaticMeshTechnique();
if(l_Technique==NULL)
l_Technique=m_Techniques[i];
if(l_Technique!=NULL)
{
l_Technique->BeginRender(m_pV3fSelfIlluminationColor);
(*l_Iter)->Render(RM, l_Technique);
}
}
}
void CStaticMesh::Release()
{
vector<CRenderableVertexs*>::iterator l_Iter = m_RVs.begin();
while(l_Iter != m_RVs.end())
{
CHECKED_DELETE(*l_Iter);
++l_Iter;
}
m_RVs.clear();
}
| [
"you@example.com"
] | you@example.com |
29fde03134c5cf12e5099bbe300a2db94d4c3a97 | 22c04c1d53f4bb526766c38619261da4b3f2494a | /Scoreboard_v1.0/Scoreboard_v1.0.ino | cf687621220d0b3b719fde744e19988a8540eaf1 | [] | no_license | educoay/Scoreboard_rev.Arduino | 3fd48440ac8289d759868b6de32088709956cd84 | 2dcee8fb37852a81b36cc318e49b6dbe11507c35 | refs/heads/master | 2020-12-20T11:21:12.230193 | 2019-12-27T23:10:05 | 2019-12-27T23:10:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,671 | ino | /*
Скетч к проекту "Бегущая строка"
Страница проекта (схемы, описания): https://alexgyver.ru/GyverString/
Исходники на GitHub: https://github.com/AlexGyver/GyverString/
Нравится, как написан код? Поддержи автора! https://alexgyver.ru/support_alex/
Автор: AlexGyver, AlexGyver Technologies, 2019
https://AlexGyver.ru/
Версия 1.1: прошивка оптимизирована под широкие матрицы (до 80 пикс)
Версия 1.3: исправлен баг с красным цветом
*/
#define C_BLACK 0x000000
#define C_GREEN 0x00FF00
#define C_RED 0xFF0000
#define C_BLUE 0x0000FF
#define C_PURPLE 0xFF00FF
#define C_YELLOW 0xFFFF00
#define C_CYAN 0x00FFFF
#define C_WHITE 0xFFFFFF
/*
String text1 = "READYBOX FOR: ";
#define COLOR1 C_GREEN
String text2 = "Andreas HERIG, Vladimir SOSHNIN, Radovan PLCH ";
#define COLOR2 C_PURPLE
String text3 = "BE READY: ";
#define COLOR3 C_YELLOW
String text4 = "Michael MISHIN ";
#define COLOR4 C_PURPLE
String text5 = "ON START: ";
#define COLOR5 C_RED
String text6 = "Vladyslav CHEBANOV ";
#define COLOR6 C_PURPLE
String text7 = "";
#define COLOR7 C_YELLOW
String text8 = "";
#define COLOR8 C_PURPLE
String text9 = "Wind speed and direction: ";
#define COLOR9 C_CYAN
String text10 = "12 m/s, 17 deg. ";
#define COLOR10 C_PURPLE
*/
String text1 = "READYBOX FOR: ";
#define COLOR1 C_GREEN
String text2 = "A. HERIG ";
#define COLOR2 C_PURPLE
String text3 = "BE READY: ";
#define COLOR3 C_YELLOW
String text4 = "M. MISHIN ";
#define COLOR4 C_PURPLE
String text5 = "ON START: ";
#define COLOR5 C_RED
String text6 = "V. CHEBANOV ";
#define COLOR6 C_PURPLE
String text7 = "";
#define COLOR7 C_YELLOW
String text8 = "";
#define COLOR8 C_PURPLE
String text9 = "Wind: ";
#define COLOR9 C_CYAN
String text10 = "12 m/s ";
#define COLOR10 C_PURPLE
String statictxt1 = "0123456789";
String statictxt2 = "ABCDEFGHIJ";
// ================ НАСТРОЙКИ ================
#define BRIGHTNESS 120 // стандартная яркость (0-255)
#define D_TEXT_SPEED 10 // скорость бегущего текста по умолчанию (мс)
#define CURRENT_LIMIT 2000 // лимит по току в миллиамперах, автоматически управляет яркостью (пожалей свой блок питания!) 0 - выключить лимит
#define WIDTH 60 // ширина матрицы
#define HEIGHT 8 // высота матрицы
#define SEGMENTS 1 // диодов в одном "пикселе" (для создания матрицы из кусков ленты)
#define COLOR_ORDER GRB // порядок цветов на ленте. Если цвет отображается некорректно - меняйте. Начать можно с RGB
#define MATRIX_TYPE 0 // тип матрицы: 0 - зигзаг, 1 - параллельная
#define CONNECTION_ANGLE 0 // угол подключения: 0 - левый нижний, 1 - левый верхний, 2 - правый верхний, 3 - правый нижний
#define STRIP_DIRECTION 0 // направление ленты из угла: 0 - вправо, 1 - вверх, 2 - влево, 3 - вниз
// при неправильной настрйоке матрицы вы получите предупреждение "Wrong matrix parameters! Set to default"
// шпаргалка по настройке матрицы здесь! https://alexgyver.ru/matrix_guide/
// ============ ДЛЯ РАЗРАБОТЧИКОВ ============
// ПИНЫ
#define LED_PIN 4
// БИБЛИОТЕКИ
//#include <FastLED.h>
#define COLOR_DEBTH 2 // цветовая глубина: 1, 2, 3 (в байтах)
#define ORDER_GRB // ORDER_GRB / ORDER_RGB
#include "microLED.h"
#include "fonts.h"
const int NUM_LEDS = WIDTH * HEIGHT * SEGMENTS;
LEDdata leds[NUM_LEDS];
microLED strip(leds, NUM_LEDS, LED_PIN); // объект лента
uint32_t scrollTimer;
String runningText = "";
boolean loadingFlag, fullTextFlag;
const uint32_t textColors[] PROGMEM = {
COLOR1,
COLOR2,
COLOR3,
COLOR4,
COLOR5,
COLOR6,
COLOR7,
COLOR8,
COLOR9,
COLOR10,
};
int colorChange[10];
void setup() {
//Serial.begin(9600);
randomSeed(analogRead(0));
// настройки ленты
//strip.addLeds<WS2812, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
strip.setBrightness(BRIGHTNESS);
//if (CURRENT_LIMIT > 0) strip.setMaxPowerInVoltsAndMilliamps(5, CURRENT_LIMIT);
strip.clear();
strip.show();
runningText = String(text1) + text2 + text3 + text4 + text5 + text6 + text7 + text8 + text9 + text10;
colorChange[0] = stringLength(text1);
colorChange[1] = colorChange[0] + stringLength(text2);
colorChange[2] = colorChange[1] + stringLength(text3);
colorChange[3] = colorChange[2] + stringLength(text4);
colorChange[4] = colorChange[3] + stringLength(text5);
colorChange[5] = colorChange[4] + stringLength(text6);
colorChange[6] = colorChange[5] + stringLength(text7);
colorChange[7] = colorChange[6] + stringLength(text8);
colorChange[8] = colorChange[7] + stringLength(text9);
colorChange[9] = colorChange[8] + stringLength(text10);
}
void loop() {
// fillString(runningText);
// delay(1000);
// fillString(statictxt1);
// delay(5000);
// fillString(statictxt2);
// delay(5000);
fillFrame(statictxt1);
delay(5000);
fillFrame(statictxt2);
delay(5000);
}
| [
"dyagilev@gmail.com"
] | dyagilev@gmail.com |
58cc94cc6cf3d72639343965e308a3679dfbae8f | 85983068d42318310065e40f43f7d9c6ad8a1114 | /Line Tracking Robot/LineTrackingRobot/LineTrackingRobot.ino | afd245ae99c3878ef2778d257ef00c019733262d | [] | no_license | WindyCityLab/equinoxLabs | 5df9b6ac0a859967ebcf623a6dd0de54e8f9c597 | 6d51a084aabfef7b5ce3f5789321d7108711da67 | refs/heads/master | 2021-01-22T15:50:55.694642 | 2015-07-19T15:49:14 | 2015-07-19T15:49:14 | 38,978,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,319 | ino | #include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"
#include "TypesAndDeclarations.h"
Adafruit_MotorShield AFMS = Adafruit_MotorShield(); // Initialize the Shield
Adafruit_DCMotor *motorFL = AFMS.getMotor(1);
Adafruit_DCMotor *motorFR = AFMS.getMotor(4);
Adafruit_DCMotor *motorBL = AFMS.getMotor(2);
Adafruit_DCMotor *motorBR = AFMS.getMotor(3);
void setMotor(Adafruit_DCMotor *motor, bool On, String motorName)
{
Serial.print(motorName); Serial.print(" ");
if (On) {
Serial.println("ON");
motor->run(FORWARD);
motor->setSpeed(DEFAULT_MOTOR_SPEED);
}
else {
Serial.println("OFF");
motor->run(BACKWARD);
motor->setSpeed(DEFAULT_MOTOR_SPEED);
}
}
void setMotors(uint8_t toSpeed)
{
switch (toSpeed) {
case BOTH_MOTORS : {
setMotor(motorFL,true, "FL");
setMotor(motorFR,true, "FR");
setMotor(motorBL,true, "BL");
setMotor(motorBR,true, "BR");
}
break;
case RIGHT_MOTOR_ONLY : {
setMotor(motorFL,false, "FL");
setMotor(motorFR,true, "FR");
setMotor(motorBL,false, "BL");
setMotor(motorBR,true, "BR");
}
break;
case LEFT_MOTOR_ONLY : {
setMotor(motorFL,true, "FL");
setMotor(motorFR,false, "FR");
setMotor(motorBL,true, "BL");
setMotor(motorBR,false, "BR");
}
break;
}
}
PossibleInputs currentRelationshipToLine() {
if ((analogRead(A0) < CENTER_LEFT_SENSOR) && (analogRead(A1) < CENTER_RIGHT_SENSOR))
{
return ON_LINE;
}
if ((analogRead(A0) < CENTER_LEFT_SENSOR) && (analogRead(A1) > CENTER_RIGHT_SENSOR))
{
return OFF_TO_THE_RIGHT;
}
if ((analogRead(A0) > CENTER_LEFT_SENSOR) && (analogRead(A1) < CENTER_RIGHT_SENSOR))
{
return OFF_TO_THE_LEFT;
}
return LOST;
}
uint8_t currentState = CENTER;
void setup() {
Serial.begin(115200);
AFMS.begin();
motorFL->run(FORWARD);
motorFR->run(FORWARD);
motorBL->run(FORWARD);
motorBR->run(FORWARD);
}
void loop() {
while (1) {
setMotors(fsm[currentState].output);
delay(fsm[currentState].timeDelay);
currentState = fsm[currentState].nextState[currentRelationshipToLine()];
Serial.print("Current state: ");
Serial.print(currentState);
Serial.print(" Input -> ");
Serial.println(currentRelationshipToLine());
}
}
| [
"kevinmcquown@me.com"
] | kevinmcquown@me.com |
d0f6d40fe1fff56d3fc975026372e3ee8ec17efa | bd2ba8f1364a12dc0ea10003a98c4ef24f34b9bc | /src/make_sift_descriptor_file.cpp | 7acceea534469a970e7e8c34987ef2baf33381af | [] | no_license | kumpakri/registration-in-dynamic-environment | 921f92c0b823abe74d791f65be95994180b963c7 | 155bf0b94674a22cb27234d9d451905d284ceb39 | refs/heads/master | 2020-08-29T10:00:34.059880 | 2019-10-28T09:31:47 | 2019-10-28T09:36:56 | 217,998,679 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | cpp | /**
* \file make_sift_descriptor_file.cpp
*
* \brief Creates SIFT descriptor file.
*
* \param 1 nFeatures
* \param 2 nOctaveLayers
* \param 3 contrastThreshold
* \param 4 edgeThreshold
* \param 5 sigma
* \param 6 path to positions file
* \param 7 path to image folder
* \param 8 output path for used positions file
* \param 9 output path for descriptors file
*
* \author kristyna kumpanova
*
* Contact: kumpakri@gmail.com
*
* Created on: July 02 2018
*/
#include <opencv2/opencv.hpp>
#include "Data_processing.h"
#include "Utils.h"
int main(int argc, char **argv)
{
// check if arguments ok
if ( ! (argc>9 && file_exists(argv[6]) && file_exists(argv[7]) ) )
{
std::cout << "Error: missing arguments or invalid file path.\n";
return -1;
}
//SIFT detector setting
float nFeatures = atof(argv[1]);
float nOctaveLayers = atof(argv[2]);
float contrastThreshold = atof(argv[3]);
float edgeThreshold = atof(argv[4]);
float sigma = atof(argv[5]);
cv::Mat all_descriptors;
cv::FeatureDetector* detector;
detector = new cv::SiftFeatureDetector( nFeatures, nOctaveLayers, contrastThreshold, edgeThreshold, sigma);
make_descriptor_file(argv[6], argv[7], argv[9], argv[8], &all_descriptors, detector);
return 0;
} | [
"kumpakri@gmail.com"
] | kumpakri@gmail.com |
87f28394715944e36b38429726920ac0944b32b0 | 8abbb97e460df68c4bed5ccaa04983bfceb9b29d | /practicas/mergeSort.cpp | 594f438e25506c6f991c68a86783acc2e80bce26 | [] | no_license | JReneHS/Comp-Programming | e89c64c0d240d95fbf36358097ab15166a3b977b | 7af46dd8682ffc96245730669399194c9412c5ce | refs/heads/main | 2023-09-02T09:09:06.672628 | 2021-11-23T21:18:35 | 2021-11-23T21:18:35 | 354,477,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | cpp | #include <bits/stdc++.h>
using namespace std;
void merge(vector<int> &arr,int lef,int rig, int mid) {
//Variables de uso muliple
int i,j,k,n1,n2;
//Pivotes para control de los bucles
n1 = mid-lef+1;
n2 = rig-mid;
//Arrays auxiliares
vector<int> auxL(n1);
vector<int> auxR(n2);
//Copia de los valores a las array auxiliares
for(i = 0; i < n1;++i) auxL[i] = arr[lef+i];
for(j = 0; j < n2;++j) auxR[j] = arr[mid+1+j];
i = j = 0;
k = lef;
//Comparacion y ordenamiento usando las arrays auxiliares
while(i < n1 && j < n2) {
if(auxL[i] <= auxR[j]) {
arr[k] = auxL[i];
i++;
} else {
arr[k] = auxR[j];
j++;
}
k++;
}
//Copiando los elementos restantes de los auxiliares en caso que haya alguno
while(i < n1) {
arr[k] = auxL[i];
k++;
i++;
}
while(j < n2) {
arr[k] = auxR[j];
k++;
j++;
}
}
void mergeSort(vector<int> &arr,int lef,int rig){
//Mientras el valor de left sea menor al de right
if(lef < rig) {
//entero para obtener el valor medio del array
auto mid = lef + (rig - lef)/2;
//LLamada recursiva a mergeSort para array Izquierdo
mergeSort(arr, lef,mid);
//LLamada recursiva a mergeSort para arrya Derecho
mergeSort(arr, mid+1,rig);
//LLamada a la funcion de mezcla
merge(arr,lef,rig,mid);
}
}
int main() {
//array que se va a ordenar
vector<int> arr;
//entero auxiliar para leer de la entrada estandar
int c;
//mientras haya que leer en el buffer almacena en arr
while(cin>>c)arr.push_back(c);
//Impresion de los valores leidos
for(auto x: arr)cout<<x<<" ";
cout<<'\n'<<endl;
//Llamada a la funcion merge sort
mergeSort(arr,0,arr.size()-1);
//Impresion de los valores leidos
for(auto x: arr)cout<<x<<" ";
cout<<'\n'<<endl;
return 0;
}
| [
"jhernandezs1509@alumno.ipn.mx"
] | jhernandezs1509@alumno.ipn.mx |
ef87e9a005d240a09debe6907ac470cdadfe38bd | a66391dc90f943137aa73b455608b71d5a0276bb | /Module/_FW_epsilon/FWepsilon.h | a6daa0cd098376eaa91abd8eb6a3729ff1adf664 | [
"MIT"
] | permissive | Schrausser/FunktionWin | 01c4f0bdacea3a0637e010a1b099206406ffc0b5 | f6920b6b6a9d84e24371ed8b07a1ea6621ce695a | refs/heads/main | 2023-06-28T11:14:52.442749 | 2023-06-11T18:05:41 | 2023-06-11T18:05:41 | 603,180,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | h | //----------------------------------------------------------------------------------------------------|FWepsilon.h, SCHRAUSSER 2010
//
#if !defined(AFX_FWepsilon_H__0AAAAE94_E8F1_4C30_86BA_B40597F3E177__INCLUDED_)
#define AFX_FWepsilon_H__0AAAAE94_E8F1_4C30_86BA_B40597F3E177__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h"
class CFWepsilonApp : public CWinApp
{
public:
CFWepsilonApp();
//{{AFX_VIRTUAL(CFWepsilonApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
//{{AFX_MSG(CFWepsilonApp)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
#endif | [
"noreply@github.com"
] | Schrausser.noreply@github.com |
2866bf78789666c3a9e0154debcc386652e07eb3 | f0a739dda86d11b615d4225662dcd89b65b3d01a | /MapEditor/Direct3D/TestModel/ModelPart.h | feb18dfff571ad7cf641bf72ddd2d9a8aa34ade7 | [] | no_license | kbm0818/Portfolio | 173d3de48902083cf575c3231448fb6dc0ab4bc3 | dc4df24bb629379d55bfa15a84cd0fc6e8dc757f | refs/heads/master | 2020-03-28T22:49:21.942143 | 2018-10-02T07:33:35 | 2018-10-02T07:33:35 | 149,260,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,362 | h | #pragma once
#include "../Shaders/Shader.h"
#include "BinaryInputOutputHandler.h"
class Model;
class ModelMaterial;
class ModelBoneWeights;
class ModelBuffer;
class ModelPart : public Shader, public BinaryInputOutputHandler
{
public:
ModelPart(Model* model);
ModelPart(Model* model, ModelMaterial* material);
ModelPart(ModelPart& otherModel);
~ModelPart();
void Update(bool isAnimation);
void Render();
void SetModel(Model* model) { this->model = model; }
//void SetModelBuffer(ModelBuffer* modelBuffer) { this->modelBuffer = modelBuffer; }
void AddVertex(D3DXVECTOR3& position, D3DXVECTOR3& normal, D3DXVECTOR2& uv, const ModelBoneWeights& boneWeights);
void CreateData();
void CreateBuffer();
ModelMaterial* GetMaterial() { return material; }
void SetMaterial(ModelMaterial* material) { this->material = material; }
void Export(BinaryWriter* bw);
void Import(BinaryReader* br);
private:
void CalculateTangents();
Model* model;
bool isSkinnedModel;
vector<D3DXVECTOR3> positions;
vector<D3DXVECTOR3> normals;
vector<D3DXVECTOR3> tangents;
vector<D3DXVECTOR2> uvs;
vector<UINT> indices;
vector<ModelBoneWeights> boneWeights;
ModelMaterial* material;
UINT materialIndex;
UINT vertexCount;
VertexTextureNormalTangentBlend* vertex;
ID3D11Buffer* vertexBuffer;
UINT indexCount;
UINT* index;
ID3D11Buffer* indexBuffer;
}; | [
"kbm0818@naver.com"
] | kbm0818@naver.com |
7581acb310afb7c5277669879a62f11c9ff80d7e | 0c9958ed35900fffb025aa6526527e7fc63a38b0 | /glengine.cpp | 42a04687744e75ef3e31884b029645c67815abe9 | [] | no_license | on62/fltk_opengl | 7dbea0bfe7a02cf1123a8a2dadf2905decbbca76 | db0e97aa447f41b85c5dd46961232a67c5bf6c86 | refs/heads/master | 2021-05-27T23:18:32.537044 | 2014-08-16T14:06:22 | 2014-08-16T14:06:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,683 | cpp | #include "glengine.h"
void GLEngine::InitializeProgram(std::vector<shaderName> & shaderNames)
{
// std::string strVertexShader = getFile("v.perspective.shader");
// std::string strFragmentShader = getFile("fragment.shader");
std::vector<GLuint> shaderList;
std::vector<shaderName>::iterator it;
for( it = shaderNames.begin(); it != shaderNames.end(); it++) {
std::string strShader(getFile(it->second.c_str()));
shaderList.push_back(CreateShader(it->first,strShader));
}
// shaderList.push_back(CreateShader(GL_VERTEX_SHADER, strVertexShader));
// shaderList.push_back(CreateShader(GL_FRAGMENT_SHADER, strFragmentShader));
theProgram = CreateProgram(shaderList);
std::for_each(shaderList.begin(), shaderList.end(), glDeleteShader);
// glUseProgram(0);
//Perspective Uniform Matrix.
// perspectiveMatrixUnif = glGetUniformLocation(theProgram, "perspectiveMatrix");
// SetPerspective();
}
GLuint GLEngine::CreateShader(GLenum eShaderType, const std::string &strShaderFile) {
GLuint shader = glCreateShader(eShaderType);
const char *strFileData = strShaderFile.c_str();
glShaderSource(shader, 1, &strFileData, NULL);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *strInfoLog = new GLchar[infoLogLength + 1];
glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);
const char *strShaderType = NULL;
switch(eShaderType) {
case GL_VERTEX_SHADER: strShaderType = "vertex"; break;
case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break;
case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break;
}
fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog);
delete[] strInfoLog;
}
return shader;
}
GLuint GLEngine::CreateProgram(const std::vector<GLuint> &shaderList) {
GLuint program = glCreateProgram();
for(size_t iLoop = 0; iLoop < shaderList.size(); iLoop++)
glAttachShader(program, shaderList[iLoop]);
glLinkProgram(program);
CheckProgram(program);
for( size_t iLoop = 0; iLoop < shaderList.size(); iLoop++)
glDetachShader(program, shaderList[iLoop]);
return program;
}
void GLEngine::CheckProgram(GLuint & program) {
GLint status;
glGetProgramiv (program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
GLint infoLogLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *strInfoLog = new GLchar[infoLogLength + 1];
glGetProgramInfoLog(program, infoLogLength, NULL, strInfoLog);
fprintf(stderr, "Linker failure: %s\n", strInfoLog);
delete[] strInfoLog;
}
}
| [
"j.gleesawn@gmail.com"
] | j.gleesawn@gmail.com |
e1fb7c5cddefd14837917de3d08c4963b0ac5ca8 | c901b8389d196012f3cd1a3230ead6c2fc46a89b | /code/Substractive Synth/synth_with_tunings/synth_with_tunings.ino | d209cd700197a438de6fd5ac788f0430bc82d381 | [] | no_license | Marquets/SMC-Master-Thesis | 99ec41ec69bf3a40a168a8f334f65e10f0989ac3 | 675ace2cd14dfeb4151baf9b901f69a042bf03a1 | refs/heads/master | 2023-01-31T10:35:27.432119 | 2020-12-17T13:55:57 | 2020-12-17T13:55:57 | 296,834,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,928 | ino | // Waveform Example - Create 2 waveforms with adjustable
// frequency and phase
//
// This example is meant to be used with 3 buttons (pin 0,
// 1, 2) and 2 knobs (pins 16/A2, 17/A3), which are present
// on the audio tutorial kit.
// https://www.pjrc.com/store/audio_tutorial_kit.html
//
// Use an oscilloscope to view the 2 waveforms.
//
// Button0 changes the waveform shape
//
// Knob A2 changes the frequency of both waveforms
// You should see both waveforms "stretch" as you turn
//
// Knob A3 changes the phase of waveform #1
// You should see the waveform shift horizontally
//
// This example code is in the public domain.
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
#include <ResponsiveAnalogRead.h>
// GUItool: begin automatically generated code
AudioSynthWaveform waveform1; //xy=392,118
AudioSynthWaveform waveform2; //xy=410,177
AudioMixer4 mixer3;
AudioFilterStateVariable filter1; //xy=758,136
AudioOutputI2S i2s2; //xy=931,198
AudioConnection patchCord1(waveform1, 0, mixer3, 0);
AudioConnection patchCord2(waveform2, 0, mixer3, 1);
AudioConnection patchCord5(mixer3, 0, filter1, 0);
AudioConnection patchCord6(filter1, 1, i2s2, 0);
AudioConnection patchCord7(filter1, 1, i2s2, 1);
AudioControlSGTL5000 sgtl5000_1; //xy=239,232
//Mux control pins for analog signal (Sig_pin)
const int S0 = 0;
const int S1 = 1;
const int S2 = 2;
const int S3 = 3;
// Mux in "SIG" pin default
const int SIG_PIN = A0;
//Mux 1 control pins for analog signal (Sig_pin)
const int W0 = 19;
const int W1 = 18;
const int W2 = 17;
const int W3 = 16;
// Mux 1 in "SIG" pin default
const int WIG_PIN = 22;
int current_waveform1 = 0;
int current_waveform2 = 0;
int waveforms[] = {WAVEFORM_SINE,WAVEFORM_SAWTOOTH, WAVEFORM_TRIANGLE, WAVEFORM_SQUARE,WAVEFORM_SAWTOOTH_REVERSE,WAVEFORM_PULSE};
float lowestNotes[] = {41.204 * 4,55 * 4,73.416 * 4,97.999 * 4};
//Array of values for selecting the disered channel of the multiplexers
const boolean muxChannel[16][4] = {
{0, 0, 0, 0}, //channel 0
{1, 0, 0, 0}, //channel 1
{0, 1, 0, 0}, //channel 2
{1, 1, 0, 0}, //channel 3
{0, 0, 1, 0}, //channel 4
{1, 0, 1, 0}, //channel 5
{0, 1, 1, 0}, //channel 6
{1, 1, 1, 0}, //channel 7
{0, 0, 0, 1}, //channel 8
{1, 0, 0, 1}, //channel 9
{0, 1, 0, 1}, //channel 10
{1, 1, 0, 1}, //channel 11
{0, 0, 1, 1}, //channel 12
{1, 0, 1, 1}, //channel 13
{0, 1, 1, 1}, //channel 14
{1, 1, 1, 1} //channel 15
};
float just_intonation[] = {1,(float)256/243,(float)9/8,(float)32/27,(float)81/64,(float)4/3,(float)729/512,(float)3/2,(float)128/81,(float)27/16,(float)16/9,(float)243/128,2};
float shruti[] = {1,(float)256/243,(float)16/15,(float)10/9,(float)9/8,(float)32/27,(float)6/5,(float)5/4,(float)81/64,(float)4/3,(float)27/20,(float)45/32,(float)729/512,(float)3/2,
(float)128/81, (float)8/5, (float) 5/3, (float)27/16, (float)16/9, (float)9/5, (float)15/8, (float)243/128,2};
float quarter_tone[] = {1,(float)33/32,(float)17/16,(float)12/11,(float)9/8,(float)22/19,(float)19/16,(float)11/9,(float)24/19,(float) 22/17,(float)4/3,(float)11/8,(float)17/12,(float)16/11,
(float)3/2, (float)17/11, (float) 19/12, (float)18/11, (float)32/19, (float)16/9, (float)11/6, (float)33/17,2};
void setup() {
Serial.begin(9600);
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(SIG_PIN, INPUT);
pinMode(W0, OUTPUT);
pinMode(W1, OUTPUT);
pinMode(W2, OUTPUT);
pinMode(W3, OUTPUT);
//pinMode(WIG_PIN, INPUT);
digitalWrite(S0, LOW);
digitalWrite(S1, LOW);
digitalWrite(S2, LOW);
digitalWrite(S3, LOW);
digitalWrite(W0, LOW);
digitalWrite(W1, LOW);
digitalWrite(W2, LOW);
digitalWrite(W3, LOW);
// Audio connections require memory to work. For more
// detailed information, see the MemoryAndCpuUsage example
AudioMemory(20);
// Comment these out if not using the audio adaptor board.
// This may wait forever if the SDA & SCL pins lack
// pullup resistors
sgtl5000_1.enable();
sgtl5000_1.volume(0.5); // caution: very loud - use oscilloscope only!
current_waveform1 = WAVEFORM_SINE;
waveform1.begin(current_waveform1);
current_waveform2 = WAVEFORM_SINE;
waveform2.begin(current_waveform2);
}
void loop() {
// Read the buttons and knobs, scale knobs to 0-1.0
float freq = 0.0;
int i = 0;
while( i < 4) {
int index = map(readMux(0 + i*3), 0, 1023,0,21);
int cut_off = (readMux(1 + i*3) / 1023.0) * 200.0;
int cut_off2 = (readMux(2 + i*3) / 1023.0) * 1000.0;
double pitchbend = map(readMux(2 + i*3), 500, 1023,0.000,21.000);
// float general_vol = map(readMux2(0), 0, 1023, 0, 0.7);
int wave = map(readMux2(0), 0, 1023, 0, 5);
int wave2 = map(readMux2(7), 0, 1023, 0, 5);
Serial.println(readMux2(1));
freq = lowestNotes[i] * shruti[index];
if (freq != lowestNotes[i]) {
filter1.frequency(cut_off2);
filter1.resonance(1);
waveform1.begin(waveforms[wave]);
waveform1.frequency(freq/2);
waveform1.amplitude(1.0);
waveform2.begin(waveforms[wave2]);
waveform2.frequency(freq*2);
waveform2.amplitude(1);
//sgtl5000_1.volume(general_vol);
}
else {
waveform1.amplitude(0);
waveform2.amplitude(0);
sgtl5000_1.disable();
i++;
}
}
// if (analog5.hasChanged()) {
// waveform1.begin(waveforms[wave]);
// }
//
// if (analog6.hasChanged()) {
// waveform2.begin(waveforms[wave2]);
// }
//
// if (analog7.hasChanged()) {
// waveform1.phase(analog7.getValue() * 360.0);
// }
//AudioNoInterrupts();
// use Knob A2 to adjust the frequency of both waveforms
//waveform1.frequency(100.0 + knob_A2 * 900.0);
//waveform2.frequency(100.0 + knob_A2 * 900.0);
// use Knob A3 to adjust the phase of only waveform #1
//waveform1.phase(knob_A3 * 360.0);
//AudioInterrupts();
//Serial.println(analog4.getValue());
//Serial.println(readMux(3));
delay(5);
}
int readMux(byte channel){
byte controlPin[] = {S0, S1, S2, S3};
//byte controlPin2[] = {W0, W1, W2, W3};
for(int i = 0; i < 4; i ++){
digitalWrite(controlPin[i], muxChannel[channel][i]);
}
//read the value at the SIG pin
delayMicroseconds(50);
int val = analogRead(SIG_PIN);
//return the value
return val;
}
int readMux2(byte channel){
byte controlPin[] = {W0, W1, W2, W3};
for(int i = 0; i < 4; i ++){
digitalWrite(controlPin[i], muxChannel[channel][i]);
//Serial.println(muxChannel[channel][i]);
}
//read the value at the SIG pin
delayMicroseconds(50);
int val = analogRead(WIG_PIN);
Serial.println(analogRead(WIG_PIN));
//return the value
return val;
}
| [
"marcog07@ucm.es"
] | marcog07@ucm.es |
995dafd25e152defc978ef66ea666665ccdaddeb | ed444c4a0ed1fe679da64b81ec6aa1ddf885a185 | /Foundation/System/Thread/Thread.h | a35ae338c6c8567cb7a5a51a7d4e7f78208ab2b4 | [] | no_license | swaphack/CodeLib | 54e07db129d38be0fd55504ef917bbe522338aa6 | fff8ed54afc334e1ff5e3dd34ec5cfcf6ce7bdc9 | refs/heads/master | 2022-05-16T20:31:45.123321 | 2022-05-12T03:38:45 | 2022-05-12T03:38:45 | 58,099,874 | 1 | 0 | null | 2016-05-11T09:46:07 | 2016-05-05T02:57:24 | C++ | GB18030 | C++ | false | false | 998 | h | #pragma once
#include <functional>
#include <thread>
namespace sys
{
// 线程
class Thread
{
public:
friend class ThreadPool;
// 无效的线程id
static const int32_t INVALID_THREAD_ID = -1;
public:
Thread();
~Thread();
public:
// 执行
template<class _Fn, class... _Args>
void startWithParams(_Fn&& handler, _Args&&... _Ax);
// 执行
void start(const std::function<void()>& handler);
// 剥离执行
bool detach();
// 堵塞执行
bool join();
// 停止
bool isFinish() const;
// 获取线程id
int32_t getID() const;
private:
// 控制线程
std::thread m_pThread;
// 线程id
size_t m_nID = 0;
// 是否结束
bool m_bFinish = false;
};
template<class _Fn, class... _Args>
void Thread::startWithParams(_Fn&& handler, _Args&&... _Ax)
{
m_pThread = std::thread([=](_Args&&... _Bx){
do
{
handler(_Bx...);
m_bFinish = true;
} while (0);
}, _Ax...);
m_nID = m_pThread.get_id().hash();
m_bFinish = false;
}
} | [
"809406730@qq.com"
] | 809406730@qq.com |
3c0d836107f7b77c3fad63d1dbb630fe9450afa3 | 03ff59ad83be606ce82349173765ca2e5ab3c914 | /BFS_7562_나이트의이동.cpp | 7d70ee3ed7241605f4feed9629e0273eba69523d | [] | no_license | koreantique/CodingStudy | d59ada31fc6af3e1b39583a99df1fc27be11c0c4 | 405c5bfb79bd7f656751c77794d4a703c2172470 | refs/heads/master | 2022-07-28T07:47:28.609203 | 2020-05-22T06:46:24 | 2020-05-22T06:46:24 | 259,563,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | cpp | #include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
int d[301][301];
int c[301][301];
int dx[] = {-2,-1,1,2,-2,-1,1,2};
int dy[] = {-1,-2,-2,-1,1,2,2,1};
int n;
int cnt = 0;
void bfs(int x, int y, int cnt){
queue<pair<int,int>> q;
q.push(make_pair(x,y));
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
for(int k=0; k<8; k++){
int nx = x + dx[k];
int ny = y + dy[k];
if(0 <= nx && nx < n && 0 <= ny && ny < n){
if(d[nx][ny] == 0 && c[nx][ny] != 0){
q.push(make_pair(nx,ny));
cnt += 1;
}
}
}
}
}
int main(){
int t;
int q,w,e,r;
cin >> t;
while(t--){
cin >> n;
memset(d,-1,sizeof(d));
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
d[i][j] = 0;
}
}
}
} | [
"koreantique_@naver.com"
] | koreantique_@naver.com |
1eb850fce25590db76e4893353d22f7cb14a8f96 | 92fb6d1d4d4928e556537ee719430e89faa65850 | /Cpp-Exerceise/chap06-析构函数/06-2_deconstructor.cpp | 9463d4621679ac0ed9c4ad2157512a7df4d9fdcf | [] | no_license | lekjons/Linux-Cpp-Development-Advanced-Learning | ebe825d3424e7d15bbff2e226de251db11ebf882 | 9ca47d6b1bb4719b919cae1f9d0e74a0f70e88f2 | refs/heads/master | 2023-02-19T05:59:55.584696 | 2021-01-04T11:43:54 | 2021-01-04T11:43:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 434 | cpp | //
// Created by Yang Shuangzhen on 2020/10/3.
//
#include <stdio.h>
class Test
{
int mi;
public:
Test(int i)
{
mi = i;
printf("Test(): %d\n", mi);
}
~Test()
{
printf("~Test(): %d\n", mi);
}
};
int main()
{
Test t(1); // 构造 Test(1)
Test* pt = new Test(2); // 构造Test(2)
delete pt; // 析构Test(2)
// 析构Test(1)
return 0;
}
| [
"dreamre21@gmail.com"
] | dreamre21@gmail.com |
e5b3e13f8616bb527621fd382fdb92cd59ef95b8 | 96ccf2b290d2a289d2f5173a71f58173d457bbf1 | /code_analyser/llvm/tools/clang/include/clang/AST/ExprCXX.h | 9361011ff4fef16f4af4efce6f77a8cc7cc5b586 | [
"NCSA"
] | permissive | ProframFiles/cs410-octo-nemesis | b08244b741cb489392ee167afcf1673f41e493d1 | b14e565f32ad401ece41c58d8d3e0bba8c351041 | refs/heads/master | 2016-09-15T19:55:30.173078 | 2013-11-22T10:49:50 | 2013-11-22T10:49:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 152,841 | h | //===--- ExprCXX.h - Classes for representing expressions -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines the clang::Expr interface and subclasses for C++ expressions.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_EXPRCXX_H
#define LLVM_CLANG_AST_EXPRCXX_H
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/UnresolvedSet.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/Lambda.h"
#include "clang/Basic/TypeTraits.h"
#include "llvm/Support/Compiler.h"
namespace clang {
class CXXConstructorDecl;
class CXXDestructorDecl;
class CXXMethodDecl;
class CXXTemporary;
class MSPropertyDecl;
class TemplateArgumentListInfo;
class UuidAttr;
//===--------------------------------------------------------------------===//
// C++ Expressions.
//===--------------------------------------------------------------------===//
/// \brief A call to an overloaded operator written using operator
/// syntax.
///
/// Represents a call to an overloaded operator written using operator
/// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
/// normal call, this AST node provides better information about the
/// syntactic representation of the call.
///
/// In a C++ template, this expression node kind will be used whenever
/// any of the arguments are type-dependent. In this case, the
/// function itself will be a (possibly empty) set of functions and
/// function templates that were found by name lookup at template
/// definition time.
class CXXOperatorCallExpr : public CallExpr {
/// \brief The overloaded operator.
OverloadedOperatorKind Operator;
SourceRange Range;
// Record the FP_CONTRACT state that applies to this operator call. Only
// meaningful for floating point types. For other types this value can be
// set to false.
unsigned FPContractable : 1;
SourceRange getSourceRangeImpl() const LLVM_READONLY;
public:
CXXOperatorCallExpr(ASTContext& C, OverloadedOperatorKind Op, Expr *fn,
ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
SourceLocation operatorloc, bool fpContractable)
: CallExpr(C, CXXOperatorCallExprClass, fn, 0, args, t, VK,
operatorloc),
Operator(Op), FPContractable(fpContractable) {
Range = getSourceRangeImpl();
}
explicit CXXOperatorCallExpr(ASTContext& C, EmptyShell Empty) :
CallExpr(C, CXXOperatorCallExprClass, Empty) { }
/// \brief Returns the kind of overloaded operator that this
/// expression refers to.
OverloadedOperatorKind getOperator() const { return Operator; }
/// \brief Returns the location of the operator symbol in the expression.
///
/// When \c getOperator()==OO_Call, this is the location of the right
/// parentheses; when \c getOperator()==OO_Subscript, this is the location
/// of the right bracket.
SourceLocation getOperatorLoc() const { return getRParenLoc(); }
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
SourceRange getSourceRange() const { return Range; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXOperatorCallExprClass;
}
// Set the FP contractability status of this operator. Only meaningful for
// operations on floating point types.
void setFPContractable(bool FPC) { FPContractable = FPC; }
// Get the FP contractability status of this operator. Only meaningful for
// operations on floating point types.
bool isFPContractable() const { return FPContractable; }
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// Represents a call to a member function that
/// may be written either with member call syntax (e.g., "obj.func()"
/// or "objptr->func()") or with normal function-call syntax
/// ("func()") within a member function that ends up calling a member
/// function. The callee in either case is a MemberExpr that contains
/// both the object argument and the member function, while the
/// arguments are the arguments within the parentheses (not including
/// the object argument).
class CXXMemberCallExpr : public CallExpr {
public:
CXXMemberCallExpr(ASTContext &C, Expr *fn, ArrayRef<Expr*> args,
QualType t, ExprValueKind VK, SourceLocation RP)
: CallExpr(C, CXXMemberCallExprClass, fn, 0, args, t, VK, RP) {}
CXXMemberCallExpr(ASTContext &C, EmptyShell Empty)
: CallExpr(C, CXXMemberCallExprClass, Empty) { }
/// \brief Retrieves the implicit object argument for the member call.
///
/// For example, in "x.f(5)", this returns the sub-expression "x".
Expr *getImplicitObjectArgument() const;
/// \brief Retrieves the declaration of the called method.
CXXMethodDecl *getMethodDecl() const;
/// \brief Retrieves the CXXRecordDecl for the underlying type of
/// the implicit object argument.
///
/// Note that this is may not be the same declaration as that of the class
/// context of the CXXMethodDecl which this function is calling.
/// FIXME: Returns 0 for member pointer call exprs.
CXXRecordDecl *getRecordDecl() const;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXMemberCallExprClass;
}
};
/// \brief Represents a call to a CUDA kernel function.
class CUDAKernelCallExpr : public CallExpr {
private:
enum { CONFIG, END_PREARG };
public:
CUDAKernelCallExpr(ASTContext &C, Expr *fn, CallExpr *Config,
ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
SourceLocation RP)
: CallExpr(C, CUDAKernelCallExprClass, fn, END_PREARG, args, t, VK, RP) {
setConfig(Config);
}
CUDAKernelCallExpr(ASTContext &C, EmptyShell Empty)
: CallExpr(C, CUDAKernelCallExprClass, END_PREARG, Empty) { }
const CallExpr *getConfig() const {
return cast_or_null<CallExpr>(getPreArg(CONFIG));
}
CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
void setConfig(CallExpr *E) { setPreArg(CONFIG, E); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CUDAKernelCallExprClass;
}
};
/// \brief Abstract class common to all of the C++ "named"/"keyword" casts.
///
/// This abstract class is inherited by all of the classes
/// representing "named" casts: CXXStaticCastExpr for \c static_cast,
/// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
/// reinterpret_cast, and CXXConstCastExpr for \c const_cast.
class CXXNamedCastExpr : public ExplicitCastExpr {
private:
SourceLocation Loc; // the location of the casting op
SourceLocation RParenLoc; // the location of the right parenthesis
SourceRange AngleBrackets; // range for '<' '>'
protected:
CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
CastKind kind, Expr *op, unsigned PathSize,
TypeSourceInfo *writtenTy, SourceLocation l,
SourceLocation RParenLoc,
SourceRange AngleBrackets)
: ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, writtenTy), Loc(l),
RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
: ExplicitCastExpr(SC, Shell, PathSize) { }
friend class ASTStmtReader;
public:
const char *getCastName() const;
/// \brief Retrieve the location of the cast operator keyword, e.g.,
/// \c static_cast.
SourceLocation getOperatorLoc() const { return Loc; }
/// \brief Retrieve the location of the closing parenthesis.
SourceLocation getRParenLoc() const { return RParenLoc; }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
SourceRange getAngleBrackets() const LLVM_READONLY { return AngleBrackets; }
static bool classof(const Stmt *T) {
switch (T->getStmtClass()) {
case CXXStaticCastExprClass:
case CXXDynamicCastExprClass:
case CXXReinterpretCastExprClass:
case CXXConstCastExprClass:
return true;
default:
return false;
}
}
};
/// \brief A C++ \c static_cast expression (C++ [expr.static.cast]).
///
/// This expression node represents a C++ static cast, e.g.,
/// \c static_cast<int>(1.0).
class CXXStaticCastExpr : public CXXNamedCastExpr {
CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
unsigned pathSize, TypeSourceInfo *writtenTy,
SourceLocation l, SourceLocation RParenLoc,
SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
writtenTy, l, RParenLoc, AngleBrackets) {}
explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize)
: CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) { }
public:
static CXXStaticCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK, CastKind K, Expr *Op,
const CXXCastPath *Path,
TypeSourceInfo *Written, SourceLocation L,
SourceLocation RParenLoc,
SourceRange AngleBrackets);
static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
unsigned PathSize);
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXStaticCastExprClass;
}
};
/// \brief A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
///
/// This expression node represents a dynamic cast, e.g.,
/// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
/// check to determine how to perform the type conversion.
class CXXDynamicCastExpr : public CXXNamedCastExpr {
CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind,
Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy,
SourceLocation l, SourceLocation RParenLoc,
SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
writtenTy, l, RParenLoc, AngleBrackets) {}
explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
: CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) { }
public:
static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK, CastKind Kind, Expr *Op,
const CXXCastPath *Path,
TypeSourceInfo *Written, SourceLocation L,
SourceLocation RParenLoc,
SourceRange AngleBrackets);
static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context,
unsigned pathSize);
bool isAlwaysNull() const;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDynamicCastExprClass;
}
};
/// \brief A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
///
/// This expression node represents a reinterpret cast, e.g.,
/// @c reinterpret_cast<int>(VoidPtr).
///
/// A reinterpret_cast provides a differently-typed view of a value but
/// (in Clang, as in most C++ implementations) performs no actual work at
/// run time.
class CXXReinterpretCastExpr : public CXXNamedCastExpr {
CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
Expr *op, unsigned pathSize,
TypeSourceInfo *writtenTy, SourceLocation l,
SourceLocation RParenLoc,
SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
pathSize, writtenTy, l, RParenLoc, AngleBrackets) {}
CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
: CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) { }
public:
static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK, CastKind Kind,
Expr *Op, const CXXCastPath *Path,
TypeSourceInfo *WrittenTy, SourceLocation L,
SourceLocation RParenLoc,
SourceRange AngleBrackets);
static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context,
unsigned pathSize);
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXReinterpretCastExprClass;
}
};
/// \brief A C++ \c const_cast expression (C++ [expr.const.cast]).
///
/// This expression node represents a const cast, e.g.,
/// \c const_cast<char*>(PtrToConstChar).
///
/// A const_cast can remove type qualifiers but does not change the underlying
/// value.
class CXXConstCastExpr : public CXXNamedCastExpr {
CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
TypeSourceInfo *writtenTy, SourceLocation l,
SourceLocation RParenLoc, SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
0, writtenTy, l, RParenLoc, AngleBrackets) {}
explicit CXXConstCastExpr(EmptyShell Empty)
: CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) { }
public:
static CXXConstCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK, Expr *Op,
TypeSourceInfo *WrittenTy, SourceLocation L,
SourceLocation RParenLoc,
SourceRange AngleBrackets);
static CXXConstCastExpr *CreateEmpty(const ASTContext &Context);
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXConstCastExprClass;
}
};
/// \brief A call to a literal operator (C++11 [over.literal])
/// written as a user-defined literal (C++11 [lit.ext]).
///
/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
/// is semantically equivalent to a normal call, this AST node provides better
/// information about the syntactic representation of the literal.
///
/// Since literal operators are never found by ADL and can only be declared at
/// namespace scope, a user-defined literal is never dependent.
class UserDefinedLiteral : public CallExpr {
/// \brief The location of a ud-suffix within the literal.
SourceLocation UDSuffixLoc;
public:
UserDefinedLiteral(const ASTContext &C, Expr *Fn, ArrayRef<Expr*> Args,
QualType T, ExprValueKind VK, SourceLocation LitEndLoc,
SourceLocation SuffixLoc)
: CallExpr(C, UserDefinedLiteralClass, Fn, 0, Args, T, VK, LitEndLoc),
UDSuffixLoc(SuffixLoc) {}
explicit UserDefinedLiteral(const ASTContext &C, EmptyShell Empty)
: CallExpr(C, UserDefinedLiteralClass, Empty) {}
/// The kind of literal operator which is invoked.
enum LiteralOperatorKind {
LOK_Raw, ///< Raw form: operator "" X (const char *)
LOK_Template, ///< Raw form: operator "" X<cs...> ()
LOK_Integer, ///< operator "" X (unsigned long long)
LOK_Floating, ///< operator "" X (long double)
LOK_String, ///< operator "" X (const CharT *, size_t)
LOK_Character ///< operator "" X (CharT)
};
/// \brief Returns the kind of literal operator invocation
/// which this expression represents.
LiteralOperatorKind getLiteralOperatorKind() const;
/// \brief If this is not a raw user-defined literal, get the
/// underlying cooked literal (representing the literal with the suffix
/// removed).
Expr *getCookedLiteral();
const Expr *getCookedLiteral() const {
return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
}
SourceLocation getLocStart() const {
if (getLiteralOperatorKind() == LOK_Template)
return getRParenLoc();
return getArg(0)->getLocStart();
}
SourceLocation getLocEnd() const { return getRParenLoc(); }
/// \brief Returns the location of a ud-suffix in the expression.
///
/// For a string literal, there may be multiple identical suffixes. This
/// returns the first.
SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
/// \brief Returns the ud-suffix specified for this literal.
const IdentifierInfo *getUDSuffix() const;
static bool classof(const Stmt *S) {
return S->getStmtClass() == UserDefinedLiteralClass;
}
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief A boolean literal, per ([C++ lex.bool] Boolean literals).
///
class CXXBoolLiteralExpr : public Expr {
bool Value;
SourceLocation Loc;
public:
CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l) :
Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
false, false),
Value(val), Loc(l) {}
explicit CXXBoolLiteralExpr(EmptyShell Empty)
: Expr(CXXBoolLiteralExprClass, Empty) { }
bool getValue() const { return Value; }
void setValue(bool V) { Value = V; }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
SourceLocation getLocation() const { return Loc; }
void setLocation(SourceLocation L) { Loc = L; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXBoolLiteralExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief The null pointer literal (C++11 [lex.nullptr])
///
/// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
class CXXNullPtrLiteralExpr : public Expr {
SourceLocation Loc;
public:
CXXNullPtrLiteralExpr(QualType Ty, SourceLocation l) :
Expr(CXXNullPtrLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
false, false),
Loc(l) {}
explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
: Expr(CXXNullPtrLiteralExprClass, Empty) { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
SourceLocation getLocation() const { return Loc; }
void setLocation(SourceLocation L) { Loc = L; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXNullPtrLiteralExprClass;
}
child_range children() { return child_range(); }
};
/// \brief Implicit construction of a std::initializer_list<T> object from an
/// array temporary within list-initialization (C++11 [dcl.init.list]p5).
class CXXStdInitializerListExpr : public Expr {
Stmt *SubExpr;
CXXStdInitializerListExpr(EmptyShell Empty)
: Expr(CXXStdInitializerListExprClass, Empty), SubExpr(0) {}
public:
CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
: Expr(CXXStdInitializerListExprClass, Ty, VK_RValue, OK_Ordinary,
Ty->isDependentType(), SubExpr->isValueDependent(),
SubExpr->isInstantiationDependent(),
SubExpr->containsUnexpandedParameterPack()),
SubExpr(SubExpr) {}
Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
SourceLocation getLocStart() const LLVM_READONLY {
return SubExpr->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY {
return SubExpr->getLocEnd();
}
SourceRange getSourceRange() const LLVM_READONLY {
return SubExpr->getSourceRange();
}
static bool classof(const Stmt *S) {
return S->getStmtClass() == CXXStdInitializerListExprClass;
}
child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
friend class ASTReader;
friend class ASTStmtReader;
};
/// A C++ \c typeid expression (C++ [expr.typeid]), which gets
/// the \c type_info that corresponds to the supplied type, or the (possibly
/// dynamic) type of the supplied expression.
///
/// This represents code like \c typeid(int) or \c typeid(*objPtr)
class CXXTypeidExpr : public Expr {
private:
llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
SourceRange Range;
public:
CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
: Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
// typeid is never type-dependent (C++ [temp.dep.expr]p4)
false,
// typeid is value-dependent if the type or expression are dependent
Operand->getType()->isDependentType(),
Operand->getType()->isInstantiationDependentType(),
Operand->getType()->containsUnexpandedParameterPack()),
Operand(Operand), Range(R) { }
CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
: Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
// typeid is never type-dependent (C++ [temp.dep.expr]p4)
false,
// typeid is value-dependent if the type or expression are dependent
Operand->isTypeDependent() || Operand->isValueDependent(),
Operand->isInstantiationDependent(),
Operand->containsUnexpandedParameterPack()),
Operand(Operand), Range(R) { }
CXXTypeidExpr(EmptyShell Empty, bool isExpr)
: Expr(CXXTypeidExprClass, Empty) {
if (isExpr)
Operand = (Expr*)0;
else
Operand = (TypeSourceInfo*)0;
}
/// Determine whether this typeid has a type operand which is potentially
/// evaluated, per C++11 [expr.typeid]p3.
bool isPotentiallyEvaluated() const;
bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
/// \brief Retrieves the type operand of this typeid() expression after
/// various required adjustments (removing reference types, cv-qualifiers).
QualType getTypeOperand() const;
/// \brief Retrieve source information for the type operand.
TypeSourceInfo *getTypeOperandSourceInfo() const {
assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
return Operand.get<TypeSourceInfo *>();
}
void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
Operand = TSI;
}
Expr *getExprOperand() const {
assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
return static_cast<Expr*>(Operand.get<Stmt *>());
}
void setExprOperand(Expr *E) {
assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
Operand = E;
}
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
SourceRange getSourceRange() const LLVM_READONLY { return Range; }
void setSourceRange(SourceRange R) { Range = R; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXTypeidExprClass;
}
// Iterators
child_range children() {
if (isTypeOperand()) return child_range();
Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
return child_range(begin, begin + 1);
}
};
/// \brief A member reference to an MSPropertyDecl.
///
/// This expression always has pseudo-object type, and therefore it is
/// typically not encountered in a fully-typechecked expression except
/// within the syntactic form of a PseudoObjectExpr.
class MSPropertyRefExpr : public Expr {
Expr *BaseExpr;
MSPropertyDecl *TheDecl;
SourceLocation MemberLoc;
bool IsArrow;
NestedNameSpecifierLoc QualifierLoc;
public:
MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
QualType ty, ExprValueKind VK,
NestedNameSpecifierLoc qualifierLoc,
SourceLocation nameLoc)
: Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary,
/*type-dependent*/ false, baseExpr->isValueDependent(),
baseExpr->isInstantiationDependent(),
baseExpr->containsUnexpandedParameterPack()),
BaseExpr(baseExpr), TheDecl(decl),
MemberLoc(nameLoc), IsArrow(isArrow),
QualifierLoc(qualifierLoc) {}
MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
SourceRange getSourceRange() const LLVM_READONLY {
return SourceRange(getLocStart(), getLocEnd());
}
bool isImplicitAccess() const {
return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
}
SourceLocation getLocStart() const {
if (!isImplicitAccess())
return BaseExpr->getLocStart();
else if (QualifierLoc)
return QualifierLoc.getBeginLoc();
else
return MemberLoc;
}
SourceLocation getLocEnd() const { return getMemberLoc(); }
child_range children() {
return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == MSPropertyRefExprClass;
}
Expr *getBaseExpr() const { return BaseExpr; }
MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
bool isArrow() const { return IsArrow; }
SourceLocation getMemberLoc() const { return MemberLoc; }
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
friend class ASTStmtReader;
};
/// A Microsoft C++ @c __uuidof expression, which gets
/// the _GUID that corresponds to the supplied type or expression.
///
/// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
class CXXUuidofExpr : public Expr {
private:
llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
SourceRange Range;
public:
CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
: Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
false, Operand->getType()->isDependentType(),
Operand->getType()->isInstantiationDependentType(),
Operand->getType()->containsUnexpandedParameterPack()),
Operand(Operand), Range(R) { }
CXXUuidofExpr(QualType Ty, Expr *Operand, SourceRange R)
: Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
false, Operand->isTypeDependent(),
Operand->isInstantiationDependent(),
Operand->containsUnexpandedParameterPack()),
Operand(Operand), Range(R) { }
CXXUuidofExpr(EmptyShell Empty, bool isExpr)
: Expr(CXXUuidofExprClass, Empty) {
if (isExpr)
Operand = (Expr*)0;
else
Operand = (TypeSourceInfo*)0;
}
bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
/// \brief Retrieves the type operand of this __uuidof() expression after
/// various required adjustments (removing reference types, cv-qualifiers).
QualType getTypeOperand() const;
/// \brief Retrieve source information for the type operand.
TypeSourceInfo *getTypeOperandSourceInfo() const {
assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
return Operand.get<TypeSourceInfo *>();
}
void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
Operand = TSI;
}
Expr *getExprOperand() const {
assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
return static_cast<Expr*>(Operand.get<Stmt *>());
}
void setExprOperand(Expr *E) {
assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
Operand = E;
}
StringRef getUuidAsStringRef(ASTContext &Context) const;
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
SourceRange getSourceRange() const LLVM_READONLY { return Range; }
void setSourceRange(SourceRange R) { Range = R; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXUuidofExprClass;
}
/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
/// a single GUID.
static UuidAttr *GetUuidAttrOfType(QualType QT,
bool *HasMultipleGUIDsPtr = 0);
// Iterators
child_range children() {
if (isTypeOperand()) return child_range();
Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
return child_range(begin, begin + 1);
}
};
/// \brief Represents the \c this expression in C++.
///
/// This is a pointer to the object on which the current member function is
/// executing (C++ [expr.prim]p3). Example:
///
/// \code
/// class Foo {
/// public:
/// void bar();
/// void test() { this->bar(); }
/// };
/// \endcode
class CXXThisExpr : public Expr {
SourceLocation Loc;
bool Implicit : 1;
public:
CXXThisExpr(SourceLocation L, QualType Type, bool isImplicit)
: Expr(CXXThisExprClass, Type, VK_RValue, OK_Ordinary,
// 'this' is type-dependent if the class type of the enclosing
// member function is dependent (C++ [temp.dep.expr]p2)
Type->isDependentType(), Type->isDependentType(),
Type->isInstantiationDependentType(),
/*ContainsUnexpandedParameterPack=*/false),
Loc(L), Implicit(isImplicit) { }
CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
SourceLocation getLocation() const { return Loc; }
void setLocation(SourceLocation L) { Loc = L; }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
bool isImplicit() const { return Implicit; }
void setImplicit(bool I) { Implicit = I; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXThisExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief A C++ throw-expression (C++ [except.throw]).
///
/// This handles 'throw' (for re-throwing the current exception) and
/// 'throw' assignment-expression. When assignment-expression isn't
/// present, Op will be null.
class CXXThrowExpr : public Expr {
Stmt *Op;
SourceLocation ThrowLoc;
/// \brief Whether the thrown variable (if any) is in scope.
unsigned IsThrownVariableInScope : 1;
friend class ASTStmtReader;
public:
// \p Ty is the void type which is used as the result type of the
// expression. The \p l is the location of the throw keyword. \p expr
// can by null, if the optional expression to throw isn't present.
CXXThrowExpr(Expr *expr, QualType Ty, SourceLocation l,
bool IsThrownVariableInScope) :
Expr(CXXThrowExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
expr && expr->isInstantiationDependent(),
expr && expr->containsUnexpandedParameterPack()),
Op(expr), ThrowLoc(l), IsThrownVariableInScope(IsThrownVariableInScope) {}
CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
const Expr *getSubExpr() const { return cast_or_null<Expr>(Op); }
Expr *getSubExpr() { return cast_or_null<Expr>(Op); }
SourceLocation getThrowLoc() const { return ThrowLoc; }
/// \brief Determines whether the variable thrown by this expression (if any!)
/// is within the innermost try block.
///
/// This information is required to determine whether the NRVO can apply to
/// this variable.
bool isThrownVariableInScope() const { return IsThrownVariableInScope; }
SourceLocation getLocStart() const LLVM_READONLY { return ThrowLoc; }
SourceLocation getLocEnd() const LLVM_READONLY {
if (getSubExpr() == 0)
return ThrowLoc;
return getSubExpr()->getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXThrowExprClass;
}
// Iterators
child_range children() {
return child_range(&Op, Op ? &Op+1 : &Op);
}
};
/// \brief A default argument (C++ [dcl.fct.default]).
///
/// This wraps up a function call argument that was created from the
/// corresponding parameter's default argument, when the call did not
/// explicitly supply arguments for all of the parameters.
class CXXDefaultArgExpr : public Expr {
/// \brief The parameter whose default is being used.
///
/// When the bit is set, the subexpression is stored after the
/// CXXDefaultArgExpr itself. When the bit is clear, the parameter's
/// actual default expression is the subexpression.
llvm::PointerIntPair<ParmVarDecl *, 1, bool> Param;
/// \brief The location where the default argument expression was used.
SourceLocation Loc;
CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param)
: Expr(SC,
param->hasUnparsedDefaultArg()
? param->getType().getNonReferenceType()
: param->getDefaultArg()->getType(),
param->getDefaultArg()->getValueKind(),
param->getDefaultArg()->getObjectKind(), false, false, false, false),
Param(param, false), Loc(Loc) { }
CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param,
Expr *SubExpr)
: Expr(SC, SubExpr->getType(),
SubExpr->getValueKind(), SubExpr->getObjectKind(),
false, false, false, false),
Param(param, true), Loc(Loc) {
*reinterpret_cast<Expr **>(this + 1) = SubExpr;
}
public:
CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
// \p Param is the parameter whose default argument is used by this
// expression.
static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
ParmVarDecl *Param) {
return new (C) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param);
}
// \p Param is the parameter whose default argument is used by this
// expression, and \p SubExpr is the expression that will actually be used.
static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
ParmVarDecl *Param, Expr *SubExpr);
// Retrieve the parameter that the argument was created from.
const ParmVarDecl *getParam() const { return Param.getPointer(); }
ParmVarDecl *getParam() { return Param.getPointer(); }
// Retrieve the actual argument to the function call.
const Expr *getExpr() const {
if (Param.getInt())
return *reinterpret_cast<Expr const * const*> (this + 1);
return getParam()->getDefaultArg();
}
Expr *getExpr() {
if (Param.getInt())
return *reinterpret_cast<Expr **> (this + 1);
return getParam()->getDefaultArg();
}
/// \brief Retrieve the location where this default argument was actually
/// used.
SourceLocation getUsedLocation() const { return Loc; }
/// Default argument expressions have no representation in the
/// source, so they have an empty source range.
SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDefaultArgExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief A use of a default initializer in a constructor or in aggregate
/// initialization.
///
/// This wraps a use of a C++ default initializer (technically,
/// a brace-or-equal-initializer for a non-static data member) when it
/// is implicitly used in a mem-initializer-list in a constructor
/// (C++11 [class.base.init]p8) or in aggregate initialization
/// (C++1y [dcl.init.aggr]p7).
class CXXDefaultInitExpr : public Expr {
/// \brief The field whose default is being used.
FieldDecl *Field;
/// \brief The location where the default initializer expression was used.
SourceLocation Loc;
CXXDefaultInitExpr(const ASTContext &C, SourceLocation Loc, FieldDecl *Field,
QualType T);
CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
public:
/// \p Field is the non-static data member whose default initializer is used
/// by this expression.
static CXXDefaultInitExpr *Create(const ASTContext &C, SourceLocation Loc,
FieldDecl *Field) {
return new (C) CXXDefaultInitExpr(C, Loc, Field, Field->getType());
}
/// \brief Get the field whose initializer will be used.
FieldDecl *getField() { return Field; }
const FieldDecl *getField() const { return Field; }
/// \brief Get the initialization expression that will be used.
const Expr *getExpr() const { return Field->getInClassInitializer(); }
Expr *getExpr() { return Field->getInClassInitializer(); }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDefaultInitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTReader;
friend class ASTStmtReader;
};
/// \brief Represents a C++ temporary.
class CXXTemporary {
/// \brief The destructor that needs to be called.
const CXXDestructorDecl *Destructor;
explicit CXXTemporary(const CXXDestructorDecl *destructor)
: Destructor(destructor) { }
public:
static CXXTemporary *Create(const ASTContext &C,
const CXXDestructorDecl *Destructor);
const CXXDestructorDecl *getDestructor() const { return Destructor; }
void setDestructor(const CXXDestructorDecl *Dtor) {
Destructor = Dtor;
}
};
/// \brief Represents binding an expression to a temporary.
///
/// This ensures the destructor is called for the temporary. It should only be
/// needed for non-POD, non-trivially destructable class types. For example:
///
/// \code
/// struct S {
/// S() { } // User defined constructor makes S non-POD.
/// ~S() { } // User defined destructor makes it non-trivial.
/// };
/// void test() {
/// const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
/// }
/// \endcode
class CXXBindTemporaryExpr : public Expr {
CXXTemporary *Temp;
Stmt *SubExpr;
CXXBindTemporaryExpr(CXXTemporary *temp, Expr* SubExpr)
: Expr(CXXBindTemporaryExprClass, SubExpr->getType(),
VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),
SubExpr->isValueDependent(),
SubExpr->isInstantiationDependent(),
SubExpr->containsUnexpandedParameterPack()),
Temp(temp), SubExpr(SubExpr) { }
public:
CXXBindTemporaryExpr(EmptyShell Empty)
: Expr(CXXBindTemporaryExprClass, Empty), Temp(0), SubExpr(0) {}
static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp,
Expr* SubExpr);
CXXTemporary *getTemporary() { return Temp; }
const CXXTemporary *getTemporary() const { return Temp; }
void setTemporary(CXXTemporary *T) { Temp = T; }
const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
Expr *getSubExpr() { return cast<Expr>(SubExpr); }
void setSubExpr(Expr *E) { SubExpr = E; }
SourceLocation getLocStart() const LLVM_READONLY {
return SubExpr->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
// Implement isa/cast/dyncast/etc.
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXBindTemporaryExprClass;
}
// Iterators
child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
};
/// \brief Represents a call to a C++ constructor.
class CXXConstructExpr : public Expr {
public:
enum ConstructionKind {
CK_Complete,
CK_NonVirtualBase,
CK_VirtualBase,
CK_Delegating
};
private:
CXXConstructorDecl *Constructor;
SourceLocation Loc;
SourceRange ParenOrBraceRange;
unsigned NumArgs : 16;
bool Elidable : 1;
bool HadMultipleCandidates : 1;
bool ListInitialization : 1;
bool ZeroInitialization : 1;
unsigned ConstructKind : 2;
Stmt **Args;
protected:
CXXConstructExpr(const ASTContext &C, StmtClass SC, QualType T,
SourceLocation Loc,
CXXConstructorDecl *d, bool elidable,
ArrayRef<Expr *> Args,
bool HadMultipleCandidates,
bool ListInitialization,
bool ZeroInitialization,
ConstructionKind ConstructKind,
SourceRange ParenOrBraceRange);
/// \brief Construct an empty C++ construction expression.
CXXConstructExpr(StmtClass SC, EmptyShell Empty)
: Expr(SC, Empty), Constructor(0), NumArgs(0), Elidable(false),
HadMultipleCandidates(false), ListInitialization(false),
ZeroInitialization(false), ConstructKind(0), Args(0)
{ }
public:
/// \brief Construct an empty C++ construction expression.
explicit CXXConstructExpr(EmptyShell Empty)
: Expr(CXXConstructExprClass, Empty), Constructor(0),
NumArgs(0), Elidable(false), HadMultipleCandidates(false),
ListInitialization(false), ZeroInitialization(false),
ConstructKind(0), Args(0)
{ }
static CXXConstructExpr *Create(const ASTContext &C, QualType T,
SourceLocation Loc,
CXXConstructorDecl *D, bool Elidable,
ArrayRef<Expr *> Args,
bool HadMultipleCandidates,
bool ListInitialization,
bool ZeroInitialization,
ConstructionKind ConstructKind,
SourceRange ParenOrBraceRange);
CXXConstructorDecl* getConstructor() const { return Constructor; }
void setConstructor(CXXConstructorDecl *C) { Constructor = C; }
SourceLocation getLocation() const { return Loc; }
void setLocation(SourceLocation Loc) { this->Loc = Loc; }
/// \brief Whether this construction is elidable.
bool isElidable() const { return Elidable; }
void setElidable(bool E) { Elidable = E; }
/// \brief Whether the referred constructor was resolved from
/// an overloaded set having size greater than 1.
bool hadMultipleCandidates() const { return HadMultipleCandidates; }
void setHadMultipleCandidates(bool V) { HadMultipleCandidates = V; }
/// \brief Whether this constructor call was written as list-initialization.
bool isListInitialization() const { return ListInitialization; }
void setListInitialization(bool V) { ListInitialization = V; }
/// \brief Whether this construction first requires
/// zero-initialization before the initializer is called.
bool requiresZeroInitialization() const { return ZeroInitialization; }
void setRequiresZeroInitialization(bool ZeroInit) {
ZeroInitialization = ZeroInit;
}
/// \brief Determine whether this constructor is actually constructing
/// a base class (rather than a complete object).
ConstructionKind getConstructionKind() const {
return (ConstructionKind)ConstructKind;
}
void setConstructionKind(ConstructionKind CK) {
ConstructKind = CK;
}
typedef ExprIterator arg_iterator;
typedef ConstExprIterator const_arg_iterator;
arg_iterator arg_begin() { return Args; }
arg_iterator arg_end() { return Args + NumArgs; }
const_arg_iterator arg_begin() const { return Args; }
const_arg_iterator arg_end() const { return Args + NumArgs; }
Expr **getArgs() const { return reinterpret_cast<Expr **>(Args); }
unsigned getNumArgs() const { return NumArgs; }
/// \brief Return the specified argument.
Expr *getArg(unsigned Arg) {
assert(Arg < NumArgs && "Arg access out of range!");
return cast<Expr>(Args[Arg]);
}
const Expr *getArg(unsigned Arg) const {
assert(Arg < NumArgs && "Arg access out of range!");
return cast<Expr>(Args[Arg]);
}
/// \brief Set the specified argument.
void setArg(unsigned Arg, Expr *ArgExpr) {
assert(Arg < NumArgs && "Arg access out of range!");
Args[Arg] = ArgExpr;
}
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY;
SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; }
void setParenOrBraceRange(SourceRange Range) { ParenOrBraceRange = Range; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXConstructExprClass ||
T->getStmtClass() == CXXTemporaryObjectExprClass;
}
// Iterators
child_range children() {
return child_range(&Args[0], &Args[0]+NumArgs);
}
friend class ASTStmtReader;
};
/// \brief Represents an explicit C++ type conversion that uses "functional"
/// notation (C++ [expr.type.conv]).
///
/// Example:
/// \code
/// x = int(0.5);
/// \endcode
class CXXFunctionalCastExpr : public ExplicitCastExpr {
SourceLocation LParenLoc;
SourceLocation RParenLoc;
CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
TypeSourceInfo *writtenTy,
CastKind kind, Expr *castExpr, unsigned pathSize,
SourceLocation lParenLoc, SourceLocation rParenLoc)
: ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
castExpr, pathSize, writtenTy),
LParenLoc(lParenLoc), RParenLoc(rParenLoc) {}
explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize)
: ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) { }
public:
static CXXFunctionalCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK,
TypeSourceInfo *Written,
CastKind Kind, Expr *Op,
const CXXCastPath *Path,
SourceLocation LPLoc,
SourceLocation RPLoc);
static CXXFunctionalCastExpr *CreateEmpty(const ASTContext &Context,
unsigned PathSize);
SourceLocation getLParenLoc() const { return LParenLoc; }
void setLParenLoc(SourceLocation L) { LParenLoc = L; }
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation L) { RParenLoc = L; }
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXFunctionalCastExprClass;
}
};
/// @brief Represents a C++ functional cast expression that builds a
/// temporary object.
///
/// This expression type represents a C++ "functional" cast
/// (C++[expr.type.conv]) with N != 1 arguments that invokes a
/// constructor to build a temporary object. With N == 1 arguments the
/// functional cast expression will be represented by CXXFunctionalCastExpr.
/// Example:
/// \code
/// struct X { X(int, float); }
///
/// X create_X() {
/// return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
/// };
/// \endcode
class CXXTemporaryObjectExpr : public CXXConstructExpr {
TypeSourceInfo *Type;
public:
CXXTemporaryObjectExpr(const ASTContext &C, CXXConstructorDecl *Cons,
TypeSourceInfo *Type,
ArrayRef<Expr *> Args,
SourceRange ParenOrBraceRange,
bool HadMultipleCandidates,
bool ListInitialization,
bool ZeroInitialization);
explicit CXXTemporaryObjectExpr(EmptyShell Empty)
: CXXConstructExpr(CXXTemporaryObjectExprClass, Empty), Type() { }
TypeSourceInfo *getTypeSourceInfo() const { return Type; }
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXTemporaryObjectExprClass;
}
friend class ASTStmtReader;
};
/// \brief A C++ lambda expression, which produces a function object
/// (of unspecified type) that can be invoked later.
///
/// Example:
/// \code
/// void low_pass_filter(std::vector<double> &values, double cutoff) {
/// values.erase(std::remove_if(values.begin(), values.end(),
/// [=](double value) { return value > cutoff; });
/// }
/// \endcode
///
/// C++11 lambda expressions can capture local variables, either by copying
/// the values of those local variables at the time the function
/// object is constructed (not when it is called!) or by holding a
/// reference to the local variable. These captures can occur either
/// implicitly or can be written explicitly between the square
/// brackets ([...]) that start the lambda expression.
///
/// C++1y introduces a new form of "capture" called an init-capture that
/// includes an initializing expression (rather than capturing a variable),
/// and which can never occur implicitly.
class LambdaExpr : public Expr {
enum {
/// \brief Flag used by the Capture class to indicate that the given
/// capture was implicit.
Capture_Implicit = 0x01,
/// \brief Flag used by the Capture class to indicate that the
/// given capture was by-copy.
///
/// This includes the case of a non-reference init-capture.
Capture_ByCopy = 0x02
};
/// \brief The source range that covers the lambda introducer ([...]).
SourceRange IntroducerRange;
/// \brief The source location of this lambda's capture-default ('=' or '&').
SourceLocation CaptureDefaultLoc;
/// \brief The number of captures.
unsigned NumCaptures : 16;
/// \brief The default capture kind, which is a value of type
/// LambdaCaptureDefault.
unsigned CaptureDefault : 2;
/// \brief Whether this lambda had an explicit parameter list vs. an
/// implicit (and empty) parameter list.
unsigned ExplicitParams : 1;
/// \brief Whether this lambda had the result type explicitly specified.
unsigned ExplicitResultType : 1;
/// \brief Whether there are any array index variables stored at the end of
/// this lambda expression.
unsigned HasArrayIndexVars : 1;
/// \brief The location of the closing brace ('}') that completes
/// the lambda.
///
/// The location of the brace is also available by looking up the
/// function call operator in the lambda class. However, it is
/// stored here to improve the performance of getSourceRange(), and
/// to avoid having to deserialize the function call operator from a
/// module file just to determine the source range.
SourceLocation ClosingBrace;
// Note: The capture initializers are stored directly after the lambda
// expression, along with the index variables used to initialize by-copy
// array captures.
public:
/// \brief Describes the capture of a variable or of \c this, or of a
/// C++1y init-capture.
class Capture {
llvm::PointerIntPair<Decl *, 2> DeclAndBits;
SourceLocation Loc;
SourceLocation EllipsisLoc;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
/// \brief Create a new capture of a variable or of \c this.
///
/// \param Loc The source location associated with this capture.
///
/// \param Kind The kind of capture (this, byref, bycopy), which must
/// not be init-capture.
///
/// \param Implicit Whether the capture was implicit or explicit.
///
/// \param Var The local variable being captured, or null if capturing
/// \c this.
///
/// \param EllipsisLoc The location of the ellipsis (...) for a
/// capture that is a pack expansion, or an invalid source
/// location to indicate that this is not a pack expansion.
Capture(SourceLocation Loc, bool Implicit,
LambdaCaptureKind Kind, VarDecl *Var = 0,
SourceLocation EllipsisLoc = SourceLocation());
/// \brief Create a new init-capture.
Capture(FieldDecl *Field);
/// \brief Determine the kind of capture.
LambdaCaptureKind getCaptureKind() const;
/// \brief Determine whether this capture handles the C++ \c this
/// pointer.
bool capturesThis() const { return DeclAndBits.getPointer() == 0; }
/// \brief Determine whether this capture handles a variable.
bool capturesVariable() const {
return dyn_cast_or_null<VarDecl>(DeclAndBits.getPointer());
}
/// \brief Determine whether this is an init-capture.
bool isInitCapture() const { return getCaptureKind() == LCK_Init; }
/// \brief Retrieve the declaration of the local variable being
/// captured.
///
/// This operation is only valid if this capture is a variable capture
/// (other than a capture of \c this).
VarDecl *getCapturedVar() const {
assert(capturesVariable() && "No variable available for 'this' capture");
return cast<VarDecl>(DeclAndBits.getPointer());
}
/// \brief Retrieve the field for an init-capture.
///
/// This works only for an init-capture. To retrieve the FieldDecl for
/// a captured variable or for a capture of \c this, use
/// LambdaExpr::getLambdaClass and CXXRecordDecl::getCaptureFields.
FieldDecl *getInitCaptureField() const {
assert(getCaptureKind() == LCK_Init && "no field for non-init-capture");
return cast<FieldDecl>(DeclAndBits.getPointer());
}
/// \brief Determine whether this was an implicit capture (not
/// written between the square brackets introducing the lambda).
bool isImplicit() const { return DeclAndBits.getInt() & Capture_Implicit; }
/// \brief Determine whether this was an explicit capture (written
/// between the square brackets introducing the lambda).
bool isExplicit() const { return !isImplicit(); }
/// \brief Retrieve the source location of the capture.
///
/// For an explicit capture, this returns the location of the
/// explicit capture in the source. For an implicit capture, this
/// returns the location at which the variable or \c this was first
/// used.
SourceLocation getLocation() const { return Loc; }
/// \brief Determine whether this capture is a pack expansion,
/// which captures a function parameter pack.
bool isPackExpansion() const { return EllipsisLoc.isValid(); }
/// \brief Retrieve the location of the ellipsis for a capture
/// that is a pack expansion.
SourceLocation getEllipsisLoc() const {
assert(isPackExpansion() && "No ellipsis location for a non-expansion");
return EllipsisLoc;
}
};
private:
/// \brief Construct a lambda expression.
LambdaExpr(QualType T, SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
ArrayRef<Capture> Captures,
bool ExplicitParams,
bool ExplicitResultType,
ArrayRef<Expr *> CaptureInits,
ArrayRef<VarDecl *> ArrayIndexVars,
ArrayRef<unsigned> ArrayIndexStarts,
SourceLocation ClosingBrace,
bool ContainsUnexpandedParameterPack);
/// \brief Construct an empty lambda expression.
LambdaExpr(EmptyShell Empty, unsigned NumCaptures, bool HasArrayIndexVars)
: Expr(LambdaExprClass, Empty),
NumCaptures(NumCaptures), CaptureDefault(LCD_None), ExplicitParams(false),
ExplicitResultType(false), HasArrayIndexVars(true) {
getStoredStmts()[NumCaptures] = 0;
}
Stmt **getStoredStmts() const {
return reinterpret_cast<Stmt **>(const_cast<LambdaExpr *>(this) + 1);
}
/// \brief Retrieve the mapping from captures to the first array index
/// variable.
unsigned *getArrayIndexStarts() const {
return reinterpret_cast<unsigned *>(getStoredStmts() + NumCaptures + 1);
}
/// \brief Retrieve the complete set of array-index variables.
VarDecl **getArrayIndexVars() const {
unsigned ArrayIndexSize =
llvm::RoundUpToAlignment(sizeof(unsigned) * (NumCaptures + 1),
llvm::alignOf<VarDecl*>());
return reinterpret_cast<VarDecl **>(
reinterpret_cast<char*>(getArrayIndexStarts()) + ArrayIndexSize);
}
public:
/// \brief Construct a new lambda expression.
static LambdaExpr *Create(const ASTContext &C,
CXXRecordDecl *Class,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
ArrayRef<Capture> Captures,
bool ExplicitParams,
bool ExplicitResultType,
ArrayRef<Expr *> CaptureInits,
ArrayRef<VarDecl *> ArrayIndexVars,
ArrayRef<unsigned> ArrayIndexStarts,
SourceLocation ClosingBrace,
bool ContainsUnexpandedParameterPack);
/// \brief Construct a new lambda expression that will be deserialized from
/// an external source.
static LambdaExpr *CreateDeserialized(const ASTContext &C,
unsigned NumCaptures,
unsigned NumArrayIndexVars);
/// \brief Determine the default capture kind for this lambda.
LambdaCaptureDefault getCaptureDefault() const {
return static_cast<LambdaCaptureDefault>(CaptureDefault);
}
/// \brief Retrieve the location of this lambda's capture-default, if any.
SourceLocation getCaptureDefaultLoc() const {
return CaptureDefaultLoc;
}
/// \brief An iterator that walks over the captures of the lambda,
/// both implicit and explicit.
typedef const Capture *capture_iterator;
/// \brief Retrieve an iterator pointing to the first lambda capture.
capture_iterator capture_begin() const;
/// \brief Retrieve an iterator pointing past the end of the
/// sequence of lambda captures.
capture_iterator capture_end() const;
/// \brief Determine the number of captures in this lambda.
unsigned capture_size() const { return NumCaptures; }
/// \brief Retrieve an iterator pointing to the first explicit
/// lambda capture.
capture_iterator explicit_capture_begin() const;
/// \brief Retrieve an iterator pointing past the end of the sequence of
/// explicit lambda captures.
capture_iterator explicit_capture_end() const;
/// \brief Retrieve an iterator pointing to the first implicit
/// lambda capture.
capture_iterator implicit_capture_begin() const;
/// \brief Retrieve an iterator pointing past the end of the sequence of
/// implicit lambda captures.
capture_iterator implicit_capture_end() const;
/// \brief Iterator that walks over the capture initialization
/// arguments.
typedef Expr **capture_init_iterator;
/// \brief Retrieve the first initialization argument for this
/// lambda expression (which initializes the first capture field).
capture_init_iterator capture_init_begin() const {
return reinterpret_cast<Expr **>(getStoredStmts());
}
/// \brief Retrieve the iterator pointing one past the last
/// initialization argument for this lambda expression.
capture_init_iterator capture_init_end() const {
return capture_init_begin() + NumCaptures;
}
/// \brief Retrieve the initializer for an init-capture.
Expr *getInitCaptureInit(capture_iterator Capture) {
assert(Capture >= explicit_capture_begin() &&
Capture <= explicit_capture_end() && Capture->isInitCapture());
return capture_init_begin()[Capture - capture_begin()];
}
const Expr *getInitCaptureInit(capture_iterator Capture) const {
return const_cast<LambdaExpr*>(this)->getInitCaptureInit(Capture);
}
/// \brief Retrieve the set of index variables used in the capture
/// initializer of an array captured by copy.
///
/// \param Iter The iterator that points at the capture initializer for
/// which we are extracting the corresponding index variables.
ArrayRef<VarDecl *> getCaptureInitIndexVars(capture_init_iterator Iter) const;
/// \brief Retrieve the source range covering the lambda introducer,
/// which contains the explicit capture list surrounded by square
/// brackets ([...]).
SourceRange getIntroducerRange() const { return IntroducerRange; }
/// \brief Retrieve the class that corresponds to the lambda.
///
/// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
/// captures in its fields and provides the various operations permitted
/// on a lambda (copying, calling).
CXXRecordDecl *getLambdaClass() const;
/// \brief Retrieve the function call operator associated with this
/// lambda expression.
CXXMethodDecl *getCallOperator() const;
/// \brief Retrieve the body of the lambda.
CompoundStmt *getBody() const;
/// \brief Determine whether the lambda is mutable, meaning that any
/// captures values can be modified.
bool isMutable() const;
/// \brief Determine whether this lambda has an explicit parameter
/// list vs. an implicit (empty) parameter list.
bool hasExplicitParameters() const { return ExplicitParams; }
/// \brief Whether this lambda had its result type explicitly specified.
bool hasExplicitResultType() const { return ExplicitResultType; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == LambdaExprClass;
}
SourceLocation getLocStart() const LLVM_READONLY {
return IntroducerRange.getBegin();
}
SourceLocation getLocEnd() const LLVM_READONLY { return ClosingBrace; }
child_range children() {
return child_range(getStoredStmts(), getStoredStmts() + NumCaptures + 1);
}
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// An expression "T()" which creates a value-initialized rvalue of type
/// T, which is a non-class type. See (C++98 [5.2.3p2]).
class CXXScalarValueInitExpr : public Expr {
SourceLocation RParenLoc;
TypeSourceInfo *TypeInfo;
friend class ASTStmtReader;
public:
/// \brief Create an explicitly-written scalar-value initialization
/// expression.
CXXScalarValueInitExpr(QualType Type,
TypeSourceInfo *TypeInfo,
SourceLocation rParenLoc ) :
Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary,
false, false, Type->isInstantiationDependentType(), false),
RParenLoc(rParenLoc), TypeInfo(TypeInfo) {}
explicit CXXScalarValueInitExpr(EmptyShell Shell)
: Expr(CXXScalarValueInitExprClass, Shell) { }
TypeSourceInfo *getTypeSourceInfo() const {
return TypeInfo;
}
SourceLocation getRParenLoc() const { return RParenLoc; }
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXScalarValueInitExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief Represents a new-expression for memory allocation and constructor
/// calls, e.g: "new CXXNewExpr(foo)".
class CXXNewExpr : public Expr {
/// Contains an optional array size expression, an optional initialization
/// expression, and any number of optional placement arguments, in that order.
Stmt **SubExprs;
/// \brief Points to the allocation function used.
FunctionDecl *OperatorNew;
/// \brief Points to the deallocation function used in case of error. May be
/// null.
FunctionDecl *OperatorDelete;
/// \brief The allocated type-source information, as written in the source.
TypeSourceInfo *AllocatedTypeInfo;
/// \brief If the allocated type was expressed as a parenthesized type-id,
/// the source range covering the parenthesized type-id.
SourceRange TypeIdParens;
/// \brief Range of the entire new expression.
SourceRange Range;
/// \brief Source-range of a paren-delimited initializer.
SourceRange DirectInitRange;
/// Was the usage ::new, i.e. is the global new to be used?
bool GlobalNew : 1;
/// Do we allocate an array? If so, the first SubExpr is the size expression.
bool Array : 1;
/// If this is an array allocation, does the usual deallocation
/// function for the allocated type want to know the allocated size?
bool UsualArrayDeleteWantsSize : 1;
/// The number of placement new arguments.
unsigned NumPlacementArgs : 13;
/// What kind of initializer do we have? Could be none, parens, or braces.
/// In storage, we distinguish between "none, and no initializer expr", and
/// "none, but an implicit initializer expr".
unsigned StoredInitializationStyle : 2;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
enum InitializationStyle {
NoInit, ///< New-expression has no initializer as written.
CallInit, ///< New-expression has a C++98 paren-delimited initializer.
ListInit ///< New-expression has a C++11 list-initializer.
};
CXXNewExpr(const ASTContext &C, bool globalNew, FunctionDecl *operatorNew,
FunctionDecl *operatorDelete, bool usualArrayDeleteWantsSize,
ArrayRef<Expr*> placementArgs,
SourceRange typeIdParens, Expr *arraySize,
InitializationStyle initializationStyle, Expr *initializer,
QualType ty, TypeSourceInfo *AllocatedTypeInfo,
SourceRange Range, SourceRange directInitRange);
explicit CXXNewExpr(EmptyShell Shell)
: Expr(CXXNewExprClass, Shell), SubExprs(0) { }
void AllocateArgsArray(const ASTContext &C, bool isArray,
unsigned numPlaceArgs, bool hasInitializer);
QualType getAllocatedType() const {
assert(getType()->isPointerType());
return getType()->getAs<PointerType>()->getPointeeType();
}
TypeSourceInfo *getAllocatedTypeSourceInfo() const {
return AllocatedTypeInfo;
}
/// \brief True if the allocation result needs to be null-checked.
///
/// C++11 [expr.new]p13:
/// If the allocation function returns null, initialization shall
/// not be done, the deallocation function shall not be called,
/// and the value of the new-expression shall be null.
///
/// An allocation function is not allowed to return null unless it
/// has a non-throwing exception-specification. The '03 rule is
/// identical except that the definition of a non-throwing
/// exception specification is just "is it throw()?".
bool shouldNullCheckAllocation(const ASTContext &Ctx) const;
FunctionDecl *getOperatorNew() const { return OperatorNew; }
void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
bool isArray() const { return Array; }
Expr *getArraySize() {
return Array ? cast<Expr>(SubExprs[0]) : 0;
}
const Expr *getArraySize() const {
return Array ? cast<Expr>(SubExprs[0]) : 0;
}
unsigned getNumPlacementArgs() const { return NumPlacementArgs; }
Expr **getPlacementArgs() {
return reinterpret_cast<Expr **>(SubExprs + Array + hasInitializer());
}
Expr *getPlacementArg(unsigned i) {
assert(i < NumPlacementArgs && "Index out of range");
return getPlacementArgs()[i];
}
const Expr *getPlacementArg(unsigned i) const {
assert(i < NumPlacementArgs && "Index out of range");
return const_cast<CXXNewExpr*>(this)->getPlacementArg(i);
}
bool isParenTypeId() const { return TypeIdParens.isValid(); }
SourceRange getTypeIdParens() const { return TypeIdParens; }
bool isGlobalNew() const { return GlobalNew; }
/// \brief Whether this new-expression has any initializer at all.
bool hasInitializer() const { return StoredInitializationStyle > 0; }
/// \brief The kind of initializer this new-expression has.
InitializationStyle getInitializationStyle() const {
if (StoredInitializationStyle == 0)
return NoInit;
return static_cast<InitializationStyle>(StoredInitializationStyle-1);
}
/// \brief The initializer of this new-expression.
Expr *getInitializer() {
return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
}
const Expr *getInitializer() const {
return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
}
/// \brief Returns the CXXConstructExpr from this new-expression, or null.
const CXXConstructExpr* getConstructExpr() const {
return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
}
/// Answers whether the usual array deallocation function for the
/// allocated type expects the size of the allocation as a
/// parameter.
bool doesUsualArrayDeleteWantSize() const {
return UsualArrayDeleteWantsSize;
}
typedef ExprIterator arg_iterator;
typedef ConstExprIterator const_arg_iterator;
arg_iterator placement_arg_begin() {
return SubExprs + Array + hasInitializer();
}
arg_iterator placement_arg_end() {
return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
}
const_arg_iterator placement_arg_begin() const {
return SubExprs + Array + hasInitializer();
}
const_arg_iterator placement_arg_end() const {
return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
}
typedef Stmt **raw_arg_iterator;
raw_arg_iterator raw_arg_begin() { return SubExprs; }
raw_arg_iterator raw_arg_end() {
return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
}
const_arg_iterator raw_arg_begin() const { return SubExprs; }
const_arg_iterator raw_arg_end() const {
return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
}
SourceLocation getStartLoc() const { return Range.getBegin(); }
SourceLocation getEndLoc() const { return Range.getEnd(); }
SourceRange getDirectInitRange() const { return DirectInitRange; }
SourceRange getSourceRange() const LLVM_READONLY {
return Range;
}
SourceLocation getLocStart() const LLVM_READONLY { return getStartLoc(); }
SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXNewExprClass;
}
// Iterators
child_range children() {
return child_range(raw_arg_begin(), raw_arg_end());
}
};
/// \brief Represents a \c delete expression for memory deallocation and
/// destructor calls, e.g. "delete[] pArray".
class CXXDeleteExpr : public Expr {
/// Points to the operator delete overload that is used. Could be a member.
FunctionDecl *OperatorDelete;
/// The pointer expression to be deleted.
Stmt *Argument;
/// Location of the expression.
SourceLocation Loc;
/// Is this a forced global delete, i.e. "::delete"?
bool GlobalDelete : 1;
/// Is this the array form of delete, i.e. "delete[]"?
bool ArrayForm : 1;
/// ArrayFormAsWritten can be different from ArrayForm if 'delete' is applied
/// to pointer-to-array type (ArrayFormAsWritten will be false while ArrayForm
/// will be true).
bool ArrayFormAsWritten : 1;
/// Does the usual deallocation function for the element type require
/// a size_t argument?
bool UsualArrayDeleteWantsSize : 1;
public:
CXXDeleteExpr(QualType ty, bool globalDelete, bool arrayForm,
bool arrayFormAsWritten, bool usualArrayDeleteWantsSize,
FunctionDecl *operatorDelete, Expr *arg, SourceLocation loc)
: Expr(CXXDeleteExprClass, ty, VK_RValue, OK_Ordinary, false, false,
arg->isInstantiationDependent(),
arg->containsUnexpandedParameterPack()),
OperatorDelete(operatorDelete), Argument(arg), Loc(loc),
GlobalDelete(globalDelete),
ArrayForm(arrayForm), ArrayFormAsWritten(arrayFormAsWritten),
UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize) { }
explicit CXXDeleteExpr(EmptyShell Shell)
: Expr(CXXDeleteExprClass, Shell), OperatorDelete(0), Argument(0) { }
bool isGlobalDelete() const { return GlobalDelete; }
bool isArrayForm() const { return ArrayForm; }
bool isArrayFormAsWritten() const { return ArrayFormAsWritten; }
/// Answers whether the usual array deallocation function for the
/// allocated type expects the size of the allocation as a
/// parameter. This can be true even if the actual deallocation
/// function that we're using doesn't want a size.
bool doesUsualArrayDeleteWantSize() const {
return UsualArrayDeleteWantsSize;
}
FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
Expr *getArgument() { return cast<Expr>(Argument); }
const Expr *getArgument() const { return cast<Expr>(Argument); }
/// \brief Retrieve the type being destroyed.
///
/// If the type being destroyed is a dependent type which may or may not
/// be a pointer, return an invalid type.
QualType getDestroyedType() const;
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY {return Argument->getLocEnd();}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDeleteExprClass;
}
// Iterators
child_range children() { return child_range(&Argument, &Argument+1); }
friend class ASTStmtReader;
};
/// \brief Stores the type being destroyed by a pseudo-destructor expression.
class PseudoDestructorTypeStorage {
/// \brief Either the type source information or the name of the type, if
/// it couldn't be resolved due to type-dependence.
llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
/// \brief The starting source location of the pseudo-destructor type.
SourceLocation Location;
public:
PseudoDestructorTypeStorage() { }
PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
: Type(II), Location(Loc) { }
PseudoDestructorTypeStorage(TypeSourceInfo *Info);
TypeSourceInfo *getTypeSourceInfo() const {
return Type.dyn_cast<TypeSourceInfo *>();
}
IdentifierInfo *getIdentifier() const {
return Type.dyn_cast<IdentifierInfo *>();
}
SourceLocation getLocation() const { return Location; }
};
/// \brief Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
///
/// A pseudo-destructor is an expression that looks like a member access to a
/// destructor of a scalar type, except that scalar types don't have
/// destructors. For example:
///
/// \code
/// typedef int T;
/// void f(int *p) {
/// p->T::~T();
/// }
/// \endcode
///
/// Pseudo-destructors typically occur when instantiating templates such as:
///
/// \code
/// template<typename T>
/// void destroy(T* ptr) {
/// ptr->T::~T();
/// }
/// \endcode
///
/// for scalar types. A pseudo-destructor expression has no run-time semantics
/// beyond evaluating the base expression.
class CXXPseudoDestructorExpr : public Expr {
/// \brief The base expression (that is being destroyed).
Stmt *Base;
/// \brief Whether the operator was an arrow ('->'); otherwise, it was a
/// period ('.').
bool IsArrow : 1;
/// \brief The location of the '.' or '->' operator.
SourceLocation OperatorLoc;
/// \brief The nested-name-specifier that follows the operator, if present.
NestedNameSpecifierLoc QualifierLoc;
/// \brief The type that precedes the '::' in a qualified pseudo-destructor
/// expression.
TypeSourceInfo *ScopeType;
/// \brief The location of the '::' in a qualified pseudo-destructor
/// expression.
SourceLocation ColonColonLoc;
/// \brief The location of the '~'.
SourceLocation TildeLoc;
/// \brief The type being destroyed, or its name if we were unable to
/// resolve the name.
PseudoDestructorTypeStorage DestroyedType;
friend class ASTStmtReader;
public:
CXXPseudoDestructorExpr(const ASTContext &Context,
Expr *Base, bool isArrow, SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
TypeSourceInfo *ScopeType,
SourceLocation ColonColonLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
explicit CXXPseudoDestructorExpr(EmptyShell Shell)
: Expr(CXXPseudoDestructorExprClass, Shell),
Base(0), IsArrow(false), QualifierLoc(), ScopeType(0) { }
Expr *getBase() const { return cast<Expr>(Base); }
/// \brief Determines whether this member expression actually had
/// a C++ nested-name-specifier prior to the name of the member, e.g.,
/// x->Base::foo.
bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
/// \brief Retrieves the nested-name-specifier that qualifies the type name,
/// with source-location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief If the member name was qualified, retrieves the
/// nested-name-specifier that precedes the member name. Otherwise, returns
/// null.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
/// \brief Determine whether this pseudo-destructor expression was written
/// using an '->' (otherwise, it used a '.').
bool isArrow() const { return IsArrow; }
/// \brief Retrieve the location of the '.' or '->' operator.
SourceLocation getOperatorLoc() const { return OperatorLoc; }
/// \brief Retrieve the scope type in a qualified pseudo-destructor
/// expression.
///
/// Pseudo-destructor expressions can have extra qualification within them
/// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
/// Here, if the object type of the expression is (or may be) a scalar type,
/// \p T may also be a scalar type and, therefore, cannot be part of a
/// nested-name-specifier. It is stored as the "scope type" of the pseudo-
/// destructor expression.
TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
/// \brief Retrieve the location of the '::' in a qualified pseudo-destructor
/// expression.
SourceLocation getColonColonLoc() const { return ColonColonLoc; }
/// \brief Retrieve the location of the '~'.
SourceLocation getTildeLoc() const { return TildeLoc; }
/// \brief Retrieve the source location information for the type
/// being destroyed.
///
/// This type-source information is available for non-dependent
/// pseudo-destructor expressions and some dependent pseudo-destructor
/// expressions. Returns null if we only have the identifier for a
/// dependent pseudo-destructor expression.
TypeSourceInfo *getDestroyedTypeInfo() const {
return DestroyedType.getTypeSourceInfo();
}
/// \brief In a dependent pseudo-destructor expression for which we do not
/// have full type information on the destroyed type, provides the name
/// of the destroyed type.
IdentifierInfo *getDestroyedTypeIdentifier() const {
return DestroyedType.getIdentifier();
}
/// \brief Retrieve the type being destroyed.
QualType getDestroyedType() const;
/// \brief Retrieve the starting location of the type being destroyed.
SourceLocation getDestroyedTypeLoc() const {
return DestroyedType.getLocation();
}
/// \brief Set the name of destroyed type for a dependent pseudo-destructor
/// expression.
void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
DestroyedType = PseudoDestructorTypeStorage(II, Loc);
}
/// \brief Set the destroyed type.
void setDestroyedType(TypeSourceInfo *Info) {
DestroyedType = PseudoDestructorTypeStorage(Info);
}
SourceLocation getLocStart() const LLVM_READONLY {return Base->getLocStart();}
SourceLocation getLocEnd() const LLVM_READONLY;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXPseudoDestructorExprClass;
}
// Iterators
child_range children() { return child_range(&Base, &Base + 1); }
};
/// \brief Represents a GCC or MS unary type trait, as used in the
/// implementation of TR1/C++11 type trait templates.
///
/// Example:
/// \code
/// __is_pod(int) == true
/// __is_enum(std::string) == false
/// \endcode
class UnaryTypeTraitExpr : public Expr {
/// \brief The trait. A UnaryTypeTrait enum in MSVC compatible unsigned.
unsigned UTT : 31;
/// The value of the type trait. Unspecified if dependent.
bool Value : 1;
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing paren.
SourceLocation RParen;
/// \brief The type being queried.
TypeSourceInfo *QueriedType;
public:
UnaryTypeTraitExpr(SourceLocation loc, UnaryTypeTrait utt,
TypeSourceInfo *queried, bool value,
SourceLocation rparen, QualType ty)
: Expr(UnaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
false, queried->getType()->isDependentType(),
queried->getType()->isInstantiationDependentType(),
queried->getType()->containsUnexpandedParameterPack()),
UTT(utt), Value(value), Loc(loc), RParen(rparen), QueriedType(queried) { }
explicit UnaryTypeTraitExpr(EmptyShell Empty)
: Expr(UnaryTypeTraitExprClass, Empty), UTT(0), Value(false),
QueriedType() { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
UnaryTypeTrait getTrait() const { return static_cast<UnaryTypeTrait>(UTT); }
QualType getQueriedType() const { return QueriedType->getType(); }
TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
bool getValue() const { return Value; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == UnaryTypeTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
};
/// \brief Represents a GCC or MS binary type trait, as used in the
/// implementation of TR1/C++11 type trait templates.
///
/// Example:
/// \code
/// __is_base_of(Base, Derived) == true
/// \endcode
class BinaryTypeTraitExpr : public Expr {
/// \brief The trait. A BinaryTypeTrait enum in MSVC compatible unsigned.
unsigned BTT : 8;
/// The value of the type trait. Unspecified if dependent.
bool Value : 1;
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing paren.
SourceLocation RParen;
/// \brief The lhs type being queried.
TypeSourceInfo *LhsType;
/// \brief The rhs type being queried.
TypeSourceInfo *RhsType;
public:
BinaryTypeTraitExpr(SourceLocation loc, BinaryTypeTrait btt,
TypeSourceInfo *lhsType, TypeSourceInfo *rhsType,
bool value, SourceLocation rparen, QualType ty)
: Expr(BinaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary, false,
lhsType->getType()->isDependentType() ||
rhsType->getType()->isDependentType(),
(lhsType->getType()->isInstantiationDependentType() ||
rhsType->getType()->isInstantiationDependentType()),
(lhsType->getType()->containsUnexpandedParameterPack() ||
rhsType->getType()->containsUnexpandedParameterPack())),
BTT(btt), Value(value), Loc(loc), RParen(rparen),
LhsType(lhsType), RhsType(rhsType) { }
explicit BinaryTypeTraitExpr(EmptyShell Empty)
: Expr(BinaryTypeTraitExprClass, Empty), BTT(0), Value(false),
LhsType(), RhsType() { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
BinaryTypeTrait getTrait() const {
return static_cast<BinaryTypeTrait>(BTT);
}
QualType getLhsType() const { return LhsType->getType(); }
QualType getRhsType() const { return RhsType->getType(); }
TypeSourceInfo *getLhsTypeSourceInfo() const { return LhsType; }
TypeSourceInfo *getRhsTypeSourceInfo() const { return RhsType; }
bool getValue() const { assert(!isTypeDependent()); return Value; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == BinaryTypeTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
};
/// \brief A type trait used in the implementation of various C++11 and
/// Library TR1 trait templates.
///
/// \code
/// __is_trivially_constructible(vector<int>, int*, int*)
/// \endcode
class TypeTraitExpr : public Expr {
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing parenthesis.
SourceLocation RParenLoc;
// Note: The TypeSourceInfos for the arguments are allocated after the
// TypeTraitExpr.
TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc,
bool Value);
TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) { }
/// \brief Retrieve the argument types.
TypeSourceInfo **getTypeSourceInfos() {
return reinterpret_cast<TypeSourceInfo **>(this+1);
}
/// \brief Retrieve the argument types.
TypeSourceInfo * const *getTypeSourceInfos() const {
return reinterpret_cast<TypeSourceInfo * const*>(this+1);
}
public:
/// \brief Create a new type trait expression.
static TypeTraitExpr *Create(const ASTContext &C, QualType T,
SourceLocation Loc, TypeTrait Kind,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc,
bool Value);
static TypeTraitExpr *CreateDeserialized(const ASTContext &C,
unsigned NumArgs);
/// \brief Determine which type trait this expression uses.
TypeTrait getTrait() const {
return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
}
bool getValue() const {
assert(!isValueDependent());
return TypeTraitExprBits.Value;
}
/// \brief Determine the number of arguments to this type trait.
unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
/// \brief Retrieve the Ith argument.
TypeSourceInfo *getArg(unsigned I) const {
assert(I < getNumArgs() && "Argument out-of-range");
return getArgs()[I];
}
/// \brief Retrieve the argument types.
ArrayRef<TypeSourceInfo *> getArgs() const {
return ArrayRef<TypeSourceInfo *>(getTypeSourceInfos(), getNumArgs());
}
typedef TypeSourceInfo **arg_iterator;
arg_iterator arg_begin() {
return getTypeSourceInfos();
}
arg_iterator arg_end() {
return getTypeSourceInfos() + getNumArgs();
}
typedef TypeSourceInfo const * const *arg_const_iterator;
arg_const_iterator arg_begin() const { return getTypeSourceInfos(); }
arg_const_iterator arg_end() const {
return getTypeSourceInfos() + getNumArgs();
}
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == TypeTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief An Embarcadero array type trait, as used in the implementation of
/// __array_rank and __array_extent.
///
/// Example:
/// \code
/// __array_rank(int[10][20]) == 2
/// __array_extent(int, 1) == 20
/// \endcode
class ArrayTypeTraitExpr : public Expr {
virtual void anchor();
/// \brief The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
unsigned ATT : 2;
/// \brief The value of the type trait. Unspecified if dependent.
uint64_t Value;
/// \brief The array dimension being queried, or -1 if not used.
Expr *Dimension;
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing paren.
SourceLocation RParen;
/// \brief The type being queried.
TypeSourceInfo *QueriedType;
public:
ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
TypeSourceInfo *queried, uint64_t value,
Expr *dimension, SourceLocation rparen, QualType ty)
: Expr(ArrayTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
false, queried->getType()->isDependentType(),
(queried->getType()->isInstantiationDependentType() ||
(dimension && dimension->isInstantiationDependent())),
queried->getType()->containsUnexpandedParameterPack()),
ATT(att), Value(value), Dimension(dimension),
Loc(loc), RParen(rparen), QueriedType(queried) { }
explicit ArrayTypeTraitExpr(EmptyShell Empty)
: Expr(ArrayTypeTraitExprClass, Empty), ATT(0), Value(false),
QueriedType() { }
virtual ~ArrayTypeTraitExpr() { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
QualType getQueriedType() const { return QueriedType->getType(); }
TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
uint64_t getValue() const { assert(!isTypeDependent()); return Value; }
Expr *getDimensionExpression() const { return Dimension; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == ArrayTypeTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
};
/// \brief An expression trait intrinsic.
///
/// Example:
/// \code
/// __is_lvalue_expr(std::cout) == true
/// __is_lvalue_expr(1) == false
/// \endcode
class ExpressionTraitExpr : public Expr {
/// \brief The trait. A ExpressionTrait enum in MSVC compatible unsigned.
unsigned ET : 31;
/// \brief The value of the type trait. Unspecified if dependent.
bool Value : 1;
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing paren.
SourceLocation RParen;
/// \brief The expression being queried.
Expr* QueriedExpression;
public:
ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,
Expr *queried, bool value,
SourceLocation rparen, QualType resultType)
: Expr(ExpressionTraitExprClass, resultType, VK_RValue, OK_Ordinary,
false, // Not type-dependent
// Value-dependent if the argument is type-dependent.
queried->isTypeDependent(),
queried->isInstantiationDependent(),
queried->containsUnexpandedParameterPack()),
ET(et), Value(value), Loc(loc), RParen(rparen),
QueriedExpression(queried) { }
explicit ExpressionTraitExpr(EmptyShell Empty)
: Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false),
QueriedExpression() { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
Expr *getQueriedExpression() const { return QueriedExpression; }
bool getValue() const { return Value; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == ExpressionTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
};
/// \brief A reference to an overloaded function set, either an
/// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
class OverloadExpr : public Expr {
/// \brief The common name of these declarations.
DeclarationNameInfo NameInfo;
/// \brief The nested-name-specifier that qualifies the name, if any.
NestedNameSpecifierLoc QualifierLoc;
/// The results. These are undesugared, which is to say, they may
/// include UsingShadowDecls. Access is relative to the naming
/// class.
// FIXME: Allocate this data after the OverloadExpr subclass.
DeclAccessPair *Results;
unsigned NumResults;
protected:
/// \brief Whether the name includes info for explicit template
/// keyword and arguments.
bool HasTemplateKWAndArgsInfo;
/// \brief Return the optional template keyword and arguments info.
ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo(); // defined far below.
/// \brief Return the optional template keyword and arguments info.
const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
return const_cast<OverloadExpr*>(this)->getTemplateKWAndArgsInfo();
}
OverloadExpr(StmtClass K, const ASTContext &C,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
UnresolvedSetIterator Begin, UnresolvedSetIterator End,
bool KnownDependent,
bool KnownInstantiationDependent,
bool KnownContainsUnexpandedParameterPack);
OverloadExpr(StmtClass K, EmptyShell Empty)
: Expr(K, Empty), QualifierLoc(), Results(0), NumResults(0),
HasTemplateKWAndArgsInfo(false) { }
void initializeResults(const ASTContext &C,
UnresolvedSetIterator Begin,
UnresolvedSetIterator End);
public:
struct FindResult {
OverloadExpr *Expression;
bool IsAddressOfOperand;
bool HasFormOfMemberPointer;
};
/// \brief Finds the overloaded expression in the given expression \p E of
/// OverloadTy.
///
/// \return the expression (which must be there) and true if it has
/// the particular form of a member pointer expression
static FindResult find(Expr *E) {
assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
FindResult Result;
E = E->IgnoreParens();
if (isa<UnaryOperator>(E)) {
assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
E = cast<UnaryOperator>(E)->getSubExpr();
OverloadExpr *Ovl = cast<OverloadExpr>(E->IgnoreParens());
Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
Result.IsAddressOfOperand = true;
Result.Expression = Ovl;
} else {
Result.HasFormOfMemberPointer = false;
Result.IsAddressOfOperand = false;
Result.Expression = cast<OverloadExpr>(E);
}
return Result;
}
/// \brief Gets the naming class of this lookup, if any.
CXXRecordDecl *getNamingClass() const;
typedef UnresolvedSetImpl::iterator decls_iterator;
decls_iterator decls_begin() const { return UnresolvedSetIterator(Results); }
decls_iterator decls_end() const {
return UnresolvedSetIterator(Results + NumResults);
}
/// \brief Gets the number of declarations in the unresolved set.
unsigned getNumDecls() const { return NumResults; }
/// \brief Gets the full name info.
const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
/// \brief Gets the name looked up.
DeclarationName getName() const { return NameInfo.getName(); }
/// \brief Gets the location of the name.
SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
/// \brief Fetches the nested-name qualifier, if one was given.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
/// \brief Fetches the nested-name qualifier with source-location
/// information, if one was given.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the location of the template keyword preceding
/// this name, if any.
SourceLocation getTemplateKeywordLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
}
/// \brief Retrieve the location of the left angle bracket starting the
/// explicit template argument list following the name, if any.
SourceLocation getLAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->LAngleLoc;
}
/// \brief Retrieve the location of the right angle bracket ending the
/// explicit template argument list following the name, if any.
SourceLocation getRAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->RAngleLoc;
}
/// \brief Determines whether the name was preceded by the template keyword.
bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
/// \brief Determines whether this expression had explicit template arguments.
bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
// Note that, inconsistently with the explicit-template-argument AST
// nodes, users are *forbidden* from calling these methods on objects
// without explicit template arguments.
ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
assert(hasExplicitTemplateArgs());
return *getTemplateKWAndArgsInfo();
}
const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
return const_cast<OverloadExpr*>(this)->getExplicitTemplateArgs();
}
TemplateArgumentLoc const *getTemplateArgs() const {
return getExplicitTemplateArgs().getTemplateArgs();
}
unsigned getNumTemplateArgs() const {
return getExplicitTemplateArgs().NumTemplateArgs;
}
/// \brief Copies the template arguments into the given structure.
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
getExplicitTemplateArgs().copyInto(List);
}
/// \brief Retrieves the optional explicit template arguments.
///
/// This points to the same data as getExplicitTemplateArgs(), but
/// returns null if there are no explicit template arguments.
const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
if (!hasExplicitTemplateArgs()) return 0;
return &getExplicitTemplateArgs();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == UnresolvedLookupExprClass ||
T->getStmtClass() == UnresolvedMemberExprClass;
}
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief A reference to a name which we were able to look up during
/// parsing but could not resolve to a specific declaration.
///
/// This arises in several ways:
/// * we might be waiting for argument-dependent lookup;
/// * the name might resolve to an overloaded function;
/// and eventually:
/// * the lookup might have included a function template.
///
/// These never include UnresolvedUsingValueDecls, which are always class
/// members and therefore appear only in UnresolvedMemberLookupExprs.
class UnresolvedLookupExpr : public OverloadExpr {
/// True if these lookup results should be extended by
/// argument-dependent lookup if this is the operand of a function
/// call.
bool RequiresADL;
/// True if these lookup results are overloaded. This is pretty
/// trivially rederivable if we urgently need to kill this field.
bool Overloaded;
/// The naming class (C++ [class.access.base]p5) of the lookup, if
/// any. This can generally be recalculated from the context chain,
/// but that can be fairly expensive for unqualified lookups. If we
/// want to improve memory use here, this could go in a union
/// against the qualified-lookup bits.
CXXRecordDecl *NamingClass;
UnresolvedLookupExpr(const ASTContext &C,
CXXRecordDecl *NamingClass,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool RequiresADL, bool Overloaded,
const TemplateArgumentListInfo *TemplateArgs,
UnresolvedSetIterator Begin, UnresolvedSetIterator End)
: OverloadExpr(UnresolvedLookupExprClass, C, QualifierLoc, TemplateKWLoc,
NameInfo, TemplateArgs, Begin, End, false, false, false),
RequiresADL(RequiresADL),
Overloaded(Overloaded), NamingClass(NamingClass)
{}
UnresolvedLookupExpr(EmptyShell Empty)
: OverloadExpr(UnresolvedLookupExprClass, Empty),
RequiresADL(false), Overloaded(false), NamingClass(0)
{}
friend class ASTStmtReader;
public:
static UnresolvedLookupExpr *Create(const ASTContext &C,
CXXRecordDecl *NamingClass,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo,
bool ADL, bool Overloaded,
UnresolvedSetIterator Begin,
UnresolvedSetIterator End) {
return new(C) UnresolvedLookupExpr(C, NamingClass, QualifierLoc,
SourceLocation(), NameInfo,
ADL, Overloaded, 0, Begin, End);
}
static UnresolvedLookupExpr *Create(const ASTContext &C,
CXXRecordDecl *NamingClass,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool ADL,
const TemplateArgumentListInfo *Args,
UnresolvedSetIterator Begin,
UnresolvedSetIterator End);
static UnresolvedLookupExpr *CreateEmpty(const ASTContext &C,
bool HasTemplateKWAndArgsInfo,
unsigned NumTemplateArgs);
/// True if this declaration should be extended by
/// argument-dependent lookup.
bool requiresADL() const { return RequiresADL; }
/// True if this lookup is overloaded.
bool isOverloaded() const { return Overloaded; }
/// Gets the 'naming class' (in the sense of C++0x
/// [class.access.base]p5) of the lookup. This is the scope
/// that was looked in to find these results.
CXXRecordDecl *getNamingClass() const { return NamingClass; }
SourceLocation getLocStart() const LLVM_READONLY {
if (NestedNameSpecifierLoc l = getQualifierLoc())
return l.getBeginLoc();
return getNameInfo().getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY {
if (hasExplicitTemplateArgs())
return getRAngleLoc();
return getNameInfo().getLocEnd();
}
child_range children() { return child_range(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == UnresolvedLookupExprClass;
}
};
/// \brief A qualified reference to a name whose declaration cannot
/// yet be resolved.
///
/// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
/// it expresses a reference to a declaration such as
/// X<T>::value. The difference, however, is that an
/// DependentScopeDeclRefExpr node is used only within C++ templates when
/// the qualification (e.g., X<T>::) refers to a dependent type. In
/// this case, X<T>::value cannot resolve to a declaration because the
/// declaration will differ from on instantiation of X<T> to the
/// next. Therefore, DependentScopeDeclRefExpr keeps track of the
/// qualifier (X<T>::) and the name of the entity being referenced
/// ("value"). Such expressions will instantiate to a DeclRefExpr once the
/// declaration can be found.
class DependentScopeDeclRefExpr : public Expr {
/// \brief The nested-name-specifier that qualifies this unresolved
/// declaration name.
NestedNameSpecifierLoc QualifierLoc;
/// \brief The name of the entity we will be referencing.
DeclarationNameInfo NameInfo;
/// \brief Whether the name includes info for explicit template
/// keyword and arguments.
bool HasTemplateKWAndArgsInfo;
/// \brief Return the optional template keyword and arguments info.
ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
if (!HasTemplateKWAndArgsInfo) return 0;
return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
}
/// \brief Return the optional template keyword and arguments info.
const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
return const_cast<DependentScopeDeclRefExpr*>(this)
->getTemplateKWAndArgsInfo();
}
DependentScopeDeclRefExpr(QualType T,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *Args);
public:
static DependentScopeDeclRefExpr *Create(const ASTContext &C,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
static DependentScopeDeclRefExpr *CreateEmpty(const ASTContext &C,
bool HasTemplateKWAndArgsInfo,
unsigned NumTemplateArgs);
/// \brief Retrieve the name that this expression refers to.
const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
/// \brief Retrieve the name that this expression refers to.
DeclarationName getDeclName() const { return NameInfo.getName(); }
/// \brief Retrieve the location of the name within the expression.
SourceLocation getLocation() const { return NameInfo.getLoc(); }
/// \brief Retrieve the nested-name-specifier that qualifies the
/// name, with source location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the nested-name-specifier that qualifies this
/// declaration.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
/// \brief Retrieve the location of the template keyword preceding
/// this name, if any.
SourceLocation getTemplateKeywordLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
}
/// \brief Retrieve the location of the left angle bracket starting the
/// explicit template argument list following the name, if any.
SourceLocation getLAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->LAngleLoc;
}
/// \brief Retrieve the location of the right angle bracket ending the
/// explicit template argument list following the name, if any.
SourceLocation getRAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->RAngleLoc;
}
/// Determines whether the name was preceded by the template keyword.
bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
/// Determines whether this lookup had explicit template arguments.
bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
// Note that, inconsistently with the explicit-template-argument AST
// nodes, users are *forbidden* from calling these methods on objects
// without explicit template arguments.
ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
assert(hasExplicitTemplateArgs());
return *reinterpret_cast<ASTTemplateArgumentListInfo*>(this + 1);
}
/// Gets a reference to the explicit template argument list.
const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
assert(hasExplicitTemplateArgs());
return *reinterpret_cast<const ASTTemplateArgumentListInfo*>(this + 1);
}
/// \brief Retrieves the optional explicit template arguments.
///
/// This points to the same data as getExplicitTemplateArgs(), but
/// returns null if there are no explicit template arguments.
const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
if (!hasExplicitTemplateArgs()) return 0;
return &getExplicitTemplateArgs();
}
/// \brief Copies the template arguments (if present) into the given
/// structure.
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
getExplicitTemplateArgs().copyInto(List);
}
TemplateArgumentLoc const *getTemplateArgs() const {
return getExplicitTemplateArgs().getTemplateArgs();
}
unsigned getNumTemplateArgs() const {
return getExplicitTemplateArgs().NumTemplateArgs;
}
SourceLocation getLocStart() const LLVM_READONLY {
return QualifierLoc.getBeginLoc();
}
SourceLocation getLocEnd() const LLVM_READONLY {
if (hasExplicitTemplateArgs())
return getRAngleLoc();
return getLocation();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == DependentScopeDeclRefExprClass;
}
child_range children() { return child_range(); }
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// Represents an expression -- generally a full-expression -- that
/// introduces cleanups to be run at the end of the sub-expression's
/// evaluation. The most common source of expression-introduced
/// cleanups is temporary objects in C++, but several other kinds of
/// expressions can create cleanups, including basically every
/// call in ARC that returns an Objective-C pointer.
///
/// This expression also tracks whether the sub-expression contains a
/// potentially-evaluated block literal. The lifetime of a block
/// literal is the extent of the enclosing scope.
class ExprWithCleanups : public Expr {
public:
/// The type of objects that are kept in the cleanup.
/// It's useful to remember the set of blocks; we could also
/// remember the set of temporaries, but there's currently
/// no need.
typedef BlockDecl *CleanupObject;
private:
Stmt *SubExpr;
ExprWithCleanups(EmptyShell, unsigned NumObjects);
ExprWithCleanups(Expr *SubExpr, ArrayRef<CleanupObject> Objects);
CleanupObject *getObjectsBuffer() {
return reinterpret_cast<CleanupObject*>(this + 1);
}
const CleanupObject *getObjectsBuffer() const {
return reinterpret_cast<const CleanupObject*>(this + 1);
}
friend class ASTStmtReader;
public:
static ExprWithCleanups *Create(const ASTContext &C, EmptyShell empty,
unsigned numObjects);
static ExprWithCleanups *Create(const ASTContext &C, Expr *subexpr,
ArrayRef<CleanupObject> objects);
ArrayRef<CleanupObject> getObjects() const {
return ArrayRef<CleanupObject>(getObjectsBuffer(), getNumObjects());
}
unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
CleanupObject getObject(unsigned i) const {
assert(i < getNumObjects() && "Index out of range");
return getObjects()[i];
}
Expr *getSubExpr() { return cast<Expr>(SubExpr); }
const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
/// As with any mutator of the AST, be very careful
/// when modifying an existing AST to preserve its invariants.
void setSubExpr(Expr *E) { SubExpr = E; }
SourceLocation getLocStart() const LLVM_READONLY {
return SubExpr->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
// Implement isa/cast/dyncast/etc.
static bool classof(const Stmt *T) {
return T->getStmtClass() == ExprWithCleanupsClass;
}
// Iterators
child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
};
/// \brief Describes an explicit type conversion that uses functional
/// notion but could not be resolved because one or more arguments are
/// type-dependent.
///
/// The explicit type conversions expressed by
/// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
/// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
/// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
/// type-dependent. For example, this would occur in a template such
/// as:
///
/// \code
/// template<typename T, typename A1>
/// inline T make_a(const A1& a1) {
/// return T(a1);
/// }
/// \endcode
///
/// When the returned expression is instantiated, it may resolve to a
/// constructor call, conversion function call, or some kind of type
/// conversion.
class CXXUnresolvedConstructExpr : public Expr {
/// \brief The type being constructed.
TypeSourceInfo *Type;
/// \brief The location of the left parentheses ('(').
SourceLocation LParenLoc;
/// \brief The location of the right parentheses (')').
SourceLocation RParenLoc;
/// \brief The number of arguments used to construct the type.
unsigned NumArgs;
CXXUnresolvedConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
ArrayRef<Expr*> Args,
SourceLocation RParenLoc);
CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
: Expr(CXXUnresolvedConstructExprClass, Empty), Type(), NumArgs(NumArgs) { }
friend class ASTStmtReader;
public:
static CXXUnresolvedConstructExpr *Create(const ASTContext &C,
TypeSourceInfo *Type,
SourceLocation LParenLoc,
ArrayRef<Expr*> Args,
SourceLocation RParenLoc);
static CXXUnresolvedConstructExpr *CreateEmpty(const ASTContext &C,
unsigned NumArgs);
/// \brief Retrieve the type that is being constructed, as specified
/// in the source code.
QualType getTypeAsWritten() const { return Type->getType(); }
/// \brief Retrieve the type source information for the type being
/// constructed.
TypeSourceInfo *getTypeSourceInfo() const { return Type; }
/// \brief Retrieve the location of the left parentheses ('(') that
/// precedes the argument list.
SourceLocation getLParenLoc() const { return LParenLoc; }
void setLParenLoc(SourceLocation L) { LParenLoc = L; }
/// \brief Retrieve the location of the right parentheses (')') that
/// follows the argument list.
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation L) { RParenLoc = L; }
/// \brief Retrieve the number of arguments.
unsigned arg_size() const { return NumArgs; }
typedef Expr** arg_iterator;
arg_iterator arg_begin() { return reinterpret_cast<Expr**>(this + 1); }
arg_iterator arg_end() { return arg_begin() + NumArgs; }
typedef const Expr* const * const_arg_iterator;
const_arg_iterator arg_begin() const {
return reinterpret_cast<const Expr* const *>(this + 1);
}
const_arg_iterator arg_end() const {
return arg_begin() + NumArgs;
}
Expr *getArg(unsigned I) {
assert(I < NumArgs && "Argument index out-of-range");
return *(arg_begin() + I);
}
const Expr *getArg(unsigned I) const {
assert(I < NumArgs && "Argument index out-of-range");
return *(arg_begin() + I);
}
void setArg(unsigned I, Expr *E) {
assert(I < NumArgs && "Argument index out-of-range");
*(arg_begin() + I) = E;
}
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY {
assert(RParenLoc.isValid() || NumArgs == 1);
return RParenLoc.isValid() ? RParenLoc : getArg(0)->getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXUnresolvedConstructExprClass;
}
// Iterators
child_range children() {
Stmt **begin = reinterpret_cast<Stmt**>(this+1);
return child_range(begin, begin + NumArgs);
}
};
/// \brief Represents a C++ member access expression where the actual
/// member referenced could not be resolved because the base
/// expression or the member name was dependent.
///
/// Like UnresolvedMemberExprs, these can be either implicit or
/// explicit accesses. It is only possible to get one of these with
/// an implicit access if a qualifier is provided.
class CXXDependentScopeMemberExpr : public Expr {
/// \brief The expression for the base pointer or class reference,
/// e.g., the \c x in x.f. Can be null in implicit accesses.
Stmt *Base;
/// \brief The type of the base expression. Never null, even for
/// implicit accesses.
QualType BaseType;
/// \brief Whether this member expression used the '->' operator or
/// the '.' operator.
bool IsArrow : 1;
/// \brief Whether this member expression has info for explicit template
/// keyword and arguments.
bool HasTemplateKWAndArgsInfo : 1;
/// \brief The location of the '->' or '.' operator.
SourceLocation OperatorLoc;
/// \brief The nested-name-specifier that precedes the member name, if any.
NestedNameSpecifierLoc QualifierLoc;
/// \brief In a qualified member access expression such as t->Base::f, this
/// member stores the resolves of name lookup in the context of the member
/// access expression, to be used at instantiation time.
///
/// FIXME: This member, along with the QualifierLoc, could
/// be stuck into a structure that is optionally allocated at the end of
/// the CXXDependentScopeMemberExpr, to save space in the common case.
NamedDecl *FirstQualifierFoundInScope;
/// \brief The member to which this member expression refers, which
/// can be name, overloaded operator, or destructor.
///
/// FIXME: could also be a template-id
DeclarationNameInfo MemberNameInfo;
/// \brief Return the optional template keyword and arguments info.
ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
if (!HasTemplateKWAndArgsInfo) return 0;
return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
}
/// \brief Return the optional template keyword and arguments info.
const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
return const_cast<CXXDependentScopeMemberExpr*>(this)
->getTemplateKWAndArgsInfo();
}
CXXDependentScopeMemberExpr(const ASTContext &C, Expr *Base,
QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierFoundInScope,
DeclarationNameInfo MemberNameInfo,
const TemplateArgumentListInfo *TemplateArgs);
public:
CXXDependentScopeMemberExpr(const ASTContext &C, Expr *Base,
QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
NamedDecl *FirstQualifierFoundInScope,
DeclarationNameInfo MemberNameInfo);
static CXXDependentScopeMemberExpr *
Create(const ASTContext &C, Expr *Base, QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
DeclarationNameInfo MemberNameInfo,
const TemplateArgumentListInfo *TemplateArgs);
static CXXDependentScopeMemberExpr *
CreateEmpty(const ASTContext &C, bool HasTemplateKWAndArgsInfo,
unsigned NumTemplateArgs);
/// \brief True if this is an implicit access, i.e. one in which the
/// member being accessed was not written in the source. The source
/// location of the operator is invalid in this case.
bool isImplicitAccess() const;
/// \brief Retrieve the base object of this member expressions,
/// e.g., the \c x in \c x.m.
Expr *getBase() const {
assert(!isImplicitAccess());
return cast<Expr>(Base);
}
QualType getBaseType() const { return BaseType; }
/// \brief Determine whether this member expression used the '->'
/// operator; otherwise, it used the '.' operator.
bool isArrow() const { return IsArrow; }
/// \brief Retrieve the location of the '->' or '.' operator.
SourceLocation getOperatorLoc() const { return OperatorLoc; }
/// \brief Retrieve the nested-name-specifier that qualifies the member
/// name.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
/// \brief Retrieve the nested-name-specifier that qualifies the member
/// name, with source location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the first part of the nested-name-specifier that was
/// found in the scope of the member access expression when the member access
/// was initially parsed.
///
/// This function only returns a useful result when member access expression
/// uses a qualified member name, e.g., "x.Base::f". Here, the declaration
/// returned by this function describes what was found by unqualified name
/// lookup for the identifier "Base" within the scope of the member access
/// expression itself. At template instantiation time, this information is
/// combined with the results of name lookup into the type of the object
/// expression itself (the class type of x).
NamedDecl *getFirstQualifierFoundInScope() const {
return FirstQualifierFoundInScope;
}
/// \brief Retrieve the name of the member that this expression
/// refers to.
const DeclarationNameInfo &getMemberNameInfo() const {
return MemberNameInfo;
}
/// \brief Retrieve the name of the member that this expression
/// refers to.
DeclarationName getMember() const { return MemberNameInfo.getName(); }
// \brief Retrieve the location of the name of the member that this
// expression refers to.
SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
/// \brief Retrieve the location of the template keyword preceding the
/// member name, if any.
SourceLocation getTemplateKeywordLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
}
/// \brief Retrieve the location of the left angle bracket starting the
/// explicit template argument list following the member name, if any.
SourceLocation getLAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->LAngleLoc;
}
/// \brief Retrieve the location of the right angle bracket ending the
/// explicit template argument list following the member name, if any.
SourceLocation getRAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->RAngleLoc;
}
/// Determines whether the member name was preceded by the template keyword.
bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
/// \brief Determines whether this member expression actually had a C++
/// template argument list explicitly specified, e.g., x.f<int>.
bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
/// \brief Retrieve the explicit template argument list that followed the
/// member template name, if any.
ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
assert(hasExplicitTemplateArgs());
return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
}
/// \brief Retrieve the explicit template argument list that followed the
/// member template name, if any.
const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
return const_cast<CXXDependentScopeMemberExpr *>(this)
->getExplicitTemplateArgs();
}
/// \brief Retrieves the optional explicit template arguments.
///
/// This points to the same data as getExplicitTemplateArgs(), but
/// returns null if there are no explicit template arguments.
const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
if (!hasExplicitTemplateArgs()) return 0;
return &getExplicitTemplateArgs();
}
/// \brief Copies the template arguments (if present) into the given
/// structure.
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
getExplicitTemplateArgs().copyInto(List);
}
/// \brief Initializes the template arguments using the given structure.
void initializeTemplateArgumentsFrom(const TemplateArgumentListInfo &List) {
getExplicitTemplateArgs().initializeFrom(List);
}
/// \brief Retrieve the template arguments provided as part of this
/// template-id.
const TemplateArgumentLoc *getTemplateArgs() const {
return getExplicitTemplateArgs().getTemplateArgs();
}
/// \brief Retrieve the number of template arguments provided as part of this
/// template-id.
unsigned getNumTemplateArgs() const {
return getExplicitTemplateArgs().NumTemplateArgs;
}
SourceLocation getLocStart() const LLVM_READONLY {
if (!isImplicitAccess())
return Base->getLocStart();
if (getQualifier())
return getQualifierLoc().getBeginLoc();
return MemberNameInfo.getBeginLoc();
}
SourceLocation getLocEnd() const LLVM_READONLY {
if (hasExplicitTemplateArgs())
return getRAngleLoc();
return MemberNameInfo.getEndLoc();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDependentScopeMemberExprClass;
}
// Iterators
child_range children() {
if (isImplicitAccess()) return child_range();
return child_range(&Base, &Base + 1);
}
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief Represents a C++ member access expression for which lookup
/// produced a set of overloaded functions.
///
/// The member access may be explicit or implicit:
/// \code
/// struct A {
/// int a, b;
/// int explicitAccess() { return this->a + this->A::b; }
/// int implicitAccess() { return a + A::b; }
/// };
/// \endcode
///
/// In the final AST, an explicit access always becomes a MemberExpr.
/// An implicit access may become either a MemberExpr or a
/// DeclRefExpr, depending on whether the member is static.
class UnresolvedMemberExpr : public OverloadExpr {
/// \brief Whether this member expression used the '->' operator or
/// the '.' operator.
bool IsArrow : 1;
/// \brief Whether the lookup results contain an unresolved using
/// declaration.
bool HasUnresolvedUsing : 1;
/// \brief The expression for the base pointer or class reference,
/// e.g., the \c x in x.f.
///
/// This can be null if this is an 'unbased' member expression.
Stmt *Base;
/// \brief The type of the base expression; never null.
QualType BaseType;
/// \brief The location of the '->' or '.' operator.
SourceLocation OperatorLoc;
UnresolvedMemberExpr(const ASTContext &C, bool HasUnresolvedUsing,
Expr *Base, QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &MemberNameInfo,
const TemplateArgumentListInfo *TemplateArgs,
UnresolvedSetIterator Begin, UnresolvedSetIterator End);
UnresolvedMemberExpr(EmptyShell Empty)
: OverloadExpr(UnresolvedMemberExprClass, Empty), IsArrow(false),
HasUnresolvedUsing(false), Base(0) { }
friend class ASTStmtReader;
public:
static UnresolvedMemberExpr *
Create(const ASTContext &C, bool HasUnresolvedUsing,
Expr *Base, QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &MemberNameInfo,
const TemplateArgumentListInfo *TemplateArgs,
UnresolvedSetIterator Begin, UnresolvedSetIterator End);
static UnresolvedMemberExpr *
CreateEmpty(const ASTContext &C, bool HasTemplateKWAndArgsInfo,
unsigned NumTemplateArgs);
/// \brief True if this is an implicit access, i.e., one in which the
/// member being accessed was not written in the source.
///
/// The source location of the operator is invalid in this case.
bool isImplicitAccess() const;
/// \brief Retrieve the base object of this member expressions,
/// e.g., the \c x in \c x.m.
Expr *getBase() {
assert(!isImplicitAccess());
return cast<Expr>(Base);
}
const Expr *getBase() const {
assert(!isImplicitAccess());
return cast<Expr>(Base);
}
QualType getBaseType() const { return BaseType; }
/// \brief Determine whether the lookup results contain an unresolved using
/// declaration.
bool hasUnresolvedUsing() const { return HasUnresolvedUsing; }
/// \brief Determine whether this member expression used the '->'
/// operator; otherwise, it used the '.' operator.
bool isArrow() const { return IsArrow; }
/// \brief Retrieve the location of the '->' or '.' operator.
SourceLocation getOperatorLoc() const { return OperatorLoc; }
/// \brief Retrieve the naming class of this lookup.
CXXRecordDecl *getNamingClass() const;
/// \brief Retrieve the full name info for the member that this expression
/// refers to.
const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); }
/// \brief Retrieve the name of the member that this expression
/// refers to.
DeclarationName getMemberName() const { return getName(); }
// \brief Retrieve the location of the name of the member that this
// expression refers to.
SourceLocation getMemberLoc() const { return getNameLoc(); }
// \brief Return the preferred location (the member name) for the arrow when
// diagnosing a problem with this expression.
SourceLocation getExprLoc() const LLVM_READONLY { return getMemberLoc(); }
SourceLocation getLocStart() const LLVM_READONLY {
if (!isImplicitAccess())
return Base->getLocStart();
if (NestedNameSpecifierLoc l = getQualifierLoc())
return l.getBeginLoc();
return getMemberNameInfo().getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY {
if (hasExplicitTemplateArgs())
return getRAngleLoc();
return getMemberNameInfo().getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == UnresolvedMemberExprClass;
}
// Iterators
child_range children() {
if (isImplicitAccess()) return child_range();
return child_range(&Base, &Base + 1);
}
};
/// \brief Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
///
/// The noexcept expression tests whether a given expression might throw. Its
/// result is a boolean constant.
class CXXNoexceptExpr : public Expr {
bool Value : 1;
Stmt *Operand;
SourceRange Range;
friend class ASTStmtReader;
public:
CXXNoexceptExpr(QualType Ty, Expr *Operand, CanThrowResult Val,
SourceLocation Keyword, SourceLocation RParen)
: Expr(CXXNoexceptExprClass, Ty, VK_RValue, OK_Ordinary,
/*TypeDependent*/false,
/*ValueDependent*/Val == CT_Dependent,
Val == CT_Dependent || Operand->isInstantiationDependent(),
Operand->containsUnexpandedParameterPack()),
Value(Val == CT_Cannot), Operand(Operand), Range(Keyword, RParen)
{ }
CXXNoexceptExpr(EmptyShell Empty)
: Expr(CXXNoexceptExprClass, Empty)
{ }
Expr *getOperand() const { return static_cast<Expr*>(Operand); }
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
SourceRange getSourceRange() const LLVM_READONLY { return Range; }
bool getValue() const { return Value; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXNoexceptExprClass;
}
// Iterators
child_range children() { return child_range(&Operand, &Operand + 1); }
};
/// \brief Represents a C++11 pack expansion that produces a sequence of
/// expressions.
///
/// A pack expansion expression contains a pattern (which itself is an
/// expression) followed by an ellipsis. For example:
///
/// \code
/// template<typename F, typename ...Types>
/// void forward(F f, Types &&...args) {
/// f(static_cast<Types&&>(args)...);
/// }
/// \endcode
///
/// Here, the argument to the function object \c f is a pack expansion whose
/// pattern is \c static_cast<Types&&>(args). When the \c forward function
/// template is instantiated, the pack expansion will instantiate to zero or
/// or more function arguments to the function object \c f.
class PackExpansionExpr : public Expr {
SourceLocation EllipsisLoc;
/// \brief The number of expansions that will be produced by this pack
/// expansion expression, if known.
///
/// When zero, the number of expansions is not known. Otherwise, this value
/// is the number of expansions + 1.
unsigned NumExpansions;
Stmt *Pattern;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions)
: Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
Pattern->getObjectKind(), /*TypeDependent=*/true,
/*ValueDependent=*/true, /*InstantiationDependent=*/true,
/*ContainsUnexpandedParameterPack=*/false),
EllipsisLoc(EllipsisLoc),
NumExpansions(NumExpansions? *NumExpansions + 1 : 0),
Pattern(Pattern) { }
PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty) { }
/// \brief Retrieve the pattern of the pack expansion.
Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
/// \brief Retrieve the pattern of the pack expansion.
const Expr *getPattern() const { return reinterpret_cast<Expr *>(Pattern); }
/// \brief Retrieve the location of the ellipsis that describes this pack
/// expansion.
SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
/// \brief Determine the number of expansions that will be produced when
/// this pack expansion is instantiated, if already known.
Optional<unsigned> getNumExpansions() const {
if (NumExpansions)
return NumExpansions - 1;
return None;
}
SourceLocation getLocStart() const LLVM_READONLY {
return Pattern->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY { return EllipsisLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == PackExpansionExprClass;
}
// Iterators
child_range children() {
return child_range(&Pattern, &Pattern + 1);
}
};
inline ASTTemplateKWAndArgsInfo *OverloadExpr::getTemplateKWAndArgsInfo() {
if (!HasTemplateKWAndArgsInfo) return 0;
if (isa<UnresolvedLookupExpr>(this))
return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
(cast<UnresolvedLookupExpr>(this) + 1);
else
return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
(cast<UnresolvedMemberExpr>(this) + 1);
}
/// \brief Represents an expression that computes the length of a parameter
/// pack.
///
/// \code
/// template<typename ...Types>
/// struct count {
/// static const unsigned value = sizeof...(Types);
/// };
/// \endcode
class SizeOfPackExpr : public Expr {
/// \brief The location of the \c sizeof keyword.
SourceLocation OperatorLoc;
/// \brief The location of the name of the parameter pack.
SourceLocation PackLoc;
/// \brief The location of the closing parenthesis.
SourceLocation RParenLoc;
/// \brief The length of the parameter pack, if known.
///
/// When this expression is value-dependent, the length of the parameter pack
/// is unknown. When this expression is not value-dependent, the length is
/// known.
unsigned Length;
/// \brief The parameter pack itself.
NamedDecl *Pack;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
/// \brief Create a value-dependent expression that computes the length of
/// the given parameter pack.
SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
SourceLocation PackLoc, SourceLocation RParenLoc)
: Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
/*TypeDependent=*/false, /*ValueDependent=*/true,
/*InstantiationDependent=*/true,
/*ContainsUnexpandedParameterPack=*/false),
OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
Length(0), Pack(Pack) { }
/// \brief Create an expression that computes the length of
/// the given parameter pack, which is already known.
SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
SourceLocation PackLoc, SourceLocation RParenLoc,
unsigned Length)
: Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
/*TypeDependent=*/false, /*ValueDependent=*/false,
/*InstantiationDependent=*/false,
/*ContainsUnexpandedParameterPack=*/false),
OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
Length(Length), Pack(Pack) { }
/// \brief Create an empty expression.
SizeOfPackExpr(EmptyShell Empty) : Expr(SizeOfPackExprClass, Empty) { }
/// \brief Determine the location of the 'sizeof' keyword.
SourceLocation getOperatorLoc() const { return OperatorLoc; }
/// \brief Determine the location of the parameter pack.
SourceLocation getPackLoc() const { return PackLoc; }
/// \brief Determine the location of the right parenthesis.
SourceLocation getRParenLoc() const { return RParenLoc; }
/// \brief Retrieve the parameter pack.
NamedDecl *getPack() const { return Pack; }
/// \brief Retrieve the length of the parameter pack.
///
/// This routine may only be invoked when the expression is not
/// value-dependent.
unsigned getPackLength() const {
assert(!isValueDependent() &&
"Cannot get the length of a value-dependent pack size expression");
return Length;
}
SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == SizeOfPackExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief Represents a reference to a non-type template parameter
/// that has been substituted with a template argument.
class SubstNonTypeTemplateParmExpr : public Expr {
/// \brief The replaced parameter.
NonTypeTemplateParmDecl *Param;
/// \brief The replacement expression.
Stmt *Replacement;
/// \brief The location of the non-type template parameter reference.
SourceLocation NameLoc;
friend class ASTReader;
friend class ASTStmtReader;
explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
: Expr(SubstNonTypeTemplateParmExprClass, Empty) { }
public:
SubstNonTypeTemplateParmExpr(QualType type,
ExprValueKind valueKind,
SourceLocation loc,
NonTypeTemplateParmDecl *param,
Expr *replacement)
: Expr(SubstNonTypeTemplateParmExprClass, type, valueKind, OK_Ordinary,
replacement->isTypeDependent(), replacement->isValueDependent(),
replacement->isInstantiationDependent(),
replacement->containsUnexpandedParameterPack()),
Param(param), Replacement(replacement), NameLoc(loc) {}
SourceLocation getNameLoc() const { return NameLoc; }
SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
Expr *getReplacement() const { return cast<Expr>(Replacement); }
NonTypeTemplateParmDecl *getParameter() const { return Param; }
static bool classof(const Stmt *s) {
return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
}
// Iterators
child_range children() { return child_range(&Replacement, &Replacement+1); }
};
/// \brief Represents a reference to a non-type template parameter pack that
/// has been substituted with a non-template argument pack.
///
/// When a pack expansion in the source code contains multiple parameter packs
/// and those parameter packs correspond to different levels of template
/// parameter lists, this node is used to represent a non-type template
/// parameter pack from an outer level, which has already had its argument pack
/// substituted but that still lives within a pack expansion that itself
/// could not be instantiated. When actually performing a substitution into
/// that pack expansion (e.g., when all template parameters have corresponding
/// arguments), this type will be replaced with the appropriate underlying
/// expression at the current pack substitution index.
class SubstNonTypeTemplateParmPackExpr : public Expr {
/// \brief The non-type template parameter pack itself.
NonTypeTemplateParmDecl *Param;
/// \brief A pointer to the set of template arguments that this
/// parameter pack is instantiated with.
const TemplateArgument *Arguments;
/// \brief The number of template arguments in \c Arguments.
unsigned NumArguments;
/// \brief The location of the non-type template parameter pack reference.
SourceLocation NameLoc;
friend class ASTReader;
friend class ASTStmtReader;
explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
: Expr(SubstNonTypeTemplateParmPackExprClass, Empty) { }
public:
SubstNonTypeTemplateParmPackExpr(QualType T,
NonTypeTemplateParmDecl *Param,
SourceLocation NameLoc,
const TemplateArgument &ArgPack);
/// \brief Retrieve the non-type template parameter pack being substituted.
NonTypeTemplateParmDecl *getParameterPack() const { return Param; }
/// \brief Retrieve the location of the parameter pack name.
SourceLocation getParameterPackLocation() const { return NameLoc; }
/// \brief Retrieve the template argument pack containing the substituted
/// template arguments.
TemplateArgument getArgumentPack() const;
SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == SubstNonTypeTemplateParmPackExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief Represents a reference to a function parameter pack that has been
/// substituted but not yet expanded.
///
/// When a pack expansion contains multiple parameter packs at different levels,
/// this node is used to represent a function parameter pack at an outer level
/// which we have already substituted to refer to expanded parameters, but where
/// the containing pack expansion cannot yet be expanded.
///
/// \code
/// template<typename...Ts> struct S {
/// template<typename...Us> auto f(Ts ...ts) -> decltype(g(Us(ts)...));
/// };
/// template struct S<int, int>;
/// \endcode
class FunctionParmPackExpr : public Expr {
/// \brief The function parameter pack which was referenced.
ParmVarDecl *ParamPack;
/// \brief The location of the function parameter pack reference.
SourceLocation NameLoc;
/// \brief The number of expansions of this pack.
unsigned NumParameters;
FunctionParmPackExpr(QualType T, ParmVarDecl *ParamPack,
SourceLocation NameLoc, unsigned NumParams,
Decl * const *Params);
friend class ASTReader;
friend class ASTStmtReader;
public:
static FunctionParmPackExpr *Create(const ASTContext &Context, QualType T,
ParmVarDecl *ParamPack,
SourceLocation NameLoc,
ArrayRef<Decl *> Params);
static FunctionParmPackExpr *CreateEmpty(const ASTContext &Context,
unsigned NumParams);
/// \brief Get the parameter pack which this expression refers to.
ParmVarDecl *getParameterPack() const { return ParamPack; }
/// \brief Get the location of the parameter pack.
SourceLocation getParameterPackLocation() const { return NameLoc; }
/// \brief Iterators over the parameters which the parameter pack expanded
/// into.
typedef ParmVarDecl * const *iterator;
iterator begin() const { return reinterpret_cast<iterator>(this+1); }
iterator end() const { return begin() + NumParameters; }
/// \brief Get the number of parameters in this parameter pack.
unsigned getNumExpansions() const { return NumParameters; }
/// \brief Get an expansion of the parameter pack by index.
ParmVarDecl *getExpansion(unsigned I) const { return begin()[I]; }
SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == FunctionParmPackExprClass;
}
child_range children() { return child_range(); }
};
/// \brief Represents a prvalue temporary that is written into memory so that
/// a reference can bind to it.
///
/// Prvalue expressions are materialized when they need to have an address
/// in memory for a reference to bind to. This happens when binding a
/// reference to the result of a conversion, e.g.,
///
/// \code
/// const int &r = 1.0;
/// \endcode
///
/// Here, 1.0 is implicitly converted to an \c int. That resulting \c int is
/// then materialized via a \c MaterializeTemporaryExpr, and the reference
/// binds to the temporary. \c MaterializeTemporaryExprs are always glvalues
/// (either an lvalue or an xvalue, depending on the kind of reference binding
/// to it), maintaining the invariant that references always bind to glvalues.
///
/// Reference binding and copy-elision can both extend the lifetime of a
/// temporary. When either happens, the expression will also track the
/// declaration which is responsible for the lifetime extension.
class MaterializeTemporaryExpr : public Expr {
public:
/// \brief The temporary-generating expression whose value will be
/// materialized.
Stmt *Temporary;
/// \brief The declaration which lifetime-extended this reference, if any.
/// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
const ValueDecl *ExtendingDecl;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
MaterializeTemporaryExpr(QualType T, Expr *Temporary,
bool BoundToLvalueReference,
const ValueDecl *ExtendedBy)
: Expr(MaterializeTemporaryExprClass, T,
BoundToLvalueReference? VK_LValue : VK_XValue, OK_Ordinary,
Temporary->isTypeDependent(), Temporary->isValueDependent(),
Temporary->isInstantiationDependent(),
Temporary->containsUnexpandedParameterPack()),
Temporary(Temporary), ExtendingDecl(ExtendedBy) {
}
MaterializeTemporaryExpr(EmptyShell Empty)
: Expr(MaterializeTemporaryExprClass, Empty) { }
/// \brief Retrieve the temporary-generating subexpression whose value will
/// be materialized into a glvalue.
Expr *GetTemporaryExpr() const { return static_cast<Expr *>(Temporary); }
/// \brief Retrieve the storage duration for the materialized temporary.
StorageDuration getStorageDuration() const {
if (!ExtendingDecl)
return SD_FullExpression;
// FIXME: This is not necessarily correct for a temporary materialized
// within a default initializer.
if (isa<FieldDecl>(ExtendingDecl))
return SD_Automatic;
return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
}
/// \brief Get the declaration which triggered the lifetime-extension of this
/// temporary, if any.
const ValueDecl *getExtendingDecl() const { return ExtendingDecl; }
void setExtendingDecl(const ValueDecl *ExtendedBy) {
ExtendingDecl = ExtendedBy;
}
/// \brief Determine whether this materialized temporary is bound to an
/// lvalue reference; otherwise, it's bound to an rvalue reference.
bool isBoundToLvalueReference() const {
return getValueKind() == VK_LValue;
}
SourceLocation getLocStart() const LLVM_READONLY {
return Temporary->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY {
return Temporary->getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == MaterializeTemporaryExprClass;
}
// Iterators
child_range children() { return child_range(&Temporary, &Temporary + 1); }
};
} // end namespace clang
#endif
| [
"aleksy.jones@gmail.com"
] | aleksy.jones@gmail.com |
c848896d11028cfa4fa9bd48a142ca941566ac1f | 69312fc3709f1e0007e9def5523cd0988081a7d2 | /sources/Crossword/app/console.h | 8f68300d3b42c10b9d10c2aa00cefae3680d3d6e | [] | no_license | Olieaw/--Crossword---Mini--Game-- | 792444dfc8a440d51745e999802a378a6f4ecd79 | 65cee2e85a12a4e556d216a643b09b6612a40239 | refs/heads/master | 2021-01-18T22:05:55.977251 | 2016-10-05T12:59:47 | 2016-10-05T12:59:47 | 52,116,312 | 2 | 3 | null | 2016-04-30T14:31:00 | 2016-02-19T21:04:41 | C++ | UTF-8 | C++ | false | false | 375 | h | #ifndef CONSOLE_H
#define CONSOLE_H
#include "vocalbulary.h"
#include "field.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstring>
class Console
{
public:
Console();
void Menu();
void PrintWords(std::vector<std::string> str);
void PrintField(std::vector<std::vector<std::string>> field);
};
#endif // CONSOLE_H
| [
"olieaw1998@yandex.ru"
] | olieaw1998@yandex.ru |
aaabceaa5b153e75119855bb8377a8135d77a9b7 | 3cf1c3336e48023d06cd3fbaf6e1a157030f6f4b | /Eigen/src/SVD/BDCSVD.h | e8bfa26c0df8bef8fd5d769ec43f9466923897c9 | [] | no_license | pochemuto/MaterialSolver | e55399d7ad2e03fc55214007565c4e7d0da4b694 | aaeea0bf1ead818801111a6467fa9789d53c8dc9 | refs/heads/master | 2021-01-25T03:49:40.147690 | 2015-05-20T21:49:51 | 2015-05-20T21:49:51 | 33,502,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,101 | h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// We used the "A Divide-And-Conquer Algorithm for the Bidiagonal SVD"
// research report written by Ming Gu and Stanley C.Eisenstat
// The code variable names correspond to the names they used in their
// report
//
// Copyright (C) 2013 Gauthier Brun <brun.gauthier@gmail.com>
// Copyright (C) 2013 Nicolas Carre <nicolas.carre@ensimag.fr>
// Copyright (C) 2013 Jean Ceccato <jean.ceccato@ensimag.fr>
// Copyright (C) 2013 Pierre Zoppitelli <pierre.zoppitelli@ensimag.fr>
// Copyright (C) 2013 Jitse Niesen <jitse@maths.leeds.ac.uk>
// Copyright (C) 2014 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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/.
#ifndef EIGEN_BDCSVD_H
#define EIGEN_BDCSVD_H
// #define EIGEN_BDCSVD_DEBUG_VERBOSE
// #define EIGEN_BDCSVD_SANITY_CHECKS
namespace Eigen {
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
IOFormat bdcsvdfmt(8, 0, ", ", "\n", " [", "]");
#endif
template<typename _MatrixType> class BDCSVD;
namespace internal {
template<typename _MatrixType>
struct traits<BDCSVD<_MatrixType> >
{
typedef _MatrixType MatrixType;
};
} // end namespace internal
/** \ingroup SVD_Module
*
*
* \class BDCSVD
*
* \brief class Bidiagonal Divide and Conquer SVD
*
* \param MatrixType the type of the matrix of which we are computing the SVD decomposition
* We plan to have a very similar interface to JacobiSVD on this class.
* It should be used to speed up the calcul of SVD for big matrices.
*/
template<typename _MatrixType>
class BDCSVD : public SVDBase<BDCSVD<_MatrixType> >
{
typedef SVDBase<BDCSVD> Base;
public:
using Base::rows;
using Base::cols;
using Base::computeU;
using Base::computeV;
typedef _MatrixType MatrixType;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
enum {
RowsAtCompileTime = MatrixType::RowsAtCompileTime,
ColsAtCompileTime = MatrixType::ColsAtCompileTime,
DiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime, ColsAtCompileTime),
MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
MaxDiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(MaxRowsAtCompileTime, MaxColsAtCompileTime),
MatrixOptions = MatrixType::Options
};
typedef typename Base::MatrixUType MatrixUType;
typedef typename Base::MatrixVType MatrixVType;
typedef typename Base::SingularValuesType SingularValuesType;
typedef Matrix<Scalar, Dynamic, Dynamic> MatrixX;
typedef Matrix<RealScalar, Dynamic, Dynamic> MatrixXr;
typedef Matrix<RealScalar, Dynamic, 1> VectorType;
typedef Array<RealScalar, Dynamic, 1> ArrayXr;
typedef Array<Index,1,Dynamic> ArrayXi;
/** \brief Default Constructor.
*
* The default constructor is useful in cases in which the user intends to
* perform decompositions via BDCSVD::compute(const MatrixType&).
*/
BDCSVD() : m_algoswap(16), m_numIters(0)
{}
/** \brief Default Constructor with memory preallocation
*
* Like the default constructor but with preallocation of the internal data
* according to the specified problem size.
* \sa BDCSVD()
*/
BDCSVD(Index rows, Index cols, unsigned int computationOptions = 0)
: m_algoswap(16), m_numIters(0)
{
allocate(rows, cols, computationOptions);
}
/** \brief Constructor performing the decomposition of given matrix.
*
* \param matrix the matrix to decompose
* \param computationOptions optional parameter allowing to specify if you want full or thin U or V unitaries to be computed.
* By default, none is computed. This is a bit - field, the possible bits are #ComputeFullU, #ComputeThinU,
* #ComputeFullV, #ComputeThinV.
*
* Thin unitaries are only available if your matrix type has a Dynamic number of columns (for example MatrixXf). They also are not
* available with the (non - default) FullPivHouseholderQR preconditioner.
*/
BDCSVD(const MatrixType& matrix, unsigned int computationOptions = 0)
: m_algoswap(16), m_numIters(0)
{
compute(matrix, computationOptions);
}
~BDCSVD()
{
}
/** \brief Method performing the decomposition of given matrix using custom options.
*
* \param matrix the matrix to decompose
* \param computationOptions optional parameter allowing to specify if you want full or thin U or V unitaries to be computed.
* By default, none is computed. This is a bit - field, the possible bits are #ComputeFullU, #ComputeThinU,
* #ComputeFullV, #ComputeThinV.
*
* Thin unitaries are only available if your matrix type has a Dynamic number of columns (for example MatrixXf). They also are not
* available with the (non - default) FullPivHouseholderQR preconditioner.
*/
BDCSVD& compute(const MatrixType& matrix, unsigned int computationOptions);
/** \brief Method performing the decomposition of given matrix using current options.
*
* \param matrix the matrix to decompose
*
* This method uses the current \a computationOptions, as already passed to the constructor or to compute(const MatrixType&, unsigned int).
*/
BDCSVD& compute(const MatrixType& matrix)
{
return compute(matrix, this->m_computationOptions);
}
void setSwitchSize(int s)
{
eigen_assert(s>3 && "BDCSVD the size of the algo switch has to be greater than 3");
m_algoswap = s;
}
private:
void allocate(Index rows, Index cols, unsigned int computationOptions);
void divide(Index firstCol, Index lastCol, Index firstRowW, Index firstColW, Index shift);
void computeSVDofM(Index firstCol, Index n, MatrixXr& U, VectorType& singVals, MatrixXr& V);
void computeSingVals(const ArrayXr& col0, const ArrayXr& diag, const ArrayXi& perm, VectorType& singVals, ArrayXr& shifts, ArrayXr& mus);
void perturbCol0(const ArrayXr& col0, const ArrayXr& diag, const ArrayXi& perm, const VectorType& singVals, const ArrayXr& shifts, const ArrayXr& mus, ArrayXr& zhat);
void computeSingVecs(const ArrayXr& zhat, const ArrayXr& diag, const ArrayXi& perm, const VectorType& singVals, const ArrayXr& shifts, const ArrayXr& mus, MatrixXr& U, MatrixXr& V);
void deflation43(Index firstCol, Index shift, Index i, Index size);
void deflation44(Index firstColu , Index firstColm, Index firstRowW, Index firstColW, Index i, Index j, Index size);
void deflation(Index firstCol, Index lastCol, Index k, Index firstRowW, Index firstColW, Index shift);
template<typename HouseholderU, typename HouseholderV, typename NaiveU, typename NaiveV>
void copyUV(const HouseholderU &householderU, const HouseholderV &householderV, const NaiveU &naiveU, const NaiveV &naivev);
static void structured_update(Block<MatrixXr,Dynamic,Dynamic> A, const MatrixXr &B, Index n1);
static RealScalar secularEq(RealScalar x, const ArrayXr& col0, const ArrayXr& diag, const ArrayXi &perm, const ArrayXr& diagShifted, RealScalar shift);
protected:
MatrixXr m_naiveU, m_naiveV;
MatrixXr m_computed;
Index m_nRec;
int m_algoswap;
bool m_isTranspose, m_compU, m_compV;
using Base::m_singularValues;
using Base::m_diagSize;
using Base::m_computeFullU;
using Base::m_computeFullV;
using Base::m_computeThinU;
using Base::m_computeThinV;
using Base::m_matrixU;
using Base::m_matrixV;
using Base::m_isInitialized;
using Base::m_nonzeroSingularValues;
public:
int m_numIters;
}; //end class BDCSVD
// Method to allocate and initialize matrix and attributes
template<typename MatrixType>
void BDCSVD<MatrixType>::allocate(Index rows, Index cols, unsigned int computationOptions)
{
m_isTranspose = (cols > rows);
if (Base::allocate(rows, cols, computationOptions))
return;
m_computed = MatrixXr::Zero(m_diagSize + 1, m_diagSize );
m_compU = computeV();
m_compV = computeU();
if (m_isTranspose)
std::swap(m_compU, m_compV);
if (m_compU) m_naiveU = MatrixXr::Zero(m_diagSize + 1, m_diagSize + 1 );
else m_naiveU = MatrixXr::Zero(2, m_diagSize + 1 );
if (m_compV) m_naiveV = MatrixXr::Zero(m_diagSize, m_diagSize);
}// end allocate
template<typename MatrixType>
BDCSVD<MatrixType>& BDCSVD<MatrixType>::compute(const MatrixType& matrix, unsigned int computationOptions)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "\n\n\n======================================================================================================================\n\n\n";
#endif
allocate(matrix.rows(), matrix.cols(), computationOptions);
using std::abs;
//**** step -1 - If the problem is too small, directly falls back to JacobiSVD and return
if(matrix.cols() < m_algoswap)
{
JacobiSVD<MatrixType> jsvd(matrix,computationOptions);
if(computeU()) m_matrixU = jsvd.matrixU();
if(computeV()) m_matrixV = jsvd.matrixV();
m_singularValues = jsvd.singularValues();
m_nonzeroSingularValues = jsvd.nonzeroSingularValues();
m_isInitialized = true;
return *this;
}
//**** step 0 - Copy the input matrix and apply scaling to reduce over/under-flows
RealScalar scale = matrix.cwiseAbs().maxCoeff();
if(scale==RealScalar(0)) scale = RealScalar(1);
MatrixX copy;
if (m_isTranspose) copy = matrix.adjoint()/scale;
else copy = matrix/scale;
//**** step 1 - Bidiagonalization
internal::UpperBidiagonalization<MatrixX> bid(copy);
//**** step 2 - Divide & Conquer
m_naiveU.setZero();
m_naiveV.setZero();
m_computed.topRows(m_diagSize) = bid.bidiagonal().toDenseMatrix().transpose();
m_computed.template bottomRows<1>().setZero();
divide(0, m_diagSize - 1, 0, 0, 0);
//**** step 3 - Copy singular values and vectors
for (int i=0; i<m_diagSize; i++)
{
RealScalar a = abs(m_computed.coeff(i, i));
m_singularValues.coeffRef(i) = a * scale;
if (a == 0)
{
m_nonzeroSingularValues = i;
m_singularValues.tail(m_diagSize - i - 1).setZero();
break;
}
else if (i == m_diagSize - 1)
{
m_nonzeroSingularValues = i + 1;
break;
}
}
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
// std::cout << "m_naiveU\n" << m_naiveU << "\n\n";
// std::cout << "m_naiveV\n" << m_naiveV << "\n\n";
#endif
if(m_isTranspose) copyUV(bid.householderV(), bid.householderU(), m_naiveV, m_naiveU);
else copyUV(bid.householderU(), bid.householderV(), m_naiveU, m_naiveV);
m_isInitialized = true;
return *this;
}// end compute
template<typename MatrixType>
template<typename HouseholderU, typename HouseholderV, typename NaiveU, typename NaiveV>
void BDCSVD<MatrixType>::copyUV(const HouseholderU &householderU, const HouseholderV &householderV, const NaiveU &naiveU, const NaiveV &naiveV)
{
// Note exchange of U and V: m_matrixU is set from m_naiveV and vice versa
if (computeU())
{
Index Ucols = m_computeThinU ? m_diagSize : householderU.cols();
m_matrixU = MatrixX::Identity(householderU.cols(), Ucols);
m_matrixU.topLeftCorner(m_diagSize, m_diagSize) = naiveV.template cast<Scalar>().topLeftCorner(m_diagSize, m_diagSize);
householderU.applyThisOnTheLeft(m_matrixU);
}
if (computeV())
{
Index Vcols = m_computeThinV ? m_diagSize : householderV.cols();
m_matrixV = MatrixX::Identity(householderV.cols(), Vcols);
m_matrixV.topLeftCorner(m_diagSize, m_diagSize) = naiveU.template cast<Scalar>().topLeftCorner(m_diagSize, m_diagSize);
householderV.applyThisOnTheLeft(m_matrixV);
}
}
/** \internal
* Performs A = A * B exploiting the special structure of the matrix A. Splitting A as:
* A = [A1]
* [A2]
* such that A1.rows()==n1, then we assume that at least half of the columns of A1 and A2 are zeros.
* We can thus pack them prior to the the matrix product. However, this is only worth the effort if the matrix is large
* enough.
*/
template<typename MatrixType>
void BDCSVD<MatrixType>::structured_update(Block<MatrixXr,Dynamic,Dynamic> A, const MatrixXr &B, Index n1)
{
Index n = A.rows();
if(n>100)
{
// If the matrices are large enough, let's exploit the sparse structure of A by
// splitting it in half (wrt n1), and packing the non-zero columns.
Index n2 = n - n1;
MatrixXr A1(n1,n), A2(n2,n), B1(n,n), B2(n,n);
Index k1=0, k2=0;
for(Index j=0; j<n; ++j)
{
if( (A.col(j).head(n1).array()!=0).any() )
{
A1.col(k1) = A.col(j).head(n1);
B1.row(k1) = B.row(j);
++k1;
}
if( (A.col(j).tail(n2).array()!=0).any() )
{
A2.col(k2) = A.col(j).tail(n2);
B2.row(k2) = B.row(j);
++k2;
}
}
A.topRows(n1).noalias() = A1.leftCols(k1) * B1.topRows(k1);
A.bottomRows(n2).noalias() = A2.leftCols(k2) * B2.topRows(k2);
}
else
A *= B; // FIXME this requires a temporary
}
// The divide algorithm is done "in place", we are always working on subsets of the same matrix. The divide methods takes as argument the
// place of the submatrix we are currently working on.
//@param firstCol : The Index of the first column of the submatrix of m_computed and for m_naiveU;
//@param lastCol : The Index of the last column of the submatrix of m_computed and for m_naiveU;
// lastCol + 1 - firstCol is the size of the submatrix.
//@param firstRowW : The Index of the first row of the matrix W that we are to change. (see the reference paper section 1 for more information on W)
//@param firstRowW : Same as firstRowW with the column.
//@param shift : Each time one takes the left submatrix, one must add 1 to the shift. Why? Because! We actually want the last column of the U submatrix
// to become the first column (*coeff) and to shift all the other columns to the right. There are more details on the reference paper.
template<typename MatrixType>
void BDCSVD<MatrixType>::divide (Index firstCol, Index lastCol, Index firstRowW, Index firstColW, Index shift)
{
// requires nbRows = nbCols + 1;
using std::pow;
using std::sqrt;
using std::abs;
const Index n = lastCol - firstCol + 1;
const Index k = n/2;
RealScalar alphaK;
RealScalar betaK;
RealScalar r0;
RealScalar lambda, phi, c0, s0;
VectorType l, f;
// We use the other algorithm which is more efficient for small
// matrices.
if (n < m_algoswap)
{
JacobiSVD<MatrixXr> b(m_computed.block(firstCol, firstCol, n + 1, n), ComputeFullU | (m_compV ? ComputeFullV : 0)) ;
if (m_compU)
m_naiveU.block(firstCol, firstCol, n + 1, n + 1).real() = b.matrixU();
else
{
m_naiveU.row(0).segment(firstCol, n + 1).real() = b.matrixU().row(0);
m_naiveU.row(1).segment(firstCol, n + 1).real() = b.matrixU().row(n);
}
if (m_compV) m_naiveV.block(firstRowW, firstColW, n, n).real() = b.matrixV();
m_computed.block(firstCol + shift, firstCol + shift, n + 1, n).setZero();
m_computed.diagonal().segment(firstCol + shift, n) = b.singularValues().head(n);
return;
}
// We use the divide and conquer algorithm
alphaK = m_computed(firstCol + k, firstCol + k);
betaK = m_computed(firstCol + k + 1, firstCol + k);
// The divide must be done in that order in order to have good results. Divide change the data inside the submatrices
// and the divide of the right submatrice reads one column of the left submatrice. That's why we need to treat the
// right submatrix before the left one.
divide(k + 1 + firstCol, lastCol, k + 1 + firstRowW, k + 1 + firstColW, shift);
divide(firstCol, k - 1 + firstCol, firstRowW, firstColW + 1, shift + 1);
if (m_compU)
{
lambda = m_naiveU(firstCol + k, firstCol + k);
phi = m_naiveU(firstCol + k + 1, lastCol + 1);
}
else
{
lambda = m_naiveU(1, firstCol + k);
phi = m_naiveU(0, lastCol + 1);
}
r0 = sqrt((abs(alphaK * lambda) * abs(alphaK * lambda)) + abs(betaK * phi) * abs(betaK * phi));
if (m_compU)
{
l = m_naiveU.row(firstCol + k).segment(firstCol, k);
f = m_naiveU.row(firstCol + k + 1).segment(firstCol + k + 1, n - k - 1);
}
else
{
l = m_naiveU.row(1).segment(firstCol, k);
f = m_naiveU.row(0).segment(firstCol + k + 1, n - k - 1);
}
if (m_compV) m_naiveV(firstRowW+k, firstColW) = 1;
if (r0 == 0)
{
c0 = 1;
s0 = 0;
}
else
{
c0 = alphaK * lambda / r0;
s0 = betaK * phi / r0;
}
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
if (m_compU)
{
MatrixXr q1 (m_naiveU.col(firstCol + k).segment(firstCol, k + 1));
// we shiftW Q1 to the right
for (Index i = firstCol + k - 1; i >= firstCol; i--)
m_naiveU.col(i + 1).segment(firstCol, k + 1) = m_naiveU.col(i).segment(firstCol, k + 1);
// we shift q1 at the left with a factor c0
m_naiveU.col(firstCol).segment( firstCol, k + 1) = (q1 * c0);
// last column = q1 * - s0
m_naiveU.col(lastCol + 1).segment(firstCol, k + 1) = (q1 * ( - s0));
// first column = q2 * s0
m_naiveU.col(firstCol).segment(firstCol + k + 1, n - k) = m_naiveU.col(lastCol + 1).segment(firstCol + k + 1, n - k) * s0;
// q2 *= c0
m_naiveU.col(lastCol + 1).segment(firstCol + k + 1, n - k) *= c0;
}
else
{
RealScalar q1 = m_naiveU(0, firstCol + k);
// we shift Q1 to the right
for (Index i = firstCol + k - 1; i >= firstCol; i--)
m_naiveU(0, i + 1) = m_naiveU(0, i);
// we shift q1 at the left with a factor c0
m_naiveU(0, firstCol) = (q1 * c0);
// last column = q1 * - s0
m_naiveU(0, lastCol + 1) = (q1 * ( - s0));
// first column = q2 * s0
m_naiveU(1, firstCol) = m_naiveU(1, lastCol + 1) *s0;
// q2 *= c0
m_naiveU(1, lastCol + 1) *= c0;
m_naiveU.row(1).segment(firstCol + 1, k).setZero();
m_naiveU.row(0).segment(firstCol + k + 1, n - k - 1).setZero();
}
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
m_computed(firstCol + shift, firstCol + shift) = r0;
m_computed.col(firstCol + shift).segment(firstCol + shift + 1, k) = alphaK * l.transpose().real();
m_computed.col(firstCol + shift).segment(firstCol + shift + k + 1, n - k - 1) = betaK * f.transpose().real();
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
ArrayXr tmp1 = (m_computed.block(firstCol+shift, firstCol+shift, n, n)).jacobiSvd().singularValues();
#endif
// Second part: try to deflate singular values in combined matrix
deflation(firstCol, lastCol, k, firstRowW, firstColW, shift);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
ArrayXr tmp2 = (m_computed.block(firstCol+shift, firstCol+shift, n, n)).jacobiSvd().singularValues();
std::cout << "\n\nj1 = " << tmp1.transpose().format(bdcsvdfmt) << "\n";
std::cout << "j2 = " << tmp2.transpose().format(bdcsvdfmt) << "\n\n";
std::cout << "err: " << ((tmp1-tmp2).abs()>1e-12*tmp2.abs()).transpose() << "\n";
static int count = 0;
std::cout << "# " << ++count << "\n\n";
assert((tmp1-tmp2).matrix().norm() < 1e-14*tmp2.matrix().norm());
// assert(count<681);
// assert(((tmp1-tmp2).abs()<1e-13*tmp2.abs()).all());
#endif
// Third part: compute SVD of combined matrix
MatrixXr UofSVD, VofSVD;
VectorType singVals;
computeSVDofM(firstCol + shift, n, UofSVD, singVals, VofSVD);
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(UofSVD.allFinite());
assert(VofSVD.allFinite());
#endif
if (m_compU) structured_update(m_naiveU.block(firstCol, firstCol, n + 1, n + 1), UofSVD, (n+2)/2);
else m_naiveU.middleCols(firstCol, n + 1) *= UofSVD; // FIXME this requires a temporary, and exploit that there are 2 rows at compile time
if (m_compV) structured_update(m_naiveV.block(firstRowW, firstColW, n, n), VofSVD, (n+1)/2);
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
m_computed.block(firstCol + shift, firstCol + shift, n, n).setZero();
m_computed.block(firstCol + shift, firstCol + shift, n, n).diagonal() = singVals;
}// end divide
// Compute SVD of m_computed.block(firstCol, firstCol, n + 1, n); this block only has non-zeros in
// the first column and on the diagonal and has undergone deflation, so diagonal is in increasing
// order except for possibly the (0,0) entry. The computed SVD is stored U, singVals and V, except
// that if m_compV is false, then V is not computed. Singular values are sorted in decreasing order.
//
// TODO Opportunities for optimization: better root finding algo, better stopping criterion, better
// handling of round-off errors, be consistent in ordering
// For instance, to solve the secular equation using FMM, see http://www.stat.uchicago.edu/~lekheng/courses/302/classics/greengard-rokhlin.pdf
template <typename MatrixType>
void BDCSVD<MatrixType>::computeSVDofM(Index firstCol, Index n, MatrixXr& U, VectorType& singVals, MatrixXr& V)
{
// TODO Get rid of these copies (?)
// FIXME at least preallocate them
ArrayXr col0 = m_computed.col(firstCol).segment(firstCol, n);
ArrayXr diag = m_computed.block(firstCol, firstCol, n, n).diagonal();
diag(0) = 0;
// Allocate space for singular values and vectors
singVals.resize(n);
U.resize(n+1, n+1);
if (m_compV) V.resize(n, n);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
if (col0.hasNaN() || diag.hasNaN())
std::cout << "\n\nHAS NAN\n\n";
#endif
// Many singular values might have been deflated, the zero ones have been moved to the end,
// but others are interleaved and we must ignore them at this stage.
// To this end, let's compute a permutation skipping them:
Index actual_n = n;
while(actual_n>1 && diag(actual_n-1)==0) --actual_n;
Index m = 0; // size of the deflated problem
ArrayXi perm(actual_n);
for(Index k=0;k<actual_n;++k)
if(col0(k)!=0)
perm(m++) = k;
perm.conservativeResize(m);
ArrayXr shifts(n), mus(n), zhat(n);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "computeSVDofM using:\n";
std::cout << " z: " << col0.transpose() << "\n";
std::cout << " d: " << diag.transpose() << "\n";
#endif
// Compute singVals, shifts, and mus
computeSingVals(col0, diag, perm, singVals, shifts, mus);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << " j: " << (m_computed.block(firstCol, firstCol, n, n)).jacobiSvd().singularValues().transpose().reverse() << "\n\n";
std::cout << " sing-val: " << singVals.transpose() << "\n";
std::cout << " mu: " << mus.transpose() << "\n";
std::cout << " shift: " << shifts.transpose() << "\n";
{
Index actual_n = n;
while(actual_n>1 && col0(actual_n-1)==0) --actual_n;
std::cout << "\n\n mus: " << mus.head(actual_n).transpose() << "\n\n";
std::cout << " check1 (expect0) : " << ((singVals.array()-(shifts+mus)) / singVals.array()).head(actual_n).transpose() << "\n\n";
std::cout << " check2 (>0) : " << ((singVals.array()-diag) / singVals.array()).head(actual_n).transpose() << "\n\n";
std::cout << " check3 (>0) : " << ((diag.segment(1,actual_n-1)-singVals.head(actual_n-1).array()) / singVals.head(actual_n-1).array()).transpose() << "\n\n\n";
std::cout << " check4 (>0) : " << ((singVals.segment(1,actual_n-1)-singVals.head(actual_n-1))).transpose() << "\n\n\n";
}
#endif
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(singVals.allFinite());
assert(mus.allFinite());
assert(shifts.allFinite());
#endif
// Compute zhat
perturbCol0(col0, diag, perm, singVals, shifts, mus, zhat);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << " zhat: " << zhat.transpose() << "\n";
#endif
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(zhat.allFinite());
#endif
computeSingVecs(zhat, diag, perm, singVals, shifts, mus, U, V);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "U^T U: " << (U.transpose() * U - MatrixXr(MatrixXr::Identity(U.cols(),U.cols()))).norm() << "\n";
std::cout << "V^T V: " << (V.transpose() * V - MatrixXr(MatrixXr::Identity(V.cols(),V.cols()))).norm() << "\n";
#endif
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(U.allFinite());
assert(V.allFinite());
assert((U.transpose() * U - MatrixXr(MatrixXr::Identity(U.cols(),U.cols()))).norm() < 1e-14 * n);
assert((V.transpose() * V - MatrixXr(MatrixXr::Identity(V.cols(),V.cols()))).norm() < 1e-14 * n);
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
// Because of deflation, the singular values might not be completely sorted.
// Fortunately, reordering them is a O(n) problem
for(Index i=0; i<actual_n-1; ++i)
{
if(singVals(i)>singVals(i+1))
{
using std::swap;
swap(singVals(i),singVals(i+1));
U.col(i).swap(U.col(i+1));
if(m_compV) V.col(i).swap(V.col(i+1));
}
}
// Reverse order so that singular values in increased order
// Because of deflation, the zeros singular-values are already at the end
singVals.head(actual_n).reverseInPlace();
U.leftCols(actual_n) = U.leftCols(actual_n).rowwise().reverse().eval(); // FIXME this requires a temporary
if (m_compV) V.leftCols(actual_n) = V.leftCols(actual_n).rowwise().reverse().eval(); // FIXME this requires a temporary
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
JacobiSVD<MatrixXr> jsvd(m_computed.block(firstCol, firstCol, n, n) );
std::cout << " * j: " << jsvd.singularValues().transpose() << "\n\n";
std::cout << " * sing-val: " << singVals.transpose() << "\n";
// std::cout << " * err: " << ((jsvd.singularValues()-singVals)>1e-13*singVals.norm()).transpose() << "\n";
#endif
}
template <typename MatrixType>
typename BDCSVD<MatrixType>::RealScalar BDCSVD<MatrixType>::secularEq(RealScalar mu, const ArrayXr& col0, const ArrayXr& diag, const ArrayXi &perm, const ArrayXr& diagShifted, RealScalar shift)
{
Index m = perm.size();
RealScalar res = 1;
for(Index i=0; i<m; ++i)
{
Index j = perm(i);
res += numext::abs2(col0(j)) / ((diagShifted(j) - mu) * (diag(j) + shift + mu));
}
return res;
}
template <typename MatrixType>
void BDCSVD<MatrixType>::computeSingVals(const ArrayXr& col0, const ArrayXr& diag, const ArrayXi &perm,
VectorType& singVals, ArrayXr& shifts, ArrayXr& mus)
{
using std::abs;
using std::swap;
Index n = col0.size();
Index actual_n = n;
while(actual_n>1 && col0(actual_n-1)==0) --actual_n;
for (Index k = 0; k < n; ++k)
{
if (col0(k) == 0 || actual_n==1)
{
// if col0(k) == 0, then entry is deflated, so singular value is on diagonal
// if actual_n==1, then the deflated problem is already diagonalized
singVals(k) = k==0 ? col0(0) : diag(k);
mus(k) = 0;
shifts(k) = k==0 ? col0(0) : diag(k);
continue;
}
// otherwise, use secular equation to find singular value
RealScalar left = diag(k);
RealScalar right; // was: = (k != actual_n-1) ? diag(k+1) : (diag(actual_n-1) + col0.matrix().norm());
if(k==actual_n-1)
right = (diag(actual_n-1) + col0.matrix().norm());
else
{
// Skip deflated singular values
Index l = k+1;
while(col0(l)==0) { ++l; eigen_internal_assert(l<actual_n); }
right = diag(l);
}
// first decide whether it's closer to the left end or the right end
RealScalar mid = left + (right-left) / 2;
RealScalar fMid = secularEq(mid, col0, diag, perm, diag, 0);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << right-left << "\n";
std::cout << "fMid = " << fMid << " " << secularEq(mid-left, col0, diag, perm, diag-left, left) << " " << secularEq(mid-right, col0, diag, perm, diag-right, right) << "\n";
std::cout << " = " << secularEq(0.1*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.2*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.3*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.4*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.49*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.5*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.51*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.6*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.7*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.8*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.9*(left+right), col0, diag, perm, diag, 0) << "\n";
#endif
RealScalar shift = (k == actual_n-1 || fMid > 0) ? left : right;
// measure everything relative to shift
ArrayXr diagShifted = diag - shift;
// initial guess
RealScalar muPrev, muCur;
if (shift == left)
{
muPrev = (right - left) * 0.1;
if (k == actual_n-1) muCur = right - left;
else muCur = (right - left) * 0.5;
}
else
{
muPrev = -(right - left) * 0.1;
muCur = -(right - left) * 0.5;
}
RealScalar fPrev = secularEq(muPrev, col0, diag, perm, diagShifted, shift);
RealScalar fCur = secularEq(muCur, col0, diag, perm, diagShifted, shift);
if (abs(fPrev) < abs(fCur))
{
swap(fPrev, fCur);
swap(muPrev, muCur);
}
// rational interpolation: fit a function of the form a / mu + b through the two previous
// iterates and use its zero to compute the next iterate
bool useBisection = fPrev*fCur>0;
while (fCur!=0 && abs(muCur - muPrev) > 8 * NumTraits<RealScalar>::epsilon() * numext::maxi(abs(muCur), abs(muPrev)) && abs(fCur - fPrev)>NumTraits<RealScalar>::epsilon() && !useBisection)
{
++m_numIters;
// Find a and b such that the function f(mu) = a / mu + b matches the current and previous samples.
RealScalar a = (fCur - fPrev) / (1/muCur - 1/muPrev);
RealScalar b = fCur - a / muCur;
// And find mu such that f(mu)==0:
RealScalar muZero = -a/b;
RealScalar fZero = secularEq(muZero, col0, diag, perm, diagShifted, shift);
muPrev = muCur;
fPrev = fCur;
muCur = muZero;
fCur = fZero;
if (shift == left && (muCur < 0 || muCur > right - left)) useBisection = true;
if (shift == right && (muCur < -(right - left) || muCur > 0)) useBisection = true;
if (abs(fCur)>abs(fPrev)) useBisection = true;
}
// fall back on bisection method if rational interpolation did not work
if (useBisection)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "useBisection for k = " << k << ", actual_n = " << actual_n << "\n";
#endif
RealScalar leftShifted, rightShifted;
if (shift == left)
{
leftShifted = RealScalar(1)/NumTraits<RealScalar>::highest();
// I don't understand why the case k==0 would be special there:
// if (k == 0) rightShifted = right - left; else
rightShifted = (k==actual_n-1) ? right : ((right - left) * 0.6); // theoretically we can take 0.5, but let's be safe
}
else
{
leftShifted = -(right - left) * 0.6;
rightShifted = -RealScalar(1)/NumTraits<RealScalar>::highest();
}
RealScalar fLeft = secularEq(leftShifted, col0, diag, perm, diagShifted, shift);
RealScalar fRight = secularEq(rightShifted, col0, diag, perm, diagShifted, shift);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
if(!(fLeft * fRight<0))
std::cout << k << " : " << fLeft << " * " << fRight << " == " << fLeft * fRight << " ; " << left << " - " << right << " -> " << leftShifted << " " << rightShifted << " shift=" << shift << "\n";
#endif
eigen_internal_assert(fLeft * fRight < 0);
while (rightShifted - leftShifted > 2 * NumTraits<RealScalar>::epsilon() * numext::maxi(abs(leftShifted), abs(rightShifted)))
{
RealScalar midShifted = (leftShifted + rightShifted) / 2;
RealScalar fMid = secularEq(midShifted, col0, diag, perm, diagShifted, shift);
if (fLeft * fMid < 0)
{
rightShifted = midShifted;
fRight = fMid;
}
else
{
leftShifted = midShifted;
fLeft = fMid;
}
}
muCur = (leftShifted + rightShifted) / 2;
}
singVals[k] = shift + muCur;
shifts[k] = shift;
mus[k] = muCur;
// perturb singular value slightly if it equals diagonal entry to avoid division by zero later
// (deflation is supposed to avoid this from happening)
// - this does no seem to be necessary anymore -
// if (singVals[k] == left) singVals[k] *= 1 + NumTraits<RealScalar>::epsilon();
// if (singVals[k] == right) singVals[k] *= 1 - NumTraits<RealScalar>::epsilon();
}
}
// zhat is perturbation of col0 for which singular vectors can be computed stably (see Section 3.1)
template <typename MatrixType>
void BDCSVD<MatrixType>::perturbCol0
(const ArrayXr& col0, const ArrayXr& diag, const ArrayXi &perm, const VectorType& singVals,
const ArrayXr& shifts, const ArrayXr& mus, ArrayXr& zhat)
{
using std::sqrt;
Index n = col0.size();
Index m = perm.size();
if(m==0)
{
zhat.setZero();
return;
}
Index last = perm(m-1);
// The offset permits to skip deflated entries while computing zhat
for (Index k = 0; k < n; ++k)
{
if (col0(k) == 0) // deflated
zhat(k) = 0;
else
{
// see equation (3.6)
RealScalar dk = diag(k);
RealScalar prod = (singVals(last) + dk) * (mus(last) + (shifts(last) - dk));
for(Index l = 0; l<m; ++l)
{
Index i = perm(l);
if(i!=k)
{
Index j = i<k ? i : perm(l-1);
prod *= ((singVals(j)+dk) / ((diag(i)+dk))) * ((mus(j)+(shifts(j)-dk)) / ((diag(i)-dk)));
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
if(i!=k && std::abs(((singVals(j)+dk)*(mus(j)+(shifts(j)-dk)))/((diag(i)+dk)*(diag(i)-dk)) - 1) > 0.9 )
std::cout << " " << ((singVals(j)+dk)*(mus(j)+(shifts(j)-dk)))/((diag(i)+dk)*(diag(i)-dk)) << " == (" << (singVals(j)+dk) << " * " << (mus(j)+(shifts(j)-dk))
<< ") / (" << (diag(i)+dk) << " * " << (diag(i)-dk) << ")\n";
#endif
}
}
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "zhat(" << k << ") = sqrt( " << prod << ") ; " << (singVals(last) + dk) << " * " << mus(last) + shifts(last) << " - " << dk << "\n";
#endif
RealScalar tmp = sqrt(prod);
zhat(k) = col0(k) > 0 ? tmp : -tmp;
}
}
}
// compute singular vectors
template <typename MatrixType>
void BDCSVD<MatrixType>::computeSingVecs
(const ArrayXr& zhat, const ArrayXr& diag, const ArrayXi &perm, const VectorType& singVals,
const ArrayXr& shifts, const ArrayXr& mus, MatrixXr& U, MatrixXr& V)
{
Index n = zhat.size();
Index m = perm.size();
for (Index k = 0; k < n; ++k)
{
if (zhat(k) == 0)
{
U.col(k) = VectorType::Unit(n+1, k);
if (m_compV) V.col(k) = VectorType::Unit(n, k);
}
else
{
U.col(k).setZero();
for(Index l=0;l<m;++l)
{
Index i = perm(l);
U(i,k) = zhat(i)/(((diag(i) - shifts(k)) - mus(k)) )/( (diag(i) + singVals[k]));
}
U(n,k) = 0;
U.col(k).normalize();
if (m_compV)
{
V.col(k).setZero();
for(Index l=1;l<m;++l)
{
Index i = perm(l);
V(i,k) = diag(i) * zhat(i) / (((diag(i) - shifts(k)) - mus(k)) )/( (diag(i) + singVals[k]));
}
V(0,k) = -1;
V.col(k).normalize();
}
}
}
U.col(n) = VectorType::Unit(n+1, n);
}
// page 12_13
// i >= 1, di almost null and zi non null.
// We use a rotation to zero out zi applied to the left of M
template <typename MatrixType>
void BDCSVD<MatrixType>::deflation43(Index firstCol, Index shift, Index i, Index size)
{
using std::abs;
using std::sqrt;
using std::pow;
Index start = firstCol + shift;
RealScalar c = m_computed(start, start);
RealScalar s = m_computed(start+i, start);
RealScalar r = sqrt(numext::abs2(c) + numext::abs2(s));
if (r == 0)
{
m_computed(start+i, start+i) = 0;
return;
}
m_computed(start,start) = r;
m_computed(start+i, start) = 0;
m_computed(start+i, start+i) = 0;
JacobiRotation<RealScalar> J(c/r,-s/r);
if (m_compU) m_naiveU.middleRows(firstCol, size+1).applyOnTheRight(firstCol, firstCol+i, J);
else m_naiveU.applyOnTheRight(firstCol, firstCol+i, J);
}// end deflation 43
// page 13
// i,j >= 1, i!=j and |di - dj| < epsilon * norm2(M)
// We apply two rotations to have zj = 0;
// TODO deflation44 is still broken and not properly tested
template <typename MatrixType>
void BDCSVD<MatrixType>::deflation44(Index firstColu , Index firstColm, Index firstRowW, Index firstColW, Index i, Index j, Index size)
{
using std::abs;
using std::sqrt;
using std::conj;
using std::pow;
RealScalar c = m_computed(firstColm+i, firstColm);
RealScalar s = m_computed(firstColm+j, firstColm);
RealScalar r = sqrt(numext::abs2(c) + numext::abs2(s));
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.4: " << i << "," << j << " -> " << c << " " << s << " " << r << " ; "
<< m_computed(firstColm + i-1, firstColm) << " "
<< m_computed(firstColm + i, firstColm) << " "
<< m_computed(firstColm + i+1, firstColm) << " "
<< m_computed(firstColm + i+2, firstColm) << "\n";
std::cout << m_computed(firstColm + i-1, firstColm + i-1) << " "
<< m_computed(firstColm + i, firstColm+i) << " "
<< m_computed(firstColm + i+1, firstColm+i+1) << " "
<< m_computed(firstColm + i+2, firstColm+i+2) << "\n";
#endif
if (r==0)
{
m_computed(firstColm + i, firstColm + i) = m_computed(firstColm + j, firstColm + j);
return;
}
c/=r;
s/=r;
m_computed(firstColm + i, firstColm) = r;
m_computed(firstColm + j, firstColm + j) = m_computed(firstColm + i, firstColm + i);
m_computed(firstColm + j, firstColm) = 0;
JacobiRotation<RealScalar> J(c,-s);
if (m_compU) m_naiveU.middleRows(firstColu, size+1).applyOnTheRight(firstColu + i, firstColu + j, J);
else m_naiveU.applyOnTheRight(firstColu+i, firstColu+j, J);
if (m_compV) m_naiveV.middleRows(firstRowW, size).applyOnTheRight(firstColW + i, firstColW + j, J);
}// end deflation 44
// acts on block from (firstCol+shift, firstCol+shift) to (lastCol+shift, lastCol+shift) [inclusive]
template <typename MatrixType>
void BDCSVD<MatrixType>::deflation(Index firstCol, Index lastCol, Index k, Index firstRowW, Index firstColW, Index shift)
{
using std::sqrt;
using std::abs;
const Index length = lastCol + 1 - firstCol;
Block<MatrixXr,Dynamic,1> col0(m_computed, firstCol+shift, firstCol+shift, length, 1);
Diagonal<MatrixXr> fulldiag(m_computed);
VectorBlock<Diagonal<MatrixXr>,Dynamic> diag(fulldiag, firstCol+shift, length);
RealScalar maxDiag = diag.tail((std::max)(Index(1),length-1)).cwiseAbs().maxCoeff();
RealScalar epsilon_strict = NumTraits<RealScalar>::epsilon() * maxDiag;
RealScalar epsilon_coarse = 8 * NumTraits<RealScalar>::epsilon() * numext::maxi(col0.cwiseAbs().maxCoeff(), maxDiag);
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "\ndeflate:" << diag.head(k+1).transpose() << " | " << diag.segment(k+1,length-k-1).transpose() << "\n";
#endif
//condition 4.1
if (diag(0) < epsilon_coarse)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.1, because " << diag(0) << " < " << epsilon_coarse << "\n";
#endif
diag(0) = epsilon_coarse;
}
//condition 4.2
for (Index i=1;i<length;++i)
if (abs(col0(i)) < epsilon_strict)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.2, set z(" << i << ") to zero because " << abs(col0(i)) << " < " << epsilon_strict << " (diag(" << i << ")=" << diag(i) << ")\n";
#endif
col0(i) = 0;
}
//condition 4.3
for (Index i=1;i<length; i++)
if (diag(i) < epsilon_coarse)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.3, cancel z(" << i << ")=" << col0(i) << " because diag(" << i << ")=" << diag(i) << " < " << epsilon_coarse << "\n";
#endif
deflation43(firstCol, shift, i, length);
}
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "to be sorted: " << diag.transpose() << "\n\n";
#endif
{
// Check for total deflation
// If we have a total deflation, then we have to consider col0(0)==diag(0) as a singular value during sorting
bool total_deflation = (col0.tail(length-1).array()==RealScalar(0)).all();
// Sort the diagonal entries, since diag(1:k-1) and diag(k:length) are already sorted, let's do a sorted merge.
// First, compute the respective permutation.
Index *permutation = new Index[length]; // FIXME avoid repeated dynamic memory allocation
{
permutation[0] = 0;
Index p = 1;
// Move deflated diagonal entries at the end.
for(Index i=1; i<length; ++i)
if(diag(i)==0)
permutation[p++] = i;
Index i=1, j=k+1;
for( ; p < length; ++p)
{
if (i > k) permutation[p] = j++;
else if (j >= length) permutation[p] = i++;
else if (diag(i) < diag(j)) permutation[p] = j++;
else permutation[p] = i++;
}
}
// If we have a total deflation, then we have to insert diag(0) at the right place
if(total_deflation)
{
for(Index i=1; i<length; ++i)
{
Index pi = permutation[i];
if(diag(pi)==0 || diag(0)<diag(pi))
permutation[i-1] = permutation[i];
else
{
permutation[i-1] = 0;
break;
}
}
}
// Current index of each col, and current column of each index
Index *realInd = new Index[length]; // FIXME avoid repeated dynamic memory allocation
Index *realCol = new Index[length]; // FIXME avoid repeated dynamic memory allocation
for(int pos = 0; pos< length; pos++)
{
realCol[pos] = pos;
realInd[pos] = pos;
}
for(Index i = total_deflation?0:1; i < length; i++)
{
const Index pi = permutation[length - (total_deflation ? i+1 : i)];
const Index J = realCol[pi];
using std::swap;
// swap diagonal and first column entries:
swap(diag(i), diag(J));
if(i!=0 && J!=0) swap(col0(i), col0(J));
// change columns
if (m_compU) m_naiveU.col(firstCol+i).segment(firstCol, length + 1).swap(m_naiveU.col(firstCol+J).segment(firstCol, length + 1));
else m_naiveU.col(firstCol+i).segment(0, 2) .swap(m_naiveU.col(firstCol+J).segment(0, 2));
if (m_compV) m_naiveV.col(firstColW + i).segment(firstRowW, length).swap(m_naiveV.col(firstColW + J).segment(firstRowW, length));
//update real pos
const Index realI = realInd[i];
realCol[realI] = J;
realCol[pi] = i;
realInd[J] = realI;
realInd[i] = pi;
}
delete[] permutation;
delete[] realInd;
delete[] realCol;
}
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "sorted: " << diag.transpose().format(bdcsvdfmt) << "\n";
std::cout << " : " << col0.transpose() << "\n\n";
#endif
//condition 4.4
{
Index i = length-1;
while(i>0 && (diag(i)==0 || col0(i)==0)) --i;
for(; i>1;--i)
if( (diag(i) - diag(i-1)) < NumTraits<RealScalar>::epsilon()*maxDiag )
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.4 with i = " << i << " because " << (diag(i) - diag(i-1)) << " < " << NumTraits<RealScalar>::epsilon()*diag(i) << "\n";
#endif
eigen_internal_assert(abs(diag(i) - diag(i-1))<epsilon_coarse && " diagonal entries are not properly sorted");
deflation44(firstCol, firstCol + shift, firstRowW, firstColW, i-1, i, length);
}
}
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
for(Index j=2;j<length;++j)
assert(diag(j-1)<=diag(j) || diag(j)==0);
#endif
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
}//end deflation
#ifndef __CUDACC__
/** \svd_module
*
* \return the singular value decomposition of \c *this computed by Divide & Conquer algorithm
*
* \sa class BDCSVD
*/
template<typename Derived>
BDCSVD<typename MatrixBase<Derived>::PlainObject>
MatrixBase<Derived>::bdcSvd(unsigned int computationOptions) const
{
return BDCSVD<PlainObject>(*this, computationOptions);
}
#endif
} // end namespace Eigen
#endif
| [
"pochemuto@gmail.com"
] | pochemuto@gmail.com |
7c81584c5605163173fdf2afaff8c5f4c8732bc6 | 64573adcf26a4d94d4a84cb44cde3290868872e8 | /Tests/socket.h | c595433abadab5d940e2673b7d58040fe48bb019 | [] | no_license | vinhphuctadang/Reuse | 8cde3e57b5b7df5f3c948515ae0c5e6474d6cbcf | 272ea15f9fc9e51e344da80558815f68668ac9e7 | refs/heads/master | 2020-05-07T14:24:17.906398 | 2020-02-01T06:43:43 | 2020-02-01T06:43:43 | 180,592,839 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,042 | h | #ifndef SOCKETCPP_H
#define SOCKETCPP_H
#define WIN32_LEAN_AND_MEAN
#include <string>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <mutex>
#include "StringUtils.h"
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
//#define DEFAULT_PORT "27015"
using namespace std;
class CodeException : public exception {
protected:
string information;
int errCode;
public:
CodeException (const string& __information, int __errCode) : information (__information), errCode(__errCode) {
}
string getInformation () {
return information;
}
int getErrCode () {
return errCode;
}
const char * what () const throw () {
string result = information + ".Code=" + toString ((long long) errCode);
return result.c_str();
}
};
class Socket {
private:
addrinfo *result = NULL;
addrinfo hints;
SOCKET ListenSocket = INVALID_SOCKET;
mutex secure;
public:
static void initialize ();
static void finalize ();
// static string GetHostName (int bufferSize=255);
Socket(int family=AF_INET, int type=SOCK_STREAM, int proto=0, int fileno=AI_PASSIVE);
Socket(SOCKET socket);
// Socket(SOCKET socket);
// Socket();
void Bind (string addr, int port);
void Listen (int number=SOMAXCONN);
Socket* Accept ();
void Close();
int Connect(string addr, int port, ull timeOut=0);
void lock ();
void unlock ();
void Send(char* buffer, int bufferSize);
// void send(std::istream &stream);
int Receive(char* buffer, int bufferSize=1024, ull timeOut = 0);
// operator Socket& =(Socket& socket);
};
WSAData wsaData;
#include "socket.cpp"
#endif
| [
"noreply@github.com"
] | vinhphuctadang.noreply@github.com |
8b0df76c33486f7c17f8d577c79b0784d72f0d78 | 3433813671624fa5bb0a8a43ed9ae4f62c8ebb6f | /QuestionSet/VirtualJudge/ShortestPath/TiltheCowsComeHome.cpp | 37e0c8b837ecf53cdd94f714fa3cf6a20dbad71e | [] | no_license | Devildyw/DSA | d4310c6c7ce9eab4ab7897419e5a91f115ee6b9e | 969e62264fab5ecf15852895ce74973b13ce477d | refs/heads/main | 2023-08-29T21:41:33.202543 | 2021-10-30T15:44:14 | 2021-10-30T15:44:14 | 423,408,758 | 1 | 0 | null | 2021-11-01T09:35:19 | 2021-11-01T09:35:19 | null | UTF-8 | C++ | false | false | 1,404 | cpp | /*
* @Author: FANG
* @Date: 2021-08-22 23:25:42
* @LastEditTime: 2021-08-23 12:43:59
* @Description: https://vjudge.ppsucxtt.cn/problem/POJ-2387
* @FilePath: \DSA\QuestionSet\VirtualJudge\ShortestPath\TiltheCowsComeHome.cpp
*/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1e4 + 5;
struct Edge {
int to;
int w;
int next;
} edge[N];
int head[N], cnt, dis[N], t, n;
bool vis[N];
void add(int u, int v, int w) {
++cnt;
edge[cnt].to = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt;
}
priority_queue<pair<int, int> > q;
int main() {
memset(head, -1, sizeof(head));
memset(dis, INF, sizeof(dis));
cin >> t >> n;
for (int i=1; i<=t; i++) {
int u, v, w;
cin >> u >> v >> w;
add(u, v, w);
add(v, u, w);
}
// vis[n] = true;
dis[n] = 0;
q.push(make_pair(0, n));
while (!q.empty()) {
int x = q.top().second;
q.pop();
if (vis[x]) continue;
vis[x] = true;
for (int i=head[x]; ~i; i=edge[i].next) {
if (dis[edge[i].to] > dis[x] + edge[i].w) {
dis[edge[i].to] = dis[x] + edge[i].w;
q.push(make_pair(-dis[edge[i].to], edge[i].to));
}
}
}
cout << dis[1] << endl;
return 0;
} | [
"1639579565@qq.com"
] | 1639579565@qq.com |
7e3f9dbcf4d1ba126e2f0643c5ecb70f5df38da8 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/WebKit/Source/platform/graphics/CompositorMutableState.cpp | 6313cbfe2c1f4822de8ce4bb795b76426d3954a5 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 2,983 | cpp | // Copyright 2016 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 "platform/graphics/CompositorMutableState.h"
#include "cc/layers/layer_impl.h"
#include "cc/trees/layer_tree_impl.h"
#include "platform/graphics/CompositorMutation.h"
namespace blink {
CompositorMutableState::CompositorMutableState(CompositorMutation* mutation,
cc::LayerImpl* main,
cc::LayerImpl* scroll)
: m_mutation(mutation), m_mainLayer(main), m_scrollLayer(scroll) {}
CompositorMutableState::~CompositorMutableState() {}
double CompositorMutableState::opacity() const {
return m_mainLayer->Opacity();
}
void CompositorMutableState::setOpacity(double opacity) {
if (!m_mainLayer)
return;
m_mainLayer->layer_tree_impl()
->property_trees()
->effect_tree.OnOpacityAnimated(opacity, m_mainLayer->effect_tree_index(),
m_mainLayer->layer_tree_impl());
m_mutation->setOpacity(opacity);
}
const SkMatrix44& CompositorMutableState::transform() const {
return m_mainLayer ? m_mainLayer->Transform().matrix() : SkMatrix44::I();
}
void CompositorMutableState::setTransform(const SkMatrix44& matrix) {
if (!m_mainLayer)
return;
m_mainLayer->layer_tree_impl()
->property_trees()
->transform_tree.OnTransformAnimated(gfx::Transform(matrix),
m_mainLayer->transform_tree_index(),
m_mainLayer->layer_tree_impl());
m_mutation->setTransform(matrix);
}
double CompositorMutableState::scrollLeft() const {
return m_scrollLayer ? m_scrollLayer->CurrentScrollOffset().x() : 0.0;
}
void CompositorMutableState::setScrollLeft(double scrollLeft) {
if (!m_scrollLayer)
return;
gfx::ScrollOffset offset = m_scrollLayer->CurrentScrollOffset();
offset.set_x(scrollLeft);
m_scrollLayer->layer_tree_impl()
->property_trees()
->scroll_tree.OnScrollOffsetAnimated(
m_scrollLayer->id(), m_scrollLayer->transform_tree_index(),
m_scrollLayer->scroll_tree_index(), offset,
m_scrollLayer->layer_tree_impl());
m_mutation->setScrollLeft(scrollLeft);
}
double CompositorMutableState::scrollTop() const {
return m_scrollLayer ? m_scrollLayer->CurrentScrollOffset().y() : 0.0;
}
void CompositorMutableState::setScrollTop(double scrollTop) {
if (!m_scrollLayer)
return;
gfx::ScrollOffset offset = m_scrollLayer->CurrentScrollOffset();
offset.set_y(scrollTop);
m_scrollLayer->layer_tree_impl()
->property_trees()
->scroll_tree.OnScrollOffsetAnimated(
m_scrollLayer->id(), m_scrollLayer->transform_tree_index(),
m_scrollLayer->scroll_tree_index(), offset,
m_scrollLayer->layer_tree_impl());
m_mutation->setScrollTop(scrollTop);
}
} // namespace blink
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
978df33c8b0891d61bcef8fc46222f6e0961ff12 | 66eb3d9cdd1a66843942a71386ccc46fb0045d32 | /sort/quick_sort/quicksort.cpp | 5050b60e16a2091ee0ba04531dbe36adbc795eb3 | [] | no_license | KJTang/Algorithm | 764309818f004a25ae94be3e2cef38241873f91f | 29ae44edd462f59495338d965c92245787581f69 | refs/heads/master | 2021-01-10T18:46:51.610103 | 2017-06-30T05:42:02 | 2017-06-30T05:42:02 | 27,213,776 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,079 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
const int LENGTH = 10;
// int arr[LENGTH] = {3, 2, 7, 9, 8, 1, 0, 4, 6, 5};
int arr[LENGTH] = {9, 8, 7, 2, 5, 2, 3, 2, 1, 0};
void quickSort(int arr[], int front, int end);
void test(int arr[]) {
for (int i = 0; i != LENGTH; ++i) {
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
test(arr);
srand(time(0));
quickSort(arr, 0, LENGTH-1);
test(arr);
return 0;
}
void quickSort(int arr[], int front, int end) {
if (front >= end) {
return;
}
// random select
int random = rand()%(end-front+1)+front;
int temp = arr[end];
arr[end] = arr[random];
arr[random] = temp;
// sort
int key = arr[end];
int i = front-1, j = front;
for ( ; j != end; ++j) {
if (arr[j] <= key) {
++i;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp = arr[i+1];
arr[i+1] = arr[end];
arr[end] = temp;
quickSort(arr, front, i);
quickSort(arr, i+2, end);
} | [
"kaijietang@outlook.com"
] | kaijietang@outlook.com |
0ceda72c0a288268c794af2669933eeeb7f71b21 | 4b73addaed825276738d4c1e0ec7e96bb9b6c497 | /src/mr-controller.cpp | 4df5aef687992b6623c379b3dc8ebd7021f4c939 | [] | no_license | OohmdoO/mobile-robot-controller | 778eedc55f95c638b0c69cd5a2b49bb54663bb1b | 512b73b305c74abfa1b8f44d9eb66969f6349833 | refs/heads/master | 2023-03-17T12:04:18.522689 | 2020-09-27T11:53:12 | 2020-09-27T11:53:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | cpp | #include "ros/ros.h"
#include <tf/tf.h>
#include "nav_msgs/Odometry.h"
#include <geometry_msgs/Pose2D.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/LaserScan.h>
#include <cmath>
#include "hybridAutomata.h"
double x_d=3.0, y_d=-2.0; //target goal location
//initializing and declaring variables for robot's current pose
double x=0,y=0,roll=0,pitch=0,yaw=0;
double range[360];
void readLaserCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
for(int i=0;i<360;i++)
{
if(msg->ranges[i] > msg->range_max)
range[i] = 4.0;
else
range[i]=msg->ranges[i];
}
}
void robotPoseCallback(const nav_msgs::Odometry::ConstPtr& msg)
{
x=msg->pose.pose.position.x;
y=msg->pose.pose.position.y;
tf::Quaternion q(
msg->pose.pose.orientation.x,
msg->pose.pose.orientation.y,
msg->pose.pose.orientation.z,
msg->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
m.getRPY(roll, pitch, yaw);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "mr_controller");
ros::NodeHandle n;
ros::Subscriber odometry = n.subscribe("odom", 1000, robotPoseCallback);
ros::Subscriber laserScan = n.subscribe("scan", 10, readLaserCallback);
// Command Velocity Publisher
ros::Publisher vel_pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 100);
//Running at 10Hz
ros::Rate loop_rate(10);
while(ros::ok())
{
hybrid_automata HA;
geometry_msgs::Twist velo = HA.switcher(x,y,yaw,x_d,y_d,range);
vel_pub.publish(velo);
//For running the callbacks
ros::spinOnce();
//wait till 10Hz loop rate is satified.
loop_rate.sleep();
}
return 0;
} | [
"f20171569@hyderabad.bits-pilani.ac.in"
] | f20171569@hyderabad.bits-pilani.ac.in |
d5324d3af26b485a3ae139b372bad4c2536b6c8e | 6ff80a1dc6d0895f701c33723397caff9d7005f5 | /include/Instancia.h | 51c2a18f57a677fc3e7457a8c468dd251a6cb53e | [] | no_license | arielsonalt/Construtivo-Guloso | 03853558cb24347984c3de8099ff9e6effbe1b1b | aa6e154a1ec63cedf63326ed93061fc5e55dfa28 | refs/heads/master | 2020-03-13T02:03:29.374932 | 2018-04-24T21:39:46 | 2018-04-24T21:39:46 | 130,916,798 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | h | #ifndef INSTANCIA_H
#define INSTANCIA_H
#include "../include/Distancias.h"
#include "../include/Cliente.h"
#include "../include/CT.h"
#include <vector>
class Instancia
{
public:
Instancia();
void lerDistancias();
void lerCTs();
void lerClientes();
void imprimirDistancias();
void imprimirCTs();
void imprimirClientes();
vector <Distancias> vetorDistancias;
vector <Cliente> vetorClientes;
vector <CT> vetorCTs;
};
#endif // INSTANCIA_H
| [
"32400603+arielsonalt@users.noreply.github.com"
] | 32400603+arielsonalt@users.noreply.github.com |
97b1a6204c20277ed8d9d97d5db95f642ba0db33 | c6beef27373e962d246e0ca59e60930f33068d9a | /lab2/01_studentgroup/academicgroup.hpp | 58bcb5ed1216a59c0ba77563d0d5a87bb54efbee | [] | no_license | aganur-ahundov/oop-ki14 | 260cd3b343185d27a0aba61cedd6fc91b0e4fbef | 78d8fb653d7f7891d97a2ea0afc32ba1b7364660 | refs/heads/master | 2021-01-18T00:41:21.681434 | 2016-01-14T12:04:09 | 2016-01-14T12:04:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | hpp | // (C) 2013-2015, Sergei Zaychenko, KNURE, Kharkiv, Ukraine
#ifndef _ACADEMICGROUP_HPP_
#define _ACADEMICGROUP_HPP_
/*****************************************************************************/
class Student;
/*****************************************************************************/
class AcademicGroup
{
/*-----------------------------------------------------------------*/
public:
/*-----------------------------------------------------------------*/
// TODO put your public methods here
/*-----------------------------------------------------------------*/
private:
/*-----------------------------------------------------------------*/
// TODO put your private fields / methods here
/*-----------------------------------------------------------------*/
};
/*****************************************************************************/
#endif // _ACADEMICGROUP_HPP_
| [
"zaychenko.sergei@gmail.com"
] | zaychenko.sergei@gmail.com |
d9c91baba657064e484b9434fcbf47d3fb3fc742 | 8a11dceabdf2286777d30c32a02e8d045feac907 | /String-primary/125-validPalindrome.cpp | 0bcbb9f248956c5da51dd0478914d50d348be407 | [] | no_license | warmthless/LeetCode | 192cb83dcb33005c0a583ba293efd39684e556fc | 7d3a29162a3bde61f5a20d01ce42c76dbc52c5f7 | refs/heads/master | 2020-03-22T12:53:02.794513 | 2018-07-25T12:35:05 | 2018-07-25T12:35:05 | 140,061,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 722 | cpp | //
class Solution {
public:
bool isPalindrome(string s) {
if(s.empty()) return true;
vector<char> modi;
for(int i=0; i<s.size(); ++i){
if((s[i] >='a' && s[i] <='z') || (s[i] >='A' && s[i]<='Z') || (s[i] >='0' && s[i]<='9') ){
modi.push_back(s[i]);
}
}
for(int i=0,j=modi.size()-1; i<j; ++i,--j){
if((modi[i] + 32 - 'a') %32 != (modi[j] + 32 - 'a') % 32) return false;
}
return true;
}
/*bool isvalid(char &ch) {
if (ch >= 'a' && ch <= 'z') return true;
if (ch >= 'A' && ch <= 'Z') return true;
if (ch >= '0' && ch <= '9') return true;
return false;
}*/
};
| [
"noreply@github.com"
] | warmthless.noreply@github.com |
0b2a77f1b17bf891c59abad499a5b5103a0038e6 | 3da93763bbc39692ef6f468a91c42b335674af44 | /src/producer.cc | dd13a5291213fcc8c122342514c9fca0645a30ec | [] | no_license | mbirostris/cpt | 59f5fd0a45bf2c044b55156835dbb1c5c460ee84 | 5bae5d82647e271e686f892b0b762425563f1e50 | refs/heads/master | 2020-06-06T03:07:26.096708 | 2015-06-23T08:04:12 | 2015-06-23T08:04:12 | 27,839,425 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,214 | cc | #include "../interface/producer.h"
#include "../interface/counter.h"
chain producer::get(chain ch){
chain result = ch;
for (std::vector<std::string >::size_type i = 0; i != ch.getSize(); i++){
// czytamy oryginalny plik z drzewem
TFile *file = new TFile((ch.getFolder(i)+ch.getFilename(i)).c_str());
TTree *tree = (TTree*)file->Get(ch.getBranch(i).c_str());
// robimy odpowiedni plik z selekcja
// f->GetListOfKeys()->Print();
std::string outputFileName("./temp/");
outputFileName += ch.getFilename(i);
TFile *f = new TFile(outputFileName.c_str(),"UPDATE");
std::string key = "0";
while(f->GetKey(key.c_str())){
int inn = rand() % 10000;
key = std::to_string(inn);
}
result.setInn(key);
//tree for new cut
TTree *to = new TTree(result.getInn(),"");
// to->SetMakeClass(1); // Mowi, ze w branchu sa tylko typy podstawowe, jak float, int itp.
TTree *cut = 0;
if(f->GetKey(ch.getInn())){
cut = (TTree*)f->Get(ch.getInn());
}
this->produce(tree, to, cut);
delete to;
// f->Close();
delete f, file;
}
return result;
}
| [
"olszewski.mikael@gmail.com"
] | olszewski.mikael@gmail.com |
dee7efed53b60b78fbaef400ec19a88743d9f9e0 | 25adfb6b9406f64781535eed760272a104b3bb98 | /src/hailstone/stdafx.cpp | b9bf850878fb3db7720a9a8b96c3172a2cf0b3a1 | [] | no_license | shanfeng094/DSA | cf00d9981fbdbdf690061377a8cd615284102e27 | 3fcce6f128d7771602fa2f9809b06ee06329d006 | refs/heads/master | 2020-03-29T06:09:31.087389 | 2016-07-26T14:38:44 | 2016-07-26T14:38:44 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 262 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// hailstone.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"wanglinzhizhi@hotmail.com"
] | wanglinzhizhi@hotmail.com |
d43a966ba619d1c0c28b8df20dcad4412968fae2 | cc6d2210ef75079ebb9d3569cb228d1709434a73 | /Arduino/NTP/NTP.ino | e5eb58e1cce3f232db35193742e52e3cf6c0eb49 | [] | no_license | kkulkarni32/Martiny | bf0257079a983b3aa01485d9612ab5961e82ea39 | 7d812af1a343437c5afc2ee0557c344993f843f8 | refs/heads/master | 2023-04-06T17:54:00.160361 | 2021-04-19T21:43:34 | 2021-04-19T21:43:34 | 302,507,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,504 | ino | #include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
// Replace with your network credentials
const char *ssid = "TP-Link_82DE";
const char *password = "67244737";
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");
//Week Days
String weekDays[7]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
//Month names
String months[12]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Initialize a NTPClient to get time
timeClient.begin();
// Set offset time in seconds to adjust for your timezone, for example:
// GMT +1 = 3600
// GMT +8 = 28800
// GMT -1 = -3600
// GMT 0 = 0
timeClient.setTimeOffset(-25200);
}
void loop() {
timeClient.update();
unsigned long epochTime = timeClient.getEpochTime();
Serial.print("Epoch Time: ");
Serial.println(epochTime);
String formattedTime = timeClient.getFormattedTime();
Serial.print("Formatted Time: ");
Serial.println(formattedTime);
int currentHour = timeClient.getHours();
Serial.print("Hour: ");
Serial.println(currentHour);
int currentMinute = timeClient.getMinutes();
Serial.print("Minutes: ");
Serial.println(currentMinute);
int currentSecond = timeClient.getSeconds();
Serial.print("Seconds: ");
Serial.println(currentSecond);
String weekDay = weekDays[timeClient.getDay()];
Serial.print("Week Day: ");
Serial.println(weekDay);
//Get a time structure
struct tm *ptm = gmtime ((time_t *)&epochTime);
int monthDay = ptm->tm_mday;
Serial.print("Month day: ");
Serial.println(monthDay);
int currentMonth = ptm->tm_mon+1;
Serial.print("Month: ");
Serial.println(currentMonth);
String currentMonthName = months[currentMonth-1];
Serial.print("Month name: ");
Serial.println(currentMonthName);
int currentYear = ptm->tm_year+1900;
Serial.print("Year: ");
Serial.println(currentYear);
//Print complete date:
String currentDate = String(currentYear) + "-" + String(currentMonth) + "-" + String(monthDay);
Serial.print("Current date: ");
Serial.println(currentDate);
Serial.println("");
delay(2000);
}
| [
"kkulkar4@asu.edu"
] | kkulkar4@asu.edu |
c4d79421bd19d57235ed92c6b8e9bc081d823a1e | 352abb7b0c7cada5248183549d24e1619bbe4dc5 | /arbi5_runing/NameConverter.cpp | bedb2af24adbd6dda87c80d861054352e40313c9 | [] | no_license | 15831944/arbi6 | 048c181196305c483e94729356c3d48c57eddb62 | 86a8e673ef2b9e79c39fa1667e52ee2ffdc4f082 | refs/heads/master | 2023-03-19T11:56:24.148575 | 2015-07-13T08:06:11 | 2015-07-13T08:06:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,412 | cpp | #include "NameConverter.h"
NameConverter* NameConverter::m_pNC=NULL;
NameConverter* NameConverter::getInstance()
{
if(m_pNC==NULL)
{
m_pNC = new NameConverter();
m_pNC->init();
}
return m_pNC;
}
string& NameConverter::trim_string(string &s, const char *chars/*=NULL*/)
{
if (s.length() > 0)
{
if (chars == NULL)
chars = " \t\r\n";
while ((::strchr(chars, *s.begin())) && (s.length() > 0))
s.erase(s.begin());
while ((::strchr(chars, *s.rbegin())) && (s.length() > 0))
s.erase((s.end())-1);
}
return s;
}
void NameConverter::divide_string(const char *str, strings &parts, const char *chars/*=NULL*/, bool allow_empty_part/*=FALSE*/)
{
if (! chars)
chars = " \t";
string s = str;
parts.clear();
while (s.length())
{
int i;
string v;
i = s.find_first_of(chars);
if (i != string::npos)
{
v.assign(s, 0, i);
s.erase(0, i+1);
}
else
{
v = s;
s.erase();
}
trim_string(v);
if ((v.length() > 0) || allow_empty_part)
parts.push_back(v);
}
}
NameConverter::NameConverter(void)
{
InitializeCriticalSection(&cs);
rohonMap.clear();
rohonRevertMap.clear();
rohonMonthMap.clear();
rohonRevertMonthMap.clear();
}
NameConverter::~NameConverter(void)
{
DeleteCriticalSection(&cs);
}
void NameConverter::init(void)
{
rohonMonthMap["01"] = "JAN";
rohonMonthMap["02"] = "FEB";
rohonMonthMap["03"] = "MAR";
rohonMonthMap["04"] = "APR";
rohonMonthMap["05"] = "MAY";
rohonMonthMap["06"] = "JUN";
rohonMonthMap["07"] = "JUL";
rohonMonthMap["08"] = "AUG";
rohonMonthMap["09"] = "SEP";
rohonMonthMap["10"] = "OCT";
rohonMonthMap["11"] = "NOV";
rohonMonthMap["12"] = "DEC";
rohonRevertMonthMap["JAN"]="01";
rohonRevertMonthMap["FEB"]="02";
rohonRevertMonthMap["MAR"]="03";
rohonRevertMonthMap["APR"]="04";
rohonRevertMonthMap["MAY"]="05";
rohonRevertMonthMap["JUN"]="06";
rohonRevertMonthMap["JUL"]="07";
rohonRevertMonthMap["AUG"]="08";
rohonRevertMonthMap["SEP"]="09";
rohonRevertMonthMap["OCT"]="10";
rohonRevertMonthMap["NOV"]="11";
rohonRevertMonthMap["DEC"]="12";
// The following will be changed to read info from file later.
EnterCriticalSection(&cs);
rohonMap["ZS@CBOT"]="CME_CBT SOYBEAN";
rohonMap["ZC@CBOT"]="CME_CBT CORN";
rohonMap["ZM@CBOT"]="CME_CBT SOYMEAL";
rohonMap["ZL@CBOT"]="CME_CBT SOYOIL";
rohonMap["ZW@CBOT"]="CME_CBT WHEAT";
rohonMap["CT@NBOT"]="NYBOT NB COTT";
rohonMap["SB@NBOT"]="NYBOT NB SU11";
rohonMap["HG@NYMEX"]="CME CMX COP";
rohonMap["GC@NYMEX"]="CME CMX GLD";
rohonMap["CL@NYMEX"]="CME CRUDE";
rohonMap["PL@NYMEX"]="CME NYM PAL";
rohonMap["SI@NYMEX"]="CME CMX SIL";
rohonMap["LCA@LME"]="LME CA";
rohonMap["LZS@LME"]="LME ZS";
rohonMap["LAH@LME"]="LME AH";
rohonMap["SN@LME"]="LME SN";
rohonRevertMap["CME_CBT SOYBEAN"]="ZS@CBOT";
rohonRevertMap["CME_CBT CORN"]="ZC@CBOT";
rohonRevertMap["CME_CBT SOYMEAL"]="ZM@CBOT";
rohonRevertMap["CME_CBT SOYOIL"]="ZL@CBOT";
rohonRevertMap["CME_CBT WHEAT"]="ZW@CBOT";
rohonRevertMap["NYBOT NB COTT"]="CT@NBOT";
rohonRevertMap["NYBOT NB SU11"]="SB@NBOT";
rohonRevertMap["CME CMX COP"]="HG@NYMEX";
rohonRevertMap["CME CMX GLD"]="GC@NYMEX";
rohonRevertMap["CME CRUDE"]="CL@NYMEX";
rohonRevertMap["CME NYM PAL"]="PL@NYMEX";
rohonRevertMap["CME CMX SIL"]="SI@NYMEX";
rohonRevertMap["LME CA"]="LCA@LME";
rohonRevertMap["LME ZS"]="LZS@LME";
rohonRevertMap["LME AH"]="LAH@LME";
rohonRevertMap["LME SN"]="SN@LME";
LeaveCriticalSection(&cs);
}
string NameConverter::base2RohonName(string baseName)
{
string ret = "";
string comodity="";
string exchange="";
string month="";
strings pars;
divide_string(baseName.c_str(),pars,"@");
if(pars.size()!=2) return ret;
exchange=pars[1];
int size1 = pars[0].length();
if(pars[1]=="LME"&&pars[0].length()>2)
{
comodity = pars[0].substr(0,size1-2);
month = pars[0].substr(size1-2);
}
else if(pars[0].length()>6)
{
comodity = pars[0].substr(0,size1-6);
month = pars[0].substr(size1-6);
}
else return ret;
map<string, string>::iterator iter = rohonMap.find(comodity+"@"+exchange);
if(iter == rohonMap.end()) return ret;
string rohonExchangeComodity = iter->second;
string rohonMonth = "";
if(exchange=="LME")
{
rohonMonth = month;
}
else
{
map<string, string>::iterator monthIter = rohonMonthMap.find(month.substr(4));
if(monthIter == rohonMonthMap.end()) return ret;
rohonMonth = monthIter->second + month.substr(2,2);
}
return rohonExchangeComodity + " " + rohonMonth;
}
string NameConverter::rohon2BaseName(string rohonName)
{
string ret = "";
strings pars;
divide_string(rohonName.c_str(),pars," ");
if(pars.size()<3) return ret;
string rohonMonth=pars[pars.size()-1];
string baseMonth="";
if(pars[0]=="LME")
{
baseMonth=rohonMonth;
}
else
{
map<string, string>::iterator revertMonthIter = rohonRevertMonthMap.find(rohonMonth.substr(0,3));
if(revertMonthIter == rohonRevertMonthMap.end()) return ret;
baseMonth = "20"+ rohonMonth.substr(3) + revertMonthIter->second;
}
string rohonExchangeComodity = rohonName.substr(0,rohonName.find_last_of(" "));
map<string, string>::iterator revertIter = rohonRevertMap.find(rohonExchangeComodity);
if(revertIter == rohonRevertMap.end()) return ret;
string baseExchangeComodity = revertIter->second;
strings basePars;
divide_string(baseExchangeComodity.c_str(),basePars,"@");
if(basePars.size()!=2) return ret;
return basePars[0]+"-" + baseMonth + "@"+basePars[1];
} | [
"sunhao@sanss.com"
] | sunhao@sanss.com |
dce6e0fa6920856073d61d902d120135e2e6c566 | 276845ee0f0dfe0050a191dd94c55531cf71a839 | /mc15-smaract/smaractApp/src/O.linux-x86_64/smaract_registerRecordDeviceDriver.cpp | 06ad21fa10410a01f0d1e428280ac0a7d7de58b6 | [] | no_license | NSLS-II-LIX/xf16idc-ioc1 | fb2113d044e14e0bd4c96e9efea20668a1cbb51e | f04e6266fd4ad0ad7ad6caead7252f7e0d67e45d | refs/heads/master | 2021-07-06T22:42:49.120813 | 2021-04-27T12:51:52 | 2021-04-27T12:51:52 | 91,277,754 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,600 | cpp | /* THIS IS A GENERATED FILE. DO NOT EDIT! */
/* Generated from ../O.Common/smaract.dbd */
#include <string.h>
#include "epicsStdlib.h"
#include "iocsh.h"
#include "iocshRegisterCommon.h"
#include "registryCommon.h"
extern "C" {
epicsShareExtern rset *pvar_rset_aaiRSET;
epicsShareExtern int (*pvar_func_aaiRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_aaoRSET;
epicsShareExtern int (*pvar_func_aaoRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_aiRSET;
epicsShareExtern int (*pvar_func_aiRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_aoRSET;
epicsShareExtern int (*pvar_func_aoRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_aSubRSET;
epicsShareExtern int (*pvar_func_aSubRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_biRSET;
epicsShareExtern int (*pvar_func_biRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_boRSET;
epicsShareExtern int (*pvar_func_boRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_calcRSET;
epicsShareExtern int (*pvar_func_calcRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_calcoutRSET;
epicsShareExtern int (*pvar_func_calcoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_compressRSET;
epicsShareExtern int (*pvar_func_compressRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_dfanoutRSET;
epicsShareExtern int (*pvar_func_dfanoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_eventRSET;
epicsShareExtern int (*pvar_func_eventRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_fanoutRSET;
epicsShareExtern int (*pvar_func_fanoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_histogramRSET;
epicsShareExtern int (*pvar_func_histogramRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_longinRSET;
epicsShareExtern int (*pvar_func_longinRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_longoutRSET;
epicsShareExtern int (*pvar_func_longoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_mbbiRSET;
epicsShareExtern int (*pvar_func_mbbiRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_mbbiDirectRSET;
epicsShareExtern int (*pvar_func_mbbiDirectRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_mbboRSET;
epicsShareExtern int (*pvar_func_mbboRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_mbboDirectRSET;
epicsShareExtern int (*pvar_func_mbboDirectRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_permissiveRSET;
epicsShareExtern int (*pvar_func_permissiveRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_selRSET;
epicsShareExtern int (*pvar_func_selRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_seqRSET;
epicsShareExtern int (*pvar_func_seqRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_stateRSET;
epicsShareExtern int (*pvar_func_stateRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_stringinRSET;
epicsShareExtern int (*pvar_func_stringinRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_stringoutRSET;
epicsShareExtern int (*pvar_func_stringoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_subRSET;
epicsShareExtern int (*pvar_func_subRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_subArrayRSET;
epicsShareExtern int (*pvar_func_subArrayRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_waveformRSET;
epicsShareExtern int (*pvar_func_waveformRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_asynRSET;
epicsShareExtern int (*pvar_func_asynRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_motorRSET;
epicsShareExtern int (*pvar_func_motorRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_transformRSET;
epicsShareExtern int (*pvar_func_transformRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_scalcoutRSET;
epicsShareExtern int (*pvar_func_scalcoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_acalcoutRSET;
epicsShareExtern int (*pvar_func_acalcoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_sseqRSET;
epicsShareExtern int (*pvar_func_sseqRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_swaitRSET;
epicsShareExtern int (*pvar_func_swaitRecordSizeOffset)(dbRecordType *pdbRecordType);
static const char * const recordTypeNames[36] = {
"aai",
"aao",
"ai",
"ao",
"aSub",
"bi",
"bo",
"calc",
"calcout",
"compress",
"dfanout",
"event",
"fanout",
"histogram",
"longin",
"longout",
"mbbi",
"mbbiDirect",
"mbbo",
"mbboDirect",
"permissive",
"sel",
"seq",
"state",
"stringin",
"stringout",
"sub",
"subArray",
"waveform",
"asyn",
"motor",
"transform",
"scalcout",
"acalcout",
"sseq",
"swait"
};
static const recordTypeLocation rtl[36] = {
{pvar_rset_aaiRSET, pvar_func_aaiRecordSizeOffset},
{pvar_rset_aaoRSET, pvar_func_aaoRecordSizeOffset},
{pvar_rset_aiRSET, pvar_func_aiRecordSizeOffset},
{pvar_rset_aoRSET, pvar_func_aoRecordSizeOffset},
{pvar_rset_aSubRSET, pvar_func_aSubRecordSizeOffset},
{pvar_rset_biRSET, pvar_func_biRecordSizeOffset},
{pvar_rset_boRSET, pvar_func_boRecordSizeOffset},
{pvar_rset_calcRSET, pvar_func_calcRecordSizeOffset},
{pvar_rset_calcoutRSET, pvar_func_calcoutRecordSizeOffset},
{pvar_rset_compressRSET, pvar_func_compressRecordSizeOffset},
{pvar_rset_dfanoutRSET, pvar_func_dfanoutRecordSizeOffset},
{pvar_rset_eventRSET, pvar_func_eventRecordSizeOffset},
{pvar_rset_fanoutRSET, pvar_func_fanoutRecordSizeOffset},
{pvar_rset_histogramRSET, pvar_func_histogramRecordSizeOffset},
{pvar_rset_longinRSET, pvar_func_longinRecordSizeOffset},
{pvar_rset_longoutRSET, pvar_func_longoutRecordSizeOffset},
{pvar_rset_mbbiRSET, pvar_func_mbbiRecordSizeOffset},
{pvar_rset_mbbiDirectRSET, pvar_func_mbbiDirectRecordSizeOffset},
{pvar_rset_mbboRSET, pvar_func_mbboRecordSizeOffset},
{pvar_rset_mbboDirectRSET, pvar_func_mbboDirectRecordSizeOffset},
{pvar_rset_permissiveRSET, pvar_func_permissiveRecordSizeOffset},
{pvar_rset_selRSET, pvar_func_selRecordSizeOffset},
{pvar_rset_seqRSET, pvar_func_seqRecordSizeOffset},
{pvar_rset_stateRSET, pvar_func_stateRecordSizeOffset},
{pvar_rset_stringinRSET, pvar_func_stringinRecordSizeOffset},
{pvar_rset_stringoutRSET, pvar_func_stringoutRecordSizeOffset},
{pvar_rset_subRSET, pvar_func_subRecordSizeOffset},
{pvar_rset_subArrayRSET, pvar_func_subArrayRecordSizeOffset},
{pvar_rset_waveformRSET, pvar_func_waveformRecordSizeOffset},
{pvar_rset_asynRSET, pvar_func_asynRecordSizeOffset},
{pvar_rset_motorRSET, pvar_func_motorRecordSizeOffset},
{pvar_rset_transformRSET, pvar_func_transformRecordSizeOffset},
{pvar_rset_scalcoutRSET, pvar_func_scalcoutRecordSizeOffset},
{pvar_rset_acalcoutRSET, pvar_func_acalcoutRecordSizeOffset},
{pvar_rset_sseqRSET, pvar_func_sseqRecordSizeOffset},
{pvar_rset_swaitRSET, pvar_func_swaitRecordSizeOffset}
};
epicsShareExtern dset *pvar_dset_devAaiSoft;
epicsShareExtern dset *pvar_dset_devAaoSoft;
epicsShareExtern dset *pvar_dset_devAiSoft;
epicsShareExtern dset *pvar_dset_devAiSoftRaw;
epicsShareExtern dset *pvar_dset_devTimestampAI;
epicsShareExtern dset *pvar_dset_devAiGeneralTime;
epicsShareExtern dset *pvar_dset_asynAiInt32;
epicsShareExtern dset *pvar_dset_asynAiInt32Average;
epicsShareExtern dset *pvar_dset_asynAiFloat64;
epicsShareExtern dset *pvar_dset_asynAiFloat64Average;
epicsShareExtern dset *pvar_dset_devAoSoft;
epicsShareExtern dset *pvar_dset_devAoSoftRaw;
epicsShareExtern dset *pvar_dset_devAoSoftCallback;
epicsShareExtern dset *pvar_dset_asynAoInt32;
epicsShareExtern dset *pvar_dset_asynAoFloat64;
epicsShareExtern dset *pvar_dset_devBiSoft;
epicsShareExtern dset *pvar_dset_devBiSoftRaw;
epicsShareExtern dset *pvar_dset_devBiASStatus;
epicsShareExtern dset *pvar_dset_asynBiInt32;
epicsShareExtern dset *pvar_dset_asynBiUInt32Digital;
epicsShareExtern dset *pvar_dset_devBoSoft;
epicsShareExtern dset *pvar_dset_devBoSoftRaw;
epicsShareExtern dset *pvar_dset_devBoSoftCallback;
epicsShareExtern dset *pvar_dset_devBoGeneralTime;
epicsShareExtern dset *pvar_dset_asynBoInt32;
epicsShareExtern dset *pvar_dset_asynBoUInt32Digital;
epicsShareExtern dset *pvar_dset_devCalcoutSoft;
epicsShareExtern dset *pvar_dset_devCalcoutSoftCallback;
epicsShareExtern dset *pvar_dset_devEventSoft;
epicsShareExtern dset *pvar_dset_devHistogramSoft;
epicsShareExtern dset *pvar_dset_devLiSoft;
epicsShareExtern dset *pvar_dset_devLiGeneralTime;
epicsShareExtern dset *pvar_dset_devLiASSum;
epicsShareExtern dset *pvar_dset_asynLiInt32;
epicsShareExtern dset *pvar_dset_asynLiUInt32Digital;
epicsShareExtern dset *pvar_dset_devLoSoft;
epicsShareExtern dset *pvar_dset_devLoSoftCallback;
epicsShareExtern dset *pvar_dset_asynLoInt32;
epicsShareExtern dset *pvar_dset_asynLoUInt32Digital;
epicsShareExtern dset *pvar_dset_devMbbiSoft;
epicsShareExtern dset *pvar_dset_devMbbiSoftRaw;
epicsShareExtern dset *pvar_dset_asynMbbiInt32;
epicsShareExtern dset *pvar_dset_asynMbbiUInt32Digital;
epicsShareExtern dset *pvar_dset_devMbbiDirectSoft;
epicsShareExtern dset *pvar_dset_devMbbiDirectSoftRaw;
epicsShareExtern dset *pvar_dset_asynMbbiDirectUInt32Digital;
epicsShareExtern dset *pvar_dset_devMbboSoft;
epicsShareExtern dset *pvar_dset_devMbboSoftRaw;
epicsShareExtern dset *pvar_dset_devMbboSoftCallback;
epicsShareExtern dset *pvar_dset_asynMbboInt32;
epicsShareExtern dset *pvar_dset_asynMbboUInt32Digital;
epicsShareExtern dset *pvar_dset_devMbboDirectSoft;
epicsShareExtern dset *pvar_dset_devMbboDirectSoftRaw;
epicsShareExtern dset *pvar_dset_devMbboDirectSoftCallback;
epicsShareExtern dset *pvar_dset_asynMbboDirectUInt32Digital;
epicsShareExtern dset *pvar_dset_devSiSoft;
epicsShareExtern dset *pvar_dset_devTimestampSI;
epicsShareExtern dset *pvar_dset_devSiGeneralTime;
epicsShareExtern dset *pvar_dset_asynSiOctetCmdResponse;
epicsShareExtern dset *pvar_dset_asynSiOctetWriteRead;
epicsShareExtern dset *pvar_dset_asynSiOctetRead;
epicsShareExtern dset *pvar_dset_devSoSoft;
epicsShareExtern dset *pvar_dset_devSoSoftCallback;
epicsShareExtern dset *pvar_dset_devSoStdio;
epicsShareExtern dset *pvar_dset_asynSoOctetWrite;
epicsShareExtern dset *pvar_dset_devSASoft;
epicsShareExtern dset *pvar_dset_devWfSoft;
epicsShareExtern dset *pvar_dset_asynWfOctetCmdResponse;
epicsShareExtern dset *pvar_dset_asynWfOctetWriteRead;
epicsShareExtern dset *pvar_dset_asynWfOctetRead;
epicsShareExtern dset *pvar_dset_asynWfOctetWrite;
epicsShareExtern dset *pvar_dset_asynInt8ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynInt8ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynInt16ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynInt16ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynInt32ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynInt32ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynInt32TimeSeries;
epicsShareExtern dset *pvar_dset_asynFloat32ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynFloat32ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynFloat64ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynFloat64ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynFloat64TimeSeries;
epicsShareExtern dset *pvar_dset_asynRecordDevice;
epicsShareExtern dset *pvar_dset_devMotorAsyn;
epicsShareExtern dset *pvar_dset_devsCalcoutSoft;
epicsShareExtern dset *pvar_dset_devaCalcoutSoft;
epicsShareExtern dset *pvar_dset_devSWaitIoEvent;
static const char * const deviceSupportNames[88] = {
"devAaiSoft",
"devAaoSoft",
"devAiSoft",
"devAiSoftRaw",
"devTimestampAI",
"devAiGeneralTime",
"asynAiInt32",
"asynAiInt32Average",
"asynAiFloat64",
"asynAiFloat64Average",
"devAoSoft",
"devAoSoftRaw",
"devAoSoftCallback",
"asynAoInt32",
"asynAoFloat64",
"devBiSoft",
"devBiSoftRaw",
"devBiASStatus",
"asynBiInt32",
"asynBiUInt32Digital",
"devBoSoft",
"devBoSoftRaw",
"devBoSoftCallback",
"devBoGeneralTime",
"asynBoInt32",
"asynBoUInt32Digital",
"devCalcoutSoft",
"devCalcoutSoftCallback",
"devEventSoft",
"devHistogramSoft",
"devLiSoft",
"devLiGeneralTime",
"devLiASSum",
"asynLiInt32",
"asynLiUInt32Digital",
"devLoSoft",
"devLoSoftCallback",
"asynLoInt32",
"asynLoUInt32Digital",
"devMbbiSoft",
"devMbbiSoftRaw",
"asynMbbiInt32",
"asynMbbiUInt32Digital",
"devMbbiDirectSoft",
"devMbbiDirectSoftRaw",
"asynMbbiDirectUInt32Digital",
"devMbboSoft",
"devMbboSoftRaw",
"devMbboSoftCallback",
"asynMbboInt32",
"asynMbboUInt32Digital",
"devMbboDirectSoft",
"devMbboDirectSoftRaw",
"devMbboDirectSoftCallback",
"asynMbboDirectUInt32Digital",
"devSiSoft",
"devTimestampSI",
"devSiGeneralTime",
"asynSiOctetCmdResponse",
"asynSiOctetWriteRead",
"asynSiOctetRead",
"devSoSoft",
"devSoSoftCallback",
"devSoStdio",
"asynSoOctetWrite",
"devSASoft",
"devWfSoft",
"asynWfOctetCmdResponse",
"asynWfOctetWriteRead",
"asynWfOctetRead",
"asynWfOctetWrite",
"asynInt8ArrayWfIn",
"asynInt8ArrayWfOut",
"asynInt16ArrayWfIn",
"asynInt16ArrayWfOut",
"asynInt32ArrayWfIn",
"asynInt32ArrayWfOut",
"asynInt32TimeSeries",
"asynFloat32ArrayWfIn",
"asynFloat32ArrayWfOut",
"asynFloat64ArrayWfIn",
"asynFloat64ArrayWfOut",
"asynFloat64TimeSeries",
"asynRecordDevice",
"devMotorAsyn",
"devsCalcoutSoft",
"devaCalcoutSoft",
"devSWaitIoEvent"
};
static const dset * const devsl[88] = {
pvar_dset_devAaiSoft,
pvar_dset_devAaoSoft,
pvar_dset_devAiSoft,
pvar_dset_devAiSoftRaw,
pvar_dset_devTimestampAI,
pvar_dset_devAiGeneralTime,
pvar_dset_asynAiInt32,
pvar_dset_asynAiInt32Average,
pvar_dset_asynAiFloat64,
pvar_dset_asynAiFloat64Average,
pvar_dset_devAoSoft,
pvar_dset_devAoSoftRaw,
pvar_dset_devAoSoftCallback,
pvar_dset_asynAoInt32,
pvar_dset_asynAoFloat64,
pvar_dset_devBiSoft,
pvar_dset_devBiSoftRaw,
pvar_dset_devBiASStatus,
pvar_dset_asynBiInt32,
pvar_dset_asynBiUInt32Digital,
pvar_dset_devBoSoft,
pvar_dset_devBoSoftRaw,
pvar_dset_devBoSoftCallback,
pvar_dset_devBoGeneralTime,
pvar_dset_asynBoInt32,
pvar_dset_asynBoUInt32Digital,
pvar_dset_devCalcoutSoft,
pvar_dset_devCalcoutSoftCallback,
pvar_dset_devEventSoft,
pvar_dset_devHistogramSoft,
pvar_dset_devLiSoft,
pvar_dset_devLiGeneralTime,
pvar_dset_devLiASSum,
pvar_dset_asynLiInt32,
pvar_dset_asynLiUInt32Digital,
pvar_dset_devLoSoft,
pvar_dset_devLoSoftCallback,
pvar_dset_asynLoInt32,
pvar_dset_asynLoUInt32Digital,
pvar_dset_devMbbiSoft,
pvar_dset_devMbbiSoftRaw,
pvar_dset_asynMbbiInt32,
pvar_dset_asynMbbiUInt32Digital,
pvar_dset_devMbbiDirectSoft,
pvar_dset_devMbbiDirectSoftRaw,
pvar_dset_asynMbbiDirectUInt32Digital,
pvar_dset_devMbboSoft,
pvar_dset_devMbboSoftRaw,
pvar_dset_devMbboSoftCallback,
pvar_dset_asynMbboInt32,
pvar_dset_asynMbboUInt32Digital,
pvar_dset_devMbboDirectSoft,
pvar_dset_devMbboDirectSoftRaw,
pvar_dset_devMbboDirectSoftCallback,
pvar_dset_asynMbboDirectUInt32Digital,
pvar_dset_devSiSoft,
pvar_dset_devTimestampSI,
pvar_dset_devSiGeneralTime,
pvar_dset_asynSiOctetCmdResponse,
pvar_dset_asynSiOctetWriteRead,
pvar_dset_asynSiOctetRead,
pvar_dset_devSoSoft,
pvar_dset_devSoSoftCallback,
pvar_dset_devSoStdio,
pvar_dset_asynSoOctetWrite,
pvar_dset_devSASoft,
pvar_dset_devWfSoft,
pvar_dset_asynWfOctetCmdResponse,
pvar_dset_asynWfOctetWriteRead,
pvar_dset_asynWfOctetRead,
pvar_dset_asynWfOctetWrite,
pvar_dset_asynInt8ArrayWfIn,
pvar_dset_asynInt8ArrayWfOut,
pvar_dset_asynInt16ArrayWfIn,
pvar_dset_asynInt16ArrayWfOut,
pvar_dset_asynInt32ArrayWfIn,
pvar_dset_asynInt32ArrayWfOut,
pvar_dset_asynInt32TimeSeries,
pvar_dset_asynFloat32ArrayWfIn,
pvar_dset_asynFloat32ArrayWfOut,
pvar_dset_asynFloat64ArrayWfIn,
pvar_dset_asynFloat64ArrayWfOut,
pvar_dset_asynFloat64TimeSeries,
pvar_dset_asynRecordDevice,
pvar_dset_devMotorAsyn,
pvar_dset_devsCalcoutSoft,
pvar_dset_devaCalcoutSoft,
pvar_dset_devSWaitIoEvent
};
epicsShareExtern drvet *pvar_drvet_drvAsyn;
static const char *driverSupportNames[1] = {
"drvAsyn"
};
static struct drvet *drvsl[1] = {
pvar_drvet_drvAsyn
};
epicsShareExtern void (*pvar_func_asSub)(void);
epicsShareExtern void (*pvar_func_asynRegister)(void);
epicsShareExtern void (*pvar_func_asynInterposeFlushRegister)(void);
epicsShareExtern void (*pvar_func_asynInterposeEosRegister)(void);
epicsShareExtern void (*pvar_func_motorUtilRegister)(void);
epicsShareExtern void (*pvar_func_motorRegister)(void);
epicsShareExtern void (*pvar_func_asynMotorControllerRegister)(void);
epicsShareExtern void (*pvar_func_drvAsynIPPortRegisterCommands)(void);
epicsShareExtern void (*pvar_func_drvAsynIPServerPortRegisterCommands)(void);
epicsShareExtern void (*pvar_func_drvAsynSerialPortRegisterCommands)(void);
epicsShareExtern void (*pvar_func_smarActMCSMotorRegister)(void);
epicsShareExtern void (*pvar_func_save_restoreRegister)(void);
epicsShareExtern void (*pvar_func_dbrestoreRegister)(void);
epicsShareExtern void (*pvar_func_asInitHooksRegister)(void);
epicsShareExtern void (*pvar_func_configMenuRegistrar)(void);
epicsShareExtern void (*pvar_func_subAveRegister)(void);
epicsShareExtern void (*pvar_func_interpRegister)(void);
epicsShareExtern void (*pvar_func_arrayTestRegister)(void);
epicsShareExtern int *pvar_int_asCaDebug;
epicsShareExtern int *pvar_int_dbRecordsOnceOnly;
epicsShareExtern int *pvar_int_dbBptNotMonotonic;
epicsShareExtern int *pvar_int_save_restoreDebug;
epicsShareExtern int *pvar_int_save_restoreNumSeqFiles;
epicsShareExtern int *pvar_int_save_restoreSeqPeriodInSeconds;
epicsShareExtern int *pvar_int_save_restoreIncompleteSetsOk;
epicsShareExtern int *pvar_int_save_restoreDatedBackupFiles;
epicsShareExtern int *pvar_int_save_restoreRemountThreshold;
epicsShareExtern int *pvar_int_configMenuDebug;
epicsShareExtern int *pvar_int_debugSubAve;
epicsShareExtern int *pvar_int_sCalcPostfixDebug;
epicsShareExtern int *pvar_int_sCalcPerformDebug;
epicsShareExtern int *pvar_int_sCalcoutRecordDebug;
epicsShareExtern int *pvar_int_devsCalcoutSoftDebug;
epicsShareExtern int *pvar_int_sCalcStackHW;
epicsShareExtern int *pvar_int_sCalcStackLW;
epicsShareExtern int *pvar_int_sCalcLoopMax;
epicsShareExtern int *pvar_int_aCalcPostfixDebug;
epicsShareExtern int *pvar_int_aCalcPerformDebug;
epicsShareExtern int *pvar_int_aCalcoutRecordDebug;
epicsShareExtern int *pvar_int_devaCalcoutSoftDebug;
epicsShareExtern int *pvar_int_aCalcLoopMax;
epicsShareExtern int *pvar_int_aCalcAsyncThreshold;
epicsShareExtern int *pvar_int_transformRecordDebug;
epicsShareExtern int *pvar_int_interpDebug;
epicsShareExtern int *pvar_int_arrayTestDebug;
epicsShareExtern int *pvar_int_sseqRecDebug;
epicsShareExtern int *pvar_int_swaitRecordDebug;
static struct iocshVarDef vardefs[] = {
{"asCaDebug", iocshArgInt, (void * const)pvar_int_asCaDebug},
{"dbRecordsOnceOnly", iocshArgInt, (void * const)pvar_int_dbRecordsOnceOnly},
{"dbBptNotMonotonic", iocshArgInt, (void * const)pvar_int_dbBptNotMonotonic},
{"save_restoreDebug", iocshArgInt, (void * const)pvar_int_save_restoreDebug},
{"save_restoreNumSeqFiles", iocshArgInt, (void * const)pvar_int_save_restoreNumSeqFiles},
{"save_restoreSeqPeriodInSeconds", iocshArgInt, (void * const)pvar_int_save_restoreSeqPeriodInSeconds},
{"save_restoreIncompleteSetsOk", iocshArgInt, (void * const)pvar_int_save_restoreIncompleteSetsOk},
{"save_restoreDatedBackupFiles", iocshArgInt, (void * const)pvar_int_save_restoreDatedBackupFiles},
{"save_restoreRemountThreshold", iocshArgInt, (void * const)pvar_int_save_restoreRemountThreshold},
{"configMenuDebug", iocshArgInt, (void * const)pvar_int_configMenuDebug},
{"debugSubAve", iocshArgInt, (void * const)pvar_int_debugSubAve},
{"sCalcPostfixDebug", iocshArgInt, (void * const)pvar_int_sCalcPostfixDebug},
{"sCalcPerformDebug", iocshArgInt, (void * const)pvar_int_sCalcPerformDebug},
{"sCalcoutRecordDebug", iocshArgInt, (void * const)pvar_int_sCalcoutRecordDebug},
{"devsCalcoutSoftDebug", iocshArgInt, (void * const)pvar_int_devsCalcoutSoftDebug},
{"sCalcStackHW", iocshArgInt, (void * const)pvar_int_sCalcStackHW},
{"sCalcStackLW", iocshArgInt, (void * const)pvar_int_sCalcStackLW},
{"sCalcLoopMax", iocshArgInt, (void * const)pvar_int_sCalcLoopMax},
{"aCalcPostfixDebug", iocshArgInt, (void * const)pvar_int_aCalcPostfixDebug},
{"aCalcPerformDebug", iocshArgInt, (void * const)pvar_int_aCalcPerformDebug},
{"aCalcoutRecordDebug", iocshArgInt, (void * const)pvar_int_aCalcoutRecordDebug},
{"devaCalcoutSoftDebug", iocshArgInt, (void * const)pvar_int_devaCalcoutSoftDebug},
{"aCalcLoopMax", iocshArgInt, (void * const)pvar_int_aCalcLoopMax},
{"aCalcAsyncThreshold", iocshArgInt, (void * const)pvar_int_aCalcAsyncThreshold},
{"transformRecordDebug", iocshArgInt, (void * const)pvar_int_transformRecordDebug},
{"interpDebug", iocshArgInt, (void * const)pvar_int_interpDebug},
{"arrayTestDebug", iocshArgInt, (void * const)pvar_int_arrayTestDebug},
{"sseqRecDebug", iocshArgInt, (void * const)pvar_int_sseqRecDebug},
{"swaitRecordDebug", iocshArgInt, (void * const)pvar_int_swaitRecordDebug},
{NULL, iocshArgInt, NULL}
};
int smaract_registerRecordDeviceDriver(DBBASE *pbase)
{
const char *bldTop = "/epics/iocs/mc15-smaract";
const char *envTop = getenv("TOP");
if (envTop && strcmp(envTop, bldTop)) {
printf("Warning: IOC is booting with TOP = \"%s\"\n"
" but was built with TOP = \"%s\"\n",
envTop, bldTop);
}
if (!pbase) {
printf("pdbbase is NULL; you must load a DBD file first.\n");
return -1;
}
registerRecordTypes(pbase, 36, recordTypeNames, rtl);
registerDevices(pbase, 88, deviceSupportNames, devsl);
registerDrivers(pbase, 1, driverSupportNames, drvsl);
(*pvar_func_asSub)();
(*pvar_func_asynRegister)();
(*pvar_func_asynInterposeFlushRegister)();
(*pvar_func_asynInterposeEosRegister)();
(*pvar_func_motorUtilRegister)();
(*pvar_func_motorRegister)();
(*pvar_func_asynMotorControllerRegister)();
(*pvar_func_drvAsynIPPortRegisterCommands)();
(*pvar_func_drvAsynIPServerPortRegisterCommands)();
(*pvar_func_drvAsynSerialPortRegisterCommands)();
(*pvar_func_smarActMCSMotorRegister)();
(*pvar_func_save_restoreRegister)();
(*pvar_func_dbrestoreRegister)();
(*pvar_func_asInitHooksRegister)();
(*pvar_func_configMenuRegistrar)();
(*pvar_func_subAveRegister)();
(*pvar_func_interpRegister)();
(*pvar_func_arrayTestRegister)();
iocshRegisterVariable(vardefs);
return 0;
}
/* registerRecordDeviceDriver */
static const iocshArg registerRecordDeviceDriverArg0 =
{"pdbbase",iocshArgPdbbase};
static const iocshArg *registerRecordDeviceDriverArgs[1] =
{®isterRecordDeviceDriverArg0};
static const iocshFuncDef registerRecordDeviceDriverFuncDef =
{"smaract_registerRecordDeviceDriver",1,registerRecordDeviceDriverArgs};
static void registerRecordDeviceDriverCallFunc(const iocshArgBuf *)
{
smaract_registerRecordDeviceDriver(*iocshPpdbbase);
}
} // extern "C"
/*
* Register commands on application startup
*/
static int Registration() {
iocshRegisterCommon();
iocshRegister(®isterRecordDeviceDriverFuncDef,
registerRecordDeviceDriverCallFunc);
return 0;
}
static int done = Registration();
| [
"lyang@bnl.gov"
] | lyang@bnl.gov |
47541dec62e93a5baf4e857e2b1f4e669f40cd6b | f999711a794bd8f28b3365fa9333403df179fd90 | /hust C语言学习/第七章/trim().cpp | 83aa43b00fe182957e9a80f58f14cc03ddd1edf6 | [] | no_license | Hanray-Zhong/Computer-Science | 2423222addff275e5822a1390b43c44c1b24a252 | dfea9d3ee465c36a405e50f53589bdacbd6d2ae2 | refs/heads/master | 2021-07-04T21:35:43.730153 | 2020-08-07T09:56:58 | 2020-08-07T09:56:58 | 145,799,254 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 570 | cpp | #include <stdio.h>
int strlen(char []);
int trim(char []);
int main(void)
{
char s[30];
scanf("%s",s);
printf("%d words: %s",trim(s),s);
return 0;
}
/***********trim()********/
int trim(char s[])
{
int i,num,j=0,k=0,l=strlen(s);
while(s[j]==' '||s[j]=='\n'||s[j]=='\t'||s[j]=='\r') j++;
i=l-1;
while(s[i-k]==' '||s[i-k]=='\n'||s[i-k]=='\t'||s[i-k]=='\r') k++;
num=l-k-j;
for(i=0;i<num;i++)
{
s[i]=s[i+j];
}
s[num]='\0';
return strlen(s);
}
/***************strlen()****************/
int strlen(char s[])
{
int j=0;
while(s[j]!='\0') j++;
return j;
}
| [
"646374316@qq.com"
] | 646374316@qq.com |
db605cc7c5b71033d40eca34b9f241b0e0a0c3f6 | 38c10c01007624cd2056884f25e0d6ab85442194 | /chrome/browser/extensions/api/sync_file_system/sync_file_system_api.cc | 0b9aafc547c3634fae05f95eb0a23642f37a44ab | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 13,764 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/sync_file_system/sync_file_system_api.h"
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer.h"
#include "chrome/browser/extensions/api/sync_file_system/sync_file_system_api_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync_file_system/sync_file_status.h"
#include "chrome/browser/sync_file_system/sync_file_system_service.h"
#include "chrome/browser/sync_file_system/sync_file_system_service_factory.h"
#include "chrome/common/extensions/api/sync_file_system.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/content_client.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/fileapi/file_system_url.h"
#include "storage/browser/quota/quota_manager.h"
#include "storage/common/fileapi/file_system_types.h"
#include "storage/common/fileapi/file_system_util.h"
using content::BrowserContext;
using content::BrowserThread;
using sync_file_system::ConflictResolutionPolicy;
using sync_file_system::SyncFileStatus;
using sync_file_system::SyncFileSystemServiceFactory;
using sync_file_system::SyncStatusCode;
namespace extensions {
namespace {
// Error messages.
const char kErrorMessage[] = "%s (error code: %d).";
const char kUnsupportedConflictResolutionPolicy[] =
"Policy %s is not supported.";
sync_file_system::SyncFileSystemService* GetSyncFileSystemService(
Profile* profile) {
sync_file_system::SyncFileSystemService* service =
SyncFileSystemServiceFactory::GetForProfile(profile);
if (!service)
return nullptr;
ExtensionSyncEventObserver* observer =
ExtensionSyncEventObserver::GetFactoryInstance()->Get(profile);
if (!observer)
return nullptr;
observer->InitializeForService(service);
return service;
}
std::string ErrorToString(SyncStatusCode code) {
return base::StringPrintf(
kErrorMessage,
sync_file_system::SyncStatusCodeToString(code),
static_cast<int>(code));
}
} // namespace
bool SyncFileSystemDeleteFileSystemFunction::RunAsync() {
std::string url;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url));
scoped_refptr<storage::FileSystemContext> file_system_context =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
storage::FileSystemURL file_system_url(
file_system_context->CrackURL(GURL(url)));
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
Bind(&storage::FileSystemContext::DeleteFileSystem,
file_system_context,
source_url().GetOrigin(),
file_system_url.type(),
Bind(&SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem,
this)));
return true;
}
void SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem(
base::File::Error error) {
// Repost to switch from IO thread to UI thread for SendResponse().
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
Bind(&SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem, this,
error));
return;
}
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error != base::File::FILE_OK) {
error_ = ErrorToString(sync_file_system::FileErrorToSyncStatusCode(error));
SetResult(new base::FundamentalValue(false));
SendResponse(false);
return;
}
SetResult(new base::FundamentalValue(true));
SendResponse(true);
}
bool SyncFileSystemRequestFileSystemFunction::RunAsync() {
// SyncFileSystem initialization is done in OpenFileSystem below, but we call
// GetSyncFileSystemService here too to initialize sync event observer for
// extensions API.
if (!GetSyncFileSystemService(GetProfile()))
return false;
// Initializes sync context for this extension and continue to open
// a new file system.
BrowserThread::PostTask(BrowserThread::IO,
FROM_HERE,
Bind(&storage::FileSystemContext::OpenFileSystem,
GetFileSystemContext(),
source_url().GetOrigin(),
storage::kFileSystemTypeSyncable,
storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
base::Bind(&self::DidOpenFileSystem, this)));
return true;
}
storage::FileSystemContext*
SyncFileSystemRequestFileSystemFunction::GetFileSystemContext() {
DCHECK(render_frame_host());
return BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
}
void SyncFileSystemRequestFileSystemFunction::DidOpenFileSystem(
const GURL& root_url,
const std::string& file_system_name,
base::File::Error error) {
// Repost to switch from IO thread to UI thread for SendResponse().
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
Bind(&SyncFileSystemRequestFileSystemFunction::DidOpenFileSystem,
this, root_url, file_system_name, error));
return;
}
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error != base::File::FILE_OK) {
error_ = ErrorToString(sync_file_system::FileErrorToSyncStatusCode(error));
SendResponse(false);
return;
}
base::DictionaryValue* dict = new base::DictionaryValue();
SetResult(dict);
dict->SetString("name", file_system_name);
dict->SetString("root", root_url.spec());
SendResponse(true);
}
bool SyncFileSystemGetFileStatusFunction::RunAsync() {
std::string url;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url));
scoped_refptr<storage::FileSystemContext> file_system_context =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
storage::FileSystemURL file_system_url(
file_system_context->CrackURL(GURL(url)));
sync_file_system::SyncFileSystemService* sync_file_system_service =
GetSyncFileSystemService(GetProfile());
if (!sync_file_system_service)
return false;
sync_file_system_service->GetFileSyncStatus(
file_system_url,
Bind(&SyncFileSystemGetFileStatusFunction::DidGetFileStatus, this));
return true;
}
void SyncFileSystemGetFileStatusFunction::DidGetFileStatus(
const SyncStatusCode sync_status_code,
const SyncFileStatus sync_file_status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (sync_status_code != sync_file_system::SYNC_STATUS_OK) {
error_ = ErrorToString(sync_status_code);
SendResponse(false);
return;
}
// Convert from C++ to JavaScript enum.
results_ = api::sync_file_system::GetFileStatus::Results::Create(
SyncFileStatusToExtensionEnum(sync_file_status));
SendResponse(true);
}
SyncFileSystemGetFileStatusesFunction::SyncFileSystemGetFileStatusesFunction() {
}
SyncFileSystemGetFileStatusesFunction::~SyncFileSystemGetFileStatusesFunction(
) {}
bool SyncFileSystemGetFileStatusesFunction::RunAsync() {
// All FileEntries converted into array of URL Strings in JS custom bindings.
base::ListValue* file_entry_urls = NULL;
EXTENSION_FUNCTION_VALIDATE(args_->GetList(0, &file_entry_urls));
scoped_refptr<storage::FileSystemContext> file_system_context =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
// Map each file path->SyncFileStatus in the callback map.
// TODO(calvinlo): Overload GetFileSyncStatus to take in URL array.
num_expected_results_ = file_entry_urls->GetSize();
num_results_received_ = 0;
file_sync_statuses_.clear();
sync_file_system::SyncFileSystemService* sync_file_system_service =
GetSyncFileSystemService(GetProfile());
if (!sync_file_system_service)
return false;
for (unsigned int i = 0; i < num_expected_results_; i++) {
std::string url;
file_entry_urls->GetString(i, &url);
storage::FileSystemURL file_system_url(
file_system_context->CrackURL(GURL(url)));
sync_file_system_service->GetFileSyncStatus(
file_system_url,
Bind(&SyncFileSystemGetFileStatusesFunction::DidGetFileStatus,
this, file_system_url));
}
return true;
}
void SyncFileSystemGetFileStatusesFunction::DidGetFileStatus(
const storage::FileSystemURL& file_system_url,
SyncStatusCode sync_status_code,
SyncFileStatus sync_file_status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
num_results_received_++;
DCHECK_LE(num_results_received_, num_expected_results_);
file_sync_statuses_[file_system_url] =
std::make_pair(sync_status_code, sync_file_status);
// Keep mapping file statuses until all of them have been received.
// TODO(calvinlo): Get rid of this check when batch version of
// GetFileSyncStatus(GURL urls[]); is added.
if (num_results_received_ < num_expected_results_)
return;
// All results received. Dump array of statuses into extension enum values.
// Note that the enum types need to be set as strings manually as the
// autogenerated Results::Create function thinks the enum values should be
// returned as int values.
base::ListValue* status_array = new base::ListValue();
for (URLToStatusMap::iterator it = file_sync_statuses_.begin();
it != file_sync_statuses_.end(); ++it) {
base::DictionaryValue* dict = new base::DictionaryValue();
status_array->Append(dict);
storage::FileSystemURL url = it->first;
SyncStatusCode file_error = it->second.first;
api::sync_file_system::FileStatus file_status =
SyncFileStatusToExtensionEnum(it->second.second);
dict->Set("entry", CreateDictionaryValueForFileSystemEntry(
url, sync_file_system::SYNC_FILE_TYPE_FILE));
dict->SetString("status", ToString(file_status));
if (file_error == sync_file_system::SYNC_STATUS_OK)
continue;
dict->SetString("error", ErrorToString(file_error));
}
SetResult(status_array);
SendResponse(true);
}
bool SyncFileSystemGetUsageAndQuotaFunction::RunAsync() {
std::string url;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url));
scoped_refptr<storage::FileSystemContext> file_system_context =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
storage::FileSystemURL file_system_url(
file_system_context->CrackURL(GURL(url)));
scoped_refptr<storage::QuotaManager> quota_manager =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetQuotaManager();
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
Bind(&storage::QuotaManager::GetUsageAndQuotaForWebApps,
quota_manager,
source_url().GetOrigin(),
storage::FileSystemTypeToQuotaStorageType(file_system_url.type()),
Bind(&SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota,
this)));
return true;
}
void SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota(
storage::QuotaStatusCode status,
int64 usage,
int64 quota) {
// Repost to switch from IO thread to UI thread for SendResponse().
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
Bind(&SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota, this,
status, usage, quota));
return;
}
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (status != storage::kQuotaStatusOk) {
error_ = QuotaStatusCodeToString(status);
SendResponse(false);
return;
}
api::sync_file_system::StorageInfo info;
info.usage_bytes = usage;
info.quota_bytes = quota;
results_ = api::sync_file_system::GetUsageAndQuota::Results::Create(info);
SendResponse(true);
}
bool SyncFileSystemSetConflictResolutionPolicyFunction::RunSync() {
std::string policy_string;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &policy_string));
ConflictResolutionPolicy policy = ExtensionEnumToConflictResolutionPolicy(
api::sync_file_system::ParseConflictResolutionPolicy(policy_string));
if (policy != sync_file_system::CONFLICT_RESOLUTION_POLICY_LAST_WRITE_WIN) {
SetError(base::StringPrintf(kUnsupportedConflictResolutionPolicy,
policy_string.c_str()));
return false;
}
return true;
}
bool SyncFileSystemGetConflictResolutionPolicyFunction::RunSync() {
SetResult(new base::StringValue(
api::sync_file_system::ToString(
api::sync_file_system::CONFLICT_RESOLUTION_POLICY_LAST_WRITE_WIN)));
return true;
}
bool SyncFileSystemGetServiceStatusFunction::RunSync() {
sync_file_system::SyncFileSystemService* service =
GetSyncFileSystemService(GetProfile());
if (!service)
return false;
results_ = api::sync_file_system::GetServiceStatus::Results::Create(
SyncServiceStateToExtensionEnum(service->GetSyncServiceState()));
return true;
}
} // namespace extensions
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
8cf404733987f076fd539e23316480de1cfbc63c | 9f156c1282493ddc322c9a352c54a06f6a72bf45 | /sum.cpp | 5c5b9d763d8910096db092a18d3fa89c88a6a35e | [] | no_license | notetook/sum_test | 1cda6da888864f2daa218544145b332d965b48ab | 5ac36aacd90b50080d59698b4982195f8f11aca0 | refs/heads/master | 2020-06-26T18:15:30.605743 | 2016-09-08T08:00:20 | 2016-09-08T08:00:20 | 67,676,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45 | cpp | int sum ( int n )
{
return n * (n+1) / 2;
}
| [
"notetake@korea.ac.kr"
] | notetake@korea.ac.kr |
7bda8d0e3c66f839bba4cecff1c2c49fb1de3403 | 7f18180685eb683cc46edd9ad73306a365e501cd | /Romulus/Source/Utility/SceneToSTL.cpp | 62fabcfdeb255b401550f2f6567e24573434b853 | [] | no_license | jfhamlin/perry | fab62ace7d80cb4d661c26b901263d4ad56b0ac2 | 2ff74d5c71c254b8857f1d7fac8499eee56ea5ab | refs/heads/master | 2021-09-05T04:15:57.545952 | 2018-01-24T04:35:29 | 2018-01-24T04:35:29 | 118,711,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,834 | cpp | #include "Render/IScene.h"
#include "Math/Matrix.h"
#include "Math/Vector.h"
#include "Utility/SceneToSTL.h"
#include <map>
namespace romulus
{
using namespace render;
using namespace math;
namespace
{
void GeometryChunkInstanceToSTL(const GeometryChunkInstance& gci,
std::ostream& out)
{
const Matrix44& xform = gci.Transform();
const GeometryChunk* gc = gci.GeometryChunk();
const ushort_t* ind = gc->Indices();
for (uint_t index = 0; index < gc->IndexCount(); index += 3)
{
if (ind[index] == ind[index + 1] && ind[index] == ind[index + 2])
continue;
Vector3 v0, v1, v2;
v0 = gc->Vertices()[ind[index]];
v1 = gc->Vertices()[ind[index + 1]];
v2 = gc->Vertices()[ind[index + 2]];
Vector3 normal = Normal(Cross(Normal(v1 - v0), Normal(v2 - v1)));
normal = Submatrix<3, 3, 0, 0>(xform) * normal;
out << " facet normal " << normal[0] << ' ' << normal[1] <<
' ' << normal[2] << '\n';
out << " outer loop\n";
for (uint_t i = 0; i < 3; ++i)
{
Vector4 vert(gc->Vertices()[ind[index + i]], 1);
vert = xform * vert;
out << " vertex " << vert[0] << ' ' << vert[1] <<
' ' << vert[2] << '\n';
}
out << " endloop\n";
out << " endfacet\n";
}
}
} // namespace
void SceneFrameToSTL(const render::IScene& scene, std::ostream& out)
{
out << "solid FOO\n";
IScene::GeometryCollection geo;
scene.Geometry(geo);
// Emit the geometry chunk instances.
for (IScene::GeometryCollection::iterator it = geo.begin();
it != geo.end(); ++it)
{
GeometryChunkInstanceToSTL(**it, out);
}
out << "endsolid FOO\n";
}
} // namespace romulus
| [
"james@goforward.com"
] | james@goforward.com |
5834e2a9503c0334f18f0a723119cbc5a6b7abf0 | 12efddb38fd5bd1c2b2b3bb1b672714b694d5602 | /lualib/lualib_sharedmemory.cpp | d6fd98f2a39527474253ba79e1e322e44740cdc0 | [] | no_license | chenxp-github/SmallToolsV2 | 884d61200f556379551477030aa06c64593ce9d4 | 1a8aa863d0bc3744d376284ace85c7503b871f45 | refs/heads/master | 2022-06-01T05:19:25.417439 | 2022-04-30T05:31:53 | 2022-04-30T05:31:53 | 210,530,450 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,263 | cpp | #include "lualib_sharedmemory.h"
#include "mem_tool.h"
#include "sys_log.h"
#include "lualib_stream.h"
LUA_IS_VALID_USER_DATA_FUNC(CSharedMemory,sharedmemory)
LUA_GET_OBJ_FROM_USER_DATA_FUNC(CSharedMemory,sharedmemory)
LUA_NEW_USER_DATA_FUNC(CSharedMemory,sharedmemory,SHAREDMEMORY)
LUA_GC_FUNC(CSharedMemory,sharedmemory)
LUA_IS_SAME_FUNC(CSharedMemory,sharedmemory)
LUA_TO_STRING_FUNC(CSharedMemory,sharedmemory)
bool is_sharedmemory(lua_State *L, int idx)
{
const char* ud_names[] = {
LUA_USERDATA_SHAREDMEMORY,
};
lua_userdata *ud = NULL;
for(size_t i = 0; i < sizeof(ud_names)/sizeof(ud_names[0]); i++)
{
ud = (lua_userdata*)luaL_testudata(L, idx, ud_names[i]);
if(ud)break;
}
return sharedmemory_is_userdata_valid(ud);
}
/****************************************************/
static status_t sharedmemory_new(lua_State *L)
{
CSharedMemory *psharedmemory;
NEW(psharedmemory,CSharedMemory);
psharedmemory->Init();
sharedmemory_new_userdata(L,psharedmemory,0);
return 1;
}
static status_t sharedmemory_zero(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->Zero();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_getsize(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
int ret0 = psharedmemory->GetSize();
lua_pushinteger(L,ret0);
return 1;
}
static status_t sharedmemory_openreadwrite(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->OpenReadWrite();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_openreadonly(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->OpenReadOnly();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_opencreate(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
int size = (int)lua_tointeger(L,2);
status_t ret0 = psharedmemory->OpenCreate(size);
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_setname(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
int name = (int)lua_tointeger(L,2);
status_t ret0 = psharedmemory->SetName(name);
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_unlink(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->Unlink();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_close(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->Close();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_destroy(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->Destroy();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_stream(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
if(psharedmemory->GetData() == NULL)
return 0;
if(psharedmemory->GetSize() == 0)
return 0;
CStream *stream;
NEW(stream,CStream);
stream->Init();
stream->SetRawBuf(psharedmemory->GetData(),psharedmemory->GetSize(),false);
stream_new_userdata(L,stream,0);
return 1;
}
/****************************************************/
static const luaL_Reg sharedmemory_funcs_[] = {
{"__gc",sharedmemory_gc_},
{"__tostring",sharedmemory_tostring_},
{"__is_same",sharedmemory_issame_},
{"new",sharedmemory_new},
{"Zero",sharedmemory_zero},
{"GetSize",sharedmemory_getsize},
{"OpenReadWrite",sharedmemory_openreadwrite},
{"OpenReadOnly",sharedmemory_openreadonly},
{"OpenCreate",sharedmemory_opencreate},
{"SetName",sharedmemory_setname},
{"Unlink",sharedmemory_unlink},
{"Close",sharedmemory_close},
{"Destroy",sharedmemory_destroy},
{"Stream",sharedmemory_stream},
{NULL,NULL},
};
const luaL_Reg* get_sharedmemory_funcs()
{
return sharedmemory_funcs_;
}
static int luaL_register_sharedmemory(lua_State *L)
{
static luaL_Reg _sharedmemory_funcs_[MAX_LUA_FUNCS];
int _index = 0;
CLuaVm::CombineLuaFuncTable(_sharedmemory_funcs_,&_index,get_sharedmemory_funcs(),true);
luaL_newmetatable(L, LUA_USERDATA_SHAREDMEMORY);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L,_sharedmemory_funcs_,0);
lua_pop(L, 1);
luaL_newlib(L,_sharedmemory_funcs_);
return 1;
}
int luaopen_sharedmemory(lua_State *L)
{
luaL_requiref(L, "SharedMemory",luaL_register_sharedmemory,1);
lua_pop(L, 1);
return 0;
}
| [
"xiangpeng_chen@126.com"
] | xiangpeng_chen@126.com |
af0a587c874cb571aa4517a9f78365679e8ea266 | 3dce87b553dc904240c9c6230a5fd18371020e48 | /src/Quadraphonics.cpp | 0dc43572ca61245d7baea37fd104c7b4305ecc4f | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | KoreTeknology/Quadraphonic-Plugins-for-VCV-Rack | ce1729eb98031af8ee6acc2dccb32db08e5d43b5 | 96885ce5351d06ba3e603e4d29c4403f23edc53e | refs/heads/master | 2022-06-16T09:36:04.288728 | 2019-02-28T19:28:32 | 2019-02-28T19:28:32 | 170,126,911 | 13 | 4 | BSD-3-Clause | 2022-05-27T01:17:28 | 2019-02-11T12:42:46 | C++ | UTF-8 | C++ | false | false | 922 | cpp | //***********************************************************************************************
//
// QuadraphonicStudio Modules for VCV Rack by Uriel deveaud
// Module name: Main cpp for Quadraphonics modules
// https://github.com/KoreTeknology/Quadraphonic-Plugins-for-VCV-Rack
//
//***********************************************************************************************
#include "Quadraphonics.hpp"
Plugin *plugin;
void init(Plugin *p) {
plugin = p;
p->slug = TOSTRING(SLUG);
p->version = TOSTRING(VERSION);
// Add all Models defined throughout the plugin
p->addModel(modelQS_Diffuser);
p->addModel(modelQS_Merger);
p->addModel(modelQS_AudioOutputs);
p->addModel(modelQS_Vumeter);
p->addModel(modelQS_Blank4);
// Any other plugin initialization may go here.
// As an alternative, consider lazy-loading assets and lookup tables when your module is created to reduce startup times of Rack.
}
| [
"noreply@github.com"
] | KoreTeknology.noreply@github.com |
c6736e136dc0c5cf9feb61c3e784acd048ecb732 | 77c7744d0b303165f0418eaef588939b561c98f2 | /Module 2/Chapter03/chapter03/scenetoon.h | 2509b531c5178c556ef2bac1ba496329aca75545 | [
"MIT"
] | permissive | PacktPublishing/OpenGL-Build-High-Performance-Graphics | 3e5f0dcae0b0c60b8c41d52aa32b20fe6aacc5dc | 7e68e1f2cf1b0a02c82786c6fde93b34b42f2b86 | refs/heads/master | 2023-02-16T04:21:45.656668 | 2023-01-30T10:14:51 | 2023-01-30T10:14:51 | 88,623,563 | 81 | 26 | null | null | null | null | UTF-8 | C++ | false | false | 650 | h | #ifndef SCENETOON_H
#define SCENETOON_H
#include "scene.h"
#include "glslprogram.h"
#include "vboplane.h"
#include "vboteapot.h"
#include "vbotorus.h"
#include "cookbookogl.h"
#include <glm/glm.hpp>
using glm::mat4;
class SceneToon : public Scene
{
private:
GLSLProgram prog;
int width, height;
VBOPlane *plane;
VBOTeapot *teapot;
VBOTorus *torus;
mat4 model;
mat4 view;
mat4 projection;
float angle;
void setMatrices();
void compileAndLinkShader();
public:
SceneToon();
void initScene();
void update( float t );
void render();
void resize(int, int);
};
#endif // SCENETOON_H
| [
"jijom@packtpub.com"
] | jijom@packtpub.com |
a23e7ace9ea99cdb56e58ab77b377c0406359e74 | cc051fc770f7dce5b19750cf8eade652fe03f17c | /depthCameraPcl.h | 137f8889b4168553d3bfd7e4c8fb39b8f2ade219 | [] | no_license | underdoeg/godot-depth-camera-test | f0778f0b1444775924a28d51443b8768f5988547 | f823b0fcbc4fe74c1e88196cd2288a07aaabcf8d | refs/heads/master | 2021-01-19T20:12:15.411608 | 2017-03-11T22:33:16 | 2017-03-11T22:33:16 | 84,684,085 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 332 | h | #ifndef DEPTHCAMERAPCL_H
#define DEPTHCAMERAPCL_H
#include "depthCamera.h"
class DepthCameraPcl: public DepthCamera{
OBJ_TYPE(DepthCameraPcl, DepthCamera)
public:
DepthCameraPcl();
bool startGrabbingImpl();
bool stopGrabbingImpl();
private:
std::shared_ptr<pcl::io::OpenNI2Grabber> grabber;
};
#endif // DEPTHCAMERAPCL_H
| [
"philip@undef.ch"
] | philip@undef.ch |
9b054940c7234e0fb6f166d49f485391caebcd21 | 9e0d6d3cff2e03ab4487269f295dc872e07544e4 | /src/main.h | dacb3d07593e205e788304167fcaeb117276d78d | [
"MIT"
] | permissive | gyun0526/ESRcoin | b39c6776f6b767e6f87d57b227b1233201219515 | 25a418f88f7554a00f60a9cbfcb875f07d2c75fc | refs/heads/master | 2021-05-03T11:34:53.617508 | 2018-02-07T03:12:29 | 2018-02-07T03:12:29 | 120,550,930 | 1 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 72,423 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "script.h"
#include "scrypt.h"
#include <list>
class CWallet;
class CBlock;
class CBlockIndex;
class CKeyItem;
class CReserveKey;
class CAddress;
class CInv;
class CNode;
struct CBlockIndexWorkComparator;
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_BLOCK_SIZE = 1000000; // 1000KB block hard limit
/** Obsolete: maximum size for mined blocks */
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/4; // 250KB block soft limit
/** Default for -blockmaxsize, maximum size for mined blocks **/
static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 250000;
/** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 17000;
/** The maximum size for transactions we're willing to relay/mine */
static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
/** The maximum allowed number of signature check operations in a block (network rule) */
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
/** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 25;
/** The maximum size of a blk?????.dat file (since 0.8) */
static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
/** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
/** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
/** Dust Soft Limit, allowed with additional fee per output */
static const int64 DUST_SOFT_LIMIT = 100000; // 0.001 ESRC
/** Dust Hard Limit, ignored as wallet inputs (mininput default) */
static const int64 DUST_HARD_LIMIT = 1000; // 0.00001 ESRC mininput
/** No amount larger than this (in satoshi) is valid */
static const int64 MAX_MONEY = 144000000 * COIN;
inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
/** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
static const int COINBASE_MATURITY = 20;
/** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
/** Maximum number of script-checking threads allowed */
static const int MAX_SCRIPTCHECK_THREADS = 16;
#ifdef USE_UPNP
static const int fHaveUPnP = true;
#else
static const int fHaveUPnP = false;
#endif
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
extern uint256 hashGenesisBlock;
extern CBlockIndex* pindexGenesisBlock;
extern int nBestHeight;
extern uint256 nBestChainWork;
extern uint256 nBestInvalidWork;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated;
extern uint64 nLastBlockTx;
extern uint64 nLastBlockSize;
extern const std::string strMessageMagic;
extern double dHashesPerSec;
extern int64 nHPSTimerStart;
extern int64 nTimeBestReceived;
extern CCriticalSection cs_setpwalletRegistered;
extern std::set<CWallet*> setpwalletRegistered;
extern unsigned char pchMessageStart[4];
extern bool fImporting;
extern bool fReindex;
extern bool fBenchmark;
extern int nScriptCheckThreads;
extern bool fTxIndex;
extern unsigned int nCoinCacheSize;
// Settings
extern int64 nTransactionFee;
extern int64 nMinimumInputValue;
// Minimum disk space required - used in CheckDiskSpace()
static const uint64 nMinDiskSpace = 52428800;
class CReserveKey;
class CCoinsDB;
class CBlockTreeDB;
struct CDiskBlockPos;
class CCoins;
class CTxUndo;
class CCoinsView;
class CCoinsViewCache;
class CScriptCheck;
class CValidationState;
struct CBlockTemplate;
/** Register a wallet to receive updates from core */
void RegisterWallet(CWallet* pwalletIn);
/** Unregister a wallet from core */
void UnregisterWallet(CWallet* pwalletIn);
/** Push an updated transaction to all registered wallets */
void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
/** Process an incoming block */
bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
/** Check whether enough disk space is available for an incoming block */
bool CheckDiskSpace(uint64 nAdditionalBytes = 0);
/** Open a block file (blk?????.dat) */
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Open an undo file (rev?????.dat) */
FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Import blocks from an external file */
bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
/** Initialize a new block tree database + block data on disk */
bool InitBlockIndex();
/** Load the block tree and coins database from disk */
bool LoadBlockIndex();
/** Unload database information */
void UnloadBlockIndex();
/** Verify consistency of the block and coin databases */
bool VerifyDB(int nCheckLevel, int nCheckDepth);
/** Print the loaded block tree */
void PrintBlockTree();
/** Find a block by height in the currently-connected chain */
CBlockIndex* FindBlockByHeight(int nHeight);
/** Process protocol messages received from a given node */
bool ProcessMessages(CNode* pfrom);
/** Send queued protocol messages to be sent to a give node */
bool SendMessages(CNode* pto, bool fSendTrickle);
/** Run an instance of the script checking thread */
void ThreadScriptCheck();
/** Run the miner threads */
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
/** Generate a new block, without valid proof-of-work */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey);
/** Modify the extranonce in a block */
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
/** Do mining precalculation */
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
/** Check mined block */
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
/** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
/** Get the number of active peers */
int GetNumBlocksOfPeers();
/** Check whether we are doing an initial block download (synchronizing from disk or network) */
bool IsInitialBlockDownload();
/** Format a string that describes several potential problems detected by the core */
std::string GetWarnings(std::string strFor);
/** Retrieve a transaction (from memory pool, or from disk, if possible) */
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
/** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew);
/** Find the best known block, and make it the tip of the block chain */
bool ConnectBestBlock(CValidationState &state);
/** Create a new block index entry for a given block hash */
CBlockIndex * InsertBlockIndex(uint256 hash);
/** Verify a signature */
bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
/** Abort with a message */
bool AbortNode(const std::string &msg);
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
struct CDiskBlockPos
{
int nFile;
unsigned int nPos;
IMPLEMENT_SERIALIZE(
READWRITE(VARINT(nFile));
READWRITE(VARINT(nPos));
)
CDiskBlockPos() {
SetNull();
}
CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
nFile = nFileIn;
nPos = nPosIn;
}
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return (a.nFile == b.nFile && a.nPos == b.nPos);
}
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return !(a == b);
}
void SetNull() { nFile = -1; nPos = 0; }
bool IsNull() const { return (nFile == -1); }
};
struct CDiskTxPos : public CDiskBlockPos
{
unsigned int nTxOffset; // after header
IMPLEMENT_SERIALIZE(
READWRITE(*(CDiskBlockPos*)this);
READWRITE(VARINT(nTxOffset));
)
CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
}
CDiskTxPos() {
SetNull();
}
void SetNull() {
CDiskBlockPos::SetNull();
nTxOffset = 0;
}
};
/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
CTransaction* ptx;
unsigned int n;
CInPoint() { SetNull(); }
CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = (unsigned int) -1; }
bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
unsigned int n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { hash = 0; n = (unsigned int) -1; }
bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().c_str(), n);
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
unsigned int nSequence;
CTxIn()
{
nSequence = std::numeric_limits<unsigned int>::max();
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
)
bool IsFinal() const
{
return (nSequence == std::numeric_limits<unsigned int>::max());
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
int64 nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(nValue);
READWRITE(scriptPubKey);
)
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull() const
{
return (nValue == -1);
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
bool IsDust() const;
std::string ToString() const
{
return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
enum GetMinFee_mode
{
GMF_BLOCK,
GMF_RELAY,
GMF_SEND,
};
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
static int64 nMinTxFee;
static int64 nMinRelayTxFee;
static const int CURRENT_VERSION=1;
int nVersion;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
CTransaction()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = CTransaction::CURRENT_VERSION;
vin.clear();
vout.clear();
nLockTime = 0;
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
uint256 GetNormalizedHash() const
{
return SignatureHash(CScript(), *this, 0, SIGHASH_ALL);
}
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
{
// Time based nLockTime implemented in 0.1.6
if (nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.IsFinal())
return false;
return true;
}
bool IsNewerThan(const CTransaction& old) const
{
if (vin.size() != old.vin.size())
return false;
for (unsigned int i = 0; i < vin.size(); i++)
if (vin[i].prevout != old.vin[i].prevout)
return false;
bool fNewer = false;
unsigned int nLowest = std::numeric_limits<unsigned int>::max();
for (unsigned int i = 0; i < vin.size(); i++)
{
if (vin[i].nSequence != old.vin[i].nSequence)
{
if (vin[i].nSequence <= nLowest)
{
fNewer = false;
nLowest = vin[i].nSequence;
}
if (old.vin[i].nSequence < nLowest)
{
fNewer = true;
nLowest = old.vin[i].nSequence;
}
}
}
return fNewer;
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
/** Check for standard transaction types
@return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandard(std::string& strReason) const;
bool IsStandard() const
{
std::string strReason;
return IsStandard(strReason);
}
/** Check for standard transaction types
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return True if all inputs (scriptSigs) use only standard transaction forms
*/
bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
@return number of sigops this transaction's outputs will produce when spent
*/
unsigned int GetLegacySigOpCount() const;
/** Count ECDSA signature operations in pay-to-script-hash inputs.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return maximum number of sigops required to validate this transaction's inputs
*/
unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
/** Amount of bitcoins spent by this transaction.
@return sum of all outputs (note: does not include fees)
*/
int64 GetValueOut() const
{
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
/** Amount of bitcoins coming in to this transaction
Note that lightweight clients may not know anything besides the hash of previous transactions,
so may not be able to calculate this.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return Sum of value of all inputs (scriptSigs)
*/
int64 GetValueIn(CCoinsViewCache& mapInputs) const;
static bool AllowFree(double dPriority)
{
// Large (in bytes) low-priority (new, small-coin) transactions
// need a fee.
return dPriority > COIN * 576 / 250;
}
// Apply the effects of this transaction on the UTXO set represented by view
void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash);
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
GetHash().ToString().c_str(),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void print() const
{
printf("%s", ToString().c_str());
}
// Check whether all prevouts of this transaction are present in the UTXO set represented by view
bool HaveInputs(CCoinsViewCache &view) const;
// Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
// This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
// instead of being performed inline.
bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
std::vector<CScriptCheck> *pvChecks = NULL) const;
// Apply the effects of this transaction on the UTXO set represented by view
void UpdateCoins(CValidationState &state, CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const;
// Context-independent validity checks
bool CheckTransaction(CValidationState &state) const;
// Try to accept this transaction into the memory pool
bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree = true, bool* pfMissingInputs=NULL, bool fRejectInsaneFee = false);
protected:
static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
};
/** wrapper for CTxOut that provides a more compact serialization */
class CTxOutCompressor
{
private:
CTxOut &txout;
public:
static uint64 CompressAmount(uint64 nAmount);
static uint64 DecompressAmount(uint64 nAmount);
CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
IMPLEMENT_SERIALIZE(({
if (!fRead) {
uint64 nVal = CompressAmount(txout.nValue);
READWRITE(VARINT(nVal));
} else {
uint64 nVal = 0;
READWRITE(VARINT(nVal));
txout.nValue = DecompressAmount(nVal);
}
CScriptCompressor cscript(REF(txout.scriptPubKey));
READWRITE(cscript);
});)
};
/** Undo information for a CTxIn
*
* Contains the prevout's CTxOut being spent, and if this was the
* last output of the affected transaction, its metadata as well
* (coinbase or not, height, transaction version)
*/
class CTxInUndo
{
public:
CTxOut txout; // the txout data before being spent
bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
unsigned int nHeight; // if the outpoint was the last unspent: its height
int nVersion; // if the outpoint was the last unspent: its version
CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
unsigned int GetSerializeSize(int nType, int nVersion) const {
return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
(nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
}
template<typename Stream>
void Serialize(Stream &s, int nType, int nVersion) const {
::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
if (nHeight > 0)
::Serialize(s, VARINT(this->nVersion), nType, nVersion);
::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int nCode = 0;
::Unserialize(s, VARINT(nCode), nType, nVersion);
nHeight = nCode / 2;
fCoinBase = nCode & 1;
if (nHeight > 0)
::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
}
};
/** Undo information for a CTransaction */
class CTxUndo
{
public:
// undo information for all txins
std::vector<CTxInUndo> vprevout;
IMPLEMENT_SERIALIZE(
READWRITE(vprevout);
)
};
/** Undo information for a CBlock */
class CBlockUndo
{
public:
std::vector<CTxUndo> vtxundo; // for all but the coinbase
IMPLEMENT_SERIALIZE(
READWRITE(vtxundo);
)
bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
{
// Open history file to append
CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write undo data
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlockUndo::WriteToDisk() : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// calculate & write checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
fileout << hasher.GetHash();
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload())
FileCommit(fileout);
return true;
}
bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
{
// Open history file to read
CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed");
// Read block
uint256 hashChecksum;
try {
filein >> *this;
filein >> hashChecksum;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Verify checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
if (hashChecksum != hasher.GetHash())
return error("CBlockUndo::ReadFromDisk() : checksum mismatch");
return true;
}
};
/** pruned version of CTransaction: only retains metadata and unspent transaction outputs
*
* Serialized format:
* - VARINT(nVersion)
* - VARINT(nCode)
* - unspentness bitvector, for vout[2] and further; least significant byte first
* - the non-spent CTxOuts (via CTxOutCompressor)
* - VARINT(nHeight)
*
* The nCode value consists of:
* - bit 1: IsCoinBase()
* - bit 2: vout[0] is not spent
* - bit 4: vout[1] is not spent
* - The higher bits encode N, the number of non-zero bytes in the following bitvector.
* - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
* least one non-spent output).
*
* Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
* <><><--------------------------------------------><---->
* | \ | /
* version code vout[1] height
*
* - version = 1
* - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
* - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
* - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
* * 8358: compact amount representation for 60000000000 (600 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
* - height = 203998
*
*
* Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
* <><><--><--------------------------------------------------><----------------------------------------------><---->
* / \ \ | | /
* version code unspentness vout[4] vout[16] height
*
* - version = 1
* - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
* 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
* - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
* - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
* * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
* - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
* * bbd123: compact amount representation for 110397 (0.001 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
* - height = 120891
*/
class CCoins
{
public:
// whether transaction is a coinbase
bool fCoinBase;
// unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
std::vector<CTxOut> vout;
// at which height this transaction was included in the active block chain
int nHeight;
// version of the CTransaction; accesses to this value should probably check for nHeight as well,
// as new tx version will probably only be introduced at certain heights
int nVersion;
// construct a CCoins from a CTransaction, at a given height
CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
// empty constructor
CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
// remove spent outputs at the end of vout
void Cleanup() {
while (vout.size() > 0 && vout.back().IsNull())
vout.pop_back();
if (vout.empty())
std::vector<CTxOut>().swap(vout);
}
void swap(CCoins &to) {
std::swap(to.fCoinBase, fCoinBase);
to.vout.swap(vout);
std::swap(to.nHeight, nHeight);
std::swap(to.nVersion, nVersion);
}
// equality test
friend bool operator==(const CCoins &a, const CCoins &b) {
return a.fCoinBase == b.fCoinBase &&
a.nHeight == b.nHeight &&
a.nVersion == b.nVersion &&
a.vout == b.vout;
}
friend bool operator!=(const CCoins &a, const CCoins &b) {
return !(a == b);
}
// calculate number of bytes for the bitmask, and its number of non-zero bytes
// each bit in the bitmask represents the availability of one output, but the
// availabilities of the first two outputs are encoded separately
void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
if (!vout[2+b*8+i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool IsCoinBase() const {
return fCoinBase;
}
unsigned int GetSerializeSize(int nType, int nVersion) const {
unsigned int nSize = 0;
unsigned int nMaskSize = 0, nMaskCode = 0;
CalcMaskSize(nMaskSize, nMaskCode);
bool fFirst = vout.size() > 0 && !vout[0].IsNull();
bool fSecond = vout.size() > 1 && !vout[1].IsNull();
assert(fFirst || fSecond || nMaskCode);
unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
// version
nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
// size of header code
nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
// spentness bitmask
nSize += nMaskSize;
// txouts themself
for (unsigned int i = 0; i < vout.size(); i++)
if (!vout[i].IsNull())
nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
// height
nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
return nSize;
}
template<typename Stream>
void Serialize(Stream &s, int nType, int nVersion) const {
unsigned int nMaskSize = 0, nMaskCode = 0;
CalcMaskSize(nMaskSize, nMaskCode);
bool fFirst = vout.size() > 0 && !vout[0].IsNull();
bool fSecond = vout.size() > 1 && !vout[1].IsNull();
assert(fFirst || fSecond || nMaskCode);
unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
// version
::Serialize(s, VARINT(this->nVersion), nType, nVersion);
// header code
::Serialize(s, VARINT(nCode), nType, nVersion);
// spentness bitmask
for (unsigned int b = 0; b<nMaskSize; b++) {
unsigned char chAvail = 0;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
if (!vout[2+b*8+i].IsNull())
chAvail |= (1 << i);
::Serialize(s, chAvail, nType, nVersion);
}
// txouts themself
for (unsigned int i = 0; i < vout.size(); i++) {
if (!vout[i].IsNull())
::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
}
// coinbase height
::Serialize(s, VARINT(nHeight), nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int nCode = 0;
// version
::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
// header code
::Unserialize(s, VARINT(nCode), nType, nVersion);
fCoinBase = nCode & 1;
std::vector<bool> vAvail(2, false);
vAvail[0] = nCode & 2;
vAvail[1] = nCode & 4;
unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
// spentness bitmask
while (nMaskCode > 0) {
unsigned char chAvail = 0;
::Unserialize(s, chAvail, nType, nVersion);
for (unsigned int p = 0; p < 8; p++) {
bool f = (chAvail & (1 << p)) != 0;
vAvail.push_back(f);
}
if (chAvail != 0)
nMaskCode--;
}
// txouts themself
vout.assign(vAvail.size(), CTxOut());
for (unsigned int i = 0; i < vAvail.size(); i++) {
if (vAvail[i])
::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
}
// coinbase height
::Unserialize(s, VARINT(nHeight), nType, nVersion);
Cleanup();
}
// mark an outpoint spent, and construct undo information
bool Spend(const COutPoint &out, CTxInUndo &undo) {
if (out.n >= vout.size())
return false;
if (vout[out.n].IsNull())
return false;
undo = CTxInUndo(vout[out.n]);
vout[out.n].SetNull();
Cleanup();
if (vout.size() == 0) {
undo.nHeight = nHeight;
undo.fCoinBase = fCoinBase;
undo.nVersion = this->nVersion;
}
return true;
}
// mark a vout spent
bool Spend(int nPos) {
CTxInUndo undo;
COutPoint out(0, nPos);
return Spend(out, undo);
}
// check whether a particular output is still available
bool IsAvailable(unsigned int nPos) const {
return (nPos < vout.size() && !vout[nPos].IsNull());
}
// check whether the entire CCoins is spent
// note that only !IsPruned() CCoins can be serialized
bool IsPruned() const {
BOOST_FOREACH(const CTxOut &out, vout)
if (!out.IsNull())
return false;
return true;
}
};
/** Closure representing one script verification
* Note that this stores references to the spending transaction */
class CScriptCheck
{
private:
CScript scriptPubKey;
const CTransaction *ptxTo;
unsigned int nIn;
unsigned int nFlags;
int nHashType;
public:
CScriptCheck() {}
CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
bool operator()() const;
void swap(CScriptCheck &check) {
scriptPubKey.swap(check.scriptPubKey);
std::swap(ptxTo, check.ptxTo);
std::swap(nIn, check.nIn);
std::swap(nFlags, check.nFlags);
std::swap(nHashType, check.nHashType);
}
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
private:
int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const;
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable bool fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
// Return depth of transaction in blockchain:
// -1 : not in blockchain, and not in memory pool (conflicted transaction)
// 0 : in memory pool, waiting to be included in a block
// >=1 : this many blocks deep in the main chain
int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true);
};
/** Data structure that represents a partial merkle tree.
*
* It respresents a subset of the txid's of a known block, in a way that
* allows recovery of the list of txid's and the merkle root, in an
* authenticated way.
*
* The encoding works as follows: we traverse the tree in depth-first order,
* storing a bit for each traversed node, signifying whether the node is the
* parent of at least one matched leaf txid (or a matched txid itself). In
* case we are at the leaf level, or this bit is 0, its merkle node hash is
* stored, and its children are not explorer further. Otherwise, no hash is
* stored, but we recurse into both (or the only) child branch. During
* decoding, the same depth-first traversal is performed, consuming bits and
* hashes as they written during encoding.
*
* The serialization is fixed and provides a hard guarantee about the
* encoded size:
*
* SIZE <= 10 + ceil(32.25*N)
*
* Where N represents the number of leaf nodes of the partial tree. N itself
* is bounded by:
*
* N <= total_transactions
* N <= 1 + matched_transactions*tree_height
*
* The serialization format:
* - uint32 total_transactions (4 bytes)
* - varint number of hashes (1-3 bytes)
* - uint256[] hashes in depth-first order (<= 32*N bytes)
* - varint number of bytes of flag bits (1-3 bytes)
* - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
* The size constraints follow from this.
*/
class CPartialMerkleTree
{
protected:
// the total number of transactions in the block
unsigned int nTransactions;
// node-is-parent-of-matched-txid bits
std::vector<bool> vBits;
// txids and internal hashes
std::vector<uint256> vHash;
// flag set when encountering invalid data
bool fBad;
// helper function to efficiently calculate the number of nodes at given height in the merkle tree
unsigned int CalcTreeWidth(int height) {
return (nTransactions+(1 << height)-1) >> height;
}
// calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
// recursive function that traverses tree nodes, storing the data as bits and hashes
void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
// recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
// it returns the hash of the respective node.
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
public:
// serialization implementation
IMPLEMENT_SERIALIZE(
READWRITE(nTransactions);
READWRITE(vHash);
std::vector<unsigned char> vBytes;
if (fRead) {
READWRITE(vBytes);
CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
us.vBits.resize(vBytes.size() * 8);
for (unsigned int p = 0; p < us.vBits.size(); p++)
us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
us.fBad = false;
} else {
vBytes.resize((vBits.size()+7)/8);
for (unsigned int p = 0; p < vBits.size(); p++)
vBytes[p / 8] |= vBits[p] << (p % 8);
READWRITE(vBytes);
}
)
// Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
CPartialMerkleTree();
// extract the matching txid's represented by this partial merkle tree.
// returns the merkle root, or 0 in case of failure
uint256 ExtractMatches(std::vector<uint256> &vMatch);
};
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*/
class CBlockHeader
{
public:
// header
static const int CURRENT_VERSION=2;
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockHeader()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
void SetNull()
{
nVersion = CBlockHeader::CURRENT_VERSION;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
return Hash(BEGIN(nVersion), END(nNonce));
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
void UpdateTime(const CBlockIndex* pindexPrev);
};
class CBlock : public CBlockHeader
{
public:
// network and disk
std::vector<CTransaction> vtx;
// memory only
mutable std::vector<uint256> vMerkleTree;
CBlock()
{
SetNull();
}
CBlock(const CBlockHeader &header)
{
SetNull();
*((CBlockHeader*)this) = header;
}
IMPLEMENT_SERIALIZE
(
READWRITE(*(CBlockHeader*)this);
READWRITE(vtx);
)
void SetNull()
{
CBlockHeader::SetNull();
vtx.clear();
vMerkleTree.clear();
}
uint256 GetPoWHash() const
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
const uint256 &GetTxHash(unsigned int nIndex) const {
assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
assert(nIndex < vtx.size());
return vMerkleTree[nIndex];
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(CDiskBlockPos &pos)
{
// Open history file to append
CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlock::WriteToDisk() : OpenBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlock::WriteToDisk() : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload())
FileCommit(fileout);
return true;
}
bool ReadFromDisk(const CDiskBlockPos &pos)
{
SetNull();
// Open history file to read
CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
// Read block
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Check the header
if (!CheckProofOfWork(GetPoWHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
void print() const
{
printf("CBlock(hash=%s, input=%s, PoW=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
GetHash().ToString().c_str(),
HexStr(BEGIN(nVersion),BEGIN(nVersion)+80,false).c_str(),
GetPoWHash().ToString().c_str(),
nVersion,
hashPrevBlock.ToString().c_str(),
hashMerkleRoot.ToString().c_str(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
printf(" ");
vtx[i].print();
}
printf(" vMerkleTree: ");
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
printf("%s ", vMerkleTree[i].ToString().c_str());
printf("\n");
}
/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
* In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
* will be true if no problems were found. Otherwise, the return value will be false in case
* of problems. Note that in any case, coins may be modified. */
bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean = NULL);
// Apply the effects of this block (with given index) on the UTXO set represented by coins
bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
// Read a block from disk
bool ReadFromDisk(const CBlockIndex* pindex);
// Add this block to the block index, and if necessary, switch the active block chain to this
bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos);
// Context-independent validity checks
bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
// Store block on disk
// if dbp is provided, the file is known to already reside on disk
bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp = NULL);
};
class CBlockFileInfo
{
public:
unsigned int nBlocks; // number of blocks stored in file
unsigned int nSize; // number of used bytes of block file
unsigned int nUndoSize; // number of used bytes in the undo file
unsigned int nHeightFirst; // lowest height of block in file
unsigned int nHeightLast; // highest height of block in file
uint64 nTimeFirst; // earliest time of block in file
uint64 nTimeLast; // latest time of block in file
IMPLEMENT_SERIALIZE(
READWRITE(VARINT(nBlocks));
READWRITE(VARINT(nSize));
READWRITE(VARINT(nUndoSize));
READWRITE(VARINT(nHeightFirst));
READWRITE(VARINT(nHeightLast));
READWRITE(VARINT(nTimeFirst));
READWRITE(VARINT(nTimeLast));
)
void SetNull() {
nBlocks = 0;
nSize = 0;
nUndoSize = 0;
nHeightFirst = 0;
nHeightLast = 0;
nTimeFirst = 0;
nTimeLast = 0;
}
CBlockFileInfo() {
SetNull();
}
std::string ToString() const {
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str());
}
// update statistics (does not update nSize)
void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
if (nBlocks==0 || nHeightFirst > nHeightIn)
nHeightFirst = nHeightIn;
if (nBlocks==0 || nTimeFirst > nTimeIn)
nTimeFirst = nTimeIn;
nBlocks++;
if (nHeightIn > nHeightFirst)
nHeightLast = nHeightIn;
if (nTimeIn > nTimeLast)
nTimeLast = nTimeIn;
}
};
extern CCriticalSection cs_LastBlockFile;
extern CBlockFileInfo infoLastBlockFile;
extern int nLastBlockFile;
enum BlockStatus {
BLOCK_VALID_UNKNOWN = 0,
BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
BLOCK_VALID_MASK = 7,
BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
BLOCK_HAVE_MASK = 24,
BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, // descends from failed block
BLOCK_FAILED_MASK = 96
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. pprev and pnext link a path through the
* main/longest chain. A blockindex may have multiple pprev pointing back
* to it, but pnext will only point forward to the longest branch, or will
* be null if the block is not part of the longest chain.
*/
class CBlockIndex
{
public:
// pointer to the hash of the block, if any. memory is owned by this CBlockIndex
const uint256* phashBlock;
// pointer to the index of the predecessor of this block
CBlockIndex* pprev;
// (memory only) pointer to the index of the *active* successor of this block
CBlockIndex* pnext;
// height of the entry in the chain. The genesis block has height 0
int nHeight;
// Which # file this block is stored in (blk?????.dat)
int nFile;
// Byte offset within blk?????.dat where this block's data is stored
unsigned int nDataPos;
// Byte offset within rev?????.dat where this block's undo data is stored
unsigned int nUndoPos;
// (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
uint256 nChainWork;
// Number of transactions in this block.
// Note: in a potential headers-first mode, this number cannot be relied upon
unsigned int nTx;
// (memory only) Number of transactions in the chain up to and including this block
unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
// Verification status of this block. See enum BlockStatus
unsigned int nStatus;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(CBlockHeader& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CDiskBlockPos GetBlockPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_DATA) {
ret.nFile = nFile;
ret.nPos = nDataPos;
}
return ret;
}
CDiskBlockPos GetUndoPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_UNDO) {
ret.nFile = nFile;
ret.nPos = nUndoPos;
}
return ret;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
CBigNum GetBlockWork() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
return (CBigNum(1)<<256) / (bnTarget+1);
}
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
/** Scrypt is used for block proof-of-work, but for purposes of performance the index internally uses sha256.
* This check was considered unneccessary given the other safeguards like the genesis and checkpoints. */
return true; // return CheckProofOfWork(GetBlockHash(), nBits);
}
enum { nMedianTimeSpan=11 };
int64 GetMedianTimePast() const
{
int64 pmedian[nMedianTimeSpan];
int64* pbegin = &pmedian[nMedianTimeSpan];
int64* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
int64 GetMedianTime() const
{
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan/2; i++)
{
if (!pindex->pnext)
return GetBlockTime();
pindex = pindex->pnext;
}
return pindex->GetMedianTimePast();
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last nToCheck blocks, starting at pstart and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
unsigned int nRequired, unsigned int nToCheck);
std::string ToString() const
{
return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, pnext, nHeight,
hashMerkleRoot.ToString().c_str(),
GetBlockHash().ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
struct CBlockIndexWorkComparator
{
bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
return false; // identical blocks
}
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
CDiskBlockIndex() {
hashPrev = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(VARINT(nVersion));
READWRITE(VARINT(nHeight));
READWRITE(VARINT(nStatus));
READWRITE(VARINT(nTx));
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
READWRITE(VARINT(nFile));
if (nStatus & BLOCK_HAVE_DATA)
READWRITE(VARINT(nDataPos));
if (nStatus & BLOCK_HAVE_UNDO)
READWRITE(VARINT(nUndoPos));
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
uint256 GetBlockHash() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s)",
GetBlockHash().ToString().c_str(),
hashPrev.ToString().c_str());
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Capture information about block/transaction validation */
class CValidationState {
private:
enum mode_state {
MODE_VALID, // everything ok
MODE_INVALID, // network rule violation (DoS value may be set)
MODE_ERROR, // run-time error
} mode;
int nDoS;
bool corruptionPossible;
public:
CValidationState() : mode(MODE_VALID), nDoS(0), corruptionPossible(false) {}
bool DoS(int level, bool ret = false, bool corruptionIn = false) {
if (mode == MODE_ERROR)
return ret;
nDoS += level;
mode = MODE_INVALID;
corruptionPossible = corruptionIn;
return ret;
}
bool Invalid(bool ret = false) {
return DoS(0, ret);
}
bool Error() {
mode = MODE_ERROR;
return false;
}
bool Abort(const std::string &msg) {
AbortNode(msg);
return Error();
}
bool IsValid() {
return mode == MODE_VALID;
}
bool IsInvalid() {
return mode == MODE_INVALID;
}
bool IsError() {
return mode == MODE_ERROR;
}
bool IsInvalid(int &nDoSOut) {
if (IsInvalid()) {
nDoSOut = nDoS;
return true;
}
return false;
}
bool CorruptionPossible() {
return corruptionPossible;
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back(hashGenesisBlock);
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return hashGenesisBlock;
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
class CTxMemPool
{
public:
mutable CCriticalSection cs;
std::map<uint256, CTransaction> mapTx;
std::map<COutPoint, CInPoint> mapNextTx;
bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee = false);
bool addUnchecked(const uint256& hash, const CTransaction &tx);
bool remove(const CTransaction &tx, bool fRecursive = false);
bool removeConflicts(const CTransaction &tx);
void clear();
void queryHashes(std::vector<uint256>& vtxid);
void pruneSpent(const uint256& hash, CCoins &coins);
unsigned long size()
{
LOCK(cs);
return mapTx.size();
}
bool exists(uint256 hash)
{
return (mapTx.count(hash) != 0);
}
CTransaction& lookup(uint256 hash)
{
return mapTx[hash];
}
};
extern CTxMemPool mempool;
struct CCoinsStats
{
int nHeight;
uint256 hashBlock;
uint64 nTransactions;
uint64 nTransactionOutputs;
uint64 nSerializedSize;
uint256 hashSerialized;
int64 nTotalAmount;
CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {}
};
/** Abstract view on the open txout dataset. */
class CCoinsView
{
public:
// Retrieve the CCoins (unspent transaction outputs) for a given txid
virtual bool GetCoins(const uint256 &txid, CCoins &coins);
// Modify the CCoins for a given txid
virtual bool SetCoins(const uint256 &txid, const CCoins &coins);
// Just check whether we have data for a given txid.
// This may (but cannot always) return true for fully spent transactions
virtual bool HaveCoins(const uint256 &txid);
// Retrieve the block index whose state this CCoinsView currently represents
virtual CBlockIndex *GetBestBlock();
// Modify the currently active block index
virtual bool SetBestBlock(CBlockIndex *pindex);
// Do a bulk modification (multiple SetCoins + one SetBestBlock)
virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
// Calculate statistics about the unspent transaction output set
virtual bool GetStats(CCoinsStats &stats);
// As we use CCoinsViews polymorphically, have a virtual destructor
virtual ~CCoinsView() {}
};
/** CCoinsView backed by another CCoinsView */
class CCoinsViewBacked : public CCoinsView
{
protected:
CCoinsView *base;
public:
CCoinsViewBacked(CCoinsView &viewIn);
bool GetCoins(const uint256 &txid, CCoins &coins);
bool SetCoins(const uint256 &txid, const CCoins &coins);
bool HaveCoins(const uint256 &txid);
CBlockIndex *GetBestBlock();
bool SetBestBlock(CBlockIndex *pindex);
void SetBackend(CCoinsView &viewIn);
bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
bool GetStats(CCoinsStats &stats);
};
/** CCoinsView that adds a memory cache for transactions to another CCoinsView */
class CCoinsViewCache : public CCoinsViewBacked
{
protected:
CBlockIndex *pindexTip;
std::map<uint256,CCoins> cacheCoins;
public:
CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
// Standard CCoinsView methods
bool GetCoins(const uint256 &txid, CCoins &coins);
bool SetCoins(const uint256 &txid, const CCoins &coins);
bool HaveCoins(const uint256 &txid);
CBlockIndex *GetBestBlock();
bool SetBestBlock(CBlockIndex *pindex);
bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
// Return a modifiable reference to a CCoins. Check HaveCoins first.
// Many methods explicitly require a CCoinsViewCache because of this method, to reduce
// copying.
CCoins &GetCoins(const uint256 &txid);
// Push the modifications applied to this cache to its base.
// Failure to call this method before destruction will cause the changes to be forgotten.
bool Flush();
// Calculate the size of the cache (in number of transactions)
unsigned int GetCacheSize();
private:
std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid);
};
/** CCoinsView that brings transactions from a memorypool into view.
It does not check for spendings by memory pool transactions. */
class CCoinsViewMemPool : public CCoinsViewBacked
{
protected:
CTxMemPool &mempool;
public:
CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
bool GetCoins(const uint256 &txid, CCoins &coins);
bool HaveCoins(const uint256 &txid);
};
/** Global variable that points to the active CCoinsView (protected by cs_main) */
extern CCoinsViewCache *pcoinsTip;
/** Global variable that points to the active block tree (protected by cs_main) */
extern CBlockTreeDB *pblocktree;
struct CBlockTemplate
{
CBlock block;
std::vector<int64_t> vTxFees;
std::vector<int64_t> vTxSigOps;
};
#if defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64)
extern unsigned int cpuid_edx;
#endif
/** Used to relay blocks as header + vector<merkle branch>
* to filtered nodes.
*/
class CMerkleBlock
{
public:
// Public only for unit testing
CBlockHeader header;
CPartialMerkleTree txn;
public:
// Public only for unit testing and relay testing
// (not relayed)
std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
// Create from a CBlock, filtering transactions according to filter
// Note that this will call IsRelevantAndUpdate on the filter for each transaction,
// thus the filter will likely be modified.
CMerkleBlock(const CBlock& block, CBloomFilter& filter);
IMPLEMENT_SERIALIZE
(
READWRITE(header);
READWRITE(txn);
)
};
#endif
| [
"gyun0526@gmail.com"
] | gyun0526@gmail.com |
55fe439f98391de265ef74844cdb4454ac346bf1 | 1b0818c047ac532e38f153497de6ebcebc596359 | /src/build_tree.cpp | 30d403dc89e380e2a1f1ee3ef4eca91172fab696 | [] | no_license | peipei2015/3d_model | fbe5f7f0df736b09263b0816eebf4908ae18d4c1 | 0e4a04d6e647b395b7dc3939262d5c2609a59598 | refs/heads/master | 2021-01-20T20:36:40.304043 | 2016-06-24T11:31:33 | 2016-06-24T11:31:33 | 61,878,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,807 | cpp | #include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/console/parse.h>
#include <pcl/console/print.h>
#include <pcl/io/pcd_io.h>
#include <boost/filesystem.hpp>
#include <flann/flann.h>
#include <flann/io/hdf5.h>
#include <fstream>
typedef std::pair<std::string, std::vector<float> > vfh_model;
/** \brief Loads an n-D histogram file as a VFH signature
* \param path the input file name
* \param vfh the resultant VFH model
*/
bool loadHist (const boost::filesystem::path &path, vfh_model &vfh)
{
int vfh_idx;
// Load the file as a PCD
try
{
pcl::PCLPointCloud2 cloud;
int version;
Eigen::Vector4f origin;
Eigen::Quaternionf orientation;
pcl::PCDReader r;
int type; unsigned int idx;
r.readHeader (path.string (), cloud, origin, orientation, version, type, idx);
vfh_idx = pcl::getFieldIndex (cloud, "vfh");
if (vfh_idx == -1)
return (false);
if ((int)cloud.width * cloud.height != 1)
return (false);
}
catch (const pcl::InvalidConversionException&)
{
return (false);
}
// Treat the VFH signature as a single Point Cloud
pcl::PointCloud <pcl::VFHSignature308> point;
pcl::io::loadPCDFile (path.string (), point);
vfh.second.resize (308);
std::vector <pcl::PCLPointField> fields;
pcl::getFieldIndex (point, "vfh", fields);
for (size_t i = 0; i < fields[vfh_idx].count; ++i)
{
vfh.second[i] = point.points[0].histogram[i];
}
vfh.first = path.string ();
return (true);
}
/** \brief Load a set of VFH features that will act as the model (training data)
* \param argc the number of arguments (pass from main ())
* \param argv the actual command line arguments (pass from main ())
* \param extension the file extension containing the VFH features
* \param models the resultant vector of histogram models
*/
void loadFeatureModels (const boost::filesystem::path &base_dir, const std::string &extension,
std::vector<vfh_model> &models)
{
if (!boost::filesystem::exists (base_dir) && !boost::filesystem::is_directory (base_dir))
return;
for (boost::filesystem::directory_iterator it (base_dir); it != boost::filesystem::directory_iterator (); ++it)
{
if (boost::filesystem::is_directory (it->status ()))
{
std::stringstream ss;
ss << it->path ();
pcl::console::print_highlight ("Loading %s (%lu models loaded so far).\n", ss.str ().c_str (), (unsigned long)models.size ());
loadFeatureModels (it->path (), extension, models);
}
if (boost::filesystem::is_regular_file (it->status ()) && boost::filesystem::extension (it->path ()) == extension)
{
vfh_model m;
if (loadHist (base_dir / it->path ().filename (), m))
models.push_back (m);
}
}
}
int main (int argc, char** argv)
{
if (argc < 2)
{
PCL_ERROR ("Need at least two parameters! Syntax is: %s [model_directory] [options]\n", argv[0]);
return (-1);
}
std::string extension (".pcd");
transform (extension.begin (), extension.end (), extension.begin (), (int(*)(int))tolower);
std::string kdtree_idx_file_name = "kdtree.idx";
std::string training_data_h5_file_name = "training_data.h5";
std::string training_data_list_file_name = "training_data.list";
std::vector<vfh_model> models;
// Load the model histograms
loadFeatureModels (argv[1], extension, models);
pcl::console::print_highlight ("Loaded %d VFH models. Creating training data %s/%s.\n",
(int)models.size (), training_data_h5_file_name.c_str (), training_data_list_file_name.c_str ());
// Convert data into FLANN format
flann::Matrix<float> data (new float[models.size () * models[0].second.size ()], models.size (), models[0].second.size ());
for (size_t i = 0; i < data.rows; ++i)
for (size_t j = 0; j < data.cols; ++j)
data[i][j] = models[i].second[j];
// Save data to disk (list of models)
flann::save_to_file (data, training_data_h5_file_name, "training_data");
std::ofstream fs;
fs.open (training_data_list_file_name.c_str ());
for (size_t i = 0; i < models.size (); ++i)
fs << models[i].first << "\n";
fs.close ();
// Build the tree index and save it to disk
pcl::console::print_error ("Building the kdtree index (%s) for %d elements...\n", kdtree_idx_file_name.c_str (), (int)data.rows);
flann::Index<flann::ChiSquareDistance<float> > index (data, flann::LinearIndexParams ());
//flann::Index<flann::ChiSquareDistance<float> > index (data, flann::KDTreeIndexParams (4));
index.buildIndex ();
index.save (kdtree_idx_file_name);
delete[] data.ptr ();
return (0);
}
| [
"1607458232@qq.com"
] | 1607458232@qq.com |
3052984719aa91f18615c7937861c07a526b5082 | 2cae54fe441ad0e84b8df6917153bbe3c81ae986 | /conundrum/conundrum.cpp | 13b67d8c57c560523a8b1f629fd64b8b6202748a | [
"MIT"
] | permissive | omarchehab98/open.kattis.com-problems | 3cb08a475ca4fb156462904a221362b98c2813c9 | 0523e2e641151dad719ef05cc9811a8ef5c6a278 | refs/heads/master | 2020-03-31T04:23:06.415280 | 2019-10-29T00:50:08 | 2019-10-29T00:50:08 | 151,903,075 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 260 | cpp | #include <iostream>
using namespace std;
int main() {
string cipherText;
cin >> cipherText;
int numberOfDays = 0;
for (int i = 0; i < cipherText.size(); i++) {
if (cipherText[i] != ("PER")[i % 3]) numberOfDays++;
}
cout << numberOfDays;
} | [
"omarchehab98@gmail.com"
] | omarchehab98@gmail.com |
2981f5b7723db2c9dad0ecca3c4b790961fe5191 | 57789c0479da2d7a25478a1689ff892613ce4945 | /Classes/WXPanel.h | 5cebc8e0d8e434242d637ae9c00c956a3ab4ddbf | [] | no_license | niujianlong/Nodie | 0c83c2e762e816b3b1e25284d6379b7347361b04 | 45e25c86292a5635312b1c55545d9358fd6be7dd | refs/heads/master | 2020-04-16T22:20:56.707466 | 2015-11-12T04:29:45 | 2015-11-12T04:29:45 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,593 | h | #pragma once
#include "WXSimplePanel.h"
//移动类型
typedef enum
{
tween_type_only_start,//只从开始到结束tween
tween_type_only_end,//只从结束到开始tween
tween_type_both,//从开始到结束,结束到开始都tween
}TweenType;
class WXSimpleButton;
class WXPanel: public WXSimplePanel
{
public:
WXPanel(void);
~WXPanel(void);
virtual void initPanel();
//开关面板
virtual void toggle();
//面板移动
virtual void tween(bool isShow=true);
//创建一个关闭按钮
virtual void createCloseBtn(const char* normalName, const char* selectedName);
//关闭按钮touchBegan
virtual bool closeBtnTouchBegan(cocos2d::CCTouch* pTouch, cocos2d::CCEvent *pEvent);
//关闭按钮touchEnded
virtual bool closeBtnTouchEnded(cocos2d::CCTouch* pTouch, cocos2d::CCEvent *pEvent);
CC_SYNTHESIZE(cocos2d::CCPoint, m_startPos, StartPos);//移动开始位置
CC_SYNTHESIZE(cocos2d::CCPoint, m_endPos, EndPos);//移动停止位置
CC_SYNTHESIZE(float, m_tweenDuration, TweenDuration);//移动耗时
CC_SYNTHESIZE(bool, m_canTween, CanTween);//能否移动
CC_SYNTHESIZE(float, m_closeBtnGap, CloseBtnGap);//关闭按钮偏移
CC_SYNTHESIZE(TweenType, m_tweenType, TweenType);//滚动方式
CREATE_FUNC(WXPanel);
protected:
//tween回调(start->end)
virtual void tweenCallback();
//tween回调(end->start)
virtual void tweenBackCallback();
//关闭按钮回调
virtual void closeCallback(cocos2d::CCObject* pSender);
protected:
cocos2d::CCAction* m_tweenAction;//移动的action
WXSimpleButton* m_closeBtn;
bool m_isTweenning;//是否正在移动
};
| [
"543062527@qq.com"
] | 543062527@qq.com |
782c0973bbac9ce229c8cacca512e2321b4200c0 | 111d82bef126e3a6fb86c0dc59ded74705932213 | /src/marker.cpp | 682ad08fe2fcfa94f6f458d599e567f56ea5d011 | [] | no_license | Mekanikles/pyzzlix-c | 67919cdd0e1f1b11993aa7b26c76556b7f7a5269 | 8db46d88930a5987286f81ed7114b71dd948a520 | refs/heads/master | 2021-03-12T20:14:46.095897 | 2011-01-18T09:51:34 | 2011-01-18T09:51:34 | 1,109,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | #include "marker.h"
#include "animation.h"
Marker::Marker()
{
this->setAnimation(new Animation("marker", 32, 32));
this->boardx = 0;
this->boardy = 0;
//this->movesound = Resources().getSound("markermove");
//self.turnsound = Resources().getSound("markerturn")
//self.failsound = Resources().getSound("markerfail")
this->center = Point(16.0f, 16.0f);
}
| [
"joel@crunchbang.(none)"
] | joel@crunchbang.(none) |
bdcb896691484a4220377546bbc51070c2c22a85 | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.0045/IC3H7COC3H6-I | a7b7e569448bbb037bcb48e3fdfa5118f9cf424a | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.0045";
object IC3H7COC3H6-I;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 9.92881e-12;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
59e44ce397dffd1ed557b61e3eee4c3e45edb588 | 592a4ece8141d0192d78219e62350cdf2ba4b185 | /calculadoraniveldios.cpp | 69dd91ea54e8dcebbb1e2161c82a79e52902ff04 | [] | no_license | 31012001-RenanMariscal/Calculadora | b1d10f314ef98c948fc437255bd131d5f31a18ce | 44ac886feeebc3a93400e45c76b4cb8579e83976 | refs/heads/master | 2020-06-04T23:45:09.792671 | 2019-06-16T20:30:29 | 2019-06-16T20:30:29 | 192,237,836 | 0 | 0 | null | 2019-06-16T21:18:58 | 2019-06-16T21:18:58 | null | UTF-8 | C++ | false | false | 1,230 | cpp | /******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
int main() {
float x, y, resultado;
char op;
int valido = 1;
printf("Esta es una calculadora simple, para sumar ingrese +, para restar -, para dividir /, para multiplicar * o x\n");
printf("Ingrese operacion: ");
scanf("%c", &op);
printf("Ingrese x: ");
scanf("%f", &x);
printf("Ingrese y: ");
scanf("%f", &y);
switch (op) {
case '+':
resultado = x + y;
break;
case '-':
resultado = x - y;
break;
case '*':
case 'x':
resultado = x * y;
break;
case '/':
resultado = x / y;
break;
default:
valido = 0;
}
if (valido)
printf("El resultado es %f\n", resultado);
else
printf("Operacion invalida\n")
return 0;
}
jjj
| [
"noreply@github.com"
] | 31012001-RenanMariscal.noreply@github.com |
f370f3f568c68629f421999f4244fadc9b9f80db | cd2e994213caff60377b6fb6157651952a8241a5 | /source_code/component/animator/motion_state/knight/knight_skill_motion_state.cpp | 1be2daead9f4b30a42966d0b91d8010a69d456f9 | [] | no_license | KodFreedom/KF_Framework | 80af743da70e63c3f117d8b29aff4154d7b3af1b | ca7fadb04c12f0f39d1d40ede3729de79f844adc | refs/heads/master | 2020-12-30T16:01:49.674244 | 2018-02-25T09:54:07 | 2018-02-25T09:54:07 | 91,193,033 | 6 | 0 | null | 2018-02-25T09:54:08 | 2017-05-13T17:56:31 | C++ | UTF-8 | C++ | false | false | 945 | cpp | //--------------------------------------------------------------------------------
// knight_skill_motion_state.cpp
// this is a motion state class which is auto-created by KF_ModelAnalyzer
//--------------------------------------------------------------------------------
#include "knight_skill_motion_state.h"
#include "../../animator.h"
#include "../../../../resources/motion_data.h"
#include "knight_idle_motion_state.h"
#include "knight_death_motion_state.h"
void KnightSkillMotionState::ChangeMotion(Animator& animator)
{
if (current_frame_counter_ >= frame_to_exit_)
{
current_frame_counter_ = frame_to_exit_ - 1;
animator.Change(MY_NEW BlendMotionState(current_motion_name_, MY_NEW KnightIdleMotionState(0), current_frame_counter_, 10));
return;
}
if(animator.GetIsDead() == true)
{
animator.Change(MY_NEW BlendMotionState(current_motion_name_, MY_NEW KnightDeathMotionState(0), current_frame_counter_, 5));
return;
}
} | [
"kodfreedom@gmail.com"
] | kodfreedom@gmail.com |
60bf434358dff62c8ee13a6964c72d2a5da97abb | 047f7a970e17ab992d0a534eeb52ee893b1313a2 | /src/game/components/Player.hpp | c614e4d3990212f3855910b4e55554d54f182ac6 | [] | no_license | hhsaez/judgementday | 39607848af87f0e046c4b310e838545893fab214 | 704dabffdc053f708395a4f471f19ddbeb7319e4 | refs/heads/master | 2020-03-12T08:14:38.457364 | 2018-04-25T14:53:18 | 2018-04-25T14:53:18 | 130,523,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,436 | hpp | #ifndef JUDGEMENT_DAY_COMPONENTS_PLAYER_
#define JUDGEMENT_DAY_COMPONENTS_PLAYER_
#include "JudgementDayCommon.hpp"
namespace judgementday {
class Action;
namespace messaging {
struct SpawnPlayer {
crimild::Node *board;
};
}
namespace components {
class Board;
class Navigation;
class Player :
public crimild::NodeComponent,
public crimild::Messenger,
public crimild::DynamicSingleton< Player > {
CRIMILD_IMPLEMENT_RTTI( judgementday::components::Player )
public:
explicit Player( crimild::scripting::ScriptEvaluator & );
virtual ~Player( void );
virtual void start( void ) override;
void setCurrentWaypoint( crimild::Node *wp ) { _currentWaypoint = wp; }
crimild::Node *getCurrentWaypoint( void ) { return _currentWaypoint; }
void loot( crimild::containers::Array< crimild::SharedPointer< Action >> &actions );
private:
void onTurnBegan( void );
void onActionSelected( Action *action );
void onHit( crimild::Int16 damage );
private:
Board *_board = nullptr;
Navigation *_navigation = nullptr;
crimild::Node *_currentWaypoint = nullptr;
};
}
}
#endif
| [
"hhsaez@gmail.com"
] | hhsaez@gmail.com |
034367cb1dc13be1e08fd1780d3092a5818127de | b9c8edc82ab483ba0f0f3e94ebad9409829da73f | /Vulkan_Win32/src/renderer/modelbuffer.h | 77ef132265aa3aef063eefad7f22fea7faff04f6 | [] | no_license | vectorlist/Vulkan_Application | 27b4e2161bfc91827d3e3a94dffa3891d5406357 | f24e6b344c8b76fff7c363f7241aeefc26588536 | refs/heads/master | 2021-01-12T03:18:06.729988 | 2017-01-12T01:04:55 | 2017-01-12T01:04:55 | 78,179,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,370 | h | #pragma once
#include <renderer.h>
class ModelBuffer : public Renderer
{
public:
ModelBuffer(Window* window);
virtual~ModelBuffer();
void buildProcedural() VK_OVERRIDE;
void buildPipeline() VK_OVERRIDE;
void buildFrameBuffers() VK_OVERRIDE;
void buildCommandPool() VK_OVERRIDE;
void buildCommandBuffers() VK_OVERRIDE;
void buildSemaphores() VK_OVERRIDE;
//additional
void buildVertexBuffers();
void buildIndiceBuffers();
void render() VK_OVERRIDE;
/*MODEL*/
void buildModel(const std::string &filename);
/*DEPTH STENCIL*/
void buildDeapthStencil();
VDeleter<VkImage> m_depth_image{ m_device, vkDestroyImage };
VDeleter<VkImageView> m_depth_image_view{ m_device, vkDestroyImageView };
VDeleter<VkDeviceMemory> m_depth_image_memory{ m_device,vkFreeMemory };
/*TEXTURE BUFFER*/
void buildTextureImage();
void buildTextureImageView();
void buildTextureSampler();
VDeleter<VkImage> m_texture_image{ m_device, vkDestroyImage };
VDeleter<VkDeviceMemory> m_texture_image_memory{ m_device, vkFreeMemory };
VDeleter<VkImageView> m_texture_image_view{ m_device,vkDestroyImageView };
VDeleter<VkSampler> m_textureSampler{ m_device, vkDestroySampler };
/*UNIFORM BUFFER*/
UBO m_ubo;
void buildDescriptorSetLayout();
void buildDescriptorPool();
void buildDescriptorSet();
void buildUniformBuffer();
void updateUniformBuffer() VK_OVERRIDE;
VDeleter<VkDescriptorSetLayout> m_descriptorSetLayout{ m_device,vkDestroyDescriptorSetLayout };
//VDeleter<VkPipelineLayout> m_pipelineLayout{ m_device,vkDestroyPipelineLayout };
VDeleter<VkBuffer> m_uniform_staging_buffer{ m_device,vkDestroyBuffer };
VDeleter<VkDeviceMemory> m_uinform_staging_buffer_memory{ m_device,vkFreeMemory };
VDeleter<VkBuffer> m_uniform_buffer{ m_device,vkDestroyBuffer };
VDeleter<VkDeviceMemory> m_uinform_buffer_memory{ m_device,vkFreeMemory };
VDeleter<VkDescriptorPool> m_descriptor_pool{ m_device,vkDestroyDescriptorPool };
VkDescriptorSet m_descriptor_set;
/*VERTEX BUFFER*/
std::vector<Vertex> m_vertices;
VDeleter<VkBuffer> m_vertex_buffer{ m_device, vkDestroyBuffer };
VDeleter<VkDeviceMemory> m_vertex_buffer_memory{ m_device,vkFreeMemory };
/*INDEX BUFFER*/
std::vector<uint32_t> m_indices;
VDeleter<VkBuffer> m_indice_buffer{ m_device, vkDestroyBuffer };
VDeleter<VkDeviceMemory> m_indice_buffer_memory{ m_device,vkFreeMemory };
};
| [
"xarchx80@gmail.com"
] | xarchx80@gmail.com |
7a2e0661f38ee59346bac14376f1c821c6efba57 | 409de9ad0fa66bb905908c3de39997690524336e | /trunk/src/virtual_network.cc | c3bc965abad65ba8e4fda579d33ed76e329afe81 | [
"MIT"
] | permissive | saumitraaditya/Tincan | 0dcba7708f32ddfc4ab061aef79680f834fd1153 | 51b7b554b8c32faa04b1704e28cbab1d7ce3d8bf | refs/heads/master | 2019-07-17T03:43:04.071976 | 2017-11-27T03:25:30 | 2017-11-27T03:25:30 | 69,046,620 | 0 | 0 | null | 2016-09-23T17:30:42 | 2016-09-23T17:30:42 | null | UTF-8 | C++ | false | false | 21,166 | cc | /*
* ipop-project
* Copyright 2016, University of Florida
*
* 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 "virtual_network.h"
#include "webrtc/base/base64.h"
#include "tincan_control.h"
namespace tincan
{
VirtualNetwork::VirtualNetwork(
unique_ptr<VnetDescriptor> descriptor,
shared_ptr<IpopControllerLink> ctrl_handle) :
tdev_(nullptr),
peer_network_(nullptr),
descriptor_(move(descriptor)),
ctrl_link_(ctrl_handle)
{
tdev_ = new TapDev();
peer_network_ = new PeerNetwork(descriptor->name);
}
VirtualNetwork::~VirtualNetwork()
{
delete peer_network_;
delete tdev_;
}
void
VirtualNetwork::Configure()
{
TapDescriptor ip_desc = {
descriptor_->name,
descriptor_->vip4,
descriptor_->prefix4,
descriptor_->mtu4
};
//initialize the Tap Device
tdev_->Open(ip_desc);
//create X509 identity for secure connections
string sslid_name = descriptor_->name + descriptor_->uid;
sslid_.reset(SSLIdentity::Generate(sslid_name, rtc::KT_RSA));
if(!sslid_)
throw TCEXCEPT("Failed to generate SSL Identity");
local_fingerprint_.reset(
SSLFingerprint::Create(rtc::DIGEST_SHA_1, sslid_.get()));
if(!local_fingerprint_)
throw TCEXCEPT("Failed to create the local finger print");
}
void
VirtualNetwork::Start()
{
net_worker_.Start();
sig_worker_.Start();
if(descriptor_->l2tunnel_enabled)
{
tdev_->read_completion_.connect(this, &VirtualNetwork::TapReadCompleteL2);
tdev_->write_completion_.connect(this, &VirtualNetwork::TapWriteCompleteL2);
}
else
{
tdev_->read_completion_.connect(this, &VirtualNetwork::TapReadComplete);
tdev_->write_completion_.connect(this, &VirtualNetwork::TapWriteComplete);
}
tdev_->Up();
peer_net_thread_.Start(peer_network_);
}
void
VirtualNetwork::Shutdown()
{
tdev_->Down();
tdev_->Close();
peer_net_thread_.Stop();
}
void
VirtualNetwork::StartTunnel(
int)
{
lock_guard<mutex> lg(vn_mtx_);
for(uint8_t i = 0; i < kLinkConcurrentAIO; i++)
{
unique_ptr<TapFrame> tf = make_unique<TapFrame>();
tf->Initialize();
tf->BufferToTransfer(tf->Payload());
tf->BytesToTransfer(tf->PayloadCapacity());
tdev_->Read(*tf.release());
}
}
void
VirtualNetwork::UpdateRoute(
MacAddressType mac_dest,
MacAddressType mac_path)
{
peer_network_->UpdateRoute(mac_dest, mac_path);
}
unique_ptr<VirtualLink>
VirtualNetwork::CreateVlink(
unique_ptr<VlinkDescriptor> vlink_desc,
unique_ptr<PeerDescriptor> peer_desc,
cricket::IceRole ice_role)
{
vlink_desc->stun_addr = descriptor_->stun_addr;
vlink_desc->turn_addr = descriptor_->turn_addr;
vlink_desc->turn_user = descriptor_->turn_user;
vlink_desc->turn_pass = descriptor_->turn_pass;
unique_ptr<VirtualLink> vl = make_unique<VirtualLink>(
move(vlink_desc), move(peer_desc), &sig_worker_, &net_worker_);
unique_ptr<SSLIdentity> sslid_copy(sslid_->GetReference());
vl->Initialize(net_manager_, move(sslid_copy), *local_fingerprint_.get(),
ice_role);
if(descriptor_->l2tunnel_enabled)
{
vl->SignalMessageReceived.connect(this, &VirtualNetwork::VlinkReadCompleteL2);
}
else
{
vl->SignalMessageReceived.connect(this, &VirtualNetwork::ProcessIncomingFrame);
}
vl->SignalLinkUp.connect(this, &VirtualNetwork::StartTunnel);
return vl;
}
shared_ptr<VirtualLink>
VirtualNetwork::CreateTunnel(
unique_ptr<PeerDescriptor> peer_desc,
unique_ptr<VlinkDescriptor> vlink_desc)
{
shared_ptr<VirtualLink> vl;
MacAddressType mac;
shared_ptr<Tunnel> tnl;
string mac_str = peer_desc->mac_address;
StringToByteArray(peer_desc->mac_address, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
tnl = peer_network_->GetTunnel(mac);
}
else
{
tnl = make_shared<Tunnel>();
tnl->Id(mac);
}
vl = CreateVlink(move(vlink_desc), move(peer_desc),
cricket::ICEROLE_CONTROLLED);
if(vl)
{
tnl->AddVlinkEndpoint(vl);
peer_network_->Add(tnl);
LOG(LS_INFO) << "Created CONTROLLED vlink w/ Tunnel ID (" <<
mac_str << ")";
}
else throw TCEXCEPT("The CreateTunnelEndpoint operation failed.");
return vl;
}
void
VirtualNetwork::ConnectTunnel(
unique_ptr<PeerDescriptor> peer_desc,
unique_ptr<VlinkDescriptor> vlink_desc)
{
MacAddressType mac;
shared_ptr<Tunnel> tnl;
string mac_str = peer_desc->mac_address;
StringToByteArray(peer_desc->mac_address, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
tnl = peer_network_->GetTunnel(mac);
}
else
{
tnl = make_shared<Tunnel>();
tnl->Id(mac);
}
shared_ptr<VirtualLink> vl = CreateVlink(move(vlink_desc), move(peer_desc),
cricket::ICEROLE_CONTROLLING);
if(vl)
{
tnl->AddVlinkEndpoint(vl);
vl->StartConnections();
peer_network_->Add(tnl);
LOG(LS_INFO) << "Created CONTROLLING vlink w/ Tunnel ID (" <<
mac_str << ")";
}
else throw TCEXCEPT("The ConnectTunnel operation failed.");
}
void VirtualNetwork::TerminateTunnel(
const string & tnl_id)
{
MacAddressType mac;
StringToByteArray(tnl_id, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
peer_network_->Remove(mac);
}
}
void VirtualNetwork::TerminateLink(
const string & tnl_id,
const string & link_role)
{
MacAddressType mac;
StringToByteArray(tnl_id, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
shared_ptr<Tunnel> tnl = peer_network_->GetTunnel(mac);
if(link_role == TincanControl::Controlling.c_str())
{
tnl->ReleaseLink(cricket::ICEROLE_CONTROLLING);
}
else if (link_role == TincanControl::Controlled.c_str())
{
tnl->ReleaseLink(cricket::ICEROLE_CONTROLLED);
}
}
}
VnetDescriptor &
VirtualNetwork::Descriptor()
{
return *descriptor_.get();
}
string
VirtualNetwork::Name()
{
return descriptor_->name;
}
string
VirtualNetwork::MacAddress()
{
MacAddressType mac = tdev_->MacAddress();
return ByteArrayToString(mac.begin(), mac.end(), 0);
}
string
VirtualNetwork::Fingerprint()
{
return local_fingerprint_->ToString();
}
void
VirtualNetwork::IgnoredNetworkInterfaces(
const vector<string>& ignored_list)
{
net_manager_.set_network_ignore_list(ignored_list);
}
void VirtualNetwork::QueryTunnelStats(
const string & node_mac,
Json::Value & node_info)
{
MacAddressType mac;
StringToByteArray(node_mac, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
shared_ptr<VirtualLink> vl = peer_network_->GetTunnel(mac)->Controlling();
if(vl && vl->IsReady())
{
LinkStatsMsgData md;
md.vl = vl;
net_worker_.Post(RTC_FROM_HERE, this, MSGID_QUERY_NODE_INFO, &md);
md.msg_event.Wait(Event::kForever);
node_info[TincanControl::Controlling][TincanControl::Stats].swap(md.stats);
node_info[TincanControl::Controlling][TincanControl::Status] = "online";
}
else
{
node_info[TincanControl::Controlling][TincanControl::Status] = "offline";
node_info[TincanControl::Controlling][TincanControl::Stats] = Json::Value(Json::arrayValue);
}
vl = peer_network_->GetTunnel(mac)->Controlled();
if(vl && vl->IsReady())
{
LinkStatsMsgData md;
md.vl = vl;
net_worker_.Post(RTC_FROM_HERE, this, MSGID_QUERY_NODE_INFO, &md);
md.msg_event.Wait(Event::kForever);
node_info[TincanControl::Controlled][TincanControl::Stats].swap(md.stats);
node_info[TincanControl::Controlled][TincanControl::Status] = "online";
}
else
{
node_info[TincanControl::Controlled][TincanControl::Status] = "offline";
node_info[TincanControl::Controlled][TincanControl::Stats] = Json::Value(Json::arrayValue);
}
}
else
{
node_info[TincanControl::Controlling][TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlling][TincanControl::Status] = "unknown";
node_info[TincanControl::Controlling][TincanControl::Stats] = Json::Value(Json::arrayValue);
node_info[TincanControl::Controlled][TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlled][TincanControl::Status] = "unknown";
node_info[TincanControl::Controlled][TincanControl::Stats] = Json::Value(Json::arrayValue);
}
}
void VirtualNetwork::QueryNodeInfo(
const string & node_mac,
Json::Value & node_info)
{
MacAddressType mac;
StringToByteArray(node_mac, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
shared_ptr<VirtualLink> vl = peer_network_->GetTunnel(mac)->Vlink();
node_info[TincanControl::UID] = vl->PeerInfo().uid;
node_info[TincanControl::VIP4] = vl->PeerInfo().vip4;
//node_info[TincanControl::VIP6] = vl->PeerInfo().vip6;
node_info[TincanControl::MAC] = vl->PeerInfo().mac_address;
node_info[TincanControl::Fingerprint] = vl->PeerInfo().fingerprint;
if(vl->IsReady())
{
node_info[TincanControl::Status] = "online";
}
else
{
node_info[TincanControl::Status] = "offline";
}
////////////////////////////////////////////////////////////////////////////
vl = peer_network_->GetTunnel(mac)->Controlled();
if(vl)
{
node_info[TincanControl::Controlling][TincanControl::UID] =
vl->PeerInfo().uid;
node_info[TincanControl::Controlling][TincanControl::VIP4] =
vl->PeerInfo().vip4;
node_info[TincanControl::Controlling][TincanControl::MAC] =
vl->PeerInfo().mac_address;
node_info[TincanControl::Controlling][TincanControl::Fingerprint] =
vl->PeerInfo().fingerprint;
if(vl->IsReady())
{
node_info[TincanControl::Controlling][TincanControl::Status] = "online";
}
else
{
node_info[TincanControl::Controlling][TincanControl::Status] =
"offline";
}
}
else
{
node_info[TincanControl::Controlling][TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlled][TincanControl::MAC] = node_mac;
}
vl = peer_network_->GetTunnel(mac)->Controlling();
if(vl)
{
node_info[TincanControl::Controlled][TincanControl::UID] =
vl->PeerInfo().uid;
node_info[TincanControl::Controlled][TincanControl::VIP4] =
vl->PeerInfo().vip4;
node_info[TincanControl::Controlled][TincanControl::MAC] =
vl->PeerInfo().mac_address;
node_info[TincanControl::Controlled][TincanControl::Fingerprint] =
vl->PeerInfo().fingerprint;
if(vl->IsReady())
{
node_info[TincanControl::Controlled][TincanControl::Status] =
"online";
}
else
{
node_info[TincanControl::Controlled][TincanControl::Status] =
"offline";
}
}
else
{
node_info[TincanControl::Controlling][TincanControl::Status] =
"unknown";
node_info[TincanControl::Controlled][TincanControl::Status] =
"unknown";
}
}
else
{
node_info[TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlling][TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlled][TincanControl::MAC] = node_mac;
node_info[TincanControl::Status] = "unknown";
node_info[TincanControl::Controlling][TincanControl::Status] = "unknown";
node_info[TincanControl::Controlled][TincanControl::Status] = "unknown";
}
}
void VirtualNetwork::QueryTunnelCas(
const string & tnl_id, //peer mac address
Json::Value & cas_info)
{
shared_ptr<Tunnel> tnl = peer_network_->GetTunnel(tnl_id);
tnl->QueryCas(cas_info);
}
void
VirtualNetwork::SendIcc(
const string & recipient_mac,
const string & data)
{
unique_ptr<IccMessage> icc = make_unique<IccMessage>();
icc->Message((uint8_t*)data.c_str(), (uint16_t)data.length());
unique_ptr<TransmitMsgData> md = make_unique<TransmitMsgData>();
md->frm = move(icc);
MacAddressType mac;
StringToByteArray(recipient_mac, mac.begin(), mac.end());
md->tnl = peer_network_->GetTunnel(mac);
net_worker_.Post(RTC_FROM_HERE, this, MSGID_SEND_ICC, md.release());
}
/*
Incoming frames off the vlink are one of:
pure ethernet frame - to be delivered to the TAP device
icc message - to be delivered to the local controller
The implementing entity needs access to the TAP and controller instances to
transmit the frame. These can be provided at initialization.
Responsibility: Identify the received frame type, perfrom a transformation of
the frame
if needed and transmit it.
- Is this my ARP? Deliver to TAP.
- Is this an ICC? Send to controller.
Types of Transformation:
*/
void
VirtualNetwork::VlinkReadCompleteL2(
uint8_t * data,
uint32_t data_len,
VirtualLink &)
{
unique_ptr<TapFrame> frame = make_unique<TapFrame>(data, data_len);
TapFrameProperties fp(*frame);
if(fp.IsIccMsg())
{ // this is an ICC message, deliver to the ipop-controller
unique_ptr<TincanControl> ctrl = make_unique<TincanControl>();
ctrl->SetControlType(TincanControl::CTTincanRequest);
Json::Value & req = ctrl->GetRequest();
req[TincanControl::Command] = TincanControl::ICC;
req[TincanControl::InterfaceName] = descriptor_->name;
req[TincanControl::Data] = string((char*)frame->Payload(), frame->PayloadLength());
//LOG(TC_DBG) << " Delivering ICC to ctrl, data=\n" << req[TincanControl::Data].asString();
ctrl_link_->Deliver(move(ctrl));
}
else if(fp.IsFwdMsg())
{ // a frame to be routed on the overlay
if(peer_network_->IsRouteExists(fp.DestinationMac()))
{
shared_ptr<Tunnel> tnl = peer_network_->GetRoute(fp.DestinationMac());
TransmitMsgData *md = new TransmitMsgData;
md->frm = move(frame);
md->tnl = tnl;
net_worker_.Post(RTC_FROM_HERE, this, MSGID_FWD_FRAME, md);
}
else
{ //no route found, send to controller
unique_ptr<TincanControl> ctrl = make_unique<TincanControl>();
ctrl->SetControlType(TincanControl::CTTincanRequest);
Json::Value & req = ctrl->GetRequest();
req[TincanControl::Command] = TincanControl::UpdateRoutes;
req[TincanControl::InterfaceName] = descriptor_->name;
req[TincanControl::Data] = ByteArrayToString(frame->Payload(),
frame->PayloadEnd());
LOG(TC_DBG) << "FWDing frame to ctrl, data=\n" <<
req[TincanControl::Data].asString();
ctrl_link_->Deliver(move(ctrl));
}
}
else if (fp.IsDtfMsg())
{
frame->Dump("Frame from vlink");
frame->BufferToTransfer(frame->Payload()); //write frame payload to TAP
frame->BytesToTransfer(frame->PayloadLength());
frame->SetWriteOp();
tdev_->Write(*frame.release());
}
else
{
LOG(LS_ERROR) << "Unknown frame type received!";
frame->Dump("Invalid header");
}
}
//
//AsyncIOCompletion Routines for TAP device
/*
Frames read from the TAP device are handled here. This is an ethernet frame
from the networking stack. The implementing entity needs access to the
recipient - via its vlink, or to the controller - when there is no
vlink to the recipient.
Responsibility: Identify the recipient of the frame and route accordingly.
- Is this an ARP? Send to controller.
- Is this an IP packet? Use MAC to lookup vlink and forwrd or send to
controller.
- Is this for a device behind an IPOP switch
Note: Avoid exceptions on the IO loop
*/
void
VirtualNetwork::TapReadCompleteL2(
AsyncIo * aio_rd)
{
TapFrame * frame = static_cast<TapFrame*>(aio_rd->context_);
if(!aio_rd->good_)
{
frame->Initialize();
frame->BufferToTransfer(frame->Payload());
frame->BytesToTransfer(frame->PayloadCapacity());
if(0 != tdev_->Read(*frame))
delete frame;
return;
}
frame->PayloadLength(frame->BytesTransferred());
TapFrameProperties fp(*frame);
MacAddressType mac = fp.DestinationMac();
frame->BufferToTransfer(frame->Begin()); //write frame header + PL to vlink
frame->BytesToTransfer(frame->Length());
if(peer_network_->IsAdjacent(mac))
{
frame->Header(kDtfMagic);
frame->Dump("Unicast");
shared_ptr<Tunnel> tnl = peer_network_->GetTunnel(mac);
TransmitMsgData *md = new TransmitMsgData;
md->frm.reset(frame);
md->tnl = tnl;
net_worker_.Post(RTC_FROM_HERE, this, MSGID_TRANSMIT, md);
}
else if(peer_network_->IsRouteExists(mac))
{
frame->Header(kFwdMagic);
frame->Dump("Frame FWD");
TransmitMsgData *md = new TransmitMsgData;
md->frm.reset(frame);
md->tnl = peer_network_->GetRoute(mac);
net_worker_.Post(RTC_FROM_HERE, this, MSGID_FWD_FRAME, md);
}
else
{
frame->Header(kIccMagic);
if(fp.IsArpRequest())
{
frame->Dump("ARP Request");
}
else if(fp.IsArpResponse())
{
frame->Dump("ARP Response");
}
else if (memcmp(fp.DestinationMac().data(),"\xff\xff\xff\xff\xff\xff", 6) != 0)
{
frame->Dump("No Route Unicast");
}
//Send to IPOP Controller to find a route for this frame
unique_ptr<TincanControl> ctrl = make_unique<TincanControl>();
ctrl->SetControlType(TincanControl::CTTincanRequest);
Json::Value & req = ctrl->GetRequest();
req[TincanControl::Command] = TincanControl::UpdateRoutes;
req[TincanControl::InterfaceName] = descriptor_->name;
req[TincanControl::Data] = ByteArrayToString(frame->Payload(),
frame->PayloadEnd());
ctrl_link_->Deliver(move(ctrl));
//Post a new TAP read request
frame->Initialize(frame->Payload(), frame->PayloadCapacity());
if(0 != tdev_->Read(*frame))
delete frame;
}
}
void
VirtualNetwork::TapWriteCompleteL2(
AsyncIo * aio_wr)
{
TapFrame * frame = static_cast<TapFrame*>(aio_wr->context_);
if(frame->IsGood())
frame->Dump("TAP Write Completed");
else
LOG(LS_WARNING) << "Tap Write FAILED completion";
delete frame;
}
void VirtualNetwork::OnMessage(Message * msg)
{
switch(msg->message_id)
{
case MSGID_TRANSMIT:
{
unique_ptr<TapFrame> frame = move(((TransmitMsgData*)msg->pdata)->frm);
shared_ptr<Tunnel> tnl = ((TransmitMsgData*)msg->pdata)->tnl;
tnl->Transmit(*frame);
delete msg->pdata;
frame->Initialize(frame->Payload(), frame->PayloadCapacity());
if(0 == tdev_->Read(*frame))
frame.release();
}
break;
case MSGID_SEND_ICC:
{
unique_ptr<TapFrame> frame = move(((TransmitMsgData*)msg->pdata)->frm);
shared_ptr<Tunnel> tnl = ((TransmitMsgData*)msg->pdata)->tnl;
tnl->Transmit(*frame);
//LOG(TC_DBG) << "Sent ICC to=" <<vl->PeerInfo().vip4 << " data=\n" <<
// string((char*)(frame->begin()+4), *(uint16_t*)(frame->begin()+2));
delete msg->pdata;
}
break;
case MSGID_QUERY_NODE_INFO:
{
shared_ptr<VirtualLink> vl = ((LinkStatsMsgData*)msg->pdata)->vl;
vl->GetStats(((LinkStatsMsgData*)msg->pdata)->stats);
((LinkStatsMsgData*)msg->pdata)->msg_event.Set();
}
break;
case MSGID_FWD_FRAME:
case MSGID_FWD_FRAME_RD:
{
unique_ptr<TapFrame> frame = move(((TransmitMsgData*)msg->pdata)->frm);
shared_ptr<Tunnel> tnl = ((TransmitMsgData*)msg->pdata)->tnl;
tnl->Transmit(*frame);
//LOG(TC_DBG) << "FWDing frame to " << vl->PeerInfo().vip4;
if(msg->message_id == MSGID_FWD_FRAME_RD)
{
frame->Initialize(frame->Payload(), frame->PayloadCapacity());
if(0 == tdev_->Read(*frame))
frame.release();
}
delete msg->pdata;
}
break;
}
}
void
VirtualNetwork::ProcessIncomingFrame(
uint8_t *,
uint32_t ,
VirtualLink &)
{
}
void
VirtualNetwork::TapReadComplete(
AsyncIo *)
{
}
void
VirtualNetwork::TapWriteComplete(
AsyncIo *)
{
}
void
VirtualNetwork::InjectFame(
string && data)
{
unique_ptr<TapFrame> tf = make_unique<TapFrame>();
tf->Initialize();
if(data.length() > 2 * kTapBufferSize)
{
stringstream oss;
oss << "Inject Frame operation failed - frame size " << data.length() / 2 <<
" is larger than maximum accepted " << kTapBufferSize;
throw TCEXCEPT(oss.str().c_str());
}
size_t len = StringToByteArray(data, tf->Payload(), tf->End());
if(len != data.length() / 2)
throw TCEXCEPT("Inject Frame operation failed - ICC decode failure");
tf->SetWriteOp();
tf->PayloadLength((uint32_t)len);
tf->BufferToTransfer(tf->Payload());
tf->BytesTransferred((uint32_t)len);
tf->BytesToTransfer((uint32_t)len);
tdev_->Write(*tf.release());
//LOG(TC_DBG) << "Frame injected=\n" << data;
}
} //namespace tincan
| [
"kcratie@users.noreply.github.com"
] | kcratie@users.noreply.github.com |
98a1a792acf95b145c2230ee01d1f85fa2816369 | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_DinoColorSet_TekStrider_parameters.hpp | 45b0688d16887c5ded82675b63cdec3e17aea557 | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 740 | hpp | #pragma once
// ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoColorSet_TekStrider_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function DinoColorSet_TekStrider.DinoColorSet_TekStrider_C.ExecuteUbergraph_DinoColorSet_TekStrider
struct UDinoColorSet_TekStrider_C_ExecuteUbergraph_DinoColorSet_TekStrider_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
d2a2085762d2bd36918036f8f6c8a9028b22b2ee | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/ppapi/proxy/ppp_messaging_proxy.h | ced608a08c96a6ecd69e01296bd6a962103b41c3 | [
"BSD-3-Clause",
"LicenseRef-scancode-khronos"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 1,113 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PPAPI_PROXY_PPP_MESSAGING_PROXY_H_
#define PPAPI_PROXY_PPP_MESSAGING_PROXY_H_
#include "base/compiler_specific.h"
#include "ppapi/c/pp_instance.h"
#include "ppapi/c/ppp_messaging.h"
#include "ppapi/proxy/interface_proxy.h"
namespace ppapi {
namespace proxy {
class SerializedVarReceiveInput;
class PPP_Messaging_Proxy : public InterfaceProxy {
public:
PPP_Messaging_Proxy(Dispatcher* dispatcher);
virtual ~PPP_Messaging_Proxy();
virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
private:
void OnMsgHandleMessage(PP_Instance instance,
SerializedVarReceiveInput data);
void OnMsgHandleBlockingMessage(PP_Instance instance,
SerializedVarReceiveInput data,
IPC::Message* reply);
const PPP_Messaging* ppp_messaging_impl_;
DISALLOW_COPY_AND_ASSIGN(PPP_Messaging_Proxy);
};
}
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
8043c4205c720f0b9955915f3a6664b445e6bc24 | b4aee1d85320b398555b3782e872773044d4d685 | /practice/11.1/randwalk.cpp | 156aab4514fcfc05bd93b1236a896179e04c1394 | [] | no_license | crazyqipython/Cpp-primer-plus | 5a455ef0e16d461d963d659ff28a61eb27374269 | 0ebfe6feec17c5e920ff56b658464685cef26af1 | refs/heads/master | 2021-01-09T06:23:22.692388 | 2016-08-29T13:09:53 | 2016-08-29T13:09:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,737 | cpp | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include "vect.h"
int main()
{
using namespace std;
using VECTOR::Vector;
srand(time(0));
double direction;
Vector step;
Vector result(0.0, 0.0);
unsigned long steps = 0;
double target;
double dstep;
ofstream fout;
fout.open("the walk.txt");
cout << "Enter target distance (q to quit): ";
while (cin >> target)
{
cout << "Enter step length: ";
if (!(cin >> dstep)) break;
fout << "Target Distance: " << target
<< ", Step Size: " << dstep << endl;
while (result.magval() < target)
{
direction = rand() % 360;
step.reset(dstep, direction, Vector::POL);
result = result + step;
fout << steps << ": " << result << endl;
++steps;
}
cout << "After " << steps << " steps, the subject"
<< "has the following location:\n";
fout << "After " << steps << " steps, the subject"
<< "has the following location:\n";
cout << result << endl;
fout << result << endl;
result.polar_mode();
cout << " or\n" << result << endl;
fout << " or\n" << result << endl;
cout << "Average outward distance per step = "
<< result.magval() / steps << endl << endl;
fout << "Average outward distance per step = "
<< result.magval() / steps << endl << endl;
steps = 0;
result.reset(0.0, 0.0);
cout << "Enter target distance (q to quit): ";
}
cout << "Bye\n";
cin.clear();
while (cin.get() != '\n')
continue;
fout.close();
return 0;
}
| [
"hblee12294@gmail.com"
] | hblee12294@gmail.com |
7bfb7731f842553cd1c512716a0cb1ea41896e38 | e64de6e15e83104511203b19cddf533ab0b83858 | /test/parser-util.h | 0e10b83ba26b2c6a4b9e27afba687a176c20c9c0 | [] | no_license | brn/yatsc | 49b998ed4a55795fd28bd6a6a3964957e1740316 | d3fe64ea4b979ef93c9239b46bc8f9672faabe98 | refs/heads/master | 2021-01-01T19:00:44.883959 | 2015-03-30T00:53:09 | 2015-03-30T00:53:09 | 20,675,007 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,810 | h | /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Taketoshi Aono(brn)
*
* 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 "../src/ir/node.h"
#include "../src/parser/parser.h"
#include "../src/parser/literalbuffer.h"
#include "../src/parser/error-reporter.h"
#include "../src/parser/error-formatter.h"
#include "../src/parser/error-descriptor.h"
#include "../src/utils/stl.h"
#include "../src/utils/notificator.h"
#include "./compare-node.h"
#include "./unicode-util.h"
bool print_stack_trace = true;
bool compare_node = true;
#define PARSER_TEST(name, method_expr, type, code, expected_str, error) { int line_num = __LINE__; \
YatscParserTest(name, [&](yatsc::Parser<yatsc::SourceStream::iterator>* p){return p->method_expr;}, type, code, expected_str, error, line_num); \
}
#define WRAP_PARSER_TEST(name, method_expr, type, code, expected_str, error) { int line_num = __LINE__; \
YatscParserTest(name, [&](yatsc::Parser<yatsc::SourceStream::iterator>* p){return p->method_expr;}, type, code, expected_str, error, line_num); \
}
template <typename T>
void YatscParserTest(const char* name,
T fn,
yatsc::LanguageMode type,
const char* code,
const char* expected_str,
bool error,
int line_num) {
using namespace yatsc;
typedef yatsc::SourceStream::iterator Iterator;
auto module_info = Heap::NewHandle<ModuleInfo>(String(name), String(code), true);
CompilerOption compiler_option;
compiler_option.set_language_mode(type);
auto lb = Heap::NewHandle<yatsc::LiteralBuffer>();
auto global_scope = Heap::NewHandle<yatsc::ir::GlobalScope>(lb);
auto irfactory = Heap::NewHandle<ir::IRFactory>();
Scanner<Iterator> scanner(module_info->source_stream()->begin(), module_info->source_stream()->end(), lb.Get(), compiler_option);
Notificator<void(const yatsc::String&)> notificator;
Parser<Iterator> parser(compiler_option, &scanner, notificator, irfactory, module_info, global_scope);
ErrorFormatter error_formatter(module_info);
ParseResult result;
try {
result = fn(&parser);
} catch(const FatalParseError& fpe) {}
if (!error) {
if (!module_info->HasError() && result && result.value() && compare_node) {
yatsc::testing::CompareNode(line_num, result.value()->ToStringTree(), yatsc::String(expected_str));
} else {
if (print_stack_trace) {
parser.PrintStackTrace();
}
error_formatter.Print(stderr, module_info->error_reporter());
}
} else {
ASSERT_TRUE(module_info->error_reporter()->HasError());
}
print_stack_trace = true;
compare_node = true;
}
| [
"dobaw20@gmail.com"
] | dobaw20@gmail.com |
c4a725819c6e4da2f55dcf678a198a64f2ee3de1 | de841c20a88755e0a90d32add9948bb1c2f86f1c | /SimpleGame/SimpleGame/Classes/GameOverScene.cpp | 6cd09a2561d53bd7650205b00a7c5f7fc25b4f53 | [] | no_license | childhood/Cocos2dxLib | bad07deceb2408757ee29a8165a154e32e0d6113 | 9aecf86921df191ec1a5695546d4d517f92063b9 | refs/heads/master | 2020-12-25T04:35:49.859848 | 2012-03-08T16:09:49 | 2012-03-08T16:09:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp | //
// GameOverScene.m
// SimpleGame
//
// Created by kdanmobile09 on 12-3-8.
// Copyright 2012年 __MyCompanyName__. All rights reserved.
//
#import "GameOverScene.h"
#import"HelloWorldScene.h"
CCScene* GameOverScene::scene()
{
CCScene *scene = CCScene::node();
GameOverScene *layer = GameOverScene::node();
scene->addChild(layer);
return scene;
}
GameOverScene::~GameOverScene()
{
}
bool GameOverScene::init()
{
if (!CCLayerColor::initWithColor(ccc4(255, 255, 255, 255))) {
return false;
}
this->setLabel(CCLabelTTF::labelWithString("11", "Arial", 32));
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
this->getLabel()->setPosition(ccp(winSize.width / 2.0f, winSize.height / 2.0f));
this->getLabel()->setColor(ccc3(0, 0, 0));
this->addChild(_label);
_label->runAction(CCSequence::actions(CCDelayTime::actionWithDuration(3.0f),CCCallFunc::actionWithTarget(this, callfunc_selector(GameOverScene::gameOverDone)),NULL));
return true;
}
void GameOverScene::gameOverDone()
{
CCDirector::sharedDirector()->replaceScene(HelloWorld::scene());
}
| [
"guanghui8827@126.com"
] | guanghui8827@126.com |
b483be9c08f48bb560285bde6d3819b4b5a065f9 | c30962f9ae130128d0cc7b4946828d40643dd703 | /src/base/MDDiscreteDistribution.cc | d58b10b6b0c6276fc257668e8a5710001ddf41a5 | [
"Apache-2.0"
] | permissive | SoonyangZhang/hmdp | e3a5bfa4582c0c238cdd26517bfcd2f1ff1a101d | 8a11c1563ad75ed4cdd29c52479c5aa98b678e07 | refs/heads/master | 2022-03-03T10:44:28.111223 | 2019-08-26T10:18:10 | 2019-08-26T10:18:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,370 | cc | /**
* Copyright 2014 Emmanuel Benazera beniz@droidnik.fr
*
* 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 "MDDiscreteDistribution.h"
#include "Alg.h" /* double precision */
#include "ContinuousStateDistribution.h"
#include <algorithm> /* min */
#include <stdlib.h>
#include <assert.h>
#include <iostream>
//#define DEBUG 1
namespace hmdp_base
{
int MDDiscreteDistribution::m_counterpoints = -1;
MDDiscreteDistribution::MDDiscreteDistribution (const int &dim, const int &npoints)
: m_dimension (dim), m_nPoints (npoints)
{
//m_dist = new std::pair<double,double*>();
m_dist.resize(m_nPoints);
//= (std::pair<double,double*> *) malloc (m_nPoints * sizeof (std::pair<double, double*>));
m_intervals = new double[m_dimension];//(double *) calloc (m_dimension, sizeof (double));
m_dimPoints = new int[m_dimension]();//(int *) calloc (m_dimension, sizeof (int));
}
MDDiscreteDistribution::MDDiscreteDistribution (const int &dim,
double *lowPos, double *highPos,
double *intervals)
: m_dimension (dim), m_nPoints (1)
{
m_intervals = new double[m_dimension];//(double *) calloc (m_dimension, sizeof (double));
m_dimPoints = new int[m_dimension]();//(int *) calloc (m_dimension, sizeof (int));
for (int d=0; d<m_dimension; d++)
{
m_intervals [d] = intervals[d];
#if !defined __GNUC__ || __GNUC__ < 3
m_dimPoints[d] = static_cast<int> (ceil ((highPos[d] - lowPos[d]) / m_intervals[d]));
#else
m_dimPoints[d] = lround ((highPos[d] - lowPos[d]) / m_intervals[d]);
#endif
if (m_dimPoints[d] == 0) m_dimPoints[0] = 1;
m_nPoints *= m_dimPoints[d];
}
//m_dist = new std::pair<double,double*>();
/*m_dist
= (std::pair<double,double*> *) malloc (m_nPoints * sizeof (std::pair<double, double*>));*/
m_dist.resize(m_nPoints);
/* discretize */
discretize (lowPos, highPos);
}
MDDiscreteDistribution::MDDiscreteDistribution (const MDDiscreteDistribution &mdd)
: m_dimension (mdd.getDimension ()), m_nPoints (mdd.getNPoints ())
{
/* copy the distribution and intervals */
//m_dist = new std::pair<double,double*>();
m_dist.resize(m_nPoints);
//= (std::pair<double,double*> *) malloc (m_nPoints * sizeof (std::pair<double, double*>));
m_intervals = new double[m_dimension];//(double *) calloc (m_dimension, sizeof (double));
m_dimPoints = new int[m_dimension]();//(int *) calloc (m_dimension, sizeof (int));
/*m_dist = (std::pair<double,double*> *) malloc (m_nPoints * sizeof (std::pair<double,double*>));
m_intervals = (double*) calloc (m_dimension, sizeof (double));
m_dimPoints = (int *) calloc (m_dimension, sizeof (int));*/
for (int i=0; i<m_dimension; i++)
{
m_intervals[i] = mdd.getDiscretizationInterval (i);
m_dimPoints[i] = mdd.getDimPoints (i);
}
for (int i=0; i<m_nPoints; i++)
{
double prob = mdd.getProbability (i);
double *tab = (double*) malloc (m_dimension * sizeof (double));
for (int j=0; j<m_dimension; j++)
tab[j] = mdd.getPosition (i,j);
m_dist[i] = std::pair<double,double*> (prob, tab);
}
}
MDDiscreteDistribution::MDDiscreteDistribution (ContinuousStateDistribution *csd,
double *low, double *high)
: m_dimension (csd->getSpaceDimension ()), m_nPoints (0)
{
/* count csd leaves */
int dist_size = csd->countPositiveLeaves ();
//m_dist = (std::pair<double, double*> *) malloc (dist_size * sizeof (std::pair<double,double*>));
m_dist.resize(dist_size);
m_intervals = (double*) calloc (m_dimension, sizeof (double));
m_dimPoints = (int*) malloc (m_dimension * sizeof (int));
for (int i=0; i<m_dimension; i++)
m_dimPoints[i] = -1;
/* convert leaves */
convertContinuousStateDistribution (csd, low, high);
}
MDDiscreteDistribution::~MDDiscreteDistribution ()
{
/*for (int i=0; i<m_nPoints; i++)
delete[] m_dist[i].second;
delete[] m_dist;*/
delete[] m_intervals;
delete[] m_dimPoints;
}
void MDDiscreteDistribution::createMDDiscreteBin (const int &pt, const double &proba, double *pos)
{
m_dist[pt] = std::pair<double, double*> (proba, pos);
}
void MDDiscreteDistribution::convertContinuousStateDistribution (ContinuousStateDistribution *csd, double *low, double *high)
{
if (csd->isLeaf () && csd->getProbability ())
{
double *pos = (double*) malloc (getDimension () * sizeof (double));
for (int i=0; i<getDimension (); i++)
{
pos[i] = (high[i] + low[i]) / 2.0;
/* the discretization interval in dimension i is set to the size
of the smallest cell (in that dimension). Beware, in fact the discretization
interval is not uniform in a given dimension (following the bsp tree...). */
if (m_intervals[i])
m_intervals[i] = std::min (m_intervals[i], high[i] - low[i]);
else m_intervals[i] = high[i] - low[i];
}
m_dist[m_nPoints++] = std::pair<double, double*> (csd->getProbability (), pos);
}
else if (csd->isLeaf ()) {}
else
{
m_dimPoints[csd->getDimension ()]++;
double b=high[csd->getDimension ()];
high[csd->getDimension ()] = csd->getPosition ();
ContinuousStateDistribution *csdlt = static_cast<ContinuousStateDistribution*> (csd->getLowerTree ());
convertContinuousStateDistribution (csdlt, low, high);
high[csd->getDimension ()] = b;
b = low[csd->getDimension ()];
low[csd->getDimension ()] = csd->getPosition ();
ContinuousStateDistribution *csdge = static_cast<ContinuousStateDistribution*> (csd->getGreaterTree ());
convertContinuousStateDistribution (csdge, low, high);
low[csd->getDimension ()] = b;
}
}
/* static version */
std::pair<double, double*> MDDiscreteDistribution::createMDDiscreteBinS (const double &proba,
double *pos)
{
return std::pair<double, double*> (proba, pos);
}
void MDDiscreteDistribution::discretize (double *lowPos, double *highPos)
{
double bins[m_dimension], counters[m_dimension], pts[m_dimension];
for (int d=0; d<m_dimension; d++)
{
if (d == 0)
bins[d] = 1;
else bins[d] = m_dimPoints[d] * bins[d-1];
counters[d] = 0; pts[d] = 0;
#ifdef DEBUG
//debug
std::cout << "d: " << d << std::endl;
std::cout << "interval: " << m_intervals[d]
<< " -- dimPoints: " << m_dimPoints[d]
<< " -- bins: " << bins[d] << std::endl;
//debug
#endif
}
int count = 0;
while (count < m_nPoints)
{
double *pos = (double*) malloc (m_dimension * sizeof (double));
for (int d=m_dimension-1; d>=0; d--)
{
counters[d]++;
if (count == 0)
{
//pos[d] = lowPos[d] + m_intervals[d] / 2.0;
pos[d] = lowPos[d];
pts[d]++;
counters[d] = 0;
}
else if (counters[d] == bins[d])
{
counters[d] = 0;
//pos[d] = lowPos[d] + m_intervals[d] * (2.0 * pts[d] + 1) / 2.0;
pos[d] = lowPos[d] + m_intervals[d] * pts[d];
pts[d]++;
if (d > 0)
/* pts[d-1] = 0; */
for (int j=0; j<d; j++)
pts[j] = 0;
}
else if (count > 0) pos[d] = getPosition (count-1, d); /* remain at the same position
in this dimension */
}
createMDDiscreteBin (count, 0.0, pos);
count++;
}
}
/* TODO: speed up */
double MDDiscreteDistribution::getProbability (double *pos) const
{
bool not_in_bounds = true;
for (int i=0; i<m_dimension; i++)
{
if (pos[i] > getMinPosition (i) - m_intervals[i]/2.0
&& pos[i] < getMaxPosition (i) + m_intervals[i]/2.0)
{
not_in_bounds = false;
break;
}
}
if (not_in_bounds)
return 0.0;
for (int i=0; i<m_nPoints; i++)
{
int d = 0;
while (d < m_dimension)
{
if (m_dist[i].second[d] - m_intervals[d] / 2.0 <= pos[d]
&& m_dist[i].second[d] + m_intervals[d] / 2.0 >= pos[d])
d++;
else break;
if (d == m_dimension)
{
return m_dist[i].first;
}
}
}
return 0.0;
}
/* static methods */
int MDDiscreteDistribution::jointIndependentDiscretePoints (const int &nDists, DiscreteDistribution **dists)
{
int jDpts = 1;
for (int i=0; i<nDists; i++)
jDpts *= dists[i]->getNBins ();
return jDpts;
}
MDDiscreteDistribution* MDDiscreteDistribution::jointDiscreteDistribution (const int &nDists,
DiscreteDistribution **dists)
{
MDDiscreteDistribution::m_counterpoints = -1;
int jidd = MDDiscreteDistribution::jointIndependentDiscretePoints (nDists, dists);
MDDiscreteDistribution *jointD = new MDDiscreteDistribution (nDists, jidd);
//double *pos = (double *) malloc (nDists * sizeof (double));
double *pos = new double[nDists];
jointD = MDDiscreteDistribution::jointDiscreteDistribution (dists, 0, pos, 1.0, jointD);
if (MDDiscreteDistribution::m_counterpoints+1 != jidd)
{
jointD->reallocPoints (MDDiscreteDistribution::m_counterpoints+1);
}
for (int i=0; i<nDists; i++)
{
jointD->setDimPoint (i, dists[i]->getNBins ());
jointD->setDiscretizationInterval (i, dists[i]->getInterval ());
}
delete[] pos;
return jointD;
}
MDDiscreteDistribution* MDDiscreteDistribution::jointDiscreteDistribution (DiscreteDistribution **dists,
const int &d, double *pos,
const double &prob,
MDDiscreteDistribution *mdd)
{
double pr;
for (int i=0; i<dists[d]->getNBins (); i++) /* iterate points in dimension d */
{
pos[d]=dists[d]->getXAtBin (i);
pr = prob * dists[d]->getProbaAtBin (i);
if (d == mdd->getDimension () - 1) /* end of a joint product */
{
if (pr > 0.0)
{
double *positions = (double *) malloc (mdd->getDimension () * sizeof (double));
for (int j=0; j<mdd->getDimension (); j++)
positions[j] = pos[j];
mdd->createMDDiscreteBin (++m_counterpoints, pr, positions);
}
}
else MDDiscreteDistribution::jointDiscreteDistribution (dists, d+1, pos, pr, mdd);
}
return mdd;
}
MDDiscreteDistribution* MDDiscreteDistribution::resizeDiscretization (const MDDiscreteDistribution &mddist,
double *lowPos, double *highPos,
double *intervals)
{
MDDiscreteDistribution *rmddist = new MDDiscreteDistribution (mddist.getDimension (), lowPos, highPos,
intervals);
//std::cout << "rmddist: " << *rmddist << std::endl;
//double pos[rmddist->getDimension ()];
double sum = 0.0;
for (int pt=0; pt<rmddist->getNPoints (); pt++)
{
/* for (int d=0; d<rmddist->getDimension (); d++)
pos[d] = rmddist->getPosition (pt, d); */
//rmddist->setProbability (pt, mddist.getProbability (pos));
rmddist->setProbability (pt, mddist.getProbability (rmddist->getPosition (pt)));
sum += rmddist->getProbability (pt);
}
if (sum != 1.0)
rmddist->normalize (sum);
return rmddist;
}
MDDiscreteDistribution* MDDiscreteDistribution::convoluteMDDiscreteDistributions (const MDDiscreteDistribution &mddist1,
const MDDiscreteDistribution &mddist2,
double *low, double *high,
double *lowPos1, double *highPos1,
double *lowPos2, double *highPos2)
{
if (mddist1.getDimension () != mddist2.getDimension ())
{
std::cout << "[Error]:MDDiscreteDistribution::convoluteMDDiscreteDistributions: distributions are on continuous spaces of different dimensions. Exiting...\n";
exit (-1);
}
int dim = mddist1.getDimension ();
/* create multi-dimensional distribution of proper size */
double interval[dim], convLowPos[dim], convHighPos[dim];
bool nullprob = false;
for (int i=0; i<dim; i++)
{
#ifdef DEBUG
//debug
std::cout << i << " mddist1 min: " << mddist1.getMinPosition (i)
<< " -- mddist2 min: " << mddist2.getMinPosition (i)
<< " -- lowPos1: " << lowPos1[i] << " -- lowPos2: " << lowPos2[i]
<< std::endl;
std::cout << i << " mddist1 max: " << mddist1.getMaxPosition (i)
<< " -- mddist2 max: " << mddist2.getMaxPosition (i)
<< " -- highPos1: " << highPos1[i] << " -- highPos2: " << highPos2[i]
<< std::endl;
//debug
#endif
/* bounds */
convLowPos[i] = std::max (std::max (mddist1.getMinPosition (i) - mddist1.getDiscretizationInterval (i)/2.0
+ mddist2.getMinPosition (i) - mddist2.getDiscretizationInterval (i)/2.0,
lowPos1[i] + lowPos2[i]), low[i]);
convHighPos[i] = std::min (std::min (mddist1.getMaxPosition (i) + mddist1.getDiscretizationInterval (i)/2.0
+ mddist2.getMaxPosition (i) + mddist2.getDiscretizationInterval (i)/2.0,
highPos1[i] + highPos2[i]), high[i]);
/* select the minimal discretization interval */
interval[i] = std::min (mddist1.getDiscretizationInterval (i),
mddist2.getDiscretizationInterval (i));
#ifdef DEBUG
//debug
std::cout << i << " convLowPos: " << convLowPos[i]
<< " -- convHighPos: " << convHighPos[i]
<< " -- inverval: " << interval[i]
<< std::endl;
//debug
#endif
if (nullprob
|| convLowPos[i] >= convHighPos[i])
{
nullprob = true;
convLowPos[i] = low[i];
convHighPos[i] = high[i];
#if !defined __GNUC__ || __GNUC__ < 3
interval[i] = ceil (high[i] - low[i]);
#else
interval[i] = lround (high[i] - low[i]);
#endif
}
}
/* we consider that if probability is null on a dimension, then
it should be null over the full continuous space. Therefore we return
an empty distribution over the full space. */
/* TODO: should not be empty. Should proceed with the convolution. */
if (nullprob)
{
//debug
//std::cout << "returning 'zero' convolution\n";
//debug
return new MDDiscreteDistribution (dim, convLowPos, convHighPos, interval);
}
MDDiscreteDistribution *cmddist = new MDDiscreteDistribution (dim, convLowPos,
convHighPos, interval);
#ifdef DEBUG
//debug
std::cout << "discrete convolution points: " << cmddist->getNPoints () << std::endl;
/* std::cout << *cmddist << std::endl; */
//debug
#endif
/* sync discrete distributions and prepare for the convolution */
double lowConv[dim], highConv[dim], intervalsConv[dim];
int bins[dim], counters[dim];
for (int j=0; j<dim; j++)
{
lowConv[j] = std::min (lowPos1[j], lowPos2[j]); /* lower bounds for convolving values. */
highConv[j] = std::max (highPos1[j], highPos2[j]);
intervalsConv[j] = std::min (mddist1.getDiscretizationInterval (j),
mddist2.getDiscretizationInterval (j)); /* sync the discretization intervals */
//debug
/* std::cout << "rsc " << j << ": lowConv: " << lowConv[j]
<< " -- highConv: " << highConv[j] << " -- interval: " << intervalsConv[j]
<< std::endl; */
//debug
}
/* resize discrete distributions: cmddist1, cmddist2 */
/* MDDiscreteDistribution *cmddist1
= MDDiscreteDistribution::resizeDiscretization (mddist1, low, high, intervalsConv); */
/* MDDiscreteDistribution *cmddist2
= MDDiscreteDistribution::resizeDiscretization (mddist2, lowConv, highConv, intervalsConv); */
MDDiscreteDistribution *cmddist1
= MDDiscreteDistribution::resizeDiscretization (mddist1, lowPos1, highPos1, intervalsConv);
/* MDDiscreteDistribution *cmddist2
= MDDiscreteDistribution::resizeDiscretization (mddist2, lowPos2, highPos2, intervalsConv); */
/* MDDiscreteDistribution *cmddist1 = new MDDiscreteDistribution (mddist1); */
MDDiscreteDistribution *cmddist2 = new MDDiscreteDistribution (mddist2);
//debug
//std::cout << "resizing: " << *cmddist1 << *cmddist2 << std::endl;
//debug
for (int j=0; j<dim; j++)
{
if (j == 0)
bins[j] = 1;
else
bins[j] = cmddist1->getDimPoints (j) * bins[j-1];
counters[j] = 0;
//debug
//std::cout << "bins " << j << ": " << bins[j] << std::endl;
//debug
}
int totalPos = cmddist1->getNPoints ();
double sum = 0.0;
#ifdef DEBUG
//debug
std::cout << "convolute: totalPos: " << totalPos << std::endl;
//debug
#endif
/* multi-dimensional convolution in between bounds */
for (int p=0; p<cmddist->getNPoints (); p++) /* iterate points */
{
/* std::cout << "point: " << p << " -- position: "
<< cmddist->getPosition (p, 0) << ", " << cmddist->getPosition (p, 1)
<< std::endl; */
/* initialization */
double val = 0.0;
double pos1[dim], pos2[dim];
for (int j=0; j<dim; j++)
{
pos1[j] = cmddist1->getMinPosition (j);
//pos2[j] = cmddist->getPosition (p, j) - cmddist1->getMinPosition (j);
pos2[j] = cmddist->getPosition (p, j) - pos1[j];
}
int count = 0;
while (count < totalPos)
{
double val1 = cmddist1->getProbability (pos1);
double val2 = cmddist2->getProbability (pos2);
val += val1 * val2;
/* std::cout << "pos1: " << pos1[0] << ", " << pos1[1] << std::endl;
std::cout << "pos2: " << pos2[0] << ", " << pos2[1] << std::endl;
std::cout << "val1: " << val1 << " -- val2: " << val2 << std::endl; */
for (int i=dim-1; i>=0; i--)
{
counters[i]++;
if (counters[i] == bins[i])
{
counters[i] = 0;
pos1[i] += cmddist1->getDiscretizationInterval (i);
//pos2[i] -= cmddist2->getDiscretizationInterval (i);
pos2[i] = cmddist->getPosition (p,i) - pos1[i];
if (i > 0)
{
for (int j=0; j<i; j++)
{
counters[j] = 0;
pos1[j] = cmddist1->getMinPosition (j);
pos2[j] = cmddist->getPosition (p, j) - cmddist1->getMinPosition (j);
}
/* pos1[i-1] = cmddist1->getMinPosition (i-1);
pos2[i-1] = cmddist->getPosition (p, i-1) - cmddist1->getMinPosition (i-1); */
break;
}
}
} /* end for */
count++;
}
//std::cout << " -- val: " << val << std::endl;
sum += val;
cmddist->setProbability (p, val);
}
/* normalize */
if (sum)
cmddist->normalize (sum);
//debug
/* std::cout << "MDDiscreteDistribution::convolute: result: "
<< *cmddist << std::endl; */
//debug
delete cmddist1; delete cmddist2;
return cmddist;
}
void MDDiscreteDistribution::normalize (const double &sum)
{
for (int i=0; i<m_nPoints; i++)
setProbability (i, getProbability (i) / sum);
}
double MDDiscreteDistribution::getProbMass () const
{
double mass = 0.0;
for (int i=0; i<m_nPoints; i++)
{
mass += getProbMass (i);
}
return mass;
}
double MDDiscreteDistribution::getProbMass (const int &i) const
{
double volume = 1.0;
for (int j=0; j<m_dimension; j++)
volume *= m_intervals[j];
return volume * getProbability (i);
}
std::pair<double, double*>* MDDiscreteDistribution::getPointAndBinMass (const int &i) const
{
std::pair<double, double*> *res
= new std::pair<double, double*> (std::pair<double, double*> (getProbMass (i), m_dist[i].second));
return res;
}
void MDDiscreteDistribution::reallocPoints (const int &nnpoints)
{
m_nPoints = nnpoints;
//m_dist = (std::pair<double,double*> *) realloc (m_dist, nnpoints * sizeof (std::pair<double, double*>));
m_dist.resize(m_nPoints);
}
std::ostream& MDDiscreteDistribution::print (std::ostream &output)
{
output << "nPoints: " << getNPoints ()
<< " -- dim: " << getDimension () << '\n';
output << "intervals: ";
for (int j=0; j<getDimension (); j++)
output << "(" << j << ", " << m_intervals[j] << ") ";
output << std::endl;
for (int i=0; i<getNPoints (); i++) /* iterate discrete points */
{
output << i << ": proba: " << getProbability (i) << " [";
for (int j=0; j<getDimension (); j++)
output << getPosition (i, j) << ' ';
output << "]\n";
}
#ifdef DEBUG
std::cout << "total probability mass: " << getProbMass () << std::endl;
#endif
return output;
}
std::ostream &operator<<(std::ostream &output, MDDiscreteDistribution &mdd)
{
return mdd.print (output);
}
std::ostream &operator<<(std::ostream &output, MDDiscreteDistribution *mdd)
{
return mdd->print (output);
}
} /* end of namespace */
| [
"emmanuel.benazera@xplr.com"
] | emmanuel.benazera@xplr.com |
79c771f8062a9908ca3fcb7cfb360e1f4d875931 | ae86cda3dbbfe821694b0d59e0c9b8d83cc4aacc | /Practicas/PFinal/letras/src/diccionario.cpp | 0801c428bd0d8f30109d64d4a334ad0512bdb786 | [
"MIT"
] | permissive | josepadial/ED | 1624376d0d8fbe4923d23c6c2e14fd8faa07fea6 | c095e65843e695e05cbb4d0ae34652d223c45425 | refs/heads/master | 2020-08-11T03:57:35.319909 | 2020-04-05T18:39:40 | 2020-04-05T18:39:40 | 214,486,158 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,950 | cpp | /*
Curso: 2018/2019
Asignatura: Estructura de datos
Autores: Jose Antonio Padial Molina
Elena Ortiz Moreno
Practica: Final "Letras"
*/
#include "diccionario.h"
istream& operator>>(istream &is, Diccionario &dic){
string aux;
while(getline(is,aux)){
dic.datos.insert(aux);
}
return is;
}
ostream& operator<<(ostream &os, const Diccionario &dic){
Diccionario::const_iterator it = dic.begin();
while(it != dic.end()){
os << *it << endl;
it++;
}
return os;
}
int Diccionario::getApariciones(const char c){
int apariciones=0;
iterator it = begin();
while(it != end()){
string aux = *it;
for(int i = 0; i < aux.size(); i++){
if(aux.at(i) == c){
apariciones++;
}
}
it++;
}
return apariciones;
}
int Diccionario::getTotalLetras(){
int apariciones=0;
iterator it = begin();
while(it != end()){
string aux = *it;
apariciones += aux.size();
it++;
}
return apariciones;
}
vector<string> Diccionario::palabrasLongitud(int longitud){
vector<string> palabras;
for (iterator it_dic = begin(); it_dic != end(); ++it_dic){
if ((*it_dic).size() == longitud)
palabras.push_back(*it_dic);
}
return palabras;
}
vector<string> Diccionario::palabrasCon(const string &p){
iterator it = begin();
vector<string> v;
string aux;
while(it != end()){
aux = *it;
if(aux.find(p) != -1)
v.push_back(aux);
it++;
}
return v;
}
Diccionario& Diccionario::operator=(const Diccionario &dic){
if(this != &dic)
datos = dic.datos;
return *this;
}
string Diccionario::operator[](int n){
string s = "";
if(n >= 0 && n < datos.size()){
iterator it = datos.begin();
for(int i = 0; it != datos.end() && i < n; i++,it++){}
s = *it;
}
return s;
} | [
"joseismael511@gmail.com"
] | joseismael511@gmail.com |
3fef0e346a3753fe53285831951acd515e45c13e | cccfb7be281ca89f8682c144eac0d5d5559b2deb | /components/history_clusters/core/history_clusters_db_tasks_unittest.cc | a48de270a04385b4258af1dbf8dda33dc7b3d5c8 | [
"BSD-3-Clause"
] | permissive | SREERAGI18/chromium | 172b23d07568a4e3873983bf49b37adc92453dd0 | fd8a8914ca0183f0add65ae55f04e287543c7d4a | refs/heads/master | 2023-08-27T17:45:48.928019 | 2021-11-11T22:24:28 | 2021-11-11T22:24:28 | 428,659,250 | 1 | 0 | BSD-3-Clause | 2021-11-16T13:08:14 | 2021-11-16T13:08:14 | null | UTF-8 | C++ | false | false | 2,579 | cc | // Copyright 2021 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 "components/history_clusters/core/history_clusters_db_tasks.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace history_clusters {
TEST(HistoryClustersDBTasksTest, BeginTimeCalculation) {
struct TestData {
base::Time::Exploded end_time_exploded;
base::Time::Exploded expected_begin_time_exploded;
} test_data[] = {
// Afternoon times yield a 4AM same day `begin_time`.
// 2013-10-11 at 5:30PM and 15 seconds and 400 milliseconds.
{
{2013, 10, 6, 11, 17, 30, 15, 400},
{2013, 10, 6, 11, 4, 0, 0, 0},
},
// Early afternoon times such as 2:00PM also yield 4AM the same day.
{
{2013, 10, 6, 11, 14, 0, 0, 0},
{2013, 10, 6, 11, 4, 0, 0, 0},
},
// Morning times like 10:15AM yield 4AM the day before.
{
{2013, 10, 6, 11, 10, 15, 0, 0},
{2013, 10, 5, 10, 4, 0, 0, 0},
},
// Early morning times such as 2:10AM also yield 4AM the day before.
// Just a sanity check here.
{
{2013, 10, 6, 11, 2, 10, 0, 0},
{2013, 10, 5, 10, 4, 0, 0, 0},
},
};
for (size_t i = 0; i < base::size(test_data); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case i=%d", int(i)));
auto& test_case = test_data[i];
ASSERT_TRUE(test_case.end_time_exploded.HasValidValues());
base::Time end_time;
ASSERT_TRUE(
base::Time::FromLocalExploded(test_case.end_time_exploded, &end_time));
base::Time begin_time =
GetAnnotatedVisitsToCluster::GetBeginTimeOnDayBoundary(end_time);
base::Time::Exploded begin_exploded;
begin_time.LocalExplode(&begin_exploded);
auto& expected_begin = test_case.expected_begin_time_exploded;
EXPECT_EQ(begin_exploded.year, expected_begin.year);
EXPECT_EQ(begin_exploded.month, expected_begin.month);
// We specifically ignore day-of-week, because it uses UTC, and we don't
// actually care about which day of the week it is.
EXPECT_EQ(begin_exploded.day_of_month, expected_begin.day_of_month);
EXPECT_EQ(begin_exploded.hour, expected_begin.hour);
EXPECT_EQ(begin_exploded.minute, expected_begin.minute);
EXPECT_EQ(begin_exploded.second, expected_begin.second);
EXPECT_EQ(begin_exploded.millisecond, expected_begin.millisecond);
}
}
} // namespace history_clusters
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
a946c079a3440b612b92e482817e846b4f0ac199 | 931544d66c832c092e0b0b0c6baabbecfe0d47d0 | /solutions/hackerrank/array-left-rotation.cpp | 7c87d26614d23ea86a62ffb37426ffbd3c7c7519 | [
"MIT"
] | permissive | rahulsah123/CodeMonk | 99f006e963d2618ad29987e690e275660877179c | 700d500b56566b63252a51bac8fe30949403d243 | refs/heads/master | 2020-06-13T01:07:37.147814 | 2016-11-27T17:16:40 | 2016-11-27T17:16:40 | 75,470,634 | 1 | 0 | null | 2016-12-03T11:50:46 | 2016-12-03T11:50:46 | null | UTF-8 | C++ | false | false | 799 | cpp | /**
* @author yangyanzhan
* @email yangyanzhan@gmail.com
* @homepage http://www.yangyanzhan.com
* @github_project https://github.com/yangyanzhan/CodeMonk
* @online_judge hackerrank
* @problem_id array-left-rotation
* @problem_address https://www.hackerrank.com/challenges/array-left-rotation
**/
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <iterator>
#include <map>
#include <queue>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
int n, d;
cin >> n >> d;
int nums[n];
for (int i = 0; i < n; i++)
cin >> nums[i];
for (int i = 0; i < n; i++) {
cout << nums[(i + d) % n] << " ";
}
return 0;
}
| [
"yangyanzhan@gmail.com"
] | yangyanzhan@gmail.com |
bf4f97fe8ddaf060f64d90d9d0acdf243fb15212 | b800fcf6bc5b78a5f84c9da4c3bab74cb8693a3d | /pgm7/Wheat.cpp | a06326ab08129f75ebf0d3f319edae8dd2a947fb | [] | no_license | billymeli/CS311 | 15f3f42259cd5df0c2cf6cd1521c21456225569f | 47f4d26963a85f42b31b45bac71bf56837ec5227 | refs/heads/master | 2021-05-09T16:11:37.693620 | 2018-05-02T01:17:39 | 2018-05-02T01:17:39 | 119,101,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,317 | cpp | // File Name: Wheat.cpp
// Author: Billy Meli
// Student ID: w882x457
// Assignment Number: 7
#include <iostream>
#include <string>
#include "Wheat.hpp"
using namespace std;
namespace {
const double AVG_WEIGHT_PER_BUSHEL = 60.0;
const double IDEAL_MOISTURE_LEVEL = 13.5;
}
// Default constructor (initializes all member variables to 0)
Wheat::Wheat() : Grain()
{}
// Constructor allowing caller to specify sample's moisture level (%) and foreign material (%)
Wheat::Wheat(double moistureLevel, double foreignMaterial)
: Grain(moistureLevel, foreignMaterial)
{}
// returns a pointer pointing to a copy of the grain sample
Wheat* Wheat::clone() const
{
Wheat* clonePtr = new Wheat(this->moistureLevel, this->foreignMaterial);
return clonePtr;
}
// returns an integer representing the grain type
int Wheat::getTypeVal() const
{
int grainTypeVal = 1;
return grainTypeVal;
}
// returns string representing the grain type
string Wheat::getType() const
{
string grainType = "Wheat";
return grainType;
}
// Accessor to return grain's average test weight (lbs/bushel)
const double Wheat::getAverageTestWeight() const
{
return AVG_WEIGHT_PER_BUSHEL;
}
// Accessor to return grain's ideal moisture level (percent)
const double Wheat::getIdealMoistureLevel() const
{
return IDEAL_MOISTURE_LEVEL;
}
| [
"mstevebilly@yahoo.com"
] | mstevebilly@yahoo.com |
d17c66d77db7c434ed7dc65a34f26f819dfd9697 | 5d392ba659c3c304ea55e9efe562a730051f1d5c | /myInfixPostfix.cpp | 0a53e4fb12bddbd2fbd527677fb41d228cfba9da | [] | no_license | TimManh/CMPE_126 | b9bf1d82fddb66a354068bb7c5437d2a2262bedc | e035f494844eec35b71e808b65cece0d9f5ff290 | refs/heads/master | 2020-04-26T22:23:36.594064 | 2019-03-05T04:16:36 | 2019-03-05T04:16:36 | 173,871,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,298 | cpp | /*
* myInfixPostfix.cpp
*
* Created on: Oct 12, 2018
* Author: admin
*/
#include"arrayStack.h"
#include<iostream>
#include<string>
using namespace std;
int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}
int main(){
string eq;
string ne;
char x;
arrayStack<char> s(100);
s.push('x');
cout<<"Enter the equation for testing"<<endl;
getline(cin,eq);
for( unsigned int i=0;i<eq.length();i++){
if((eq[i]>='A'&&eq[i]<='Z')||(eq[i]>='a'&&eq[i]<='z'))
ne+=eq[i];
else if(eq[i]=='(')
s.push('(');
else if(eq[i] == ')')
{
while(s.top() != 'x' && s.top() != '(')
{
x = s.top();
s.pop();
ne += x;
}
if(s.top() == '(')
{
x = s.top();
s.pop();
}
}
else{
while(s.top() != 'x' &&prec(eq[i]) <= prec(s.top()))
{
char c = s.top();
s.pop();
ne += c;
}
s.push(eq[i]);
}
}
while(s.top() != 'x')
{
char c = s.top();
s.pop();
ne += c;
}
cout<<ne<<endl;
return 0;
}
| [
"noreply@github.com"
] | TimManh.noreply@github.com |
4e785bee270622fff1f27aa657fb53efd679a9e2 | f47b84753c54723afa751f08060b1dab39b9bd0d | /src/goto-diff/change_impact.cpp | 381cbd7e3be2fac8d99b338d7d70458a2a044ae8 | [
"BSD-4-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | pkesseli-archive/cbmc-legacy | 9d8fac56c56902cd3bc22216c37f220699348c0a | 81f06d59850db7fc2603f06d54a8736d8c596194 | refs/heads/master | 2021-05-01T17:42:37.368349 | 2016-08-12T14:04:10 | 2016-08-12T14:04:10 | 52,523,903 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,335 | cpp | /*******************************************************************\
Module: Data and control-dependencies of syntactic diff
Author: Michael Tautschnig
Date: April 2016
\*******************************************************************/
#include <iostream>
#include <goto-programs/goto_model.h>
#include <analyses/dependence_graph.h>
#include "unified_diff.h"
#include "change_impact.h"
#if 0
struct cfg_nodet
{
cfg_nodet():node_required(false)
{
}
bool node_required;
#ifdef DEBUG_FULL_SLICERT
std::set<unsigned> required_by;
#endif
};
typedef cfg_baset<cfg_nodet> cfgt;
cfgt cfg;
typedef std::vector<cfgt::entryt> dep_node_to_cfgt;
typedef std::stack<cfgt::entryt> queuet;
inline void add_to_queue(
queuet &queue,
const cfgt::entryt &entry,
goto_programt::const_targett reason)
{
#ifdef DEBUG_FULL_SLICERT
cfg[entry].required_by.insert(reason->location_number);
#endif
queue.push(entry);
}
/*******************************************************************\
Function: full_slicert::operator()
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void full_slicert::operator()(
goto_functionst &goto_functions,
const namespacet &ns,
slicing_criteriont &criterion)
{
// build the CFG data structure
cfg(goto_functions);
// fill queue with according to slicing criterion
queuet queue;
// gather all unconditional jumps as they may need to be included
jumpst jumps;
// declarations or dead instructions may be necessary as well
decl_deadt decl_dead;
for(cfgt::entry_mapt::iterator
e_it=cfg.entry_map.begin();
e_it!=cfg.entry_map.end();
e_it++)
{
if(criterion(e_it->first))
add_to_queue(queue, e_it->second, e_it->first);
else if(implicit(e_it->first))
add_to_queue(queue, e_it->second, e_it->first);
else if((e_it->first->is_goto() && e_it->first->guard.is_true()) ||
e_it->first->is_throw())
jumps.push_back(e_it->second);
else if(e_it->first->is_decl())
{
const exprt &s=to_code_decl(e_it->first->code).symbol();
decl_dead[to_symbol_expr(s).get_identifier()].push(e_it->second);
}
else if(e_it->first->is_dead())
{
const exprt &s=to_code_dead(e_it->first->code).symbol();
decl_dead[to_symbol_expr(s).get_identifier()].push(e_it->second);
}
}
// compute program dependence graph (and post-dominators)
dependence_grapht dep_graph(ns);
dep_graph(goto_functions, ns);
// compute the fixedpoint
fixedpoint(goto_functions, queue, jumps, decl_dead, dep_graph);
// now replace those instructions that are not needed
// by skips
Forall_goto_functions(f_it, goto_functions)
if(f_it->second.body_available())
{
Forall_goto_program_instructions(i_it, f_it->second.body)
{
const cfgt::entryt &e=cfg.entry_map[i_it];
if(!i_it->is_end_function() && // always retained
!cfg[e].node_required)
i_it->make_skip();
#ifdef DEBUG_FULL_SLICERT
else
{
std::string c="ins:"+i2string(i_it->location_number);
c+=" req by:";
for(std::set<unsigned>::const_iterator
req_it=cfg[e].required_by.begin();
req_it!=cfg[e].required_by.end();
++req_it)
{
if(req_it!=cfg[e].required_by.begin()) c+=",";
c+=i2string(*req_it);
}
i_it->source_location.set_column(c); // for show-goto-functions
i_it->source_location.set_comment(c); // for dump-c
}
#endif
}
}
// remove the skips
remove_skip(goto_functions);
goto_functions.update();
}
/*******************************************************************\
Function: full_slicert::fixedpoint
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void full_slicert::fixedpoint(
goto_functionst &goto_functions,
queuet &queue,
jumpst &jumps,
decl_deadt &decl_dead,
const dependence_grapht &dep_graph)
{
std::vector<cfgt::entryt> dep_node_to_cfg;
dep_node_to_cfg.reserve(dep_graph.size());
for(unsigned i=0; i<dep_graph.size(); ++i)
{
cfgt::entry_mapt::const_iterator entry=
cfg.entry_map.find(dep_graph[i].PC);
assert(entry!=cfg.entry_map.end());
dep_node_to_cfg.push_back(entry->second);
}
// process queue until empty
while(!queue.empty())
{
while(!queue.empty())
{
cfgt::entryt e=queue.top();
cfgt::nodet &node=cfg[e];
queue.pop();
// already done by some earlier iteration?
if(node.node_required)
continue;
// node is required
node.node_required=true;
// add data and control dependencies of node
add_dependencies(node, queue, dep_graph, dep_node_to_cfg);
// retain all calls of the containing function
add_function_calls(node, queue, goto_functions);
// find all the symbols it uses to add declarations
add_decl_dead(node, queue, decl_dead);
}
// add any required jumps
add_jumps(queue, jumps, dep_graph.cfg_post_dominators());
}
}
/*******************************************************************\
Function: full_slicert::add_dependencies
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void full_slicert::add_dependencies(
const cfgt::nodet &node,
queuet &queue,
const dependence_grapht &dep_graph,
const dep_node_to_cfgt &dep_node_to_cfg)
{
const dependence_grapht::nodet &d_node=
dep_graph[dep_graph[node.PC].get_node_id()];
for(dependence_grapht::edgest::const_iterator
it=d_node.in.begin();
it!=d_node.in.end();
++it)
add_to_queue(queue, dep_node_to_cfg[it->first], node.PC);
}
#endif
class change_impactt
{
public:
change_impactt(
const goto_modelt &model_old,
const goto_modelt &model_new);
void operator()();
protected:
const goto_functionst &old_goto_functions;
const namespacet ns_old;
const goto_functionst &new_goto_functions;
const namespacet ns_new;
unified_difft unified_diff;
dependence_grapht old_dep_graph;
dependence_grapht new_dep_graph;
typedef enum
{
SAME=0,
NEW=1<<0,
DELETED=1<<1,
NEW_DATA_DEP=1<<2,
DEL_DATA_DEP=1<<3,
NEW_CTRL_DEP=1<<4,
DEL_CTRL_DEP=1<<5
} mod_flagt;
typedef std::map<goto_programt::const_targett, unsigned>
goto_program_change_impactt;
typedef std::map<irep_idt, goto_program_change_impactt>
goto_functions_change_impactt;
goto_functions_change_impactt old_change_impact, new_change_impact;
void change_impact(const irep_idt &function);
void change_impact(
const goto_programt &old_goto_program,
const goto_programt &new_goto_program,
const unified_difft::goto_program_difft &diff,
goto_program_change_impactt &old_impact,
goto_program_change_impactt &new_impact);
void output_change_impact(
const irep_idt &function,
const goto_program_change_impactt &c_i,
const goto_functionst &goto_functions,
const namespacet &ns) const;
void output_change_impact(
const irep_idt &function,
const goto_program_change_impactt &o_c_i,
const goto_functionst &o_goto_functions,
const namespacet &o_ns,
const goto_program_change_impactt &n_c_i,
const goto_functionst &n_goto_functions,
const namespacet &n_ns) const;
};
/*******************************************************************\
Function: change_impactt::change_impactt
Inputs:
Outputs:
Purpose:
\*******************************************************************/
change_impactt::change_impactt(
const goto_modelt &model_old,
const goto_modelt &model_new):
old_goto_functions(model_old.goto_functions),
ns_old(model_old.symbol_table),
new_goto_functions(model_new.goto_functions),
ns_new(model_new.symbol_table),
unified_diff(model_old, model_new),
old_dep_graph(ns_old),
new_dep_graph(ns_new)
{
// syntactic difference?
if(!unified_diff())
return;
// compute program dependence graph of old code
old_dep_graph(old_goto_functions, ns_old);
// compute program dependence graph of new code
new_dep_graph(new_goto_functions, ns_new);
}
/*******************************************************************\
Function: change_impactt::change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::change_impact(const irep_idt &function)
{
unified_difft::goto_program_difft diff;
unified_diff.get_diff(function, diff);
if(diff.empty())
return;
goto_functionst::function_mapt::const_iterator old_fit=
old_goto_functions.function_map.find(function);
goto_functionst::function_mapt::const_iterator new_fit=
new_goto_functions.function_map.find(function);
goto_programt empty;
const goto_programt &old_goto_program=
old_fit==old_goto_functions.function_map.end() ?
empty :
old_fit->second.body;
const goto_programt &new_goto_program=
new_fit==new_goto_functions.function_map.end() ?
empty :
new_fit->second.body;
change_impact(
old_goto_program,
new_goto_program,
diff,
old_change_impact[function],
new_change_impact[function]);
}
/*******************************************************************\
Function: change_impactt::change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::change_impact(
const goto_programt &old_goto_program,
const goto_programt &new_goto_program,
const unified_difft::goto_program_difft &diff,
goto_program_change_impactt &old_impact,
goto_program_change_impactt &new_impact)
{
goto_programt::const_targett o_it=
old_goto_program.instructions.begin();
goto_programt::const_targett n_it=
new_goto_program.instructions.begin();
for(const auto &d : diff)
{
switch(d.second)
{
case unified_difft::differencet::SAME:
assert(o_it!=old_goto_program.instructions.end());
assert(n_it!=new_goto_program.instructions.end());
old_impact[o_it]|=SAME;
++o_it;
assert(n_it==d.first);
new_impact[n_it]|=SAME;
++n_it;
break;
case unified_difft::differencet::DELETED:
assert(o_it!=old_goto_program.instructions.end());
assert(o_it==d.first);
{
const dependence_grapht::nodet &d_node=
old_dep_graph[old_dep_graph[o_it].get_node_id()];
for(dependence_grapht::edgest::const_iterator
it=d_node.in.begin();
it!=d_node.in.end();
++it)
{
goto_programt::const_targett src=
old_dep_graph[it->first].PC;
if(it->second.get()==dep_edget::DATA ||
it->second.get()==dep_edget::BOTH)
old_change_impact[src->function][src]|=DEL_DATA_DEP;
else
old_change_impact[src->function][src]|=DEL_CTRL_DEP;
}
for(dependence_grapht::edgest::const_iterator
it=d_node.out.begin();
it!=d_node.out.end();
++it)
{
goto_programt::const_targett src=
old_dep_graph[it->first].PC;
if(it->second.get()==dep_edget::DATA ||
it->second.get()==dep_edget::BOTH)
old_change_impact[src->function][src]|=DEL_DATA_DEP;
else
old_change_impact[src->function][src]|=DEL_CTRL_DEP;
}
}
old_impact[o_it]|=DELETED;
++o_it;
break;
case unified_difft::differencet::NEW:
assert(n_it!=new_goto_program.instructions.end());
assert(n_it==d.first);
{
const dependence_grapht::nodet &d_node=
new_dep_graph[new_dep_graph[n_it].get_node_id()];
for(dependence_grapht::edgest::const_iterator
it=d_node.in.begin();
it!=d_node.in.end();
++it)
{
goto_programt::const_targett src=
new_dep_graph[it->first].PC;
if(it->second.get()==dep_edget::DATA ||
it->second.get()==dep_edget::BOTH)
new_change_impact[src->function][src]|=NEW_DATA_DEP;
else
new_change_impact[src->function][src]|=NEW_CTRL_DEP;
}
for(dependence_grapht::edgest::const_iterator
it=d_node.out.begin();
it!=d_node.out.end();
++it)
{
goto_programt::const_targett dst=
new_dep_graph[it->first].PC;
if(it->second.get()==dep_edget::DATA ||
it->second.get()==dep_edget::BOTH)
new_change_impact[dst->function][dst]|=NEW_DATA_DEP;
else
new_change_impact[dst->function][dst]|=NEW_CTRL_DEP;
}
}
new_impact[n_it]|=NEW;
++n_it;
break;
}
}
}
/*******************************************************************\
Function: change_impactt::operator()
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::operator()()
{
// sorted iteration over intersection(old functions, new functions)
typedef std::map<irep_idt,
goto_functionst::function_mapt::const_iterator>
function_mapt;
function_mapt old_funcs, new_funcs;
forall_goto_functions(it, old_goto_functions)
old_funcs.insert(std::make_pair(it->first, it));
forall_goto_functions(it, new_goto_functions)
new_funcs.insert(std::make_pair(it->first, it));
function_mapt::const_iterator ito=old_funcs.begin();
for(function_mapt::const_iterator itn=new_funcs.begin();
itn!=new_funcs.end();
++itn)
{
while(ito!=old_funcs.end() && ito->first<itn->first)
++ito;
if(ito!=old_funcs.end() && itn->first==ito->first)
{
change_impact(itn->first);
++ito;
}
}
goto_functions_change_impactt::const_iterator oc_it=
old_change_impact.begin();
for(goto_functions_change_impactt::const_iterator
nc_it=new_change_impact.begin();
nc_it!=new_change_impact.end();
++nc_it)
{
for( ;
oc_it!=old_change_impact.end() && oc_it->first<nc_it->first;
++oc_it)
output_change_impact(
oc_it->first,
oc_it->second,
old_goto_functions,
ns_old);
if(oc_it==old_change_impact.end() || nc_it->first<oc_it->first)
output_change_impact(
nc_it->first,
nc_it->second,
new_goto_functions,
ns_new);
else
{
assert(oc_it->first==nc_it->first);
output_change_impact(
nc_it->first,
oc_it->second,
old_goto_functions,
ns_old,
nc_it->second,
new_goto_functions,
ns_new);
++oc_it;
}
}
}
/*******************************************************************\
Function: change_impact::output_change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::output_change_impact(
const irep_idt &function,
const goto_program_change_impactt &c_i,
const goto_functionst &goto_functions,
const namespacet &ns) const
{
goto_functionst::function_mapt::const_iterator f_it=
goto_functions.function_map.find(function);
assert(f_it!=goto_functions.function_map.end());
const goto_programt &goto_program=f_it->second.body;
std::cout << "/** " << function << " **/\n";
forall_goto_program_instructions(target, goto_program)
{
goto_program_change_impactt::const_iterator c_entry=
c_i.find(target);
const unsigned mod_flags=
c_entry==c_i.end() ? SAME : c_entry->second;
char prefix;
// syntactic changes are preferred over data/control-dependence
// modifications
if(mod_flags==SAME)
prefix=' ';
else if(mod_flags&DELETED)
prefix='-';
else if(mod_flags&NEW)
prefix='+';
else if(mod_flags&NEW_DATA_DEP)
prefix='D';
else if(mod_flags&NEW_CTRL_DEP)
prefix='C';
else if(mod_flags&DEL_DATA_DEP)
prefix='d';
else if(mod_flags&DEL_CTRL_DEP)
prefix='c';
else
assert(false);
std::cout << prefix;
goto_program.output_instruction(ns, function, std::cout, target);
}
}
/*******************************************************************\
Function: change_impact::output_change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::output_change_impact(
const irep_idt &function,
const goto_program_change_impactt &o_c_i,
const goto_functionst &o_goto_functions,
const namespacet &o_ns,
const goto_program_change_impactt &n_c_i,
const goto_functionst &n_goto_functions,
const namespacet &n_ns) const
{
goto_functionst::function_mapt::const_iterator o_f_it=
o_goto_functions.function_map.find(function);
assert(o_f_it!=o_goto_functions.function_map.end());
const goto_programt &old_goto_program=o_f_it->second.body;
goto_functionst::function_mapt::const_iterator f_it=
n_goto_functions.function_map.find(function);
assert(f_it!=n_goto_functions.function_map.end());
const goto_programt &goto_program=f_it->second.body;
std::cout << "/** " << function << " **/\n";
goto_programt::const_targett o_target=
old_goto_program.instructions.begin();
forall_goto_program_instructions(target, goto_program)
{
goto_program_change_impactt::const_iterator o_c_entry=
o_c_i.find(o_target);
const unsigned old_mod_flags=
o_c_entry==o_c_i.end() ? SAME : o_c_entry->second;
if(old_mod_flags&DELETED)
{
std::cout << '-';
goto_program.output_instruction(
o_ns,
function,
std::cout,
o_target);
++o_target;
continue;
}
goto_program_change_impactt::const_iterator c_entry=
n_c_i.find(target);
const unsigned mod_flags=
c_entry==n_c_i.end() ? SAME : c_entry->second;
char prefix;
// syntactic changes are preferred over data/control-dependence
// modifications
if(mod_flags==SAME)
{
if(old_mod_flags==SAME)
prefix=' ';
else if(old_mod_flags&DEL_DATA_DEP)
prefix='d';
else if(old_mod_flags&DEL_CTRL_DEP)
prefix='c';
else
assert(false);
++o_target;
}
else if(mod_flags&DELETED)
assert(false);
else if(mod_flags&NEW)
prefix='+';
else if(mod_flags&NEW_DATA_DEP)
{
prefix='D';
assert(old_mod_flags==SAME ||
old_mod_flags&DEL_DATA_DEP ||
old_mod_flags&DEL_CTRL_DEP);
++o_target;
}
else if(mod_flags&NEW_CTRL_DEP)
{
prefix='C';
assert(old_mod_flags==SAME ||
old_mod_flags&DEL_DATA_DEP ||
old_mod_flags&DEL_CTRL_DEP);
++o_target;
}
else
assert(false);
std::cout << prefix;
goto_program.output_instruction(n_ns, function, std::cout, target);
}
for( ;
o_target!=old_goto_program.instructions.end();
++o_target)
{
goto_program_change_impactt::const_iterator o_c_entry=
o_c_i.find(o_target);
const unsigned old_mod_flags=
o_c_entry==o_c_i.end() ? SAME : o_c_entry->second;
char prefix;
// syntactic changes are preferred over data/control-dependence
// modifications
if(old_mod_flags==SAME)
assert(false);
else if(old_mod_flags&DELETED)
prefix='-';
else if(old_mod_flags&NEW)
assert(false);
else if(old_mod_flags&DEL_DATA_DEP)
prefix='d';
else if(old_mod_flags&DEL_CTRL_DEP)
prefix='c';
else
assert(false);
std::cout << prefix;
goto_program.output_instruction(o_ns, function, std::cout, o_target);
}
}
/*******************************************************************\
Function: change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impact(
const goto_modelt &model_old,
const goto_modelt &model_new)
{
change_impactt c(model_old, model_new);
c();
}
| [
"peter.schrammel@cs.ox.ac.uk"
] | peter.schrammel@cs.ox.ac.uk |
c3cf5e749bc43fe06e0f8254957859b0fab92a9a | bd2fd73ce4e1f7dfb76970f5948fd6a0129680a8 | /c_stuff/GUI_@/GUI_@/olcPixelGameEngine.h | 093267f0f258211154a136e826c6095a8c941d33 | [] | no_license | jglatts/randoms | 5b64f078f4f16f377a725831e75889e252309cbb | 847e0386f4cb46e8c0cebbe4cbe3a9462c90e2e7 | refs/heads/master | 2022-12-20T04:33:03.120799 | 2020-09-27T12:11:15 | 2020-09-27T12:11:15 | 263,608,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 119,107 | h | /*
olcPixelGameEngine.h
+-------------------------------------------------------------+
| OneLoneCoder Pixel Game Engine v2.06 |
| "What do you need? Pixels... Lots of Pixels..." - javidx9 |
+-------------------------------------------------------------+
What is this?
~~~~~~~~~~~~~
olc::PixelGameEngine is a single file, cross platform graphics and userinput
framework used for games, visualisations, algorithm exploration and learning.
It was developed by YouTuber "javidx9" as an assistive tool for many of his
videos. The goal of this project is to provide high speed graphics with
minimal project setup complexity, to encourage new programmers, younger people,
and anyone else that wants to make fun things.
However, olc::PixelGameEngine is not a toy! It is a powerful and fast utility
capable of delivering high resolution, high speed, high quality applications
which behave the same way regardless of the operating system or platform.
This file provides the core utility set of the olc::PixelGameEngine, including
window creation, keyboard/mouse input, main game thread, timing, pixel drawing
routines, image/sprite loading and drawing routines, and a bunch of utility
types to make rapid development of games/visualisations possible.
License (OLC-3)
~~~~~~~~~~~~~~~
Copyright 2018 - 2020 OneLoneCoder.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions or derivations of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions or derivative works in binary form must reproduce the above
copyright notice. This list of conditions and the following disclaimer must be
reproduced 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.
Links
~~~~~
YouTube: https://www.youtube.com/javidx9
https://www.youtube.com/javidx9extra
Discord: https://discord.gg/WhwHUMV
Twitter: https://www.twitter.com/javidx9
Twitch: https://www.twitch.tv/javidx9
GitHub: https://www.github.com/onelonecoder
Homepage: https://www.onelonecoder.com
Patreon: https://www.patreon.com/javidx9
Community: https://community.onelonecoder.com
Compiling in Linux
~~~~~~~~~~~~~~~~~~
You will need a modern C++ compiler, so update yours!
To compile use the command:
g++ -o YourProgName YourSource.cpp -lX11 -lGL -lpthread -lpng -lstdc++fs -std=c++17
On some Linux configurations, the frame rate is locked to the refresh
rate of the monitor. This engine tries to unlock it but may not be
able to, in which case try launching your program like this:
vblank_mode=0 ./YourProgName
Compiling in Code::Blocks on Windows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Well I wont judge you, but make sure your Code::Blocks installation
is really up to date - you may even consider updating your C++ toolchain
to use MinGW32-W64.
Guide for installing recent GCC for Windows:
https://www.msys2.org/
Guide for configuring code::blocks:
https://solarianprogrammer.com/2019/11/05/install-gcc-windows/
https://solarianprogrammer.com/2019/11/16/install-codeblocks-gcc-windows-build-c-cpp-fortran-programs/
Add these libraries to "Linker Options":
user32 gdi32 opengl32 gdiplus Shlwapi stdc++fs
Set these compiler options: -std=c++17
Ports
~~~~~
olc::PixelGameEngine has been ported and tested with varying degrees of
success to: WinXP, Win7, Win8, Win10, Various Linux, Raspberry Pi,
Chromebook, Playstation Portable (PSP) and Nintendo Switch. If you are
interested in the details of these ports, come and visit the Discord!
Thanks
~~~~~~
I'd like to extend thanks to Eremiell, slavka, gurkanctn, Phantim, IProgramInCPP
JackOJC, KrossX, Huhlig, Dragoneye, Appa, JustinRichardsMusic, SliceNDice, dandistine
Ralakus, Gorbit99, raoul, joshinils, benedani, Moros1138, SaladinAkara & MagetzUb
for advice, ideas and testing, and I'd like to extend my appreciation to the
164K YouTube followers, 70+ Patreons and 8K Discord server members who give me
the motivation to keep going with all this :D
Significant Contributors: @Moros1138, @SaladinAkara, @MaGetzUb, @slavka, @Dragoneye & @Gorbit99
Special thanks to those who bring gifts!
GnarGnarHead.......Domina
Gorbit99...........Bastion, Ori & The Blind Forest, Terraria
Marti Morta........Gris
Danicron...........Terraria
SaladinAkara.......Aseprite
AlterEgo...........Final Fantasy XII - The Zodiac Age
Special thanks to my Patreons too - I wont name you on here, but I've
certainly enjoyed my tea and flapjacks :D
Author
~~~~~~
David Barr, aka javidx9, �OneLoneCoder 2018, 2019, 2020
2.01: Made renderer and platform static for multifile projects
2.02: Added Decal destructor, optimised Pixel constructor
2.03: Added FreeBSD flags, Added DrawStringDecal()
2.04: Windows Full-Screen bug fixed
2.05: Added DrawPartialWarpedDecal(), Added DrawPartialRotatedDecal()
2.06: +GetTextSize() - returns area occupied by multiline string
+GetWindowSize() - returns actual window size
+GetElapsedTime() - returns last calculated fElapsedTime
+GetWindowMouse() - returns actual mouse location in window
+DrawExplicitDecal() - bow-chikka-bow-bow
+DrawPartialDecal(pos, size) - draws a partial decal to dpecified area
+FillRectDecal() - draws a flat shaded rectangle as a decal
+GradientFillRectDecal() - draws a rectangle, with unique colour corners
+Modified DrawCircle() & FillCircle() - Thanks IanM-Matrix1 (#PR121)
+Gone someway to appeasing pedants
*/
//////////////////////////////////////////////////////////////////////////////////////////
// O------------------------------------------------------------------------------O
// | Example "Hello World" Program (main.cpp) |
// O------------------------------------------------------------------------------O
/*
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
// Override base class with your custom functionality
class Example : public olc::PixelGameEngine
{
public:
Example()
{
// Name you application
sAppName = "Example";
}
public:
bool OnUserCreate() override
{
// Called once at the start, so create things here
return true;
}
bool OnUserUpdate(float fElapsedTime) override
{
// called once per frame, draws random coloured pixels
for (int x = 0; x < ScreenWidth(); x++)
for (int y = 0; y < ScreenHeight(); y++)
Draw(x, y, olc::Pixel(rand() % 256, rand() % 256, rand()% 256));
return true;
}
};
int main()
{
Example demo;
if (demo.Construct(256, 240, 4, 4))
demo.Start();
return 0;
}
*/
#ifndef OLC_PGE_DEF
#define OLC_PGE_DEF
// O------------------------------------------------------------------------------O
// | STANDARD INCLUDES |
// O------------------------------------------------------------------------------O
#include <cmath>
#include <cstdint>
#include <string>
#include <iostream>
#include <streambuf>
#include <sstream>
#include <chrono>
#include <vector>
#include <list>
#include <thread>
#include <atomic>
#include <fstream>
#include <map>
#include <functional>
#include <algorithm>
#include <array>
#include <cstring>
// O------------------------------------------------------------------------------O
// | COMPILER CONFIGURATION ODDITIES |
// O------------------------------------------------------------------------------O
#define USE_EXPERIMENTAL_FS
#if defined(_WIN32)
#if _MSC_VER >= 1920 && _MSVC_LANG >= 201703L
#undef USE_EXPERIMENTAL_FS
#endif
#endif
#if defined(__linux__) || defined(__MINGW32__) || defined(__EMSCRIPTEN__) || defined(__FreeBSD__)
#if __cplusplus >= 201703L
#undef USE_EXPERIMENTAL_FS
#endif
#endif
#if defined(USE_EXPERIMENTAL_FS) || defined(FORCE_EXPERIMENTAL_FS)
// C++14
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include <experimental/filesystem>
namespace _gfs = std::experimental::filesystem::v1;
#else
// C++17
#include <filesystem>
namespace _gfs = std::filesystem;
#endif
#if defined(UNICODE) || defined(_UNICODE)
#define olcT(s) L##s
#else
#define olcT(s) s
#endif
#define UNUSED(x) (void)(x)
#if !defined(OLC_GFX_OPENGL33) && !defined(OLC_GFX_DIRECTX10)
#define OLC_GFX_OPENGL10
#endif
// O------------------------------------------------------------------------------O
// | olcPixelGameEngine INTERFACE DECLARATION |
// O------------------------------------------------------------------------------O
namespace olc
{
class PixelGameEngine;
// Pixel Game Engine Advanced Configuration
constexpr uint8_t nMouseButtons = 5;
constexpr uint8_t nDefaultAlpha = 0xFF;
constexpr uint32_t nDefaultPixel = (nDefaultAlpha << 24);
enum rcode { FAIL = 0, OK = 1, NO_FILE = -1 };
// O------------------------------------------------------------------------------O
// | olc::Pixel - Represents a 32-Bit RGBA colour |
// O------------------------------------------------------------------------------O
struct Pixel
{
union
{
uint32_t n = nDefaultPixel;
struct { uint8_t r; uint8_t g; uint8_t b; uint8_t a; };
};
enum Mode { NORMAL, MASK, ALPHA, CUSTOM };
Pixel();
Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = nDefaultAlpha);
Pixel(uint32_t p);
bool operator==(const Pixel& p) const;
bool operator!=(const Pixel& p) const;
};
Pixel PixelF(float red, float green, float blue, float alpha = 1.0f);
// O------------------------------------------------------------------------------O
// | USEFUL CONSTANTS |
// O------------------------------------------------------------------------------O
static const Pixel
GREY(192, 192, 192), DARK_GREY(128, 128, 128), VERY_DARK_GREY(64, 64, 64),
RED(255, 0, 0), DARK_RED(128, 0, 0), VERY_DARK_RED(64, 0, 0),
YELLOW(255, 255, 0), DARK_YELLOW(128, 128, 0), VERY_DARK_YELLOW(64, 64, 0),
GREEN(0, 255, 0), DARK_GREEN(0, 128, 0), VERY_DARK_GREEN(0, 64, 0),
CYAN(0, 255, 255), DARK_CYAN(0, 128, 128), VERY_DARK_CYAN(0, 64, 64),
BLUE(0, 0, 255), DARK_BLUE(0, 0, 128), VERY_DARK_BLUE(0, 0, 64),
MAGENTA(255, 0, 255), DARK_MAGENTA(128, 0, 128), VERY_DARK_MAGENTA(64, 0, 64),
WHITE(255, 255, 255), BLACK(0, 0, 0), BLANK(0, 0, 0, 0);
enum Key
{
NONE,
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,
K0, K1, K2, K3, K4, K5, K6, K7, K8, K9,
F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
UP, DOWN, LEFT, RIGHT,
SPACE, TAB, SHIFT, CTRL, INS, DEL, HOME, END, PGUP, PGDN,
BACK, ESCAPE, RETURN, ENTER, PAUSE, SCROLL,
NP0, NP1, NP2, NP3, NP4, NP5, NP6, NP7, NP8, NP9,
NP_MUL, NP_DIV, NP_ADD, NP_SUB, NP_DECIMAL, PERIOD
};
// O------------------------------------------------------------------------------O
// | olc::vX2d - A generic 2D vector type |
// O------------------------------------------------------------------------------O
#if !defined(OLC_IGNORE_VEC2D)
template <class T>
struct v2d_generic
{
T x = 0;
T y = 0;
v2d_generic() : x(0), y(0) { }
v2d_generic(T _x, T _y) : x(_x), y(_y) { }
v2d_generic(const v2d_generic& v) : x(v.x), y(v.y) { }
T mag() { return std::sqrt(x * x + y * y); }
T mag2() { return x * x + y * y; }
v2d_generic norm() { T r = 1 / mag(); return v2d_generic(x * r, y * r); }
v2d_generic perp() { return v2d_generic(-y, x); }
T dot(const v2d_generic& rhs) { return this->x * rhs.x + this->y * rhs.y; }
T cross(const v2d_generic& rhs) { return this->x * rhs.y - this->y * rhs.x; }
v2d_generic operator + (const v2d_generic& rhs) const { return v2d_generic(this->x + rhs.x, this->y + rhs.y); }
v2d_generic operator - (const v2d_generic& rhs) const { return v2d_generic(this->x - rhs.x, this->y - rhs.y); }
v2d_generic operator * (const T& rhs) const { return v2d_generic(this->x * rhs, this->y * rhs); }
v2d_generic operator * (const v2d_generic& rhs) const { return v2d_generic(this->x * rhs.x, this->y * rhs.y); }
v2d_generic operator / (const T& rhs) const { return v2d_generic(this->x / rhs, this->y / rhs); }
v2d_generic operator / (const v2d_generic& rhs) const { return v2d_generic(this->x / rhs.x, this->y / rhs.y); }
v2d_generic& operator += (const v2d_generic& rhs) { this->x += rhs.x; this->y += rhs.y; return *this; }
v2d_generic& operator -= (const v2d_generic& rhs) { this->x -= rhs.x; this->y -= rhs.y; return *this; }
v2d_generic& operator *= (const T& rhs) { this->x *= rhs; this->y *= rhs; return *this; }
v2d_generic& operator /= (const T& rhs) { this->x /= rhs; this->y /= rhs; return *this; }
operator v2d_generic<int32_t>() const { return { static_cast<int32_t>(this->x), static_cast<int32_t>(this->y) }; }
operator v2d_generic<float>() const { return { static_cast<float>(this->x), static_cast<float>(this->y) }; }
operator v2d_generic<double>() const { return { static_cast<double>(this->x), static_cast<double>(this->y) }; }
};
// Note: joshinils has some good suggestions here, but they are complicated to implement at this moment,
// however they will appear in a future version of PGE
template<class T> inline v2d_generic<T> operator * (const float& lhs, const v2d_generic<T>& rhs)
{
return v2d_generic<T>((T)(lhs * (float)rhs.x), (T)(lhs * (float)rhs.y));
}
template<class T> inline v2d_generic<T> operator * (const double& lhs, const v2d_generic<T>& rhs)
{
return v2d_generic<T>((T)(lhs * (double)rhs.x), (T)(lhs * (double)rhs.y));
}
template<class T> inline v2d_generic<T> operator * (const int& lhs, const v2d_generic<T>& rhs)
{
return v2d_generic<T>((T)(lhs * (int)rhs.x), (T)(lhs * (int)rhs.y));
}
template<class T> inline v2d_generic<T> operator / (const float& lhs, const v2d_generic<T>& rhs)
{
return v2d_generic<T>((T)(lhs / (float)rhs.x), (T)(lhs / (float)rhs.y));
}
template<class T> inline v2d_generic<T> operator / (const double& lhs, const v2d_generic<T>& rhs)
{
return v2d_generic<T>((T)(lhs / (double)rhs.x), (T)(lhs / (double)rhs.y));
}
template<class T> inline v2d_generic<T> operator / (const int& lhs, const v2d_generic<T>& rhs)
{
return v2d_generic<T>((T)(lhs / (int)rhs.x), (T)(lhs / (int)rhs.y));
}
typedef v2d_generic<int32_t> vi2d;
typedef v2d_generic<uint32_t> vu2d;
typedef v2d_generic<float> vf2d;
typedef v2d_generic<double> vd2d;
#endif
// O------------------------------------------------------------------------------O
// | olc::HWButton - Represents the state of a hardware button (mouse/key/joy) |
// O------------------------------------------------------------------------------O
struct HWButton
{
bool bPressed = false; // Set once during the frame the event occurs
bool bReleased = false; // Set once during the frame the event occurs
bool bHeld = false; // Set true for all frames between pressed and released events
};
// O------------------------------------------------------------------------------O
// | olc::ResourcePack - A virtual scrambled filesystem to pack your assets into |
// O------------------------------------------------------------------------------O
struct ResourceBuffer : public std::streambuf
{
ResourceBuffer(std::ifstream& ifs, uint32_t offset, uint32_t size);
std::vector<char> vMemory;
};
class ResourcePack : public std::streambuf
{
public:
ResourcePack();
~ResourcePack();
bool AddFile(const std::string& sFile);
bool LoadPack(const std::string& sFile, const std::string& sKey);
bool SavePack(const std::string& sFile, const std::string& sKey);
ResourceBuffer GetFileBuffer(const std::string& sFile);
bool Loaded();
private:
struct sResourceFile { uint32_t nSize; uint32_t nOffset; };
std::map<std::string, sResourceFile> mapFiles;
std::ifstream baseFile;
std::vector<char> scramble(const std::vector<char>& data, const std::string& key);
std::string makeposix(const std::string& path);
};
// O------------------------------------------------------------------------------O
// | olc::Sprite - An image represented by a 2D array of olc::Pixel |
// O------------------------------------------------------------------------------O
class Sprite
{
public:
Sprite();
Sprite(const std::string& sImageFile, olc::ResourcePack* pack = nullptr);
Sprite(int32_t w, int32_t h);
~Sprite();
public:
olc::rcode LoadFromFile(const std::string& sImageFile, olc::ResourcePack* pack = nullptr);
olc::rcode LoadFromPGESprFile(const std::string& sImageFile, olc::ResourcePack* pack = nullptr);
olc::rcode SaveToPGESprFile(const std::string& sImageFile);
public:
int32_t width = 0;
int32_t height = 0;
enum Mode { NORMAL, PERIODIC };
enum Flip { NONE = 0, HORIZ = 1, VERT = 2 };
public:
void SetSampleMode(olc::Sprite::Mode mode = olc::Sprite::Mode::NORMAL);
Pixel GetPixel(int32_t x, int32_t y) const;
bool SetPixel(int32_t x, int32_t y, Pixel p);
Pixel GetPixel(const olc::vi2d& a) const;
bool SetPixel(const olc::vi2d& a, Pixel p);
Pixel Sample(float x, float y) const;
Pixel SampleBL(float u, float v) const;
Pixel* GetData();
Pixel* pColData = nullptr;
Mode modeSample = Mode::NORMAL;
};
// O------------------------------------------------------------------------------O
// | olc::Decal - A GPU resident storage of an olc::Sprite |
// O------------------------------------------------------------------------------O
class Decal
{
public:
Decal(olc::Sprite* spr);
virtual ~Decal();
void Update();
public: // But dont touch
int32_t id = -1;
olc::Sprite* sprite = nullptr;
olc::vf2d vUVScale = { 1.0f, 1.0f };
};
// O------------------------------------------------------------------------------O
// | olc::Renderable - Convenience class to keep a sprite and decal together |
// O------------------------------------------------------------------------------O
class Renderable
{
public:
Renderable() = default;
olc::rcode Load(const std::string& sFile, ResourcePack* pack = nullptr);
void Create(uint32_t width, uint32_t height);
olc::Decal* Decal() const;
olc::Sprite* Sprite() const;
private:
std::unique_ptr<olc::Sprite> pSprite = nullptr;
std::unique_ptr<olc::Decal> pDecal = nullptr;
};
// O------------------------------------------------------------------------------O
// | Auxilliary components internal to engine |
// O------------------------------------------------------------------------------O
struct DecalInstance
{
olc::Decal* decal = nullptr;
olc::vf2d pos[4] = { { 0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f} };
olc::vf2d uv[4] = { { 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f} };
float w[4] = { 1, 1, 1, 1 };
olc::Pixel tint[4] = { olc::WHITE, olc::WHITE, olc::WHITE, olc::WHITE };;
};
struct DecalTriangleInstance
{
olc::vf2d points[3];
olc::vf2d texture[3];
olc::Pixel colours[3];
olc::Decal* decal = nullptr;
};
struct LayerDesc
{
olc::vf2d vOffset = { 0, 0 };
olc::vf2d vScale = { 1, 1 };
bool bShow = false;
bool bUpdate = false;
olc::Sprite* pDrawTarget = nullptr;
uint32_t nResID = 0;
std::vector<DecalInstance> vecDecalInstance;
olc::Pixel tint = olc::WHITE;
std::function<void()> funcHook = nullptr;
};
class Renderer
{
public:
virtual void PrepareDevice() = 0;
virtual olc::rcode CreateDevice(std::vector<void*> params, bool bFullScreen, bool bVSYNC) = 0;
virtual olc::rcode DestroyDevice() = 0;
virtual void DisplayFrame() = 0;
virtual void PrepareDrawing() = 0;
virtual void DrawLayerQuad(const olc::vf2d& offset, const olc::vf2d& scale, const olc::Pixel tint) = 0;
virtual void DrawDecalQuad(const olc::DecalInstance& decal) = 0;
virtual uint32_t CreateTexture(const uint32_t width, const uint32_t height) = 0;
virtual void UpdateTexture(uint32_t id, olc::Sprite* spr) = 0;
virtual uint32_t DeleteTexture(const uint32_t id) = 0;
virtual void ApplyTexture(uint32_t id) = 0;
virtual void UpdateViewport(const olc::vi2d& pos, const olc::vi2d& size) = 0;
virtual void ClearBuffer(olc::Pixel p, bool bDepth) = 0;
static olc::PixelGameEngine* ptrPGE;
};
class Platform
{
public:
virtual olc::rcode ApplicationStartUp() = 0;
virtual olc::rcode ApplicationCleanUp() = 0;
virtual olc::rcode ThreadStartUp() = 0;
virtual olc::rcode ThreadCleanUp() = 0;
virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) = 0;
virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) = 0;
virtual olc::rcode SetWindowTitle(const std::string& s) = 0;
virtual olc::rcode StartSystemEventLoop() = 0;
virtual olc::rcode HandleSystemEvent() = 0;
static olc::PixelGameEngine* ptrPGE;
};
static std::unique_ptr<Renderer> renderer;
static std::unique_ptr<Platform> platform;
static std::map<size_t, uint8_t> mapKeys;
// O------------------------------------------------------------------------------O
// | olc::PixelGameEngine - The main BASE class for your application |
// O------------------------------------------------------------------------------O
class PixelGameEngine
{
public:
PixelGameEngine();
virtual ~PixelGameEngine();
public:
olc::rcode Construct(int32_t screen_w, int32_t screen_h, int32_t pixel_w, int32_t pixel_h,
bool full_screen = false, bool vsync = false);
olc::rcode Start();
public: // User Override Interfaces
// Called once on application startup, use to load your resources
virtual bool OnUserCreate();
// Called every frame, and provides you with a time per frame value
virtual bool OnUserUpdate(float fElapsedTime);
// Called once on application termination, so you can be one clean coder
virtual bool OnUserDestroy();
public: // Hardware Interfaces
// Returns true if window is currently in focus
bool IsFocused();
// Get the state of a specific keyboard button
HWButton GetKey(Key k);
// Get the state of a specific mouse button
HWButton GetMouse(uint32_t b);
// Get Mouse X coordinate in "pixel" space
int32_t GetMouseX();
// Get Mouse Y coordinate in "pixel" space
int32_t GetMouseY();
// Get Mouse Wheel Delta
int32_t GetMouseWheel();
// Get the ouse in window space
const olc::vi2d& GetWindowMouse() const;
public: // Utility
// Returns the width of the screen in "pixels"
int32_t ScreenWidth();
// Returns the height of the screen in "pixels"
int32_t ScreenHeight();
// Returns the width of the currently selected drawing target in "pixels"
int32_t GetDrawTargetWidth();
// Returns the height of the currently selected drawing target in "pixels"
int32_t GetDrawTargetHeight();
// Returns the currently active draw target
olc::Sprite* GetDrawTarget();
// Resize the primary screen sprite
void SetScreenSize(int w, int h);
// Specify which Sprite should be the target of drawing functions, use nullptr
// to specify the primary screen
void SetDrawTarget(Sprite* target);
// Gets the current Frames Per Second
uint32_t GetFPS();
// Gets last update of elapsed time
const float GetElapsedTime() const;
// Gets Actual Window size
const olc::vi2d& GetWindowSize() const;
public: // CONFIGURATION ROUTINES
// Layer targeting functions
void SetDrawTarget(uint8_t layer);
void EnableLayer(uint8_t layer, bool b);
void SetLayerOffset(uint8_t layer, const olc::vf2d& offset);
void SetLayerOffset(uint8_t layer, float x, float y);
void SetLayerScale(uint8_t layer, const olc::vf2d& scale);
void SetLayerScale(uint8_t layer, float x, float y);
void SetLayerTint(uint8_t layer, const olc::Pixel& tint);
void SetLayerCustomRenderFunction(uint8_t layer, std::function<void()> f);
std::vector<LayerDesc>& GetLayers();
uint32_t CreateLayer();
// Change the pixel mode for different optimisations
// olc::Pixel::NORMAL = No transparency
// olc::Pixel::MASK = Transparent if alpha is < 255
// olc::Pixel::ALPHA = Full transparency
void SetPixelMode(Pixel::Mode m);
Pixel::Mode GetPixelMode();
// Use a custom blend function
void SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel & pSource, const olc::Pixel & pDest)> pixelMode);
// Change the blend factor form between 0.0f to 1.0f;
void SetPixelBlend(float fBlend);
// Offset texels by sub-pixel amount (advanced, do not use)
[[deprecated]]
void SetSubPixelOffset(float ox, float oy);
public: // DRAWING ROUTINES
// Draws a single Pixel
virtual bool Draw(int32_t x, int32_t y, Pixel p = olc::WHITE);
bool Draw(const olc::vi2d& pos, Pixel p = olc::WHITE);
// Draws a line from (x1,y1) to (x2,y2)
void DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p = olc::WHITE, uint32_t pattern = 0xFFFFFFFF);
void DrawLine(const olc::vi2d& pos1, const olc::vi2d& pos2, Pixel p = olc::WHITE, uint32_t pattern = 0xFFFFFFFF);
// Draws a circle located at (x,y) with radius
void DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE, uint8_t mask = 0xFF);
void DrawCircle(const olc::vi2d& pos, int32_t radius, Pixel p = olc::WHITE, uint8_t mask = 0xFF);
// Fills a circle located at (x,y) with radius
void FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE);
void FillCircle(const olc::vi2d& pos, int32_t radius, Pixel p = olc::WHITE);
// Draws a rectangle at (x,y) to (x+w,y+h)
void DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE);
void DrawRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p = olc::WHITE);
// Fills a rectangle at (x,y) to (x+w,y+h)
void FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE);
void FillRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p = olc::WHITE);
// Draws a triangle between points (x1,y1), (x2,y2) and (x3,y3)
void DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE);
void DrawTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p = olc::WHITE);
// Flat fills a triangle between points (x1,y1), (x2,y2) and (x3,y3)
void FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE);
void FillTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p = olc::WHITE);
// Draws an entire sprite at well in my defencelocation (x,y)
void DrawSprite(int32_t x, int32_t y, Sprite* sprite, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE);
void DrawSprite(const olc::vi2d& pos, Sprite* sprite, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE);
// Draws an area of a sprite at location (x,y), where the
// selected area is (ox,oy) to (ox+w,oy+h)
void DrawPartialSprite(int32_t x, int32_t y, Sprite* sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE);
void DrawPartialSprite(const olc::vi2d& pos, Sprite* sprite, const olc::vi2d& sourcepos, const olc::vi2d& size, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE);
// Decal Quad functions
// Draws a whole decal, with optional scale and tinting
void DrawDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& scale = { 1.0f,1.0f }, const olc::Pixel& tint = olc::WHITE);
// Draws a region of a decal, with optional scale and tinting
void DrawPartialDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale = { 1.0f,1.0f }, const olc::Pixel& tint = olc::WHITE);
void DrawPartialDecal(const olc::vf2d& pos, const olc::vf2d& size, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE);
// Draws fully user controlled 4 vertices, pos(pixels), uv(pixels), colours
void DrawExplicitDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d* uv, const olc::Pixel* col);
// Draws a decal with 4 arbitrary points, warping the texture to look "correct"
void DrawWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::Pixel& tint = olc::WHITE);
void DrawWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::Pixel& tint = olc::WHITE);
void DrawWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::Pixel& tint = olc::WHITE);
// As above, but you can specify a region of a decal source sprite
void DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE);
void DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE);
void DrawPartialWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE);
// Draws a decal rotated to specified angle, wit point of rotation offset
void DrawRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center = { 0.0f, 0.0f }, const olc::vf2d& scale = { 1.0f,1.0f }, const olc::Pixel& tint = olc::WHITE);
void DrawPartialRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale = { 1.0f, 1.0f }, const olc::Pixel& tint = olc::WHITE);
// Draws a multiline string as a decal, with tiniting and scaling
void DrawStringDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col = olc::WHITE, const olc::vf2d& scale = { 1.0f, 1.0f });
// Draws a single shaded filled rectangle as a decal
void FillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel col = olc::WHITE);
// Draws a corner shaded rectangle as a decal
void GradientFillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel colTL, const olc::Pixel colBL, const olc::Pixel colBR, const olc::Pixel colTR);
// Draws a single line of text
void DrawString(int32_t x, int32_t y, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1);
void DrawString(const olc::vi2d& pos, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1);
olc::vi2d GetTextSize(const std::string& s);
// Clears entire draw target to Pixel
void Clear(Pixel p);
// Clears the rendering back buffer
void ClearBuffer(Pixel p, bool bDepth = true);
public: // Branding
std::string sAppName;
private: // Inner mysterious workings
Sprite* pDrawTarget = nullptr;
Pixel::Mode nPixelMode = Pixel::NORMAL;
float fBlendFactor = 1.0f;
olc::vi2d vScreenSize = { 256, 240 };
olc::vf2d vInvScreenSize = { 1.0f / 256.0f, 1.0f / 240.0f };
olc::vi2d vPixelSize = { 4, 4 };
olc::vi2d vMousePos = { 0, 0 };
int32_t nMouseWheelDelta = 0;
olc::vi2d vMousePosCache = { 0, 0 };
olc::vi2d vMouseWindowPos = { 0, 0 };
int32_t nMouseWheelDeltaCache = 0;
olc::vi2d vWindowSize = { 0, 0 };
olc::vi2d vViewPos = { 0, 0 };
olc::vi2d vViewSize = { 0,0 };
bool bFullScreen = false;
olc::vf2d vPixel = { 1.0f, 1.0f };
bool bHasInputFocus = false;
bool bHasMouseFocus = false;
bool bEnableVSYNC = false;
float fFrameTimer = 1.0f;
float fLastElapsed = 0.0f;
int nFrameCount = 0;
Sprite* fontSprite = nullptr;
Decal* fontDecal = nullptr;
Sprite* pDefaultDrawTarget = nullptr;
std::vector<LayerDesc> vLayers;
uint8_t nTargetLayer = 0;
uint32_t nLastFPS = 0;
std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> funcPixelMode;
std::chrono::time_point<std::chrono::system_clock> m_tp1, m_tp2;
// State of keyboard
bool pKeyNewState[256]{ 0 };
bool pKeyOldState[256]{ 0 };
HWButton pKeyboardState[256]{ 0 };
// State of mouse
bool pMouseNewState[nMouseButtons]{ 0 };
bool pMouseOldState[nMouseButtons]{ 0 };
HWButton pMouseState[nMouseButtons]{ 0 };
// The main engine thread
void EngineThread();
// At the very end of this file, chooses which
// components to compile
void olc_ConfigureSystem();
// If anything sets this flag to false, the engine
// "should" shut down gracefully
static std::atomic<bool> bAtomActive;
public:
// "Break In" Functions
void olc_UpdateMouse(int32_t x, int32_t y);
void olc_UpdateMouseWheel(int32_t delta);
void olc_UpdateWindowSize(int32_t x, int32_t y);
void olc_UpdateViewport();
void olc_ConstructFontSheet();
void olc_CoreUpdate();
void olc_PrepareEngine();
void olc_UpdateMouseState(int32_t button, bool state);
void olc_UpdateKeyState(int32_t key, bool state);
void olc_UpdateMouseFocus(bool state);
void olc_UpdateKeyFocus(bool state);
void olc_Terminate();
// NOTE: Items Here are to be deprecated, I have left them in for now
// in case you are using them, but they will be removed.
// olc::vf2d vSubPixelOffset = { 0.0f, 0.0f };
friend class PGEX;
};
// O------------------------------------------------------------------------------O
// | PGE EXTENSION BASE CLASS - Permits access to PGE functions from extension |
// O------------------------------------------------------------------------------O
class PGEX
{
friend class olc::PixelGameEngine;
protected:
static PixelGameEngine* pge;
};
}
#endif // OLC_PGE_DEF
/*
Object Oriented Mode
~~~~~~~~~~~~~~~~~~~~
If the olcPixelGameEngine.h is called from several sources it can cause
multiple definitions of objects. To prevent this, ONLY ONE of the pathways
to including this file must have OLC_PGE_APPLICATION defined before it. This prevents
the definitions being duplicated.
If all else fails, create a file called "olcPixelGameEngine.cpp" with the following
two lines. Then you can just #include "olcPixelGameEngine.h" as normal without worrying
about defining things. Dont forget to include that cpp file as part of your build!
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
*/
// O------------------------------------------------------------------------------O
// | START OF OLC_PGE_APPLICATION |
// O------------------------------------------------------------------------------O
#ifdef OLC_PGE_APPLICATION
#undef OLC_PGE_APPLICATION
// O------------------------------------------------------------------------------O
// | olcPixelGameEngine INTERFACE IMPLEMENTATION (CORE) |
// | Note: The core implementation is platform independent |
// O------------------------------------------------------------------------------O
namespace olc
{
// O------------------------------------------------------------------------------O
// | olc::Pixel IMPLEMENTATION |
// O------------------------------------------------------------------------------O
Pixel::Pixel()
{
r = 0; g = 0; b = 0; a = nDefaultAlpha;
}
Pixel::Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha)
{
n = red | (green << 8) | (blue << 16) | (alpha << 24);
} // Thanks jarekpelczar
Pixel::Pixel(uint32_t p)
{
n = p;
}
bool Pixel::operator==(const Pixel& p) const
{
return n == p.n;
}
bool Pixel::operator!=(const Pixel& p) const
{
return n != p.n;
}
Pixel PixelF(float red, float green, float blue, float alpha)
{
return Pixel(uint8_t(red * 255.0f), uint8_t(green * 255.0f), uint8_t(blue * 255.0f), uint8_t(alpha * 255.0f));
}
// O------------------------------------------------------------------------------O
// | olc::Sprite IMPLEMENTATION |
// O------------------------------------------------------------------------------O
Sprite::Sprite()
{
pColData = nullptr; width = 0; height = 0;
}
Sprite::Sprite(const std::string& sImageFile, olc::ResourcePack* pack)
{
LoadFromFile(sImageFile, pack);
}
Sprite::Sprite(int32_t w, int32_t h)
{
if (pColData) delete[] pColData;
width = w; height = h;
pColData = new Pixel[width * height];
for (int32_t i = 0; i < width * height; i++)
pColData[i] = Pixel();
}
Sprite::~Sprite()
{
if (pColData) delete[] pColData;
}
olc::rcode Sprite::LoadFromPGESprFile(const std::string& sImageFile, olc::ResourcePack* pack)
{
if (pColData) delete[] pColData;
auto ReadData = [&](std::istream& is)
{
is.read((char*)&width, sizeof(int32_t));
is.read((char*)&height, sizeof(int32_t));
pColData = new Pixel[width * height];
is.read((char*)pColData, (size_t)width * (size_t)height * sizeof(uint32_t));
};
// These are essentially Memory Surfaces represented by olc::Sprite
// which load very fast, but are completely uncompressed
if (pack == nullptr)
{
std::ifstream ifs;
ifs.open(sImageFile, std::ifstream::binary);
if (ifs.is_open())
{
ReadData(ifs);
return olc::OK;
}
else
return olc::FAIL;
}
else
{
ResourceBuffer rb = pack->GetFileBuffer(sImageFile);
std::istream is(&rb);
ReadData(is);
return olc::OK;
}
return olc::FAIL;
}
olc::rcode Sprite::SaveToPGESprFile(const std::string& sImageFile)
{
if (pColData == nullptr) return olc::FAIL;
std::ofstream ofs;
ofs.open(sImageFile, std::ifstream::binary);
if (ofs.is_open())
{
ofs.write((char*)&width, sizeof(int32_t));
ofs.write((char*)&height, sizeof(int32_t));
ofs.write((char*)pColData, (size_t)width * (size_t)height * sizeof(uint32_t));
ofs.close();
return olc::OK;
}
return olc::FAIL;
}
void Sprite::SetSampleMode(olc::Sprite::Mode mode)
{
modeSample = mode;
}
Pixel Sprite::GetPixel(const olc::vi2d& a) const
{
return GetPixel(a.x, a.y);
}
bool Sprite::SetPixel(const olc::vi2d& a, Pixel p)
{
return SetPixel(a.x, a.y, p);
}
Pixel Sprite::GetPixel(int32_t x, int32_t y) const
{
if (modeSample == olc::Sprite::Mode::NORMAL)
{
if (x >= 0 && x < width && y >= 0 && y < height)
return pColData[y * width + x];
else
return Pixel(0, 0, 0, 0);
}
else
{
return pColData[abs(y % height) * width + abs(x % width)];
}
}
bool Sprite::SetPixel(int32_t x, int32_t y, Pixel p)
{
if (x >= 0 && x < width && y >= 0 && y < height)
{
pColData[y * width + x] = p;
return true;
}
else
return false;
}
Pixel Sprite::Sample(float x, float y) const
{
int32_t sx = std::min((int32_t)((x * (float)width)), width - 1);
int32_t sy = std::min((int32_t)((y * (float)height)), height - 1);
return GetPixel(sx, sy);
}
Pixel Sprite::SampleBL(float u, float v) const
{
u = u * width - 0.5f;
v = v * height - 0.5f;
int x = (int)floor(u); // cast to int rounds toward zero, not downward
int y = (int)floor(v); // Thanks @joshinils
float u_ratio = u - x;
float v_ratio = v - y;
float u_opposite = 1 - u_ratio;
float v_opposite = 1 - v_ratio;
olc::Pixel p1 = GetPixel(std::max(x, 0), std::max(y, 0));
olc::Pixel p2 = GetPixel(std::min(x + 1, (int)width - 1), std::max(y, 0));
olc::Pixel p3 = GetPixel(std::max(x, 0), std::min(y + 1, (int)height - 1));
olc::Pixel p4 = GetPixel(std::min(x + 1, (int)width - 1), std::min(y + 1, (int)height - 1));
return olc::Pixel(
(uint8_t)((p1.r * u_opposite + p2.r * u_ratio) * v_opposite + (p3.r * u_opposite + p4.r * u_ratio) * v_ratio),
(uint8_t)((p1.g * u_opposite + p2.g * u_ratio) * v_opposite + (p3.g * u_opposite + p4.g * u_ratio) * v_ratio),
(uint8_t)((p1.b * u_opposite + p2.b * u_ratio) * v_opposite + (p3.b * u_opposite + p4.b * u_ratio) * v_ratio));
}
Pixel* Sprite::GetData()
{
return pColData;
}
// O------------------------------------------------------------------------------O
// | olc::Decal IMPLEMENTATION |
// O------------------------------------------------------------------------------O
Decal::Decal(olc::Sprite* spr)
{
id = -1;
if (spr == nullptr) return;
sprite = spr;
id = renderer->CreateTexture(sprite->width, sprite->height);
Update();
}
void Decal::Update()
{
if (sprite == nullptr) return;
vUVScale = { 1.0f / float(sprite->width), 1.0f / float(sprite->height) };
renderer->ApplyTexture(id);
renderer->UpdateTexture(id, sprite);
}
Decal::~Decal()
{
if (id != -1)
{
renderer->DeleteTexture(id);
id = -1;
}
}
void Renderable::Create(uint32_t width, uint32_t height)
{
pSprite = std::make_unique<olc::Sprite>(width, height);
pDecal = std::make_unique<olc::Decal>(pSprite.get());
}
olc::rcode Renderable::Load(const std::string& sFile, ResourcePack* pack)
{
pSprite = std::make_unique<olc::Sprite>();
if (pSprite->LoadFromFile(sFile, pack))
{
pDecal = std::make_unique<olc::Decal>(pSprite.get());
return olc::rcode::OK;
}
else
{
pSprite.release();
pSprite = nullptr;
return olc::rcode::NO_FILE;
}
}
olc::Decal* Renderable::Decal() const
{
return pDecal.get();
}
olc::Sprite* Renderable::Sprite() const
{
return pSprite.get();
}
// O------------------------------------------------------------------------------O
// | olc::ResourcePack IMPLEMENTATION |
// O------------------------------------------------------------------------------O
//=============================================================
// Resource Packs - Allows you to store files in one large
// scrambled file - Thanks MaGetzUb for debugging a null char in std::stringstream bug
ResourceBuffer::ResourceBuffer(std::ifstream& ifs, uint32_t offset, uint32_t size)
{
vMemory.resize(size);
ifs.seekg(offset); ifs.read(vMemory.data(), vMemory.size());
setg(vMemory.data(), vMemory.data(), vMemory.data() + size);
}
ResourcePack::ResourcePack() { }
ResourcePack::~ResourcePack() { baseFile.close(); }
bool ResourcePack::AddFile(const std::string& sFile)
{
const std::string file = makeposix(sFile);
if (_gfs::exists(file))
{
sResourceFile e;
e.nSize = (uint32_t)_gfs::file_size(file);
e.nOffset = 0; // Unknown at this stage
mapFiles[file] = e;
return true;
}
return false;
}
bool ResourcePack::LoadPack(const std::string& sFile, const std::string& sKey)
{
// Open the resource file
baseFile.open(sFile, std::ifstream::binary);
if (!baseFile.is_open()) return false;
// 1) Read Scrambled index
uint32_t nIndexSize = 0;
baseFile.read((char*)&nIndexSize, sizeof(uint32_t));
std::vector<char> buffer(nIndexSize);
for (uint32_t j = 0; j < nIndexSize; j++)
buffer[j] = baseFile.get();
std::vector<char> decoded = scramble(buffer, sKey);
size_t pos = 0;
auto read = [&decoded, &pos](char* dst, size_t size) {
memcpy((void*)dst, (const void*)(decoded.data() + pos), size);
pos += size;
};
auto get = [&read]() -> int {
char c;
read(&c, 1);
return c;
};
// 2) Read Map
uint32_t nMapEntries = 0;
read((char*)&nMapEntries, sizeof(uint32_t));
for (uint32_t i = 0; i < nMapEntries; i++)
{
uint32_t nFilePathSize = 0;
read((char*)&nFilePathSize, sizeof(uint32_t));
std::string sFileName(nFilePathSize, ' ');
for (uint32_t j = 0; j < nFilePathSize; j++)
sFileName[j] = get();
sResourceFile e;
read((char*)&e.nSize, sizeof(uint32_t));
read((char*)&e.nOffset, sizeof(uint32_t));
mapFiles[sFileName] = e;
}
// Don't close base file! we will provide a stream
// pointer when the file is requested
return true;
}
bool ResourcePack::SavePack(const std::string& sFile, const std::string& sKey)
{
// Create/Overwrite the resource file
std::ofstream ofs(sFile, std::ofstream::binary);
if (!ofs.is_open()) return false;
// Iterate through map
uint32_t nIndexSize = 0; // Unknown for now
ofs.write((char*)&nIndexSize, sizeof(uint32_t));
uint32_t nMapSize = uint32_t(mapFiles.size());
ofs.write((char*)&nMapSize, sizeof(uint32_t));
for (auto& e : mapFiles)
{
// Write the path of the file
size_t nPathSize = e.first.size();
ofs.write((char*)&nPathSize, sizeof(uint32_t));
ofs.write(e.first.c_str(), nPathSize);
// Write the file entry properties
ofs.write((char*)&e.second.nSize, sizeof(uint32_t));
ofs.write((char*)&e.second.nOffset, sizeof(uint32_t));
}
// 2) Write the individual Data
std::streampos offset = ofs.tellp();
nIndexSize = (uint32_t)offset;
for (auto& e : mapFiles)
{
// Store beginning of file offset within resource pack file
e.second.nOffset = (uint32_t)offset;
// Load the file to be added
std::vector<uint8_t> vBuffer(e.second.nSize);
std::ifstream i(e.first, std::ifstream::binary);
i.read((char*)vBuffer.data(), e.second.nSize);
i.close();
// Write the loaded file into resource pack file
ofs.write((char*)vBuffer.data(), e.second.nSize);
offset += e.second.nSize;
}
// 3) Scramble Index
std::vector<char> stream;
auto write = [&stream](const char* data, size_t size) {
size_t sizeNow = stream.size();
stream.resize(sizeNow + size);
memcpy(stream.data() + sizeNow, data, size);
};
// Iterate through map
write((char*)&nMapSize, sizeof(uint32_t));
for (auto& e : mapFiles)
{
// Write the path of the file
size_t nPathSize = e.first.size();
write((char*)&nPathSize, sizeof(uint32_t));
write(e.first.c_str(), nPathSize);
// Write the file entry properties
write((char*)&e.second.nSize, sizeof(uint32_t));
write((char*)&e.second.nOffset, sizeof(uint32_t));
}
std::vector<char> sIndexString = scramble(stream, sKey);
uint32_t nIndexStringLen = uint32_t(sIndexString.size());
// 4) Rewrite Map (it has been updated with offsets now)
// at start of file
ofs.seekp(0, std::ios::beg);
ofs.write((char*)&nIndexStringLen, sizeof(uint32_t));
ofs.write(sIndexString.data(), nIndexStringLen);
ofs.close();
return true;
}
ResourceBuffer ResourcePack::GetFileBuffer(const std::string& sFile)
{
return ResourceBuffer(baseFile, mapFiles[sFile].nOffset, mapFiles[sFile].nSize);
}
bool ResourcePack::Loaded()
{
return baseFile.is_open();
}
std::vector<char> ResourcePack::scramble(const std::vector<char>& data, const std::string& key)
{
if (key.empty()) return data;
std::vector<char> o;
size_t c = 0;
for (auto s : data) o.push_back(s ^ key[(c++) % key.size()]);
return o;
};
std::string ResourcePack::makeposix(const std::string& path)
{
std::string o;
for (auto s : path) o += std::string(1, s == '\\' ? '/' : s);
return o;
};
// O------------------------------------------------------------------------------O
// | olc::PixelGameEngine IMPLEMENTATION |
// O------------------------------------------------------------------------------O
PixelGameEngine::PixelGameEngine()
{
sAppName = "Undefined";
olc::PGEX::pge = this;
// Bring in relevant Platform & Rendering systems depending
// on compiler parameters
olc_ConfigureSystem();
}
PixelGameEngine::~PixelGameEngine()
{}
olc::rcode PixelGameEngine::Construct(int32_t screen_w, int32_t screen_h, int32_t pixel_w, int32_t pixel_h, bool full_screen, bool vsync)
{
vScreenSize = { screen_w, screen_h };
vInvScreenSize = { 1.0f / float(screen_w), 1.0f / float(screen_h) };
vPixelSize = { pixel_w, pixel_h };
vWindowSize = vScreenSize * vPixelSize;
bFullScreen = full_screen;
bEnableVSYNC = vsync;
vPixel = 2.0f / vScreenSize;
if (vPixelSize.x <= 0 || vPixelSize.y <= 0 || vScreenSize.x <= 0 || vScreenSize.y <= 0)
return olc::FAIL;
return olc::OK;
}
void PixelGameEngine::SetScreenSize(int w, int h)
{
vScreenSize = { w, h };
for (auto& layer : vLayers)
{
delete layer.pDrawTarget; // Erase existing layer sprites
layer.pDrawTarget = new Sprite(vScreenSize.x, vScreenSize.y);
layer.bUpdate = true;
}
SetDrawTarget(nullptr);
renderer->ClearBuffer(olc::BLACK, true);
renderer->DisplayFrame();
renderer->ClearBuffer(olc::BLACK, true);
renderer->UpdateViewport(vViewPos, vViewSize);
}
#if !defined(PGE_USE_CUSTOM_START)
olc::rcode PixelGameEngine::Start()
{
if (platform->ApplicationStartUp() != olc::OK) return olc::FAIL;
// Construct the window
if (platform->CreateWindowPane({ 30,30 }, vWindowSize, bFullScreen) != olc::OK) return olc::FAIL;
olc_UpdateWindowSize(vWindowSize.x, vWindowSize.y);
// Start the thread
bAtomActive = true;
std::thread t = std::thread(&PixelGameEngine::EngineThread, this);
// Some implementations may form an event loop here
platform->StartSystemEventLoop();
// Wait for thread to be exited
t.join();
if (platform->ApplicationCleanUp() != olc::OK) return olc::FAIL;
return olc::OK;
}
#endif
void PixelGameEngine::SetDrawTarget(Sprite* target)
{
if (target)
{
pDrawTarget = target;
}
else
{
nTargetLayer = 0;
pDrawTarget = vLayers[0].pDrawTarget;
}
}
void PixelGameEngine::SetDrawTarget(uint8_t layer)
{
if (layer < vLayers.size())
{
pDrawTarget = vLayers[layer].pDrawTarget;
vLayers[layer].bUpdate = true;
nTargetLayer = layer;
}
}
void PixelGameEngine::EnableLayer(uint8_t layer, bool b)
{
if (layer < vLayers.size()) vLayers[layer].bShow = b;
}
void PixelGameEngine::SetLayerOffset(uint8_t layer, const olc::vf2d& offset)
{
SetLayerOffset(layer, offset.x, offset.y);
}
void PixelGameEngine::SetLayerOffset(uint8_t layer, float x, float y)
{
if (layer < vLayers.size()) vLayers[layer].vOffset = { x, y };
}
void PixelGameEngine::SetLayerScale(uint8_t layer, const olc::vf2d& scale)
{
SetLayerScale(layer, scale.x, scale.y);
}
void PixelGameEngine::SetLayerScale(uint8_t layer, float x, float y)
{
if (layer < vLayers.size()) vLayers[layer].vScale = { x, y };
}
void PixelGameEngine::SetLayerTint(uint8_t layer, const olc::Pixel& tint)
{
if (layer < vLayers.size()) vLayers[layer].tint = tint;
}
void PixelGameEngine::SetLayerCustomRenderFunction(uint8_t layer, std::function<void()> f)
{
if (layer < vLayers.size()) vLayers[layer].funcHook = f;
}
std::vector<LayerDesc>& PixelGameEngine::GetLayers()
{
return vLayers;
}
uint32_t PixelGameEngine::CreateLayer()
{
LayerDesc ld;
ld.pDrawTarget = new olc::Sprite(vScreenSize.x, vScreenSize.y);
ld.nResID = renderer->CreateTexture(vScreenSize.x, vScreenSize.y);
renderer->UpdateTexture(ld.nResID, ld.pDrawTarget);
vLayers.push_back(ld);
return uint32_t(vLayers.size()) - 1;
}
Sprite* PixelGameEngine::GetDrawTarget()
{
return pDrawTarget;
}
int32_t PixelGameEngine::GetDrawTargetWidth()
{
if (pDrawTarget)
return pDrawTarget->width;
else
return 0;
}
int32_t PixelGameEngine::GetDrawTargetHeight()
{
if (pDrawTarget)
return pDrawTarget->height;
else
return 0;
}
uint32_t PixelGameEngine::GetFPS()
{
return nLastFPS;
}
bool PixelGameEngine::IsFocused()
{
return bHasInputFocus;
}
HWButton PixelGameEngine::GetKey(Key k)
{
return pKeyboardState[k];
}
HWButton PixelGameEngine::GetMouse(uint32_t b)
{
return pMouseState[b];
}
int32_t PixelGameEngine::GetMouseX()
{
return vMousePos.x;
}
int32_t PixelGameEngine::GetMouseY()
{
return vMousePos.y;
}
int32_t PixelGameEngine::GetMouseWheel()
{
return nMouseWheelDelta;
}
int32_t PixelGameEngine::ScreenWidth()
{
return vScreenSize.x;
}
int32_t PixelGameEngine::ScreenHeight()
{
return vScreenSize.y;
}
const float PixelGameEngine::GetElapsedTime() const
{
return fLastElapsed;
}
const olc::vi2d& PixelGameEngine::GetWindowSize() const
{
return vWindowSize;
}
const olc::vi2d& PixelGameEngine::GetWindowMouse() const
{
return vMouseWindowPos;
}
bool PixelGameEngine::Draw(const olc::vi2d& pos, Pixel p)
{
return Draw(pos.x, pos.y, p);
}
// This is it, the critical function that plots a pixel
bool PixelGameEngine::Draw(int32_t x, int32_t y, Pixel p)
{
if (!pDrawTarget) return false;
if (nPixelMode == Pixel::NORMAL)
{
return pDrawTarget->SetPixel(x, y, p);
}
if (nPixelMode == Pixel::MASK)
{
if (p.a == 255)
return pDrawTarget->SetPixel(x, y, p);
}
if (nPixelMode == Pixel::ALPHA)
{
Pixel d = pDrawTarget->GetPixel(x, y);
float a = (float)(p.a / 255.0f) * fBlendFactor;
float c = 1.0f - a;
float r = a * (float)p.r + c * (float)d.r;
float g = a * (float)p.g + c * (float)d.g;
float b = a * (float)p.b + c * (float)d.b;
return pDrawTarget->SetPixel(x, y, Pixel((uint8_t)r, (uint8_t)g, (uint8_t)b/*, (uint8_t)(p.a * fBlendFactor)*/));
}
if (nPixelMode == Pixel::CUSTOM)
{
return pDrawTarget->SetPixel(x, y, funcPixelMode(x, y, p, pDrawTarget->GetPixel(x, y)));
}
return false;
}
void PixelGameEngine::SetSubPixelOffset(float ox, float oy)
{
//vSubPixelOffset.x = ox * vPixel.x;
//vSubPixelOffset.y = oy * vPixel.y;
}
void PixelGameEngine::DrawLine(const olc::vi2d& pos1, const olc::vi2d& pos2, Pixel p, uint32_t pattern)
{
DrawLine(pos1.x, pos1.y, pos2.x, pos2.y, p, pattern);
}
void PixelGameEngine::DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p, uint32_t pattern)
{
int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i;
dx = x2 - x1; dy = y2 - y1;
auto rol = [&](void) { pattern = (pattern << 1) | (pattern >> 31); return pattern & 1; };
// straight lines idea by gurkanctn
if (dx == 0) // Line is vertical
{
if (y2 < y1) std::swap(y1, y2);
for (y = y1; y <= y2; y++) if (rol()) Draw(x1, y, p);
return;
}
if (dy == 0) // Line is horizontal
{
if (x2 < x1) std::swap(x1, x2);
for (x = x1; x <= x2; x++) if (rol()) Draw(x, y1, p);
return;
}
// Line is Funk-aye
dx1 = abs(dx); dy1 = abs(dy);
px = 2 * dy1 - dx1; py = 2 * dx1 - dy1;
if (dy1 <= dx1)
{
if (dx >= 0)
{
x = x1; y = y1; xe = x2;
}
else
{
x = x2; y = y2; xe = x1;
}
if (rol()) Draw(x, y, p);
for (i = 0; x < xe; i++)
{
x = x + 1;
if (px < 0)
px = px + 2 * dy1;
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) y = y + 1; else y = y - 1;
px = px + 2 * (dy1 - dx1);
}
if (rol()) Draw(x, y, p);
}
}
else
{
if (dy >= 0)
{
x = x1; y = y1; ye = y2;
}
else
{
x = x2; y = y2; ye = y1;
}
if (rol()) Draw(x, y, p);
for (i = 0; y < ye; i++)
{
y = y + 1;
if (py <= 0)
py = py + 2 * dx1;
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) x = x + 1; else x = x - 1;
py = py + 2 * (dx1 - dy1);
}
if (rol()) Draw(x, y, p);
}
}
}
void PixelGameEngine::DrawCircle(const olc::vi2d& pos, int32_t radius, Pixel p, uint8_t mask)
{
DrawCircle(pos.x, pos.y, radius, p, mask);
}
void PixelGameEngine::DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p, uint8_t mask)
{ // Thanks to IanM-Matrix1 #PR121
if (radius < 0 || x < -radius || y < -radius || x - GetDrawTargetWidth() > radius || y - GetDrawTargetHeight() > radius)
return;
if (radius > 0)
{
int x0 = 0;
int y0 = radius;
int d = 3 - 2 * radius;
while (y0 >= x0) // only formulate 1/8 of circle
{
// Draw even octants
if (mask & 0x01) Draw(x + x0, y - y0, p);// Q6 - upper right right
if (mask & 0x04) Draw(x + y0, y + x0, p);// Q4 - lower lower right
if (mask & 0x10) Draw(x - x0, y + y0, p);// Q2 - lower left left
if (mask & 0x40) Draw(x - y0, y - x0, p);// Q0 - upper upper left
if (x0 != 0 && x0 != y0)
{
if (mask & 0x02) Draw(x + y0, y - x0, p);// Q7 - upper upper right
if (mask & 0x08) Draw(x + x0, y + y0, p);// Q5 - lower right right
if (mask & 0x20) Draw(x - y0, y + x0, p);// Q3 - lower lower left
if (mask & 0x80) Draw(x - x0, y - y0, p);// Q1 - upper left left
}
if (d < 0)
d += 4 * x0++ + 6;
else
d += 4 * (x0++ - y0--) + 10;
}
}
else
Draw(x, y, p);
}
void PixelGameEngine::FillCircle(const olc::vi2d& pos, int32_t radius, Pixel p)
{
FillCircle(pos.x, pos.y, radius, p);
}
void PixelGameEngine::FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p)
{ // Thanks to IanM-Matrix1 #PR121
if (radius < 0 || x < -radius || y < -radius || x - GetDrawTargetWidth() > radius || y - GetDrawTargetHeight() > radius)
return;
if (radius > 0)
{
int x0 = 0;
int y0 = radius;
int d = 3 - 2 * radius;
auto drawline = [&](int sx, int ex, int y)
{
for (int x = sx; x <= ex; x++)
Draw(x, y, p);
};
while (y0 >= x0)
{
drawline(x - y0, x + y0, y - x0);
if (x0 > 0) drawline(x - y0, x + y0, y + x0);
if (d < 0)
d += 4 * x0++ + 6;
else
{
if (x0 != y0)
{
drawline(x - x0, x + x0, y - y0);
drawline(x - x0, x + x0, y + y0);
}
d += 4 * (x0++ - y0--) + 10;
}
}
}
else
Draw(x, y, p);
}
void PixelGameEngine::DrawRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p)
{
DrawRect(pos.x, pos.y, size.x, size.y, p);
}
void PixelGameEngine::DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p)
{
DrawLine(x, y, x + w, y, p);
DrawLine(x + w, y, x + w, y + h, p);
DrawLine(x + w, y + h, x, y + h, p);
DrawLine(x, y + h, x, y, p);
}
void PixelGameEngine::Clear(Pixel p)
{
int pixels = GetDrawTargetWidth() * GetDrawTargetHeight();
Pixel* m = GetDrawTarget()->GetData();
for (int i = 0; i < pixels; i++) m[i] = p;
}
void PixelGameEngine::ClearBuffer(Pixel p, bool bDepth)
{
renderer->ClearBuffer(p, bDepth);
}
void PixelGameEngine::FillRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p)
{
FillRect(pos.x, pos.y, size.x, size.y, p);
}
void PixelGameEngine::FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p)
{
int32_t x2 = x + w;
int32_t y2 = y + h;
if (x < 0) x = 0;
if (x >= (int32_t)GetDrawTargetWidth()) x = (int32_t)GetDrawTargetWidth();
if (y < 0) y = 0;
if (y >= (int32_t)GetDrawTargetHeight()) y = (int32_t)GetDrawTargetHeight();
if (x2 < 0) x2 = 0;
if (x2 >= (int32_t)GetDrawTargetWidth()) x2 = (int32_t)GetDrawTargetWidth();
if (y2 < 0) y2 = 0;
if (y2 >= (int32_t)GetDrawTargetHeight()) y2 = (int32_t)GetDrawTargetHeight();
for (int i = x; i < x2; i++)
for (int j = y; j < y2; j++)
Draw(i, j, p);
}
void PixelGameEngine::DrawTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p)
{
DrawTriangle(pos1.x, pos1.y, pos2.x, pos2.y, pos3.x, pos3.y, p);
}
void PixelGameEngine::DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p)
{
DrawLine(x1, y1, x2, y2, p);
DrawLine(x2, y2, x3, y3, p);
DrawLine(x3, y3, x1, y1, p);
}
void PixelGameEngine::FillTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p)
{
FillTriangle(pos1.x, pos1.y, pos2.x, pos2.y, pos3.x, pos3.y, p);
}
// https://www.avrfreaks.net/sites/default/files/triangles.c
void PixelGameEngine::FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p)
{
auto drawline = [&](int sx, int ex, int ny) { for (int i = sx; i <= ex; i++) Draw(i, ny, p); };
int t1x, t2x, y, minx, maxx, t1xp, t2xp;
bool changed1 = false;
bool changed2 = false;
int signx1, signx2, dx1, dy1, dx2, dy2;
int e1, e2;
// Sort vertices
if (y1 > y2) { std::swap(y1, y2); std::swap(x1, x2); }
if (y1 > y3) { std::swap(y1, y3); std::swap(x1, x3); }
if (y2 > y3) { std::swap(y2, y3); std::swap(x2, x3); }
t1x = t2x = x1; y = y1; // Starting points
dx1 = (int)(x2 - x1);
if (dx1 < 0) { dx1 = -dx1; signx1 = -1; }
else signx1 = 1;
dy1 = (int)(y2 - y1);
dx2 = (int)(x3 - x1);
if (dx2 < 0) { dx2 = -dx2; signx2 = -1; }
else signx2 = 1;
dy2 = (int)(y3 - y1);
if (dy1 > dx1) { std::swap(dx1, dy1); changed1 = true; }
if (dy2 > dx2) { std::swap(dy2, dx2); changed2 = true; }
e2 = (int)(dx2 >> 1);
// Flat top, just process the second half
if (y1 == y2) goto next;
e1 = (int)(dx1 >> 1);
for (int i = 0; i < dx1;) {
t1xp = 0; t2xp = 0;
if (t1x < t2x) { minx = t1x; maxx = t2x; }
else { minx = t2x; maxx = t1x; }
// process first line until y value is about to change
while (i < dx1) {
i++;
e1 += dy1;
while (e1 >= dx1) {
e1 -= dx1;
if (changed1) t1xp = signx1;//t1x += signx1;
else goto next1;
}
if (changed1) break;
else t1x += signx1;
}
// Move line
next1:
// process second line until y value is about to change
while (1) {
e2 += dy2;
while (e2 >= dx2) {
e2 -= dx2;
if (changed2) t2xp = signx2;//t2x += signx2;
else goto next2;
}
if (changed2) break;
else t2x += signx2;
}
next2:
if (minx > t1x) minx = t1x;
if (minx > t2x) minx = t2x;
if (maxx < t1x) maxx = t1x;
if (maxx < t2x) maxx = t2x;
drawline(minx, maxx, y); // Draw line from min to max points found on the y
// Now increase y
if (!changed1) t1x += signx1;
t1x += t1xp;
if (!changed2) t2x += signx2;
t2x += t2xp;
y += 1;
if (y == y2) break;
}
next:
// Second half
dx1 = (int)(x3 - x2); if (dx1 < 0) { dx1 = -dx1; signx1 = -1; }
else signx1 = 1;
dy1 = (int)(y3 - y2);
t1x = x2;
if (dy1 > dx1) { // swap values
std::swap(dy1, dx1);
changed1 = true;
}
else changed1 = false;
e1 = (int)(dx1 >> 1);
for (int i = 0; i <= dx1; i++) {
t1xp = 0; t2xp = 0;
if (t1x < t2x) { minx = t1x; maxx = t2x; }
else { minx = t2x; maxx = t1x; }
// process first line until y value is about to change
while (i < dx1) {
e1 += dy1;
while (e1 >= dx1) {
e1 -= dx1;
if (changed1) { t1xp = signx1; break; }//t1x += signx1;
else goto next3;
}
if (changed1) break;
else t1x += signx1;
if (i < dx1) i++;
}
next3:
// process second line until y value is about to change
while (t2x != x3) {
e2 += dy2;
while (e2 >= dx2) {
e2 -= dx2;
if (changed2) t2xp = signx2;
else goto next4;
}
if (changed2) break;
else t2x += signx2;
}
next4:
if (minx > t1x) minx = t1x;
if (minx > t2x) minx = t2x;
if (maxx < t1x) maxx = t1x;
if (maxx < t2x) maxx = t2x;
drawline(minx, maxx, y);
if (!changed1) t1x += signx1;
t1x += t1xp;
if (!changed2) t2x += signx2;
t2x += t2xp;
y += 1;
if (y > y3) return;
}
}
void PixelGameEngine::DrawSprite(const olc::vi2d& pos, Sprite* sprite, uint32_t scale, uint8_t flip)
{
DrawSprite(pos.x, pos.y, sprite, scale, flip);
}
void PixelGameEngine::DrawSprite(int32_t x, int32_t y, Sprite* sprite, uint32_t scale, uint8_t flip)
{
if (sprite == nullptr)
return;
int32_t fxs = 0, fxm = 1, fx = 0;
int32_t fys = 0, fym = 1, fy = 0;
if (flip & olc::Sprite::Flip::HORIZ) { fxs = sprite->width - 1; fxm = -1; }
if (flip & olc::Sprite::Flip::VERT) { fys = sprite->height - 1; fym = -1; }
if (scale > 1)
{
fx = fxs;
for (int32_t i = 0; i < sprite->width; i++, fx += fxm)
{
fy = fys;
for (int32_t j = 0; j < sprite->height; j++, fy += fym)
for (uint32_t is = 0; is < scale; is++)
for (uint32_t js = 0; js < scale; js++)
Draw(x + (i * scale) + is, y + (j * scale) + js, sprite->GetPixel(fx, fy));
}
}
else
{
fx = fxs;
for (int32_t i = 0; i < sprite->width; i++, fx += fxm)
{
fy = fys;
for (int32_t j = 0; j < sprite->height; j++, fy += fym)
Draw(x + i, y + j, sprite->GetPixel(fx, fy));
}
}
}
void PixelGameEngine::DrawPartialSprite(const olc::vi2d& pos, Sprite* sprite, const olc::vi2d& sourcepos, const olc::vi2d& size, uint32_t scale, uint8_t flip)
{
DrawPartialSprite(pos.x, pos.y, sprite, sourcepos.x, sourcepos.y, size.x, size.y, scale, flip);
}
void PixelGameEngine::DrawPartialSprite(int32_t x, int32_t y, Sprite* sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale, uint8_t flip)
{
if (sprite == nullptr)
return;
int32_t fxs = 0, fxm = 1, fx = 0;
int32_t fys = 0, fym = 1, fy = 0;
if (flip & olc::Sprite::Flip::HORIZ) { fxs = w - 1; fxm = -1; }
if (flip & olc::Sprite::Flip::VERT) { fys = h - 1; fym = -1; }
if (scale > 1)
{
fx = fxs;
for (int32_t i = 0; i < w; i++, fx += fxm)
{
fy = fys;
for (int32_t j = 0; j < h; j++, fy += fym)
for (uint32_t is = 0; is < scale; is++)
for (uint32_t js = 0; js < scale; js++)
Draw(x + (i * scale) + is, y + (j * scale) + js, sprite->GetPixel(fx + ox, fy + oy));
}
}
else
{
fx = fxs;
for (int32_t i = 0; i < w; i++, fx += fxm)
{
fy = fys;
for (int32_t j = 0; j < h; j++, fy += fym)
Draw(x + i, y + j, sprite->GetPixel(fx + ox, fy + oy));
}
}
}
void PixelGameEngine::DrawPartialDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale, const olc::Pixel& tint)
{
olc::vf2d vScreenSpacePos =
{
(pos.x * vInvScreenSize.x) * 2.0f - 1.0f,
((pos.y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f
};
olc::vf2d vScreenSpaceDim =
{
vScreenSpacePos.x + (2.0f * source_size.x * vInvScreenSize.x) * scale.x,
vScreenSpacePos.y - (2.0f * source_size.y * vInvScreenSize.y) * scale.y
};
DecalInstance di; di.decal = decal; di.tint[0] = tint;
di.pos[0] = { vScreenSpacePos.x, vScreenSpacePos.y };
di.pos[1] = { vScreenSpacePos.x, vScreenSpaceDim.y };
di.pos[2] = { vScreenSpaceDim.x, vScreenSpaceDim.y };
di.pos[3] = { vScreenSpaceDim.x, vScreenSpacePos.y };
olc::vf2d uvtl = source_pos * decal->vUVScale;
olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale);
di.uv[0] = { uvtl.x, uvtl.y }; di.uv[1] = { uvtl.x, uvbr.y };
di.uv[2] = { uvbr.x, uvbr.y }; di.uv[3] = { uvbr.x, uvtl.y };
vLayers[nTargetLayer].vecDecalInstance.push_back(di);
}
void PixelGameEngine::DrawPartialDecal(const olc::vf2d& pos, const olc::vf2d& size, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint)
{
olc::vf2d vScreenSpacePos =
{
(pos.x * vInvScreenSize.x) * 2.0f - 1.0f,
((pos.y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f
};
olc::vf2d vScreenSpaceDim =
{
vScreenSpacePos.x + (2.0f * size.x * vInvScreenSize.x),
vScreenSpacePos.y - (2.0f * size.y * vInvScreenSize.y)
};
DecalInstance di; di.decal = decal; di.tint[0] = tint;
di.pos[0] = { vScreenSpacePos.x, vScreenSpacePos.y };
di.pos[1] = { vScreenSpacePos.x, vScreenSpaceDim.y };
di.pos[2] = { vScreenSpaceDim.x, vScreenSpaceDim.y };
di.pos[3] = { vScreenSpaceDim.x, vScreenSpacePos.y };
olc::vf2d uvtl = source_pos * decal->vUVScale;
olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale);
di.uv[0] = { uvtl.x, uvtl.y }; di.uv[1] = { uvtl.x, uvbr.y };
di.uv[2] = { uvbr.x, uvbr.y }; di.uv[3] = { uvbr.x, uvtl.y };
vLayers[nTargetLayer].vecDecalInstance.push_back(di);
}
void PixelGameEngine::DrawDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& scale, const olc::Pixel& tint)
{
olc::vf2d vScreenSpacePos =
{
(pos.x * vInvScreenSize.x) * 2.0f - 1.0f,
((pos.y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f
};
olc::vf2d vScreenSpaceDim =
{
vScreenSpacePos.x + (2.0f * (float(decal->sprite->width) * vInvScreenSize.x)) * scale.x,
vScreenSpacePos.y - (2.0f * (float(decal->sprite->height) * vInvScreenSize.y)) * scale.y
};
DecalInstance di;
di.decal = decal;
di.tint[0] = tint;
di.pos[0] = { vScreenSpacePos.x, vScreenSpacePos.y };
di.pos[1] = { vScreenSpacePos.x, vScreenSpaceDim.y };
di.pos[2] = { vScreenSpaceDim.x, vScreenSpaceDim.y };
di.pos[3] = { vScreenSpaceDim.x, vScreenSpacePos.y };
vLayers[nTargetLayer].vecDecalInstance.push_back(di);
}
void PixelGameEngine::DrawRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center, const olc::vf2d& scale, const olc::Pixel& tint)
{
DecalInstance di;
di.decal = decal;
di.tint[0] = tint;
di.pos[0] = (olc::vf2d(0.0f, 0.0f) - center) * scale;
di.pos[1] = (olc::vf2d(0.0f, float(decal->sprite->height)) - center) * scale;
di.pos[2] = (olc::vf2d(float(decal->sprite->width), float(decal->sprite->height)) - center) * scale;
di.pos[3] = (olc::vf2d(float(decal->sprite->width), 0.0f) - center) * scale;
float c = cos(fAngle), s = sin(fAngle);
for (int i = 0; i < 4; i++)
{
di.pos[i] = pos + olc::vf2d(di.pos[i].x * c - di.pos[i].y * s, di.pos[i].x * s + di.pos[i].y * c);
di.pos[i] = di.pos[i] * vInvScreenSize * 2.0f - olc::vf2d(1.0f, 1.0f);
di.pos[i].y *= -1.0f;
}
vLayers[nTargetLayer].vecDecalInstance.push_back(di);
}
void PixelGameEngine::DrawExplicitDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d* uv, const olc::Pixel* col)
{
DecalInstance di;
for (int i = 0; i < 4; i++)
{
di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f };
di.uv[i] = uv[i];
di.tint[i] = col[i];
}
vLayers[nTargetLayer].vecDecalInstance.push_back(di);
}
void PixelGameEngine::FillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel col)
{
std::array<olc::vf2d, 4> points = { { {pos}, {pos.x, pos.y + size.y}, {pos + size}, {pos.x + size.x, pos.y} } };
std::array<olc::vf2d, 4> uvs = { {{0,0},{0,0},{0,0},{0,0}} };
std::array<olc::Pixel, 4> cols = { {col, col, col, col} };
DrawExplicitDecal(nullptr, points.data(), uvs.data(), cols.data());
}
void PixelGameEngine::GradientFillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel colTL, const olc::Pixel colBL, const olc::Pixel colBR, const olc::Pixel colTR)
{
std::array<olc::vf2d, 4> points = { { {pos}, {pos.x, pos.y + size.y}, {pos + size}, {pos.x + size.x, pos.y} } };
std::array<olc::vf2d, 4> uvs = { {{0,0},{0,0},{0,0},{0,0}} };
std::array<olc::Pixel, 4> cols = { {colTL, colBL, colBR, colTR} };
DrawExplicitDecal(nullptr, points.data(), uvs.data(), cols.data());
}
void PixelGameEngine::DrawPartialRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale, const olc::Pixel& tint)
{
DecalInstance di;
di.decal = decal;
di.tint[0] = tint;
di.pos[0] = (olc::vf2d(0.0f, 0.0f) - center) * scale;
di.pos[1] = (olc::vf2d(0.0f, source_size.y) - center) * scale;
di.pos[2] = (olc::vf2d(source_size.x, source_size.y) - center) * scale;
di.pos[3] = (olc::vf2d(source_size.x, 0.0f) - center) * scale;
float c = cos(fAngle), s = sin(fAngle);
for (int i = 0; i < 4; i++)
{
di.pos[i] = pos + olc::vf2d(di.pos[i].x * c - di.pos[i].y * s, di.pos[i].x * s + di.pos[i].y * c);
di.pos[i] = di.pos[i] * vInvScreenSize * 2.0f - olc::vf2d(1.0f, 1.0f);
di.pos[i].y *= -1.0f;
}
olc::vf2d uvtl = source_pos * decal->vUVScale;
olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale);
di.uv[0] = { uvtl.x, uvtl.y }; di.uv[1] = { uvtl.x, uvbr.y };
di.uv[2] = { uvbr.x, uvbr.y }; di.uv[3] = { uvbr.x, uvtl.y };
vLayers[nTargetLayer].vecDecalInstance.push_back(di);
}
void PixelGameEngine::DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint)
{
DecalInstance di;
di.decal = decal;
di.tint[0] = tint;
olc::vf2d center;
float rd = ((pos[2].x - pos[0].x) * (pos[3].y - pos[1].y) - (pos[3].x - pos[1].x) * (pos[2].y - pos[0].y));
if (rd != 0)
{
olc::vf2d uvtl = source_pos * decal->vUVScale;
olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale);
di.uv[0] = { uvtl.x, uvtl.y }; di.uv[1] = { uvtl.x, uvbr.y };
di.uv[2] = { uvbr.x, uvbr.y }; di.uv[3] = { uvbr.x, uvtl.y };
rd = 1.0f / rd;
float rn = ((pos[3].x - pos[1].x) * (pos[0].y - pos[1].y) - (pos[3].y - pos[1].y) * (pos[0].x - pos[1].x)) * rd;
float sn = ((pos[2].x - pos[0].x) * (pos[0].y - pos[1].y) - (pos[2].y - pos[0].y) * (pos[0].x - pos[1].x)) * rd;
if (!(rn < 0.f || rn > 1.f || sn < 0.f || sn > 1.f)) center = pos[0] + rn * (pos[2] - pos[0]);
float d[4]; for (int i = 0; i < 4; i++) d[i] = (pos[i] - center).mag();
for (int i = 0; i < 4; i++)
{
float q = d[i] == 0.0f ? 1.0f : (d[i] + d[(i + 2) & 3]) / d[(i + 2) & 3];
di.uv[i] *= q; di.w[i] *= q;
di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f };
}
vLayers[nTargetLayer].vecDecalInstance.push_back(di);
}
}
void PixelGameEngine::DrawWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::Pixel& tint)
{
// Thanks Nathan Reed, a brilliant article explaining whats going on here
// http://www.reedbeta.com/blog/quadrilateral-interpolation-part-1/
DecalInstance di;
di.decal = decal;
di.tint[0] = tint;
olc::vf2d center;
float rd = ((pos[2].x - pos[0].x) * (pos[3].y - pos[1].y) - (pos[3].x - pos[1].x) * (pos[2].y - pos[0].y));
if (rd != 0)
{
rd = 1.0f / rd;
float rn = ((pos[3].x - pos[1].x) * (pos[0].y - pos[1].y) - (pos[3].y - pos[1].y) * (pos[0].x - pos[1].x)) * rd;
float sn = ((pos[2].x - pos[0].x) * (pos[0].y - pos[1].y) - (pos[2].y - pos[0].y) * (pos[0].x - pos[1].x)) * rd;
if (!(rn < 0.f || rn > 1.f || sn < 0.f || sn > 1.f)) center = pos[0] + rn * (pos[2] - pos[0]);
float d[4]; for (int i = 0; i < 4; i++) d[i] = (pos[i] - center).mag();
for (int i = 0; i < 4; i++)
{
float q = d[i] == 0.0f ? 1.0f : (d[i] + d[(i + 2) & 3]) / d[(i + 2) & 3];
di.uv[i] *= q; di.w[i] *= q;
di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f };
}
vLayers[nTargetLayer].vecDecalInstance.push_back(di);
}
}
void PixelGameEngine::DrawWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::Pixel& tint)
{
DrawWarpedDecal(decal, pos.data(), tint);
}
void PixelGameEngine::DrawWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::Pixel& tint)
{
DrawWarpedDecal(decal, &pos[0], tint);
}
void PixelGameEngine::DrawPartialWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint)
{
DrawPartialWarpedDecal(decal, pos.data(), source_pos, source_size, tint);
}
void PixelGameEngine::DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint)
{
DrawPartialWarpedDecal(decal, &pos[0], source_pos, source_size, tint);
}
void PixelGameEngine::DrawStringDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col, const olc::vf2d& scale)
{
olc::vf2d spos = { 0.0f, 0.0f };
for (auto c : sText)
{
if (c == '\n')
{
spos.x = 0; spos.y += 8.0f * scale.y;
}
else
{
int32_t ox = (c - 32) % 16;
int32_t oy = (c - 32) / 16;
DrawPartialDecal(pos + spos, fontDecal, { float(ox) * 8.0f, float(oy) * 8.0f }, { 8.0f, 8.0f }, scale, col);
spos.x += 8.0f * scale.x;
}
}
}
olc::vi2d PixelGameEngine::GetTextSize(const std::string& s)
{
olc::vi2d size = { 0,1 };
olc::vi2d pos = { 0,1 };
for (auto c : s)
{
if (c == '\n') { pos.y++; pos.x = 0; }
else pos.x++;
size.x = std::max(size.x, pos.x);
size.y = std::max(size.y, pos.y);
}
return size * 8;
}
void PixelGameEngine::DrawString(const olc::vi2d& pos, const std::string& sText, Pixel col, uint32_t scale)
{
DrawString(pos.x, pos.y, sText, col, scale);
}
void PixelGameEngine::DrawString(int32_t x, int32_t y, const std::string& sText, Pixel col, uint32_t scale)
{
int32_t sx = 0;
int32_t sy = 0;
Pixel::Mode m = nPixelMode;
// Thanks @tucna, spotted bug with col.ALPHA :P
if (col.a != 255) SetPixelMode(Pixel::ALPHA);
else SetPixelMode(Pixel::MASK);
for (auto c : sText)
{
if (c == '\n')
{
sx = 0; sy += 8 * scale;
}
else
{
int32_t ox = (c - 32) % 16;
int32_t oy = (c - 32) / 16;
if (scale > 1)
{
for (uint32_t i = 0; i < 8; i++)
for (uint32_t j = 0; j < 8; j++)
if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0)
for (uint32_t is = 0; is < scale; is++)
for (uint32_t js = 0; js < scale; js++)
Draw(x + sx + (i * scale) + is, y + sy + (j * scale) + js, col);
}
else
{
for (uint32_t i = 0; i < 8; i++)
for (uint32_t j = 0; j < 8; j++)
if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0)
Draw(x + sx + i, y + sy + j, col);
}
sx += 8 * scale;
}
}
SetPixelMode(m);
}
void PixelGameEngine::SetPixelMode(Pixel::Mode m)
{
nPixelMode = m;
}
Pixel::Mode PixelGameEngine::GetPixelMode()
{
return nPixelMode;
}
void PixelGameEngine::SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> pixelMode)
{
funcPixelMode = pixelMode;
nPixelMode = Pixel::Mode::CUSTOM;
}
void PixelGameEngine::SetPixelBlend(float fBlend)
{
fBlendFactor = fBlend;
if (fBlendFactor < 0.0f) fBlendFactor = 0.0f;
if (fBlendFactor > 1.0f) fBlendFactor = 1.0f;
}
// User must override these functions as required. I have not made
// them abstract because I do need a default behaviour to occur if
// they are not overwritten
bool PixelGameEngine::OnUserCreate()
{
return false;
}
bool PixelGameEngine::OnUserUpdate(float fElapsedTime)
{
UNUSED(fElapsedTime); return false;
}
bool PixelGameEngine::OnUserDestroy()
{
return true;
}
//////////////////////////////////////////////////////////////////
void PixelGameEngine::olc_UpdateViewport()
{
int32_t ww = vScreenSize.x * vPixelSize.x;
int32_t wh = vScreenSize.y * vPixelSize.y;
float wasp = (float)ww / (float)wh;
vViewSize.x = (int32_t)vWindowSize.x;
vViewSize.y = (int32_t)((float)vViewSize.x / wasp);
if (vViewSize.y > vWindowSize.y)
{
vViewSize.y = vWindowSize.y;
vViewSize.x = (int32_t)((float)vViewSize.y * wasp);
}
vViewPos = (vWindowSize - vViewSize) / 2;
}
void PixelGameEngine::olc_UpdateWindowSize(int32_t x, int32_t y)
{
vWindowSize = { x, y };
olc_UpdateViewport();
}
void PixelGameEngine::olc_UpdateMouseWheel(int32_t delta)
{
nMouseWheelDeltaCache += delta;
}
void PixelGameEngine::olc_UpdateMouse(int32_t x, int32_t y)
{
// Mouse coords come in screen space
// But leave in pixel space
bHasMouseFocus = true;
vMouseWindowPos = { x, y };
// Full Screen mode may have a weird viewport we must clamp to
x -= vViewPos.x;
y -= vViewPos.y;
vMousePosCache.x = (int32_t)(((float)x / (float)(vWindowSize.x - (vViewPos.x * 2)) * (float)vScreenSize.x));
vMousePosCache.y = (int32_t)(((float)y / (float)(vWindowSize.y - (vViewPos.y * 2)) * (float)vScreenSize.y));
if (vMousePosCache.x >= (int32_t)vScreenSize.x) vMousePosCache.x = vScreenSize.x - 1;
if (vMousePosCache.y >= (int32_t)vScreenSize.y) vMousePosCache.y = vScreenSize.y - 1;
if (vMousePosCache.x < 0) vMousePosCache.x = 0;
if (vMousePosCache.y < 0) vMousePosCache.y = 0;
}
void PixelGameEngine::olc_UpdateMouseState(int32_t button, bool state)
{
pMouseNewState[button] = state;
}
void PixelGameEngine::olc_UpdateKeyState(int32_t key, bool state)
{
pKeyNewState[key] = state;
}
void PixelGameEngine::olc_UpdateMouseFocus(bool state)
{
bHasMouseFocus = state;
}
void PixelGameEngine::olc_UpdateKeyFocus(bool state)
{
bHasInputFocus = state;
}
void PixelGameEngine::olc_Terminate()
{
bAtomActive = false;
}
void PixelGameEngine::EngineThread()
{
// Allow platform to do stuff here if needed, since its now in the
// context of this thread
if (platform->ThreadStartUp() == olc::FAIL) return;
// Do engine context specific initialisation
olc_PrepareEngine();
// Create user resources as part of this thread
if (!OnUserCreate()) bAtomActive = false;
while (bAtomActive)
{
// Run as fast as possible
while (bAtomActive) { olc_CoreUpdate(); }
// Allow the user to free resources if they have overrided the destroy function
if (!OnUserDestroy())
{
// User denied destroy for some reason, so continue running
bAtomActive = true;
}
}
platform->ThreadCleanUp();
}
void PixelGameEngine::olc_PrepareEngine()
{
// Start OpenGL, the context is owned by the game thread
if (platform->CreateGraphics(bFullScreen, bEnableVSYNC, vViewPos, vViewSize) == olc::FAIL) return;
// Construct default font sheet
olc_ConstructFontSheet();
// Create Primary Layer "0"
CreateLayer();
vLayers[0].bUpdate = true;
vLayers[0].bShow = true;
SetDrawTarget(nullptr);
m_tp1 = std::chrono::system_clock::now();
m_tp2 = std::chrono::system_clock::now();
}
void PixelGameEngine::olc_CoreUpdate()
{
// Handle Timing
m_tp2 = std::chrono::system_clock::now();
std::chrono::duration<float> elapsedTime = m_tp2 - m_tp1;
m_tp1 = m_tp2;
// Our time per frame coefficient
float fElapsedTime = elapsedTime.count();
fLastElapsed = fElapsedTime;
// Some platforms will need to check for events
platform->HandleSystemEvent();
// Compare hardware input states from previous frame
auto ScanHardware = [&](HWButton* pKeys, bool* pStateOld, bool* pStateNew, uint32_t nKeyCount)
{
for (uint32_t i = 0; i < nKeyCount; i++)
{
pKeys[i].bPressed = false;
pKeys[i].bReleased = false;
if (pStateNew[i] != pStateOld[i])
{
if (pStateNew[i])
{
pKeys[i].bPressed = !pKeys[i].bHeld;
pKeys[i].bHeld = true;
}
else
{
pKeys[i].bReleased = true;
pKeys[i].bHeld = false;
}
}
pStateOld[i] = pStateNew[i];
}
};
ScanHardware(pKeyboardState, pKeyOldState, pKeyNewState, 256);
ScanHardware(pMouseState, pMouseOldState, pMouseNewState, nMouseButtons);
// Cache mouse coordinates so they remain consistent during frame
vMousePos = vMousePosCache;
nMouseWheelDelta = nMouseWheelDeltaCache;
nMouseWheelDeltaCache = 0;
renderer->ClearBuffer(olc::BLACK, true);
// Handle Frame Update
if (!OnUserUpdate(fElapsedTime))
bAtomActive = false;
// Display Frame
renderer->UpdateViewport(vViewPos, vViewSize);
renderer->ClearBuffer(olc::BLACK, true);
// Layer 0 must always exist
vLayers[0].bUpdate = true;
vLayers[0].bShow = true;
renderer->PrepareDrawing();
for (auto layer = vLayers.rbegin(); layer != vLayers.rend(); ++layer)
{
if (layer->bShow)
{
if (layer->funcHook == nullptr)
{
renderer->ApplyTexture(layer->nResID);
if (layer->bUpdate)
{
renderer->UpdateTexture(layer->nResID, layer->pDrawTarget);
layer->bUpdate = false;
}
renderer->DrawLayerQuad(layer->vOffset, layer->vScale, layer->tint);
// Display Decals in order for this layer
for (auto& decal : layer->vecDecalInstance)
renderer->DrawDecalQuad(decal);
layer->vecDecalInstance.clear();
}
else
{
// Mwa ha ha.... Have Fun!!!
layer->funcHook();
}
}
}
// Present Graphics to screen
renderer->DisplayFrame();
// Update Title Bar
fFrameTimer += fElapsedTime;
nFrameCount++;
if (fFrameTimer >= 1.0f)
{
nLastFPS = nFrameCount;
fFrameTimer -= 1.0f;
//std::string sTitle = sAppName + " - FPS: " + std::to_string(nFrameCount);
std::string sTitle = sAppName;
platform->SetWindowTitle(sTitle);
nFrameCount = 0;
}
}
void PixelGameEngine::olc_ConstructFontSheet()
{
std::string data;
data += "?Q`0001oOch0o01o@F40o0<AGD4090LAGD<090@A7ch0?00O7Q`0600>00000000";
data += "O000000nOT0063Qo4d8>?7a14Gno94AA4gno94AaOT0>o3`oO400o7QN00000400";
data += "Of80001oOg<7O7moBGT7O7lABET024@aBEd714AiOdl717a_=TH013Q>00000000";
data += "720D000V?V5oB3Q_HdUoE7a9@DdDE4A9@DmoE4A;Hg]oM4Aj8S4D84@`00000000";
data += "OaPT1000Oa`^13P1@AI[?g`1@A=[OdAoHgljA4Ao?WlBA7l1710007l100000000";
data += "ObM6000oOfMV?3QoBDD`O7a0BDDH@5A0BDD<@5A0BGeVO5ao@CQR?5Po00000000";
data += "Oc``000?Ogij70PO2D]??0Ph2DUM@7i`2DTg@7lh2GUj?0TO0C1870T?00000000";
data += "70<4001o?P<7?1QoHg43O;`h@GT0@:@LB@d0>:@hN@L0@?aoN@<0O7ao0000?000";
data += "OcH0001SOglLA7mg24TnK7ln24US>0PL24U140PnOgl0>7QgOcH0K71S0000A000";
data += "00H00000@Dm1S007@DUSg00?OdTnH7YhOfTL<7Yh@Cl0700?@Ah0300700000000";
data += "<008001QL00ZA41a@6HnI<1i@FHLM81M@@0LG81?O`0nC?Y7?`0ZA7Y300080000";
data += "O`082000Oh0827mo6>Hn?Wmo?6HnMb11MP08@C11H`08@FP0@@0004@000000000";
data += "00P00001Oab00003OcKP0006@6=PMgl<@440MglH@000000`@000001P00000000";
data += "Ob@8@@00Ob@8@Ga13R@8Mga172@8?PAo3R@827QoOb@820@0O`0007`0000007P0";
data += "O`000P08Od400g`<3V=P0G`673IP0`@3>1`00P@6O`P00g`<O`000GP800000000";
data += "?P9PL020O`<`N3R0@E4HC7b0@ET<ATB0@@l6C4B0O`H3N7b0?P01L3R000000020";
fontSprite = new olc::Sprite(128, 48);
int px = 0, py = 0;
for (size_t b = 0; b < 1024; b += 4)
{
uint32_t sym1 = (uint32_t)data[b + 0] - 48;
uint32_t sym2 = (uint32_t)data[b + 1] - 48;
uint32_t sym3 = (uint32_t)data[b + 2] - 48;
uint32_t sym4 = (uint32_t)data[b + 3] - 48;
uint32_t r = sym1 << 18 | sym2 << 12 | sym3 << 6 | sym4;
for (int i = 0; i < 24; i++)
{
int k = r & (1 << i) ? 255 : 0;
fontSprite->SetPixel(px, py, olc::Pixel(k, k, k, k));
if (++py == 48) { px++; py = 0; }
}
}
fontDecal = new olc::Decal(fontSprite);
}
// Need a couple of statics as these are singleton instances
// read from multiple locations
std::atomic<bool> PixelGameEngine::bAtomActive{ false };
olc::PixelGameEngine* olc::PGEX::pge = nullptr;
olc::PixelGameEngine* olc::Platform::ptrPGE = nullptr;
olc::PixelGameEngine* olc::Renderer::ptrPGE = nullptr;
};
// O------------------------------------------------------------------------------O
// | olcPixelGameEngine PLATFORM SPECIFIC IMPLEMENTATIONS |
// O------------------------------------------------------------------------------O
// O------------------------------------------------------------------------------O
// | START RENDERER: OpenGL 1.0 (the original, the best...) |
// O------------------------------------------------------------------------------O
#if defined(OLC_GFX_OPENGL10)
#if defined(_WIN32)
#include <windows.h>
#include <GL/gl.h>
typedef BOOL(WINAPI wglSwapInterval_t) (int interval);
static wglSwapInterval_t* wglSwapInterval = nullptr;
typedef HDC glDeviceContext_t;
typedef HGLRC glRenderContext_t;
#endif
#if defined(__linux__) || defined(__FreeBSD__)
#include <GL/gl.h>
namespace X11
{
#include <GL/glx.h>
#include <X11/X.h>
#include <X11/Xlib.h>
}
#include <png.h>
typedef int(glSwapInterval_t)(X11::Display* dpy, X11::GLXDrawable drawable, int interval);
static glSwapInterval_t* glSwapIntervalEXT;
typedef X11::GLXContext glDeviceContext_t;
typedef X11::GLXContext glRenderContext_t;
#endif
namespace olc
{
class Renderer_OGL10 : public olc::Renderer
{
private:
glDeviceContext_t glDeviceContext = 0;
glRenderContext_t glRenderContext = 0;
#if defined(__linux__) || defined(__FreeBSD__)
X11::Display* olc_Display = nullptr;
X11::Window* olc_Window = nullptr;
X11::XVisualInfo* olc_VisualInfo = nullptr;
#endif
public:
void PrepareDevice() override
{ }
olc::rcode CreateDevice(std::vector<void*> params, bool bFullScreen, bool bVSYNC) override
{
#if defined(_WIN32)
// Create Device Context
glDeviceContext = GetDC((HWND)(params[0]));
PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR), 1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
PFD_MAIN_PLANE, 0, 0, 0, 0
};
int pf = 0;
if (!(pf = ChoosePixelFormat(glDeviceContext, &pfd))) return olc::FAIL;
SetPixelFormat(glDeviceContext, pf, &pfd);
if (!(glRenderContext = wglCreateContext(glDeviceContext))) return olc::FAIL;
wglMakeCurrent(glDeviceContext, glRenderContext);
// Remove Frame cap
wglSwapInterval = (wglSwapInterval_t*)wglGetProcAddress("wglSwapIntervalEXT");
if (wglSwapInterval && !bVSYNC) wglSwapInterval(0);
#endif
#if defined(__linux__) || defined(__FreeBSD__)
using namespace X11;
// Linux has tighter coupling between OpenGL and X11, so we store
// various "platform" handles in the renderer
olc_Display = (X11::Display*)(params[0]);
olc_Window = (X11::Window*)(params[1]);
olc_VisualInfo = (X11::XVisualInfo*)(params[2]);
glDeviceContext = glXCreateContext(olc_Display, olc_VisualInfo, nullptr, GL_TRUE);
glXMakeCurrent(olc_Display, *olc_Window, glDeviceContext);
XWindowAttributes gwa;
XGetWindowAttributes(olc_Display, *olc_Window, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
glSwapIntervalEXT = nullptr;
glSwapIntervalEXT = (glSwapInterval_t*)glXGetProcAddress((unsigned char*)"glXSwapIntervalEXT");
if (glSwapIntervalEXT == nullptr && !bVSYNC)
{
printf("NOTE: Could not disable VSYNC, glXSwapIntervalEXT() was not found!\n");
printf(" Don't worry though, things will still work, it's just the\n");
printf(" frame rate will be capped to your monitors refresh rate - javidx9\n");
}
if (glSwapIntervalEXT != nullptr && !bVSYNC)
glSwapIntervalEXT(olc_Display, *olc_Window, 0);
#endif
glEnable(GL_TEXTURE_2D); // Turn on texturing
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
return olc::rcode::OK;
}
olc::rcode DestroyDevice() override
{
#if defined(_WIN32)
wglDeleteContext(glRenderContext);
#endif
#if defined(__linux__) || defined(__FreeBSD__)
glXMakeCurrent(olc_Display, None, NULL);
glXDestroyContext(olc_Display, glDeviceContext);
#endif
return olc::rcode::OK;
}
void DisplayFrame() override
{
#if defined(_WIN32)
SwapBuffers(glDeviceContext);
#endif
#if defined(__linux__) || defined(__FreeBSD__)
X11::glXSwapBuffers(olc_Display, *olc_Window);
#endif
}
void PrepareDrawing() override
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
void DrawLayerQuad(const olc::vf2d& offset, const olc::vf2d& scale, const olc::Pixel tint) override
{
glBegin(GL_QUADS);
glColor4ub(tint.r, tint.g, tint.b, tint.a);
glTexCoord2f(0.0f * scale.x + offset.x, 1.0f * scale.y + offset.y);
glVertex3f(-1.0f /*+ vSubPixelOffset.x*/, -1.0f /*+ vSubPixelOffset.y*/, 0.0f);
glTexCoord2f(0.0f * scale.x + offset.x, 0.0f * scale.y + offset.y);
glVertex3f(-1.0f /*+ vSubPixelOffset.x*/, 1.0f /*+ vSubPixelOffset.y*/, 0.0f);
glTexCoord2f(1.0f * scale.x + offset.x, 0.0f * scale.y + offset.y);
glVertex3f(1.0f /*+ vSubPixelOffset.x*/, 1.0f /*+ vSubPixelOffset.y*/, 0.0f);
glTexCoord2f(1.0f * scale.x + offset.x, 1.0f * scale.y + offset.y);
glVertex3f(1.0f /*+ vSubPixelOffset.x*/, -1.0f /*+ vSubPixelOffset.y*/, 0.0f);
glEnd();
}
void DrawDecalQuad(const olc::DecalInstance& decal) override
{
if (decal.decal == nullptr)
{
glBindTexture(GL_TEXTURE_2D, 0);
glBegin(GL_QUADS);
glColor4ub(decal.tint[0].r, decal.tint[0].g, decal.tint[0].b, decal.tint[0].a);
glTexCoord4f(decal.uv[0].x, decal.uv[0].y, 0.0f, decal.w[0]); glVertex2f(decal.pos[0].x, decal.pos[0].y);
glColor4ub(decal.tint[1].r, decal.tint[1].g, decal.tint[1].b, decal.tint[1].a);
glTexCoord4f(decal.uv[1].x, decal.uv[1].y, 0.0f, decal.w[1]); glVertex2f(decal.pos[1].x, decal.pos[1].y);
glColor4ub(decal.tint[2].r, decal.tint[2].g, decal.tint[2].b, decal.tint[2].a);
glTexCoord4f(decal.uv[2].x, decal.uv[2].y, 0.0f, decal.w[2]); glVertex2f(decal.pos[2].x, decal.pos[2].y);
glColor4ub(decal.tint[3].r, decal.tint[3].g, decal.tint[3].b, decal.tint[3].a);
glTexCoord4f(decal.uv[3].x, decal.uv[3].y, 0.0f, decal.w[3]); glVertex2f(decal.pos[3].x, decal.pos[3].y);
glEnd();
}
else
{
glBindTexture(GL_TEXTURE_2D, decal.decal->id);
glBegin(GL_QUADS);
glColor4ub(decal.tint[0].r, decal.tint[0].g, decal.tint[0].b, decal.tint[0].a);
glTexCoord4f(decal.uv[0].x, decal.uv[0].y, 0.0f, decal.w[0]); glVertex2f(decal.pos[0].x, decal.pos[0].y);
glTexCoord4f(decal.uv[1].x, decal.uv[1].y, 0.0f, decal.w[1]); glVertex2f(decal.pos[1].x, decal.pos[1].y);
glTexCoord4f(decal.uv[2].x, decal.uv[2].y, 0.0f, decal.w[2]); glVertex2f(decal.pos[2].x, decal.pos[2].y);
glTexCoord4f(decal.uv[3].x, decal.uv[3].y, 0.0f, decal.w[3]); glVertex2f(decal.pos[3].x, decal.pos[3].y);
glEnd();
}
}
uint32_t CreateTexture(const uint32_t width, const uint32_t height) override
{
uint32_t id = 0;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
return id;
}
uint32_t DeleteTexture(const uint32_t id) override
{
glDeleteTextures(1, &id);
return id;
}
void UpdateTexture(uint32_t id, olc::Sprite* spr) override
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, spr->width, spr->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spr->GetData());
}
void ApplyTexture(uint32_t id) override
{
glBindTexture(GL_TEXTURE_2D, id);
}
void ClearBuffer(olc::Pixel p, bool bDepth) override
{
glClearColor(float(p.r) / 255.0f, float(p.g) / 255.0f, float(p.b) / 255.0f, float(p.a) / 255.0f);
glClear(GL_COLOR_BUFFER_BIT);
if (bDepth) glClear(GL_DEPTH_BUFFER_BIT);
}
void UpdateViewport(const olc::vi2d& pos, const olc::vi2d& size) override
{
glViewport(pos.x, pos.y, size.x, size.y);
}
};
}
#endif
// O------------------------------------------------------------------------------O
// | END RENDERER: OpenGL 1.0 (the original, the best...) |
// O------------------------------------------------------------------------------O
// O------------------------------------------------------------------------------O
// | START PLATFORM: MICROSOFT WINDOWS XP, VISTA, 7, 8, 10 |
// O------------------------------------------------------------------------------O
#if defined(_WIN32)
#if !defined(__MINGW32__)
#pragma comment(lib, "user32.lib") // Visual Studio Only
#pragma comment(lib, "gdi32.lib") // For other Windows Compilers please add
#pragma comment(lib, "opengl32.lib") // these libs to your linker input
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "Shlwapi.lib")
#else
// In Code::Blocks
#if !defined(_WIN32_WINNT)
#ifdef HAVE_MSMF
#define _WIN32_WINNT 0x0600 // Windows Vista
#else
#define _WIN32_WINNT 0x0500 // Windows 2000
#endif
#endif
#endif
// Include WinAPI
#if !defined(NOMINMAX)
#define NOMINMAX
#endif
#define VC_EXTRALEAN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <gdiplus.h>
#include <Shlwapi.h>
namespace olc
{
// Little utility function to convert from char to wchar in Windows environments
// depending upon how the compiler is configured. This should not be necessary
// on linux platforms
std::wstring ConvertS2W(std::string s)
{
#ifdef __MINGW32__
wchar_t* buffer = new wchar_t[s.length() + 1];
mbstowcs(buffer, s.c_str(), s.length());
buffer[s.length()] = L'\0';
#else
int count = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0);
wchar_t* buffer = new wchar_t[count];
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buffer, count);
#endif
std::wstring w(buffer);
delete[] buffer;
return w;
}
// Thanks @MaGetzUb for this, which allows sprites to be defined
// at construction, by initialising the GDI subsystem
static class GDIPlusStartup
{
public:
GDIPlusStartup()
{
Gdiplus::GdiplusStartupInput startupInput;
ULONG_PTR token;
Gdiplus::GdiplusStartup(&token, &startupInput, NULL);
};
} gdistartup;
class Platform_Windows : public olc::Platform
{
private:
HWND olc_hWnd = nullptr;
std::wstring wsAppName;
public:
virtual olc::rcode ApplicationStartUp() override { return olc::rcode::OK; }
virtual olc::rcode ApplicationCleanUp() override { return olc::rcode::OK; }
virtual olc::rcode ThreadStartUp() override { return olc::rcode::OK; }
virtual olc::rcode ThreadCleanUp() override
{
renderer->DestroyDevice();
PostMessage(olc_hWnd, WM_DESTROY, 0, 0);
return olc::OK;
}
virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override
{
if (renderer->CreateDevice({ olc_hWnd }, bFullScreen, bEnableVSYNC) == olc::rcode::OK)
{
renderer->UpdateViewport(vViewPos, vViewSize);
return olc::rcode::OK;
}
else
return olc::rcode::FAIL;
}
virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override
{
WNDCLASS wc;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.hInstance = GetModuleHandle(nullptr);
wc.lpfnWndProc = olc_WindowEvent;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.lpszMenuName = nullptr;
wc.hbrBackground = nullptr;
wc.lpszClassName = olcT("OLC_PIXEL_GAME_ENGINE");
RegisterClass(&wc);
// Define window furniture
DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
DWORD dwStyle = WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_THICKFRAME;
olc::vi2d vTopLeft = vWindowPos;
// Handle Fullscreen
if (bFullScreen)
{
dwExStyle = 0;
dwStyle = WS_VISIBLE | WS_POPUP;
HMONITOR hmon = MonitorFromWindow(olc_hWnd, MONITOR_DEFAULTTONEAREST);
MONITORINFO mi = { sizeof(mi) };
if (!GetMonitorInfo(hmon, &mi)) return olc::rcode::FAIL;
vWindowSize = { mi.rcMonitor.right, mi.rcMonitor.bottom };
vTopLeft.x = 0;
vTopLeft.y = 0;
}
// Keep client size as requested
RECT rWndRect = { 0, 0, vWindowSize.x, vWindowSize.y };
AdjustWindowRectEx(&rWndRect, dwStyle, FALSE, dwExStyle);
int width = rWndRect.right - rWndRect.left;
int height = rWndRect.bottom - rWndRect.top;
olc_hWnd = CreateWindowEx(dwExStyle, olcT("OLC_PIXEL_GAME_ENGINE"), olcT(""), dwStyle,
vTopLeft.x, vTopLeft.y, width, height, NULL, NULL, GetModuleHandle(nullptr), this);
// Create Keyboard Mapping
mapKeys[0x00] = Key::NONE;
mapKeys[0x41] = Key::A; mapKeys[0x42] = Key::B; mapKeys[0x43] = Key::C; mapKeys[0x44] = Key::D; mapKeys[0x45] = Key::E;
mapKeys[0x46] = Key::F; mapKeys[0x47] = Key::G; mapKeys[0x48] = Key::H; mapKeys[0x49] = Key::I; mapKeys[0x4A] = Key::J;
mapKeys[0x4B] = Key::K; mapKeys[0x4C] = Key::L; mapKeys[0x4D] = Key::M; mapKeys[0x4E] = Key::N; mapKeys[0x4F] = Key::O;
mapKeys[0x50] = Key::P; mapKeys[0x51] = Key::Q; mapKeys[0x52] = Key::R; mapKeys[0x53] = Key::S; mapKeys[0x54] = Key::T;
mapKeys[0x55] = Key::U; mapKeys[0x56] = Key::V; mapKeys[0x57] = Key::W; mapKeys[0x58] = Key::X; mapKeys[0x59] = Key::Y;
mapKeys[0x5A] = Key::Z;
mapKeys[VK_F1] = Key::F1; mapKeys[VK_F2] = Key::F2; mapKeys[VK_F3] = Key::F3; mapKeys[VK_F4] = Key::F4;
mapKeys[VK_F5] = Key::F5; mapKeys[VK_F6] = Key::F6; mapKeys[VK_F7] = Key::F7; mapKeys[VK_F8] = Key::F8;
mapKeys[VK_F9] = Key::F9; mapKeys[VK_F10] = Key::F10; mapKeys[VK_F11] = Key::F11; mapKeys[VK_F12] = Key::F12;
mapKeys[VK_DOWN] = Key::DOWN; mapKeys[VK_LEFT] = Key::LEFT; mapKeys[VK_RIGHT] = Key::RIGHT; mapKeys[VK_UP] = Key::UP;
mapKeys[VK_RETURN] = Key::ENTER; //mapKeys[VK_RETURN] = Key::RETURN;
mapKeys[VK_BACK] = Key::BACK; mapKeys[VK_ESCAPE] = Key::ESCAPE; mapKeys[VK_RETURN] = Key::ENTER; mapKeys[VK_PAUSE] = Key::PAUSE;
mapKeys[VK_SCROLL] = Key::SCROLL; mapKeys[VK_TAB] = Key::TAB; mapKeys[VK_DELETE] = Key::DEL; mapKeys[VK_HOME] = Key::HOME;
mapKeys[VK_END] = Key::END; mapKeys[VK_PRIOR] = Key::PGUP; mapKeys[VK_NEXT] = Key::PGDN; mapKeys[VK_INSERT] = Key::INS;
mapKeys[VK_SHIFT] = Key::SHIFT; mapKeys[VK_CONTROL] = Key::CTRL;
mapKeys[VK_SPACE] = Key::SPACE;
mapKeys[0x30] = Key::K0; mapKeys[0x31] = Key::K1; mapKeys[0x32] = Key::K2; mapKeys[0x33] = Key::K3; mapKeys[0x34] = Key::K4;
mapKeys[0x35] = Key::K5; mapKeys[0x36] = Key::K6; mapKeys[0x37] = Key::K7; mapKeys[0x38] = Key::K8; mapKeys[0x39] = Key::K9;
mapKeys[VK_NUMPAD0] = Key::NP0; mapKeys[VK_NUMPAD1] = Key::NP1; mapKeys[VK_NUMPAD2] = Key::NP2; mapKeys[VK_NUMPAD3] = Key::NP3; mapKeys[VK_NUMPAD4] = Key::NP4;
mapKeys[VK_NUMPAD5] = Key::NP5; mapKeys[VK_NUMPAD6] = Key::NP6; mapKeys[VK_NUMPAD7] = Key::NP7; mapKeys[VK_NUMPAD8] = Key::NP8; mapKeys[VK_NUMPAD9] = Key::NP9;
mapKeys[VK_MULTIPLY] = Key::NP_MUL; mapKeys[VK_ADD] = Key::NP_ADD; mapKeys[VK_DIVIDE] = Key::NP_DIV; mapKeys[VK_SUBTRACT] = Key::NP_SUB; mapKeys[VK_DECIMAL] = Key::NP_DECIMAL;
return olc::OK;
}
virtual olc::rcode SetWindowTitle(const std::string& s) override
{
#ifdef UNICODE
SetWindowText(olc_hWnd, ConvertS2W(s).c_str());
#else
SetWindowText(olc_hWnd, s.c_str());
#endif
return olc::OK;
}
virtual olc::rcode StartSystemEventLoop() override
{
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return olc::OK;
}
virtual olc::rcode HandleSystemEvent() override { return olc::rcode::FAIL; }
// Windows Event Handler - this is statically connected to the windows event system
static LRESULT CALLBACK olc_WindowEvent(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_MOUSEMOVE:
{
// Thanks @ForAbby (Discord)
uint16_t x = lParam & 0xFFFF; uint16_t y = (lParam >> 16) & 0xFFFF;
int16_t ix = *(int16_t*)&x; int16_t iy = *(int16_t*)&y;
ptrPGE->olc_UpdateMouse(ix, iy);
return 0;
}
case WM_SIZE: ptrPGE->olc_UpdateWindowSize(lParam & 0xFFFF, (lParam >> 16) & 0xFFFF); return 0;
case WM_MOUSEWHEEL: ptrPGE->olc_UpdateMouseWheel(GET_WHEEL_DELTA_WPARAM(wParam)); return 0;
case WM_MOUSELEAVE: ptrPGE->olc_UpdateMouseFocus(false); return 0;
case WM_SETFOCUS: ptrPGE->olc_UpdateKeyFocus(true); return 0;
case WM_KILLFOCUS: ptrPGE->olc_UpdateKeyFocus(false); return 0;
case WM_KEYDOWN: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], true); return 0;
case WM_KEYUP: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], false); return 0;
case WM_LBUTTONDOWN:ptrPGE->olc_UpdateMouseState(0, true); return 0;
case WM_LBUTTONUP: ptrPGE->olc_UpdateMouseState(0, false); return 0;
case WM_RBUTTONDOWN:ptrPGE->olc_UpdateMouseState(1, true); return 0;
case WM_RBUTTONUP: ptrPGE->olc_UpdateMouseState(1, false); return 0;
case WM_MBUTTONDOWN:ptrPGE->olc_UpdateMouseState(2, true); return 0;
case WM_MBUTTONUP: ptrPGE->olc_UpdateMouseState(2, false); return 0;
case WM_CLOSE: ptrPGE->olc_Terminate(); return 0;
case WM_DESTROY: PostQuitMessage(0); return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
};
// On Windows load images using GDI+ library
olc::rcode Sprite::LoadFromFile(const std::string& sImageFile, olc::ResourcePack* pack)
{
UNUSED(pack);
Gdiplus::Bitmap* bmp = nullptr;
if (pack != nullptr)
{
// Load sprite from input stream
ResourceBuffer rb = pack->GetFileBuffer(sImageFile);
bmp = Gdiplus::Bitmap::FromStream(SHCreateMemStream((BYTE*)rb.vMemory.data(), UINT(rb.vMemory.size())));
}
else
{
// Load sprite from file
bmp = Gdiplus::Bitmap::FromFile(ConvertS2W(sImageFile).c_str());
}
if (bmp->GetLastStatus() != Gdiplus::Ok) return olc::NO_FILE;
width = bmp->GetWidth();
height = bmp->GetHeight();
pColData = new Pixel[width * height];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
Gdiplus::Color c;
bmp->GetPixel(x, y, &c);
SetPixel(x, y, olc::Pixel(c.GetRed(), c.GetGreen(), c.GetBlue(), c.GetAlpha()));
}
delete bmp;
return olc::OK;
}
}
#endif
// O------------------------------------------------------------------------------O
// | END PLATFORM: MICROSOFT WINDOWS XP, VISTA, 7, 8, 10 |
// O------------------------------------------------------------------------------O
// O------------------------------------------------------------------------------O
// | START PLATFORM: LINUX |
// O------------------------------------------------------------------------------O
#if defined(__linux__) || defined(__FreeBSD__)
namespace olc
{
class Platform_Linux : public olc::Platform
{
private:
X11::Display* olc_Display = nullptr;
X11::Window olc_WindowRoot;
X11::Window olc_Window;
X11::XVisualInfo* olc_VisualInfo;
X11::Colormap olc_ColourMap;
X11::XSetWindowAttributes olc_SetWindowAttribs;
public:
virtual olc::rcode ApplicationStartUp() override
{
return olc::rcode::OK;
}
virtual olc::rcode ApplicationCleanUp() override
{
return olc::rcode::OK;
}
virtual olc::rcode ThreadStartUp() override
{
return olc::rcode::OK;
}
virtual olc::rcode ThreadCleanUp() override
{
renderer->DestroyDevice();
return olc::OK;
}
virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override
{
if (renderer->CreateDevice({ olc_Display, &olc_Window, olc_VisualInfo }, bFullScreen, bEnableVSYNC) == olc::rcode::OK)
{
renderer->UpdateViewport(vViewPos, vViewSize);
return olc::rcode::OK;
}
else
return olc::rcode::FAIL;
}
virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override
{
using namespace X11;
XInitThreads();
// Grab the deafult display and window
olc_Display = XOpenDisplay(NULL);
olc_WindowRoot = DefaultRootWindow(olc_Display);
// Based on the display capabilities, configure the appearance of the window
GLint olc_GLAttribs[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
olc_VisualInfo = glXChooseVisual(olc_Display, 0, olc_GLAttribs);
olc_ColourMap = XCreateColormap(olc_Display, olc_WindowRoot, olc_VisualInfo->visual, AllocNone);
olc_SetWindowAttribs.colormap = olc_ColourMap;
// Register which events we are interested in receiving
olc_SetWindowAttribs.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask |
ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask | StructureNotifyMask;
// Create the window
olc_Window = XCreateWindow(olc_Display, olc_WindowRoot, vWindowPos.x, vWindowPos.y,
vWindowSize.x, vWindowSize.y,
0, olc_VisualInfo->depth, InputOutput, olc_VisualInfo->visual,
CWColormap | CWEventMask, &olc_SetWindowAttribs);
Atom wmDelete = XInternAtom(olc_Display, "WM_DELETE_WINDOW", true);
XSetWMProtocols(olc_Display, olc_Window, &wmDelete, 1);
XMapWindow(olc_Display, olc_Window);
XStoreName(olc_Display, olc_Window, "OneLoneCoder.com - Pixel Game Engine");
if (bFullScreen) // Thanks DragonEye, again :D
{
Atom wm_state;
Atom fullscreen;
wm_state = XInternAtom(olc_Display, "_NET_WM_STATE", False);
fullscreen = XInternAtom(olc_Display, "_NET_WM_STATE_FULLSCREEN", False);
XEvent xev{ 0 };
xev.type = ClientMessage;
xev.xclient.window = olc_Window;
xev.xclient.message_type = wm_state;
xev.xclient.format = 32;
xev.xclient.data.l[0] = (bFullScreen ? 1 : 0); // the action (0: off, 1: on, 2: toggle)
xev.xclient.data.l[1] = fullscreen; // first property to alter
xev.xclient.data.l[2] = 0; // second property to alter
xev.xclient.data.l[3] = 0; // source indication
XMapWindow(olc_Display, olc_Window);
XSendEvent(olc_Display, DefaultRootWindow(olc_Display), False,
SubstructureRedirectMask | SubstructureNotifyMask, &xev);
XFlush(olc_Display);
XWindowAttributes gwa;
XGetWindowAttributes(olc_Display, olc_Window, &gwa);
vWindowSize.x = gwa.width;
vWindowSize.y = gwa.height;
}
// Create Keyboard Mapping
mapKeys[0x00] = Key::NONE;
mapKeys[0x61] = Key::A; mapKeys[0x62] = Key::B; mapKeys[0x63] = Key::C; mapKeys[0x64] = Key::D; mapKeys[0x65] = Key::E;
mapKeys[0x66] = Key::F; mapKeys[0x67] = Key::G; mapKeys[0x68] = Key::H; mapKeys[0x69] = Key::I; mapKeys[0x6A] = Key::J;
mapKeys[0x6B] = Key::K; mapKeys[0x6C] = Key::L; mapKeys[0x6D] = Key::M; mapKeys[0x6E] = Key::N; mapKeys[0x6F] = Key::O;
mapKeys[0x70] = Key::P; mapKeys[0x71] = Key::Q; mapKeys[0x72] = Key::R; mapKeys[0x73] = Key::S; mapKeys[0x74] = Key::T;
mapKeys[0x75] = Key::U; mapKeys[0x76] = Key::V; mapKeys[0x77] = Key::W; mapKeys[0x78] = Key::X; mapKeys[0x79] = Key::Y;
mapKeys[0x7A] = Key::Z;
mapKeys[XK_F1] = Key::F1; mapKeys[XK_F2] = Key::F2; mapKeys[XK_F3] = Key::F3; mapKeys[XK_F4] = Key::F4;
mapKeys[XK_F5] = Key::F5; mapKeys[XK_F6] = Key::F6; mapKeys[XK_F7] = Key::F7; mapKeys[XK_F8] = Key::F8;
mapKeys[XK_F9] = Key::F9; mapKeys[XK_F10] = Key::F10; mapKeys[XK_F11] = Key::F11; mapKeys[XK_F12] = Key::F12;
mapKeys[XK_Down] = Key::DOWN; mapKeys[XK_Left] = Key::LEFT; mapKeys[XK_Right] = Key::RIGHT; mapKeys[XK_Up] = Key::UP;
mapKeys[XK_KP_Enter] = Key::ENTER; mapKeys[XK_Return] = Key::ENTER;
mapKeys[XK_BackSpace] = Key::BACK; mapKeys[XK_Escape] = Key::ESCAPE; mapKeys[XK_Linefeed] = Key::ENTER; mapKeys[XK_Pause] = Key::PAUSE;
mapKeys[XK_Scroll_Lock] = Key::SCROLL; mapKeys[XK_Tab] = Key::TAB; mapKeys[XK_Delete] = Key::DEL; mapKeys[XK_Home] = Key::HOME;
mapKeys[XK_End] = Key::END; mapKeys[XK_Page_Up] = Key::PGUP; mapKeys[XK_Page_Down] = Key::PGDN; mapKeys[XK_Insert] = Key::INS;
mapKeys[XK_Shift_L] = Key::SHIFT; mapKeys[XK_Shift_R] = Key::SHIFT; mapKeys[XK_Control_L] = Key::CTRL; mapKeys[XK_Control_R] = Key::CTRL;
mapKeys[XK_space] = Key::SPACE; mapKeys[XK_period] = Key::PERIOD;
mapKeys[XK_0] = Key::K0; mapKeys[XK_1] = Key::K1; mapKeys[XK_2] = Key::K2; mapKeys[XK_3] = Key::K3; mapKeys[XK_4] = Key::K4;
mapKeys[XK_5] = Key::K5; mapKeys[XK_6] = Key::K6; mapKeys[XK_7] = Key::K7; mapKeys[XK_8] = Key::K8; mapKeys[XK_9] = Key::K9;
mapKeys[XK_KP_0] = Key::NP0; mapKeys[XK_KP_1] = Key::NP1; mapKeys[XK_KP_2] = Key::NP2; mapKeys[XK_KP_3] = Key::NP3; mapKeys[XK_KP_4] = Key::NP4;
mapKeys[XK_KP_5] = Key::NP5; mapKeys[XK_KP_6] = Key::NP6; mapKeys[XK_KP_7] = Key::NP7; mapKeys[XK_KP_8] = Key::NP8; mapKeys[XK_KP_9] = Key::NP9;
mapKeys[XK_KP_Multiply] = Key::NP_MUL; mapKeys[XK_KP_Add] = Key::NP_ADD; mapKeys[XK_KP_Divide] = Key::NP_DIV; mapKeys[XK_KP_Subtract] = Key::NP_SUB; mapKeys[XK_KP_Decimal] = Key::NP_DECIMAL;
return olc::OK;
}
virtual olc::rcode SetWindowTitle(const std::string& s) override
{
X11::XStoreName(olc_Display, olc_Window, s.c_str());
return olc::OK;
}
virtual olc::rcode StartSystemEventLoop() override
{
return olc::OK;
}
virtual olc::rcode HandleSystemEvent() override
{
using namespace X11;
// Handle Xlib Message Loop - we do this in the
// same thread that OpenGL was created so we dont
// need to worry too much about multithreading with X11
XEvent xev;
while (XPending(olc_Display))
{
XNextEvent(olc_Display, &xev);
if (xev.type == Expose)
{
XWindowAttributes gwa;
XGetWindowAttributes(olc_Display, olc_Window, &gwa);
ptrPGE->olc_UpdateWindowSize(gwa.width, gwa.height);
}
else if (xev.type == ConfigureNotify)
{
XConfigureEvent xce = xev.xconfigure;
ptrPGE->olc_UpdateWindowSize(xce.width, xce.height);
}
else if (xev.type == KeyPress)
{
KeySym sym = XLookupKeysym(&xev.xkey, 0);
ptrPGE->olc_UpdateKeyState(mapKeys[sym], true);
XKeyEvent* e = (XKeyEvent*)&xev; // Because DragonEye loves numpads
XLookupString(e, NULL, 0, &sym, NULL);
ptrPGE->olc_UpdateKeyState(mapKeys[sym], true);
}
else if (xev.type == KeyRelease)
{
KeySym sym = XLookupKeysym(&xev.xkey, 0);
ptrPGE->olc_UpdateKeyState(mapKeys[sym], false);
XKeyEvent* e = (XKeyEvent*)&xev;
XLookupString(e, NULL, 0, &sym, NULL);
ptrPGE->olc_UpdateKeyState(mapKeys[sym], false);
}
else if (xev.type == ButtonPress)
{
switch (xev.xbutton.button)
{
case 1: ptrPGE->olc_UpdateMouseState(0, true); break;
case 2: ptrPGE->olc_UpdateMouseState(2, true); break;
case 3: ptrPGE->olc_UpdateMouseState(1, true); break;
case 4: ptrPGE->olc_UpdateMouseWheel(120); break;
case 5: ptrPGE->olc_UpdateMouseWheel(-120); break;
default: break;
}
}
else if (xev.type == ButtonRelease)
{
switch (xev.xbutton.button)
{
case 1: ptrPGE->olc_UpdateMouseState(0, false); break;
case 2: ptrPGE->olc_UpdateMouseState(2, false); break;
case 3: ptrPGE->olc_UpdateMouseState(1, false); break;
default: break;
}
}
else if (xev.type == MotionNotify)
{
ptrPGE->olc_UpdateMouse(xev.xmotion.x, xev.xmotion.y);
}
else if (xev.type == FocusIn)
{
ptrPGE->olc_UpdateKeyFocus(true);
}
else if (xev.type == FocusOut)
{
ptrPGE->olc_UpdateKeyFocus(false);
}
else if (xev.type == ClientMessage)
{
ptrPGE->olc_Terminate();
}
}
return olc::OK;
}
};
void pngReadStream(png_structp pngPtr, png_bytep data, png_size_t length)
{
png_voidp a = png_get_io_ptr(pngPtr);
((std::istream*)a)->read((char*)data, length);
}
olc::rcode Sprite::LoadFromFile(const std::string& sImageFile, olc::ResourcePack* pack)
{
UNUSED(pack);
////////////////////////////////////////////////////////////////////////////
// Use libpng, Thanks to Guillaume Cottenceau
// https://gist.github.com/niw/5963798
// Also reading png from streams
// http://www.piko3d.net/tutorials/libpng-tutorial-loading-png-files-from-streams/
png_structp png;
png_infop info;
auto loadPNG = [&]()
{
png_read_info(png, info);
png_byte color_type;
png_byte bit_depth;
png_bytep* row_pointers;
width = png_get_image_width(png, info);
height = png_get_image_height(png, info);
color_type = png_get_color_type(png, info);
bit_depth = png_get_bit_depth(png, info);
if (bit_depth == 16) png_set_strip_16(png);
if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png);
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png);
if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png);
if (color_type == PNG_COLOR_TYPE_RGB ||
color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_PALETTE)
png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
if (color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png);
png_read_update_info(png, info);
row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * height);
for (int y = 0; y < height; y++) {
row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png, info));
}
png_read_image(png, row_pointers);
////////////////////////////////////////////////////////////////////////////
// Create sprite array
pColData = new Pixel[width * height];
// Iterate through image rows, converting into sprite format
for (int y = 0; y < height; y++)
{
png_bytep row = row_pointers[y];
for (int x = 0; x < width; x++)
{
png_bytep px = &(row[x * 4]);
SetPixel(x, y, Pixel(px[0], px[1], px[2], px[3]));
}
}
for (int y = 0; y < height; y++) // Thanks maksym33
free(row_pointers[y]);
free(row_pointers);
png_destroy_read_struct(&png, &info, nullptr);
};
png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png) goto fail_load;
info = png_create_info_struct(png);
if (!info) goto fail_load;
if (setjmp(png_jmpbuf(png))) goto fail_load;
if (pack == nullptr)
{
FILE* f = fopen(sImageFile.c_str(), "rb");
if (!f) return olc::NO_FILE;
png_init_io(png, f);
loadPNG();
fclose(f);
}
else
{
ResourceBuffer rb = pack->GetFileBuffer(sImageFile);
std::istream is(&rb);
png_set_read_fn(png, (png_voidp)&is, pngReadStream);
loadPNG();
}
return olc::OK;
fail_load:
width = 0;
height = 0;
pColData = nullptr;
return olc::FAIL;
}
}
#endif
// O------------------------------------------------------------------------------O
// | END PLATFORM: LINUX |
// O------------------------------------------------------------------------------O
namespace olc
{
void PixelGameEngine::olc_ConfigureSystem()
{
#if defined(_WIN32)
platform = std::make_unique<olc::Platform_Windows>();
#endif
#if defined(__linux__) || defined(__FreeBSD__)
platform = std::make_unique<olc::Platform_Linux>();
#endif
#if defined(OLC_GFX_OPENGL10)
renderer = std::make_unique<olc::Renderer_OGL10>();
#endif
#if defined(OLC_GFX_OPENGL33)
renderer = std::make_unique<olc::Renderer_OGL33>();
#endif
#if defined(OLC_GFX_DIRECTX10)
renderer = std::make_unique<olc::Renderer_DX10>();
#endif
//// Associate components with PGE instance
platform->ptrPGE = this;
renderer->ptrPGE = this;
}
}
#endif // End olc namespace
// O------------------------------------------------------------------------------O
// | END OF OLC_PGE_APPLICATION |
// O------------------------------------------------------------------------------O
| [
"noreply@github.com"
] | jglatts.noreply@github.com |
2dce4897b7da98d999fca1c1983f4a8c41c82376 | de4a7f00df913bec160e91e2b255e41d0518eabe | /http_asio/connection.cpp | 119da6267fa189f914d3673bb21ebadd3a542452 | [] | no_license | octocat9lee/practical-network-programming | 67fd7b923d3826461b7aa3c4f77ff3be67614781 | 66707ed0523254cebe62baad6fdf4856857125f7 | refs/heads/master | 2021-05-12T06:44:36.494923 | 2019-03-08T04:00:33 | 2019-03-08T04:00:33 | 117,224,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,994 | cpp | //
// connection.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "connection.h"
#include <vector>
#include <boost/bind.hpp>
#include "request_handler.h"
namespace http
{
namespace server2
{
connection::connection(boost::asio::io_service& io_service,
request_handler& handler)
: socket_(io_service),
request_handler_(handler)
{
}
boost::asio::ip::tcp::socket& connection::socket()
{
return socket_;
}
void connection::start()
{
socket_.async_read_some(boost::asio::buffer(buffer_),
boost::bind(&connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void connection::handle_read(const boost::system::error_code& e,
std::size_t bytes_transferred)
{
if(!e)
{
boost::tribool result;
boost::tie(result, boost::tuples::ignore) = request_parser_.parse(
request_, buffer_.data(), buffer_.data() + bytes_transferred);
if(result)
{
request_handler_.handle_request(request_, reply_);
boost::asio::async_write(socket_, reply_.to_buffers(),
boost::bind(&connection::handle_write, shared_from_this(),
boost::asio::placeholders::error));
}
else if(!result)
{
reply_ = reply::stock_reply(reply::bad_request);
boost::asio::async_write(socket_, reply_.to_buffers(),
boost::bind(&connection::handle_write, shared_from_this(),
boost::asio::placeholders::error));
}
else
{
socket_.async_read_some(boost::asio::buffer(buffer_),
boost::bind(&connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
}
// If an error occurs then no new asynchronous operations are started. This
// means that all shared_ptr references to the connection object will
// disappear and the object will be destroyed automatically after this
// handler returns. The connection class's destructor closes the socket.
}
void connection::handle_write(const boost::system::error_code& e)
{
if(!e)
{
// Initiate graceful connection closure.
boost::system::error_code ignored_ec;
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
}
// No new asynchronous operations are started. This means that all shared_ptr
// references to the connection object will disappear and the object will be
// destroyed automatically after this handler returns. The connection class's
// destructor closes the socket.
}
} // namespace server2
} // namespace http | [
"295861542@qq.com"
] | 295861542@qq.com |
b76554fcebe4c4eb3e962a9663c32f7e3e59e548 | 6ae1105a9ee4ec00eaf4a7c8d29af03e218ae68c | /Home_Automation_Slave_2/Home_Automation_Slave_2.ino | 8c0f042464e6b2b4ad5013666a16a362fca75070 | [] | no_license | kaustubhcs/Home-Automation | e2c49b3f7f3a9a704739277837f910361db41c03 | 192a52ea3c1af677c8f76b3ebc5917d2a574ea38 | refs/heads/master | 2021-01-22T21:13:09.958546 | 2015-10-22T15:48:32 | 2015-10-22T15:48:32 | 41,579,976 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,327 | ino | #include <SoftwareSerial.h>
#define relay_0 2 // T
#define relay_1 3 // E
#define relay_2 11 // C
#define relay_3 6 // H
#define relay_4 4 // N
#define relay_5 45 // O
#define relay_6 47 // V
#define relay_7 52 // A
#define relay_8 51 // N
#define relay_9 53 // Z
#define relay_10 49// A
#define cfl relay_0
#define tubes relay_1
#define fan relay_2
#define night_lamp relay_3
//#define
#define table_plug_2 relay_5
#define table_plug_1 relay_6
#define bell relay_7
#define master_plug relay_8
#define tv relay_9
//#define
#define buzzer 35
#define passage_door_open_led 23
#define passage_door_lock_led 25
#define passage_door_open_ldr A8
#define passage_door_lock_ldr A7
#define passage_door_bell_led 27
#define passage_door_bell_switch A6
#define pir_1 A5
#define pir_2 A4
#define pir_3 A3
#define living_room_door_open_led 29
#define living_room_door_lock_led 31
#define living_room_door_lock_ldr A2
#define living_room_door_open_ldr A1
#define gallery_door_open_led 33
#define gallery_door_open_ldr A0
SoftwareSerial master(10,14);
int relay[11] = {
2,3,11,6,4,45,47,52,51,53,49};
int commands[15] ={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int bell_t=0;
unsigned long time=0;
int gmode=0;
int fmode=0;
unsigned long y= 0;
unsigned long x= 0;
unsigned long str = millis();
unsigned long md = 0;
unsigned long me = 0;
unsigned long mn = 0;
unsigned long ms = 0;
unsigned long adder=3000;
void setup()
{
initialise_pins();
Serial.begin(9600);
master.begin(9600);
digitalWrite(master_plug,HIGH);
}
void loop()
{
// adder_setter();
mode();
bell_detect();
// delay(1000);
// tests();
}
void tests()
{
// sensor_test();
// sensor_test_2();
//pir_test_3();
// comm_test();
//relay_test();
//pir_test_2();
//analog_pir();
/*
pir(1);
pir(2);
pir(3);
*/
}
void initialise_pins()
{
for (int i=0;i<11;i++)
{
pinMode(relay[i],OUTPUT);
digitalWrite(relay[i],LOW);
}
pinMode(buzzer,OUTPUT);
pinMode(passage_door_open_led,OUTPUT);
pinMode(passage_door_lock_led,OUTPUT);
pinMode(passage_door_open_ldr,INPUT);
pinMode(passage_door_lock_ldr,INPUT);
pinMode(passage_door_bell_led,OUTPUT);
pinMode(passage_door_bell_switch,INPUT);
pinMode(pir_1,INPUT);
pinMode(pir_2,INPUT);
pinMode(pir_3,INPUT);
pinMode(living_room_door_open_led,OUTPUT);
pinMode(living_room_door_lock_led,OUTPUT);
pinMode(living_room_door_lock_ldr,INPUT);
pinMode(living_room_door_open_ldr,INPUT);
pinMode(gallery_door_open_led,OUTPUT);
pinMode(gallery_door_open_ldr,INPUT);
digitalWrite(buzzer,LOW);
digitalWrite(passage_door_open_led,HIGH);
digitalWrite(passage_door_lock_led,HIGH);
analogWrite(passage_door_open_ldr,1023);
analogWrite(passage_door_lock_ldr,1023);
digitalWrite(passage_door_bell_led,HIGH);
analogWrite(passage_door_bell_switch,1023);
analogWrite(pir_1,1023);
analogWrite(pir_2,1023);
analogWrite(pir_3,1023);
digitalWrite(living_room_door_open_led,HIGH);
digitalWrite(living_room_door_lock_led,HIGH);
analogWrite(living_room_door_lock_ldr,1023);
analogWrite(living_room_door_open_ldr,1023);
digitalWrite(gallery_door_open_led,HIGH);
analogWrite(gallery_door_open_ldr,1023);
analogWrite(pir_1,0);
analogWrite(pir_2,0);
analogWrite(pir_3,0);
}
| [
"kaustubhcs07@gmail.com"
] | kaustubhcs07@gmail.com |
158440f78aac2c4880d01eb933291266822cdba7 | 3285e052b9d7e492160c91116a698193a6337d28 | /Graphic_base/formgraph.cpp | 27b8a682f8f78ef79158fd1b608558c9da5e4738 | [] | no_license | Schuka48/Ghost | 483771b362fb4d11d7ed55bb8e45667526d77e8d | e9313ff359faba9e258d724839842f88231dc36d | refs/heads/main | 2023-06-21T20:04:33.462765 | 2021-07-21T15:18:52 | 2021-07-21T15:18:52 | 381,788,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,180 | cpp | #include "formgraph.h"
#include "ui_formgraph.h"
#include <QJsonDocument>
FormGraph::FormGraph(QWidget *parent) :
QWidget(parent), ui(new Ui::FormGraph),
_source(nullptr), connFlag(false)
{
ui->setupUi(this);
dlgInput = new DlgInput();
connect(ui->btnCreateNode, &QPushButton::clicked, this, &FormGraph::onBtnCreateNodeClicked);
connect(ui->btnConnectNode, &QPushButton::clicked, this, &FormGraph::onBtnConnectNodeClicked);
connect(ui->btnDelete, &QPushButton::clicked, this, &FormGraph::onBtnDeleteClicked);
connect(ui->grafViewScene->scene(), &QGraphicsScene::selectionChanged, this, &FormGraph::sceneSelectionChanged);
connect(dlgInput->btnApply, &QPushButton::clicked, this, &FormGraph::onBtnApplyClicked);
connect(ui->grafViewScene, &GraphWidget::editItem, this, &FormGraph::showInput);
}
FormGraph::~FormGraph()
{
ui->grafViewScene->scene()->clearSelection();
nodes.clear();
edges.clear();
delete ui;
delete dlgInput;
}
void FormGraph::closeEvent(QCloseEvent */*event*/)
{
dlgInput->close();
// Важно! disconnect нужен для корректного выхода из приложения!
disconnect(ui->grafViewScene->scene(), nullptr, nullptr, nullptr);
}
void FormGraph::showInput()
{
if (ui->grafViewScene->scene()->selectedItems().size() == 0) { // nullptr
// Ничего не выделено
dlgInput->lTipInput->clear();
dlgInput->eInput->clear();
//dlgInput->eInput->setEnabled(false);
dlgInput->hide();
} else {
QGraphicsItem *it;
it = ui->grafViewScene->scene()->selectedItems().at(0);
//dlgInput->eInput->setEnabled(true);
if (Node *n = dynamic_cast<Node *>(it)) {
dlgInput->lTipInput->setText("Введите текст");
dlgInput->eInput->setText(n->textContent());
} else if (EdgeParent *e = dynamic_cast<EdgeParent *>(it)) {
dlgInput->lTipInput->setText("Введи текст");
dlgInput->eInput->setText(e->textContent());
}
//dlgInput->show();
//dlgInput->raise();
//dlgInput->activateWindow();
dlgInput->exec();
}
}
void FormGraph::onBtnCreateNodeClicked()
{
ui->btnConnectNode->setChecked(false);
int x, y; // расположение вершины на сцене
int numNode = 0;
bool flFinding = false; // флаг нахождения, при решение с каким состоянием создавать вершину
Node *node;
node = new Node(ui->grafViewScene);
numNode = node->id();
// Определяет сколько вершин будут появлятся на одной оси У
int nodeInRow = 6;
x = - 2 * (2 * Node::Radius + 10) +
((!flFinding ? numNode : nodes.size()) % nodeInRow)
* (2 * Node::Radius + 10);
y = -100 + 2 * Node::Radius + 10 +
((!flFinding ? numNode : nodes.size()) / nodeInRow)
* (2 * Node::Radius + 10);
nodes.append(node);
node->setPos(x, y);
_source = nullptr;
connFlag = 0;
ui->lTip->setText("Добавлена вершина.");
if (nodes.size()==9){
ui->btnCreateNode->setEnabled(false);
}
}
void FormGraph::onBtnConnectNodeClicked()
{
if (ui->grafViewScene->scene()->selectedItems().size() > 0) {
_source = dynamic_cast<Node *> (ui->grafViewScene->scene()->selectedItems().at(0));
if (_source) {
ui->grafViewScene->scene()->clearSelection();
ui->lTip->setText("Выберите, куда будет проведена дуга.");
connFlag = 2;
} else {
ui->lTip->clear();
connFlag = 0;
}
}
/* if (!_source) {
if (connFlag == 0) { // это условие не обязательное
lTip->setText("Выберите вершину источник, потом получатель дуги");
connFlag = 1;
grafViewScene->scene()->clearSelection();
}
}*/
}
void FormGraph::onBtnDeleteClicked()
{
if (ui->grafViewScene->scene()->selectedItems().size()) {
_source = nullptr;
connFlag = 0;
auto i = ui->grafViewScene->scene()->selectedItems().at(0);
if (Node* n = dynamic_cast<Node*>(i)) {
foreach (auto e, n->edges()) {
edges.removeAll(e);
}
if (n) {
nodes.removeAll(n);
} else {
qDebug() << "dynamic_cast returned 0";
}
ui->btnCreateNode->setEnabled(true);
ui->lTip->setText("Вершина удалена.");
} else if (EdgeParent *e = dynamic_cast<EdgeParent*>(i)) {
if (e) {
edges.removeAll(e);
} else {
qDebug() << "dynamic_cast returned 0";
}
ui->lTip->setText("Дуга удалена.");
} else {
qDebug() << tr("I don't know what it is. type == %1").arg(i->type());
}
ui->grafViewScene->scene()->removeItem(i);
delete i;
}
}
void FormGraph::eInputTextChange()
{
if(dlgInput->eInput->text().size() != 0 && dlgInput->eInput->hasAcceptableInput()) {
dlgInput->btnApply->setEnabled(true);
} else {
dlgInput->btnApply->setEnabled(false);
}
}
void FormGraph::onBtnApplyClicked()
{
if (dlgInput->eInput->hasAcceptableInput()){
if (ui->grafViewScene->scene()->selectedItems().size() != 1) {
qDebug() << "grafViewScene->scene()->selectedItems().size() == "
<< ui->grafViewScene->scene()->selectedItems().size();
return;
}
auto it = ui->grafViewScene->scene()->selectedItems().at(0);
NodeEdgeParent *nodeEdge = dynamic_cast<NodeEdgeParent*>(it);
if (nodeEdge) {
nodeEdge->setTextContent(dlgInput->eInput->text());
} else { // if (it->type() == Edge::Type) {
qDebug() << "It does not NodeEdgeParent";
}
dlgInput->hide();
} else {
dlgInput->lTipInput->setText("Неверный формат.");
}
}
void FormGraph::sceneSelectionChanged()
{
dlgInput->hide();
QList<QGraphicsItem *> l = ui->grafViewScene->scene()->selectedItems();
if (l.size() == 1) {
ui->lTip->setText("Выделена вершина.");
if (Node *node = dynamic_cast<Node *>(l.at(0))) {
// Выделена вершина!
ui->btnConnectNode->setEnabled(true);
if (connFlag == 1) {
// Назначен "Источник"
_source = node;
connFlag = 2;
ui->lTip->setText("Выберите вершину куда будет проведена дуга.");
} else if (connFlag == 2) {
// Нужно соединить с новой вершиной
EdgeParent *e;
if (_source == node) {
e = new EdgeCircle(_source);
} else {
e = new Edge(_source, node);
}
edges.append(e);
ui->btnConnectNode->setChecked(false);
connFlag = 0;
_source = nullptr;
} else if (connFlag==3){
}
} else {
// Выделена стрелка
ui->lTip->setText("Выделена дуга.");
ui->btnConnectNode->setEnabled(false);
connFlag = false;
_source = nullptr;
}
ui->btnDelete->setEnabled(true);
} else if (l.size() > 1) {
// Всегда должено быть выделено не более 1ого элемента
qDebug() << "grafViewScene->scene()->selectedItems().size() == " << l.size();
} else {
// Пропало выделение (после удаления или нажатия на "Соединить")
ui->lTip->setText("");
ui->btnDelete->setEnabled(false);
ui->btnConnectNode->setEnabled(false);
}
}
void FormGraph::savePng(QString fileName) const
{
QPixmap pixMap = QPixmap::grabWidget(ui->grafViewScene);
pixMap.save(fileName);
}
bool FormGraph::saveGraph(QString fileName, bool jsonFormat) const
{
QFile saveFile(fileName);
if (!saveFile.open(QIODevice::WriteOnly)) {
qWarning("Couldn't open save file.");
return false;
}
QJsonObject graphJson;
// automat->writeToJson(graphJson); // automat
ui->grafViewScene->writeToJson(graphJson); // scene
QJsonArray jsonNodes;
std::for_each(nodes.begin(), nodes.end(), [&] (Node *n) {
QJsonObject json;
n->writeToJson(json);
jsonNodes.append(json); });
graphJson["nodes"] = jsonNodes; // nodes
QJsonArray jsonEdges;
std::for_each(edges.begin(), edges.end(), [&] (EdgeParent *e) {
QJsonObject json;
e->writeToJson(json);
jsonEdges.append(json); });
graphJson["edges"] = jsonEdges; // edges
QJsonDocument saveDoc(graphJson);
saveFile.write(jsonFormat ?
saveDoc.toJson()
: saveDoc.toBinaryData());
saveFile.close();
return true;
}
void FormGraph::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Delete:
onBtnDeleteClicked();
break;
case Qt::Key_N:
case 1058:
onBtnCreateNodeClicked();
break;
case Qt::Key_C:
case 1057:
onBtnConnectNodeClicked();
break;
default:
break;
}
QWidget::keyPressEvent(event);
}
FormGraph *FormGraph::openGraph(QString fileName, bool jsonFormat) {
QFile loadFile(fileName);
if (!loadFile.open(QIODevice::ReadOnly)) {
qWarning("Couldn't open graph file.");
return nullptr;
}
QByteArray saveData = loadFile.readAll();
QJsonDocument loadDoc(jsonFormat ?
QJsonDocument::fromJson(saveData)
: QJsonDocument::fromBinaryData(saveData));
const QJsonObject json = loadDoc.object(); // тут всё
FormGraph *g = new FormGraph;
g->ui->grafViewScene->readFromJson(json); // scene
if (missKeys(json, QStringList { "nodes", "edges" })) {
delete g;
return nullptr;
}
QJsonArray jsonNodes = json["nodes"].toArray();
std::for_each(jsonNodes.begin(), jsonNodes.end(), [&] (QJsonValue j) {
Node *n = new Node(g->ui->grafViewScene);
n->readFromJson(j.toObject());
g->nodes.append(n);
});
QJsonArray jsonEdges = json["edges"].toArray();
std::for_each(jsonEdges.begin(), jsonEdges.end(), [&] (QJsonValue j) {
EdgeParent *e = EdgeParent::create(j.toObject(), g->ui->grafViewScene);
g->edges.append(e);
});
g->ui->btnConnectNode->setEnabled(false);
g->ui->btnDelete->setEnabled(false);
return g;
}
| [
"artem.shchukin.2000@mail.ru"
] | artem.shchukin.2000@mail.ru |
93ef035a42a7ba146d4a0abfd7af4ed709b3c046 | 415b65fc161ca9dc99b99c409c039864471fe131 | /Customer/customer.h | 878346d9a3241ca321624621166184245d207e12 | [] | no_license | Austin0077/Cpp | c87bf9e9821d729faea328eeec8215209e18ed0c | 862753680a83d12d86b877e6de8baee74d3fc1c3 | refs/heads/master | 2021-09-03T23:06:14.455575 | 2018-01-12T18:20:29 | 2018-01-12T18:20:29 | 105,043,560 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 288 | h | # include<iostream>
#include <string>
using namespace std;
class Customer
{
private:
int Id;
string Fname;
string Sname;
double Credit;
public:
void setid(int);
void setFname(string);
void setSname(string);
void setCredit(double);
void Display();
};
| [
"austinqweyu@gmail.com"
] | austinqweyu@gmail.com |
32f56ed8ee3266d588edc9f946f355b01579dae0 | a615c4057ddb49f14dca11a45947fdacfebb5c1c | /Graphics/XYQ/Sprite2.h | bf9376c518abae61c3bea2b69d4dfb0e8dd5a839 | [] | no_license | oceancx/XYQEngine | 6dae130cbb997f585fd9b2a5a8965c3d7fddc3cd | 6f93e788d5df2d34774f51f6cae2ff52b3024094 | refs/heads/master | 2021-01-12T04:44:34.328169 | 2017-02-28T13:23:18 | 2017-02-28T13:23:18 | 77,779,051 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 491 | h | #ifndef SPRITE2_H
#define SPRITE2_H
#include "../../defines.h"
#include <vector>
/*
一个动画序列组
*/
class Sprite2
{
public:
Sprite2();
~Sprite2();
int mGroupSize; //方向数
int mFrameSize; //帧数
int mWidth; //宽度
int mHeight; //高度
int mKeyX; //关键帧X
int mKeyY; //关键帧Y
struct Sequence
{
int key_x;
int key_y;
int width;
int height;
uint32 format;
uint32* src;
};
Sequence** mFrames;
void SaveImage(int index);
};
#endif | [
"oceancx@gmail.com"
] | oceancx@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.