text stringlengths 54 60.6k |
|---|
<commit_before>ac7b70da-35ca-11e5-a85c-6c40088e03e4<commit_msg>ac8237dc-35ca-11e5-b348-6c40088e03e4<commit_after>ac8237dc-35ca-11e5-b348-6c40088e03e4<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
using namespace std;
bool isKlinker(const char a){
bool res = false;
if(a == 'a'){
res = true;
} else if(a == 'e'){
res = true;
} else if(a == 'i'){
res = true;
} else if(a == 'o'){
res = true;
} else if(a == 'u'){
res = true;
}
return res;
}
class Generator {
private:
string s;
public:
void setString(string str);
string getPPConversion();
string getPPConversion(string str);
};
void Generator::setString(string str){
s = str;
}
string Generator::getPPConversion(){
string res = "";
for(int i = 0; i< s.length(); i++){
if(isKlinker(s[i])){
res += s[i];
res += 'p';
}
res += s[i];
}
return res;
}
string Generator::getPPConversion(string str){
setString(str);
return getPPConversion();
}
int main(){
string input;
Generator gen;
cout << "Schrijf een woord: ";
cin >> input;
gen.setString(input);
cout << "'" << input << "' " << "in pepekestaal is: '"
<< gen.getPPConversion() << "'" <<endl;
return 0;
}<commit_msg>added function to generator class<commit_after>#include <iostream>
#include <string>
using namespace std;
class Generator {
private:
string s;
bool isKlinker(const char a);
public:
void setString(string str);
string getPPConversion();
string getPPConversion(string str);
};
bool Generator::isKlinker(const char a){
bool res = false;
if(a == 'a'){
res = true;
} else if(a == 'e'){
res = true;
} else if(a == 'i'){
res = true;
} else if(a == 'o'){
res = true;
} else if(a == 'u'){
res = true;
}
return res;
}
void Generator::setString(string str){
s = str;
}
string Generator::getPPConversion(){
string res = "";
for(int i = 0; i< s.length(); i++){
if(isKlinker(s[i])){
res += s[i];
res += 'p';
}
res += s[i];
}
return res;
}
string Generator::getPPConversion(string str){
setString(str);
return getPPConversion();
}
int main(){
string input;
Generator gen;
cout << "Schrijf een woord: ";
cin >> input;
gen.setString(input);
cout << "'" << input << "' " << "in pepekestaal is: '"
<< gen.getPPConversion() << "'" <<endl;
return 0;
}<|endoftext|> |
<commit_before>5e589400-2d16-11e5-af21-0401358ea401<commit_msg>5e589401-2d16-11e5-af21-0401358ea401<commit_after>5e589401-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>d9c9fbf3-313a-11e5-a313-3c15c2e10482<commit_msg>d9cf631c-313a-11e5-8b81-3c15c2e10482<commit_after>d9cf631c-313a-11e5-8b81-3c15c2e10482<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
#define MAXN 100005
#define clip(X) min(X,10000)
// IMPLEMENTACAO/TESTES
// procurar formulas menores nas maiores, mais ou menos R² * d(phi) (melhoria1)
// dp para otimizar o renaming limitando o nro maximo de literais (melhoria2)
// procurar um benchmark e adaptar a entrada para ele
// adaptar a saida para algum provador, colocando em CNF
// MONOGRAFIA
// colocar exemplo 3.2
// formula
enum {CONJ=0,DISJ,IMPL,EQUI,NEGA,ATOM};
struct Vertex {
char type;
int literal;
int up;
vector<int> down;
int p;
Vertex() : p(1) {}
} G[MAXN];
int V = 0;
// create tree parsing formula from string
// first: tree
// second: number of literals
pair<vector<Vertex>,int> parse(string phi) {
// tells if a character is valid for a variable name
auto isvarsym = [](char c) {
return
('0' <= c && c <= '9') ||
('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z')
;
};
vector<Vertex> ret(1);
ret.back().type = CONJ;
ret.back().up = 0;
stack<int> S;
S.push(0);
map<string,int> id;
int nextlit = 1;
for (int i = 0; i < phi.size(); i++) {
char c = phi[i];
if (c == ' ' || c == '\t') continue;
else if (c == '&') ret[S.top()].type = CONJ;
else if (c == '|') ret[S.top()].type = DISJ;
else if (c == '=') { ret[S.top()].type = IMPL; i++; }
else if (c == '<') { ret[S.top()].type = EQUI; i += 2; }
else if (c == '(' || c == '~') { // push
S.push(ret.size());
ret.emplace_back();
ret.back().type = (c == '(' ? CONJ : NEGA);
}
else if (c == ')') { // pop
int u = S.top();
S.pop();
ret[u].up = S.top();
ret[S.top()].down.push_back(u);
// removing multiple parentheses
if (ret[u].type != NEGA && ret[u].down.size() == 1) {
int u1 = ret[u].down.front();
ret[u].type = ret[u1].type;
ret[u].down = ret[u1].down;
for (int v : ret[u].down) ret[v].up = u;
}
}
else { // literal
string tmp = {phi[i]};
while (i+1 < phi.size() && isvarsym(phi[i+1])) tmp += phi[++i];
int& lit = id[tmp];
if (!lit) lit = nextlit++;
ret[S.top()].down.push_back(ret.size());
ret.emplace_back();
ret.back().type = ATOM;
ret.back().literal = lit;
ret.back().up = S.top();
if (ret[S.top()].type == NEGA) { phi[i] = ')'; i--; }
}
}
// removing multiple parentheses
if (ret[0].down.size() == 1) {
int u = ret[0].down.front();
ret[0].type = ret[u].type;
ret[0].down = ret[u].down;
for (int v : ret[0].down) ret[v].up = 0;
}
return make_pair(ret,id.size());
}
void nnf(vector<Vertex>& T) {
// copy tree rooted at u
function<int(int)> copy = [&](int u) {
int nu = T.size(); T.emplace_back();
T[nu].type = T[u].type;
T[nu].literal = T[u].literal;
for (int v : T[u].down) {
int tmp = copy(v);
T[tmp].up = nu;
T[nu].down.push_back(tmp);
}
return nu;
};
// remove implications and equivalences
function<void(int)> dfs1 = [&](int u) {
if (T[u].type == IMPL) {
T[u].type = DISJ;
int v = T[u].down.front();
int negi = T.size(); T.emplace_back();
T[negi].type = NEGA;
T[u].down.front() = negi;
T[negi].up = u;
T[negi].down.push_back(v);
T[v].up = negi;
}
else if (T[u].type == EQUI) {
auto f = [&](int a, int b) {
int impi = T.size(); T.emplace_back();
T[impi].type = IMPL;
T[u].down.push_back(impi);
T[impi].up = u;
T[impi].down.push_back(a), T[impi].down.push_back(b);
T[a].up = impi, T[b].up = impi;
};
T[u].type = CONJ;
int a = T[u].down.front(), b = T[u].down.back();
int c = copy(b), d = copy(a);
T[u].down.clear();
f(a,b);
f(c,d);
}
for (int v : T[u].down) dfs1(v);
};
dfs1(0);
// remove negations
function<void(int,bool)> dfs2 = [&](int u, bool neg) {
if (!neg) {
if (T[u].type == NEGA) {
auto& phi1 = T[T[u].down.front()];
if (phi1.type == NEGA) {
auto& phi2 = T[phi1.down.front()];
T[u].type = phi2.type;
T[u].literal = phi2.literal;
T[u].down = phi2.down;
for (int v : T[u].down) T[v].up = u;
phi1.type = CONJ, phi2.type = CONJ; // removing phi1 and phi2
}
else if (phi1.type != ATOM) { // CONJ or DISJ
T[u].type = (phi1.type == CONJ ? DISJ : CONJ);
T[u].down = phi1.down;
for (int v : T[u].down) T[v].up = u;
phi1.type = CONJ; // removing phi1
neg = true;
}
}
}
else {
if (T[u].type == NEGA) {
auto& phi1 = T[T[u].down.front()];
T[u].type = phi1.type;
T[u].literal = phi1.literal;
T[u].down = phi1.down;
for (int v : T[u].down) T[v].up = u;
phi1.type = CONJ; // removing phi1
neg = false;
}
else if (T[u].type != ATOM) { // CONJ or DISJ
T[u].type = (T[u].type == CONJ ? DISJ : CONJ);
}
else { // ATOM
int atmi = copy(u);
T[u].type = NEGA;
T[u].down.push_back(atmi);
T[atmi].up = u;
neg = false;
}
}
for (int v : T[u].down) dfs2(v,neg);
};
dfs2(0,false);
}
// build DAG from tree T
void build(const vector<Vertex>& T) {
map<int,int> lit_newu;
map<int,multiset<int>> oldp_newc;
V = 1;
// create vertices for literals
for (int i = 0; i < T.size(); i++) if (T[i].type == ATOM) {
auto& phi = T[i];
int& u = lit_newu[phi.literal];
if (!u) {
u = ++V;
G[u].type = ATOM;
G[u].literal = phi.literal;
}
oldp_newc[phi.up].insert(u);
}
// search tree bottom-up to create vertices for subformulas
for (map<multiset<int>,int> newc_newp; !oldp_newc.empty();) {
list<pair<int,int>> tmp;
for (auto kv = oldp_newc.begin(); kv != oldp_newc.end();) {
auto& phi = T[kv->first];
if (kv->second.size() < phi.down.size()) { kv++; continue; }
int& u = newc_newp[kv->second];
if (!u) {
u = (phi.up != kv->first) ? ++V : 1;
G[u].type = phi.type;
for (int v : kv->second) G[u].down.push_back(v);
}
if (phi.up != kv->first) tmp.emplace_back(phi.up,u);
oldp_newc.erase(kv++);
}
for (auto& kv : tmp) oldp_newc[kv.first].insert(kv.second);
}
}
// position of u in a reverse toposort
int pos(int u) {
static int next = 1, dp[MAXN] = {};
int& ans = dp[u];
if (ans) return ans;
for (int v : G[u].down) pos(v);
return ans = next++;
}
// p(phi(u))
int p(int u) {
static int dp[MAXN] = {};
int& ans = dp[u];
if (ans) return ans;
switch (G[u].type) {
case CONJ: ans = 0; for (int v : G[u].down) ans = clip(ans+p(v)); break;
case DISJ: ans = 1; for (int v : G[u].down) ans = clip(ans*p(v)); break;
default: ans = 1; break;
}
return ans;
}
// Boy de la Tour's top-down renaming
vector<int> R;
int nextR;
void R_rec(int u, int a) {
auto& phi = G[u];
if (phi.p == 1) return;
// check renaming condition
bool renamed = false;
if (a > 1) {
a = 1;
renamed = true;
}
// search children
if (phi.type == CONJ) {
for (int v : phi.down) R_rec(v,a);
phi.p = 0; for (int v : phi.down) phi.p = clip(phi.p+G[v].p);
}
else { // phi.type == DISJ
int n = phi.down.size();
vector<int> dp(n,1); // dp[i] = prod(phi_j.p), i < j < n
for (int i = n-2; 0 <= i; i--) dp[i] = clip(G[phi.down[i+1]].p*dp[i+1]);
int ai = a; // ai = a*prod(phi_j.p), 0 <= j < i
for (int i = 0; i < n; i++) {
R_rec(phi.down[i],clip(ai*dp[i]));
ai = clip(ai*G[phi.down[i]].p);
}
phi.p = 1; for (int v : phi.down) phi.p = clip(phi.p*G[v].p);
}
if (renamed) {
R.push_back(u);
phi.type |= (1<<7);
phi.literal = nextR++;
phi.p = 1;
}
}
// pretty print a formula
string array2str(Vertex formula[], int root) {
stringstream ss;
function<void(int)> dfs = [&](int u) {
auto& phi = formula[u];
if (phi.type == ATOM || phi.type&(1<<7)) {
ss << "p" << phi.literal;
return;
}
if (phi.type == NEGA) {
ss << "~";
dfs(phi.down.front());
return;
}
ss << "(";
char op = phi.type == CONJ ? '&' : '|';
bool printed = false;
for (int u : phi.down) {
if (printed) ss << " " << op << " ";
printed = true;
dfs(u);
}
ss << ")";
};
auto& phi = formula[root];
char op = phi.type == CONJ ? '&' : '|';
bool printed = false;
for (int u : phi.down) {
if (printed) ss << " " << op << " ";
printed = true;
dfs(u);
}
return ss.str();
}
int main() {
// input
string phi;
getline(cin,phi);
// preprocess
auto tree = parse(phi);
nnf(tree.first);
build(tree.first);
auto toposort = [](int u, int v){ return pos(u) < pos(v); };
for (int u = 1; u <= V; u++) {
auto& phi = G[u];
sort(phi.down.begin(),phi.down.end(),toposort);
phi.p = p(u);
}
cout << array2str(G,1) << endl;
// renaming
nextR = tree.second+1;
R_rec(1,1);
// output
cout << "(" << array2str(G,1) << ")";
for (int u : R) {
auto& phi = G[u];
phi.type &= ~(1<<7);
cout << " & (~p" << phi.literal << " | (" << array2str(G,u) << "))";
phi.type |= (1<<7);
}
cout << endl;
return 0;
}
<commit_msg>Improving comments<commit_after>#include <bits/stdc++.h>
using namespace std;
#define MAXN 100005
#define clip(X) min(X,10000)
// IMPLEMENTACAO/TESTES
// procurar formulas menores nas maiores, mais ou menos R² * d(phi) (melhoria1)
// dp para otimizar o renaming limitando o nro maximo de literais (melhoria2)
// procurar um benchmark e adaptar a entrada para ele
// adaptar a saida para algum provador, colocando em CNF
// MONOGRAFIA
// colocar exemplo 3.2
// formula
enum {CONJ=0,DISJ,IMPL,EQUI,NEGA,ATOM};
struct Vertex {
char type;
int literal;
int up;
vector<int> down;
int p;
Vertex() : p(1) {}
} G[MAXN];
int V = 0;
// parse string to create tree
// first: tree
// second: number of literals
pair<vector<Vertex>,int> parse(string phi) {
// tells if a character is valid for a variable name
auto isvarsym = [](char c) {
return
('0' <= c && c <= '9') ||
('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z')
;
};
vector<Vertex> ret(1);
ret.back().type = CONJ;
ret.back().up = 0;
stack<int> S;
S.push(0);
map<string,int> id;
int nextlit = 1;
for (int i = 0; i < phi.size(); i++) {
char c = phi[i];
if (c == ' ' || c == '\t') continue;
else if (c == '&') ret[S.top()].type = CONJ;
else if (c == '|') ret[S.top()].type = DISJ;
else if (c == '=') { ret[S.top()].type = IMPL; i++; }
else if (c == '<') { ret[S.top()].type = EQUI; i += 2; }
else if (c == '(' || c == '~') { // push
S.push(ret.size());
ret.emplace_back();
ret.back().type = (c == '(' ? CONJ : NEGA);
}
else if (c == ')') { // pop
int u = S.top();
S.pop();
ret[u].up = S.top();
ret[S.top()].down.push_back(u);
// removing multiple parentheses
if (ret[u].type != NEGA && ret[u].down.size() == 1) {
int u1 = ret[u].down.front();
ret[u].type = ret[u1].type;
ret[u].down = ret[u1].down;
for (int v : ret[u].down) ret[v].up = u;
}
}
else { // literal
string tmp = {phi[i]};
while (i+1 < phi.size() && isvarsym(phi[i+1])) tmp += phi[++i];
int& lit = id[tmp];
if (!lit) lit = nextlit++;
ret[S.top()].down.push_back(ret.size());
ret.emplace_back();
ret.back().type = ATOM;
ret.back().literal = lit;
ret.back().up = S.top();
if (ret[S.top()].type == NEGA) { phi[i] = ')'; i--; }
}
}
// removing multiple parentheses
if (ret[0].down.size() == 1) {
int u = ret[0].down.front();
ret[0].type = ret[u].type;
ret[0].down = ret[u].down;
for (int v : ret[0].down) ret[v].up = 0;
}
return make_pair(ret,id.size());
}
void nnf(vector<Vertex>& T) {
// copy tree rooted at u
function<int(int)> copy = [&](int u) {
int nu = T.size(); T.emplace_back();
T[nu].type = T[u].type;
T[nu].literal = T[u].literal;
for (int v : T[u].down) {
int tmp = copy(v);
T[tmp].up = nu;
T[nu].down.push_back(tmp);
}
return nu;
};
// remove implications and equivalences
function<void(int)> dfs1 = [&](int u) {
if (T[u].type == IMPL) {
T[u].type = DISJ;
int v = T[u].down.front();
int negi = T.size(); T.emplace_back();
T[negi].type = NEGA;
T[u].down.front() = negi;
T[negi].up = u;
T[negi].down.push_back(v);
T[v].up = negi;
}
else if (T[u].type == EQUI) {
auto f = [&](int a, int b) {
int impi = T.size(); T.emplace_back();
T[impi].type = IMPL;
T[u].down.push_back(impi);
T[impi].up = u;
T[impi].down.push_back(a), T[impi].down.push_back(b);
T[a].up = impi, T[b].up = impi;
};
T[u].type = CONJ;
int a = T[u].down.front(), b = T[u].down.back();
int c = copy(b), d = copy(a);
T[u].down.clear();
f(a,b);
f(c,d);
}
for (int v : T[u].down) dfs1(v);
};
dfs1(0);
// remove negations
function<void(int,bool)> dfs2 = [&](int u, bool neg) {
if (!neg) {
if (T[u].type == NEGA) {
auto& phi1 = T[T[u].down.front()];
if (phi1.type == NEGA) {
auto& phi2 = T[phi1.down.front()];
T[u].type = phi2.type;
T[u].literal = phi2.literal;
T[u].down = phi2.down;
for (int v : T[u].down) T[v].up = u;
phi1.type = CONJ, phi2.type = CONJ; // removing phi1 and phi2
}
else if (phi1.type != ATOM) { // CONJ or DISJ
T[u].type = (phi1.type == CONJ ? DISJ : CONJ);
T[u].down = phi1.down;
for (int v : T[u].down) T[v].up = u;
phi1.type = CONJ; // removing phi1
neg = true;
}
}
}
else {
if (T[u].type == NEGA) {
auto& phi1 = T[T[u].down.front()];
T[u].type = phi1.type;
T[u].literal = phi1.literal;
T[u].down = phi1.down;
for (int v : T[u].down) T[v].up = u;
phi1.type = CONJ; // removing phi1
neg = false;
}
else if (T[u].type != ATOM) { // CONJ or DISJ
T[u].type = (T[u].type == CONJ ? DISJ : CONJ);
}
else { // ATOM
int atmi = copy(u);
T[u].type = NEGA;
T[u].down.push_back(atmi);
T[atmi].up = u;
neg = false;
}
}
for (int v : T[u].down) dfs2(v,neg);
};
dfs2(0,false);
}
// build DAG from tree T
void build(const vector<Vertex>& T) {
map<int,int> lit_newu;
map<int,multiset<int>> oldp_newc;
V = 1;
// create vertices for literals
for (int i = 0; i < T.size(); i++) if (T[i].type == ATOM) {
auto& phi = T[i];
int& u = lit_newu[phi.literal];
if (!u) {
u = ++V;
G[u].type = ATOM;
G[u].literal = phi.literal;
}
oldp_newc[phi.up].insert(u);
}
// search tree bottom-up to create vertices for subformulas
for (map<multiset<int>,int> newc_newp; !oldp_newc.empty();) {
list<pair<int,int>> tmp;
for (auto kv = oldp_newc.begin(); kv != oldp_newc.end();) {
auto& phi = T[kv->first];
if (kv->second.size() < phi.down.size()) { kv++; continue; }
int& u = newc_newp[kv->second];
if (!u) {
u = (phi.up != kv->first) ? ++V : 1;
G[u].type = phi.type;
for (int v : kv->second) G[u].down.push_back(v);
}
if (phi.up != kv->first) tmp.emplace_back(phi.up,u);
oldp_newc.erase(kv++);
}
for (auto& kv : tmp) oldp_newc[kv.first].insert(kv.second);
}
}
// position of u in a reverse toposort
int pos(int u) {
static int next = 1, dp[MAXN] = {};
int& ans = dp[u];
if (ans) return ans;
for (int v : G[u].down) pos(v);
return ans = next++;
}
// p(phi(u))
int p(int u) {
static int dp[MAXN] = {};
int& ans = dp[u];
if (ans) return ans;
switch (G[u].type) {
case CONJ: ans = 0; for (int v : G[u].down) ans = clip(ans+p(v)); break;
case DISJ: ans = 1; for (int v : G[u].down) ans = clip(ans*p(v)); break;
default: ans = 1; break;
}
return ans;
}
// Boy de la Tour's top-down renaming
vector<int> R;
int nextR;
void R_rec(int u, int a) {
auto& phi = G[u];
if (phi.p == 1) return;
// check renaming condition
bool renamed = false;
if (a > 1) {
a = 1;
renamed = true;
}
// search children
if (phi.type == CONJ) {
for (int v : phi.down) R_rec(v,a);
phi.p = 0; for (int v : phi.down) phi.p = clip(phi.p+G[v].p);
}
else { // phi.type == DISJ
int n = phi.down.size();
vector<int> dp(n,1); // dp[i] = prod(phi_j.p), i < j < n
for (int i = n-2; 0 <= i; i--) dp[i] = clip(G[phi.down[i+1]].p*dp[i+1]);
int ai = a; // ai = a*prod(phi_j.p), 0 <= j < i
for (int i = 0; i < n; i++) {
R_rec(phi.down[i],clip(ai*dp[i]));
ai = clip(ai*G[phi.down[i]].p);
}
phi.p = 1; for (int v : phi.down) phi.p = clip(phi.p*G[v].p);
}
if (renamed) {
R.push_back(u);
phi.type |= (1<<7);
phi.literal = nextR++;
phi.p = 1;
}
}
// pretty print a formula
string array2str(Vertex formula[], int root) {
stringstream ss;
function<void(int)> dfs = [&](int u) {
auto& phi = formula[u];
if (phi.type == ATOM || phi.type&(1<<7)) {
ss << "p" << phi.literal;
return;
}
if (phi.type == NEGA) {
ss << "~";
dfs(phi.down.front());
return;
}
ss << "(";
char op = phi.type == CONJ ? '&' : '|';
bool printed = false;
for (int u : phi.down) {
if (printed) ss << " " << op << " ";
printed = true;
dfs(u);
}
ss << ")";
};
auto& phi = formula[root];
char op = phi.type == CONJ ? '&' : '|';
bool printed = false;
for (int u : phi.down) {
if (printed) ss << " " << op << " ";
printed = true;
dfs(u);
}
return ss.str();
}
int main() {
// input
string phi;
getline(cin,phi);
// preprocess
auto tree = parse(phi);
nnf(tree.first);
build(tree.first);
auto toposort = [](int u, int v){ return pos(u) < pos(v); };
for (int u = 1; u <= V; u++) {
auto& phi = G[u];
sort(phi.down.begin(),phi.down.end(),toposort);
phi.p = p(u);
}
cout << array2str(G,1) << endl;
// renaming
nextR = tree.second+1;
R_rec(1,1);
// output
cout << "(" << array2str(G,1) << ")";
for (int u : R) {
auto& phi = G[u];
phi.type &= ~(1<<7);
cout << " & (~p" << phi.literal << " | (" << array2str(G,u) << "))";
phi.type |= (1<<7);
}
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>0b9f4fa6-2e4f-11e5-a5ab-28cfe91dbc4b<commit_msg>0ba72105-2e4f-11e5-aa37-28cfe91dbc4b<commit_after>0ba72105-2e4f-11e5-aa37-28cfe91dbc4b<|endoftext|> |
<commit_before>1e3922de-2e4f-11e5-b975-28cfe91dbc4b<commit_msg>1e473e5c-2e4f-11e5-a633-28cfe91dbc4b<commit_after>1e473e5c-2e4f-11e5-a633-28cfe91dbc4b<|endoftext|> |
<commit_before>0c701f8c-2e4f-11e5-b08f-28cfe91dbc4b<commit_msg>0c783726-2e4f-11e5-be96-28cfe91dbc4b<commit_after>0c783726-2e4f-11e5-be96-28cfe91dbc4b<|endoftext|> |
<commit_before>ccf00fde-327f-11e5-a3b6-9cf387a8033e<commit_msg>ccf5c73a-327f-11e5-bae9-9cf387a8033e<commit_after>ccf5c73a-327f-11e5-bae9-9cf387a8033e<|endoftext|> |
<commit_before>06b162d2-585b-11e5-b9ba-6c40088e03e4<commit_msg>06b845ca-585b-11e5-856d-6c40088e03e4<commit_after>06b845ca-585b-11e5-856d-6c40088e03e4<|endoftext|> |
<commit_before>bb6daf11-2747-11e6-b81a-e0f84713e7b8<commit_msg>Did ANOTHER thing<commit_after>bb87afa1-2747-11e6-a3dd-e0f84713e7b8<|endoftext|> |
<commit_before>493adc34-2e3a-11e5-980e-c03896053bdd<commit_msg>494a9670-2e3a-11e5-88b3-c03896053bdd<commit_after>494a9670-2e3a-11e5-88b3-c03896053bdd<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>
/*
* Utility:
* ./exectuable pageAddress width height decoration
*
* - pageAddress: the html file path or url
* - width: integer that represent the width of the window
* - height: integer that represent the height of the window
* - decoration: if it is "UNDECORATED" the window will be undecorated (it will not have
* borders and the window buttons
*
* */
QWebView *webView;
/*
* Javascript functions (Public API)
* */
class MyJavaScriptOperations : public QObject {
Q_OBJECT
public:
/*
* Close window
* $API.closeWindow();
*
**/
Q_INVOKABLE void closeWindow () {
webView->close();
}
/*
* Resize
* $API.resize(width, height);
*
**/
Q_INVOKABLE void resize (int width, int height) {
webView->resize(width, height);
}
/*
* Set window flags
* $API.setWindowFlags (type)
* - UNDECORATED
*
* */
Q_INVOKABLE void setWindowFlags (QString type) {
QStringList options;
options << "UNDECORATED";
switch (options.indexOf(type)) {
case 0:
webView->setWindowFlags(Qt::FramelessWindowHint);
webView->show();
break;
// TODO Other cases
}
}
/*
* Set window state
* $API.setWindowState (value)
* - MAXIMIZED
* - MINIMIZED
* - FULLSCREEN
* - ACTIVE
* */
Q_INVOKABLE void setWindowState (QString type) {
QStringList options;
options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE";
switch (options.indexOf(type)) {
case 0:
webView->setWindowState(Qt::WindowMaximized);
break;
case 1:
webView->setWindowState(Qt::WindowMinimized);
break;
case 2:
webView->setWindowState(Qt::WindowFullScreen);
break;
case 3:
webView->setWindowState(Qt::WindowActive);
break;
}
}
/*
* Get window size
* $API.getWindowSize ()
* */
Q_INVOKABLE QObject *getWindowSize () {
QObject *size = new QObject();
QSize winSize = webView->size();
size->setProperty("width", winSize.width());
size->setProperty("height", winSize.height());
return size;
}
/*
* Set window position
* $API.setWindowPosition (left, top)
* */
Q_INVOKABLE void setWindowPosition (int left, int top) {
webView->move(left, top);
}
/*
* Get window position
* $API.getWindowPosition (left, top)
* */
Q_INVOKABLE QObject *getWindowPosition () {
QObject *position = new QObject();
QPoint point = webView->pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Debug
* $API.debug(message)
*
* */
Q_INVOKABLE void debug (QString message) {
qDebug() << message;
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// build the web view
QWebView *view = new QWebView();
webView = view;
// get the html path
QString HTML_PATH = QString(argv[1]);
// the path is NOT a web site url
if (!HTML_PATH.startsWith("htt"))
{
// get it from the local machine
HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
}
// set window width and height
int WINDOW_WIDTH = QString(argv[2]).toInt();
int WINDOW_HEIGHT = QString(argv[3]).toInt();
// handle "UNDECORATED" flag
if (QString(argv[4]) == "UNDECORATED") {
view->setWindowFlags(Qt::FramelessWindowHint);
}
// add the public api functions
view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);
// resize the window
view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);
// load that HTML file or website
view->load(QUrl(HTML_PATH));
// show the web view
view->show();
return app.exec();
}
#include "main.moc"
<commit_msg>Added getMousePosition function. Trying to set transparent background for web view.<commit_after>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>
/*
* Utility:
* ./exectuable pageAddress width height decoration
*
* - pageAddress: the html file path or url
* - width: integer that represent the width of the window
* - height: integer that represent the height of the window
* - decoration: if it is "UNDECORATED" the window will be undecorated (it will not have
* borders and the window buttons
*
* */
QWebView *webView;
/*
* Javascript functions (Public API)
* */
class MyJavaScriptOperations : public QObject {
Q_OBJECT
public:
/*
* Close window
* $API.closeWindow();
*
**/
Q_INVOKABLE void closeWindow () {
webView->close();
}
/*
* Resize
* $API.resize(width, height);
*
**/
Q_INVOKABLE void resize (int width, int height) {
webView->resize(width, height);
}
/*
* Set window flags
* $API.setWindowFlags (type)
* - UNDECORATED
*
* */
Q_INVOKABLE void setWindowFlags (QString type) {
QStringList options;
options << "UNDECORATED";
switch (options.indexOf(type)) {
case 0:
webView->setWindowFlags(Qt::FramelessWindowHint);
webView->show();
break;
// TODO Other cases
}
}
/*
* Set window state
* $API.setWindowState (value)
* - MAXIMIZED
* - MINIMIZED
* - FULLSCREEN
* - ACTIVE
* */
Q_INVOKABLE void setWindowState (QString type) {
QStringList options;
options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE";
switch (options.indexOf(type)) {
case 0:
webView->setWindowState(Qt::WindowMaximized);
break;
case 1:
webView->setWindowState(Qt::WindowMinimized);
break;
case 2:
webView->setWindowState(Qt::WindowFullScreen);
break;
case 3:
webView->setWindowState(Qt::WindowActive);
break;
}
}
/*
* Get window size
* $API.getWindowSize ()
* */
Q_INVOKABLE QObject *getWindowSize () {
QObject *size = new QObject();
QSize winSize = webView->size();
size->setProperty("width", winSize.width());
size->setProperty("height", winSize.height());
return size;
}
/*
* Set window position
* $API.setWindowPosition (left, top)
* */
Q_INVOKABLE void setWindowPosition (int left, int top) {
webView->move(left, top);
}
/*
* Get window position
* $API.getWindowPosition (left, top)
* */
Q_INVOKABLE QObject *getWindowPosition () {
QObject *position = new QObject();
QPoint point = webView->pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Get mouse position
* $API.getMousePosition()
*
* */
Q_INVOKABLE QObject *getMousePosition () {
QObject *position = new QObject();
QPoint point = QCursor::pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Debug
* $API.debug(message)
*
* */
Q_INVOKABLE void debug (QString message) {
qDebug() << message;
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// build the web view
QWebView *view = new QWebView();
webView = view;
// get the html path
QString HTML_PATH = QString(argv[1]);
// the path is NOT a web site url
if (!HTML_PATH.startsWith("htt"))
{
// get it from the local machine
HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
}
// set window width and height
int WINDOW_WIDTH = QString(argv[2]).toInt();
int WINDOW_HEIGHT = QString(argv[3]).toInt();
// handle "UNDECORATED" flag
if (QString(argv[4]) == "UNDECORATED") {
view->setWindowFlags(Qt::FramelessWindowHint);
QPalette palette = view->palette();
palette.setBrush(QPalette::Base, Qt::transparent);
view->page()->setPalette(palette);
view->setAttribute(Qt::WA_OpaquePaintEvent, false);
}
// add the public api functions
view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);
// resize the window
view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);
// load that HTML file or website
view->load(QUrl(HTML_PATH));
// show the web view
view->show();
return app.exec();
}
#include "main.moc"
<|endoftext|> |
<commit_before>8d6dfcfd-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfcfe-2d14-11e5-af21-0401358ea401<commit_after>8d6dfcfe-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>7031cf14-2fa5-11e5-a08c-00012e3d3f12<commit_msg>7033cae4-2fa5-11e5-ad2e-00012e3d3f12<commit_after>7033cae4-2fa5-11e5-ad2e-00012e3d3f12<|endoftext|> |
<commit_before>83000dc6-2d15-11e5-af21-0401358ea401<commit_msg>83000dc7-2d15-11e5-af21-0401358ea401<commit_after>83000dc7-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>be8c71e8-2e4f-11e5-a694-28cfe91dbc4b<commit_msg>be92b5bd-2e4f-11e5-bec3-28cfe91dbc4b<commit_after>be92b5bd-2e4f-11e5-bec3-28cfe91dbc4b<|endoftext|> |
<commit_before>c8ff529c-327f-11e5-9834-9cf387a8033e<commit_msg>c90883cf-327f-11e5-be76-9cf387a8033e<commit_after>c90883cf-327f-11e5-be76-9cf387a8033e<|endoftext|> |
<commit_before>779383b4-2d53-11e5-baeb-247703a38240<commit_msg>779404b0-2d53-11e5-baeb-247703a38240<commit_after>779404b0-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>8fd0491d-2d14-11e5-af21-0401358ea401<commit_msg>8fd0491e-2d14-11e5-af21-0401358ea401<commit_after>8fd0491e-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>7271886c-5216-11e5-a842-6c40088e03e4<commit_msg>72782d66-5216-11e5-8df4-6c40088e03e4<commit_after>72782d66-5216-11e5-8df4-6c40088e03e4<|endoftext|> |
<commit_before>8c3d20d2-2d14-11e5-af21-0401358ea401<commit_msg>8c3d20d3-2d14-11e5-af21-0401358ea401<commit_after>8c3d20d3-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>5e589436-2d16-11e5-af21-0401358ea401<commit_msg>5e589437-2d16-11e5-af21-0401358ea401<commit_after>5e589437-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>98ed4188-35ca-11e5-84a9-6c40088e03e4<commit_msg>98f3cb5c-35ca-11e5-8261-6c40088e03e4<commit_after>98f3cb5c-35ca-11e5-8261-6c40088e03e4<|endoftext|> |
<commit_before>9dab1b63-2e4f-11e5-a261-28cfe91dbc4b<commit_msg>9db6a56b-2e4f-11e5-a9d5-28cfe91dbc4b<commit_after>9db6a56b-2e4f-11e5-a9d5-28cfe91dbc4b<|endoftext|> |
<commit_before>5f8949b0-2d16-11e5-af21-0401358ea401<commit_msg>5f8949b1-2d16-11e5-af21-0401358ea401<commit_after>5f8949b1-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>83000e27-2d15-11e5-af21-0401358ea401<commit_msg>83000e28-2d15-11e5-af21-0401358ea401<commit_after>83000e28-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>e96b89f0-2747-11e6-baa5-e0f84713e7b8<commit_msg>Initial commit.13<commit_after>e974fee1-2747-11e6-aa12-e0f84713e7b8<|endoftext|> |
<commit_before>8d6dfd51-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd52-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd52-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>8cf4ffd8-35ca-11e5-b04b-6c40088e03e4<commit_msg>8cfb561c-35ca-11e5-b3c2-6c40088e03e4<commit_after>8cfb561c-35ca-11e5-b3c2-6c40088e03e4<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <windows.h>
#include <sstream>
#include <ctype.h>
using namespace std;
int main()
{
string url, cont, format, selection;
stringstream update;
//Welcome message
system("color A");
cout << "Welcome to Youtube-dl helper\n\n " << endl;
cout << "This little 'tool' was written by Aljaz Gros" << endl;
cout << "Youtube-dl and FFmpeg belong to their respective owners and are not owned by me" << endl;
cout << "I wrote this just to make downloading/conversion easier for windows users" << endl << endl;
cout << "If you haven't got youtube-dl and/or FFMpeg get them now as they are required for this 'tool' to work properly" << endl;
cout << "If you experiance any ffprobe errors please read README.txt\n\n" << endl;
system("pause");
system("cls");
system("color F"); //Clears text and sets color to bright white after user presses any key
//Selection menu
select:
cout << "What would you like to do?" << endl;
cout << "1) Update" << endl;
cout << "2) Download (no convertion)" << endl;
cout << "2) Download & convert video" << endl;
cout << "Your input: ";
cin >> selection;
string keep_file="";
//If for selection
if(selection == "1")
{
update << "youtube-dl -U";
system(update.str().c_str());
system("pause");
goto select;
}
else if (selection == "2")
{
goto input_noformat;
}
else if (selection == "3")
{
goto input_format;
}
else
{
goto select;
cout << "Wrong input!" << endl;
}
//URL input /w.o converting
input_noformat:
cout << "Input video URL: ";
cin >> url;
system("cls");
goto no_format_skip;
//URL Input /w converting
input_format:
cout << "Input video URL: ";
cin >> url;
system("cls");
//Formats
cout << "Here are recommended formats:"<<endl;
cout << "best (1)" << endl;
cout << "aac (2)" << endl;
cout << "vorbis (3)" << endl;
cout << "mp3 (4)" << endl;
cout << "m4a (5)" << endl;
cout << "opus (6)" << endl;
cout << "wav (7)" << endl;
cout << "Either write in number or input format name on your own" << endl;
cout << "Input format: ";
cin >> format;
//Formats by number
if(format == "1")
{
format="best";
}
else if(format == "2")
{
format="aac";
}
else if(format == "3")
{
format="vorbis";
}
else if(format == "4")
{
format="mp3";
}
else if(format == "5")
{
format="m4a";
}
else if(format == "6")
{
format="opus";
}
else if(format == "7")
{
format="wav";
}
//Keeping original file Y/N
keepfile:
cout << "Would you like to keep original file?(Y/N) ";
cin >> keep_file;
Sleep(1000);
system("cls");
//String for system()
no_format_skip:
stringstream call_line;
if (keep_file == "Y" || keep_file == "y" )
{
call_line << "youtube-dl --output /output/%(title)s.%(ext)s --console-title --k --ignore-errors --extract-audio --audio-quality 0 --audio-format " << format << " " << url;
}
else if (keep_file == "N" || keep_file == "n")
{
call_line << "youtube-dl --output /output/%(title)s.%(ext)s --console-title --ignore-errors --extract-audio --audio-quality 0 --audio-format " << format << " " << url;
}
else if (selection == "2")
{
call_line << "youtube-dl --output /output/%(title)s.%(ext)s --console-title --ignore-errors --audio-quality 0 " << url;
}
else //If input is not Y/y or N/n
{
cout<<"Wrong input";
goto keepfile;
}
system(call_line.str().c_str());
contini:
cout << endl << "To continue write Y to end write N." << endl;
//Returns to start if User inputs Y
cin >> cont;
if(cont=="Y" || cont=="y")
{
goto select;
system("cls");
}
else if(cont=="N" || cont=="n")
{
//Ends program if anything else is input by User than Y or y.
cout << endl << "Ending program" << endl;
Sleep(1000);
return 0;
}
else
{
cout << "Invalid input." <<endl;
goto contini;
}
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <windows.h>
#include <sstream>
#include <ctype.h>
using namespace std;
//Funckija za posodobitev youtube-dl
void posodobitev()
{
stringstream posodobitev_string;
posodobitev_string << "youtube-dl.exe -U"; //String za posodobitev
system(posodobitev_string.str().c_str());
}
//Funkcija za pretvorbo prenesenega videa
void pretvorba_prenesenega() //Trenutno v testni fazi
{
system("cls");
system("cd output & dir /b *.mp4"); //Prikaže vse .mp4 datoteke v mapi output.
cout << "\n" << endl;
cout << "Vnesite naslov videa:" << endl;
cout << "OPOMBA: Naslov vnesi v narekovajih drugace ne bo delovalo!" << endl;
cout << "Naslov: ";
string naslov_videa ="";
cin.ignore();
getline(cin, naslov_videa); //Uporaba getline namesto navadnega cin da zazna celoten vnos z narekovaji.
izbris_prompt:
int izbris;
cout << "\nZelite obdrzati .mp4 datoteko? (1[da]/0[ne]): ";
cin >> izbris;
stringstream premakni_mp4, konvertiraj, premakni_mp3, zbris_mp4, obdrzi_mp4;
cout << naslov_videa;
premakni_mp4 << "cd output & move " << naslov_videa << " .."; //Premakne .mp4 datoteko iz output mape v mapo kjer se nahaja program
konvertiraj << "ffmpeg -i " << naslov_videa << " -c:v lib264 " << naslov_videa << ".mp3"; //Pretvori premaknjeno .mp4 datoteko
premakni_mp3 << "move " << naslov_videa << ".mp3 output"; //Premakne novo .mp3 datoteko katera je bila pretvorjena v mapo output
zbris_mp4 << "del /q /f " << naslov_videa; //Zbrise .mp4 datoteko po pretvorbi
obdrzi_mp4 << "move " << naslov_videa << " output"; //Premakne .mp4 datoteko v primeru da je ne zelimo izbrisati
if(izbris == 1)
{
system(premakni_mp4.str().c_str());
system(konvertiraj.str().c_str());
system(premakni_mp3.str().c_str());
system(obdrzi_mp4.str().c_str());
}
else if (izbris == 0)
{
system(premakni_mp4.str().c_str());
system(konvertiraj.str().c_str());
system(premakni_mp3.str().c_str());
system(zbris_mp4.str().c_str());
}
else
goto izbris_prompt;
}
//Funkcija poslje informacije za formate
void format_info()
{
cout << "\"Hitri\" formati:" << endl;
cout << "1. mp3" << endl;
cout << "2. aac" << endl;
cout << "3. wav" << endl;
cout << "4. vorbis" << endl;
cout << "5. opus" << endl;
cout << "6. m4a" << endl;
cout << "Vpisi stevilko za hitri format ali vpisi ime formata v katerega zelis pretvoriti" << endl;
}
//Funkcija za pretvorbo stevilk hitrih formatov(int) v string
string formati(string vhodni_format)
{
//Program preveri ce je uporabnik uporabil številko za hitri format, ce ne uporabi vpisan format
if(vhodni_format == "1")
{
vhodni_format = "mp3";
}
else if(vhodni_format == "2")
{
vhodni_format = "aac";
}
else if(vhodni_format == "3")
{
vhodni_format = "wav";
}
else if(vhodni_format == "4")
{
vhodni_format = "vorbis";
}
else if(vhodni_format == "5")
{
vhodni_format = "opus";
}
else if(vhodni_format == "6")
{
vhodni_format = "m4a";
}
return vhodni_format;
}
//Funkcija samo za prenos videa
void prenos_videa()
{
string url;
system("cls");
cout << "URL Naslov videa: ";
cin >> url;
stringstream vnos_podatkov;
vnos_podatkov << "youtube-dl.exe --output /output/%(title)s.%(ext)s --console-title --keep-video --ignore-errors -f best " << url; //String za prenos videa v mp4 formatu
system(vnos_podatkov.str().c_str());
}
//Funkcija za prenos in pretvorbo videa
void prenos_in_pretvorba()
{
pip_vnos: //Zaèetek za vnosa; V primeru da uporanbik ne vpiše èesar pravilno ga vrne na zaèetek vpisa za prenos in pretvorbo
string url, format;
int obdrzi;
stringstream obdrzi_datoteko_string, zbrisi_datoteko_string;
system("cls");
cout << "Vnesi URL videa: ";
cin >> url;
format_info();
cout << "Vnesi format: ";
cin >> format;
format=formati(format); //Poklice funkcijo s formati in vrne string v primeru da smo vnesli stevilko.
cout << "Zelite obdrzati izvorno datoteko? (DA [1]/NE [0]) " << endl;
cout << "Vasa izbira: ";
cin >> obdrzi;
switch(obdrzi)
{
//Pretvori izvorno datoteko in jo obdrzi
case 1:
obdrzi_datoteko_string << "youtube-dl.exe --output /output/%(title)s.%(ext)s --console-title --keep-video --ignore-errors --extract-audio --audio-quality 0 --audio-format " << format << " " << url;
system(obdrzi_datoteko_string.str().c_str());
break;
//Izbris izvorne datoteke po pretvorbi
case 0:
zbrisi_datoteko_string << "youtube-dl.exe --output /output/%(title)s.%(ext)s --console-title --ignore-errors --extract-audio --audio-quality 0 --audio-format " << format << " " << url;
system(zbrisi_datoteko_string.str().c_str());
break;
//Povrne uporabnika nazaj na vpis v primeru, da ni vpisal 1(da) ali 0 (ne).
default:
goto pip_vnos;
}
}
int main()
{
int zacetna_izbira;
//Program nastavi pisavo na zeleno barvo in prikaze zagonsko sporocilo
system("color A");
cout << "Dobrodosli v uporabniskem vmesniku za Youtube-dl \n" << endl;
cout << "Program Youtube-dl in ffmpeg sta tuja programa in pripadata svojim lastnikom" << endl;
cout << "Ta program je samo uporabniski vmesnik kateri je namenjen lazji uporabi teh programov" << endl;
//Program pocaka uporabnika, da pritisne tipko za nadaljevanje, pobirse sporocilo in nastavi pisavo nazaj na belo
system("pause");
system("cls");
system("color F");
//Zacetna izbira
zacetek:
cout << "1. Posodobitev" << endl;
cout << "2. Prenos videa" << endl;
cout << "3. Prenos in pretvorba videa" << endl;
cout << "4. Pretvorba prenesenega videa v mp3" << endl;
cout << "0. Izhod iz programa" << endl;
cout << "Vasa izbira: ";
cin >> zacetna_izbira;
//Switch za zacetno izbiro glede na uporabnikov vnos
switch(zacetna_izbira)
{
//Izhod iz programa
case 0:
return 0;
break;
//Program gre na funkcijo za posodobitev
case 1:
posodobitev();
break;
//Funkcija za samo prenos videa
case 2:
prenos_videa();
break;
//Funkcija za prenos in pretvorbo videa
case 3:
prenos_in_pretvorba();
break;
//Funkcija za pretvorbo prenesenih videev
case 4:
pretvorba_prenesenega();
break;
//Vrne uporabnika na zacetek ce je vnesel napacno stevilko
default:
goto zacetek;
cout << "Napacna izbira! Poskusi znova." << endl;
system("pause");
system("cls");
break;
}
//Se izvede po pretvorbi, prenosu ali kater koli drugi funkciji
nadaljevanje:
int nadaljuj;
system("cls");
cout << "Zelite nadaljevati? (DA [1]/NE [0]): " ;
cin >> nadaljuj;
switch(nadaljuj)
{
//Vrne se na zacetek za izbiro funkcij
case 1:
goto zacetek;
break;
//Konca program
case 0:
return 0;
break;
//Pozove uporabnika za ponoven vnos v primeru napacnega vnosa.
default:
cout << "Napacen vnos! Poskusi znova.";
break;
}
}
<|endoftext|> |
<commit_before>8431fbf1-2d15-11e5-af21-0401358ea401<commit_msg>8431fbf2-2d15-11e5-af21-0401358ea401<commit_after>8431fbf2-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>7b27fc94-2749-11e6-a4d7-e0f84713e7b8<commit_msg>lets try again<commit_after>7b338a00-2749-11e6-9ab3-e0f84713e7b8<|endoftext|> |
<commit_before>c6470f40-327f-11e5-b31a-9cf387a8033e<commit_msg>c64e5051-327f-11e5-ae25-9cf387a8033e<commit_after>c64e5051-327f-11e5-ae25-9cf387a8033e<|endoftext|> |
<commit_before>5f894989-2d16-11e5-af21-0401358ea401<commit_msg>5f89498a-2d16-11e5-af21-0401358ea401<commit_after>5f89498a-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>c5429635-2d3c-11e5-ba9a-c82a142b6f9b<commit_msg>c5d9decc-2d3c-11e5-b64d-c82a142b6f9b<commit_after>c5d9decc-2d3c-11e5-b64d-c82a142b6f9b<|endoftext|> |
<commit_before>#include "main.h"
#include <chrono>
int num_rows;
int num_cols;
int num_nonzeros;
std::chrono::duration<double> blaze_time;
std::chrono::duration<double> vcl_time;
std::chrono::duration<double> vexcl_time;
std::chrono::duration<double> elapsed;
std::chrono::time_point<std::chrono::system_clock> start, end;
#include "utils.h"
void ReadSparse(COO& data, const std::string filename) {
std::cout << "Reading: " << filename << std::endl;
std::stringstream ss(ReadFileAsString(filename));
size_t i, j;
double v;
while (true) {
ss >> i;
// Make sure that after reading things are still valid
// If so then the line is good and continue
if (ss.fail() == true) {
break;
}
ss >> j >> v;
data.row.push_back(i);
data.col.push_back(j);
data.val.push_back(v);
}
data.update();
}
void ReadVector(std::vector<double>& data, const std::string filename) {
std::cout << "Reading: " << filename << std::endl;
std::stringstream ss(ReadFileAsString(filename));
double v;
while (true) {
ss >> v;
// Make sure that after reading things are still valid
// If so then the line is good and continue
if (ss.fail() == true) {
break;
}
data.push_back(v);
}
}
int main(int argc, char* argv[]) {
COO D_T, M_invD;
std::vector<double> gamma;
std::cout << "Read in data to sparse COO structure: \n";
start = std::chrono::system_clock::now();
ReadSparse(D_T, "D_T_" + std::string(argv[1]) + ".mat");
ReadSparse(M_invD, "M_invD_" + std::string(argv[1]) + ".mat");
ReadVector(gamma, "gamma_" + std::string(argv[1]) + ".mat");
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to read data from file: " << elapsed.count() << std::endl;
start = std::chrono::system_clock::now();
blaze::CompressedMatrix<double> D_T_blaze = BlazeTest::ConvertMatrix(D_T);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Blaze: " << elapsed.count() << std::endl;
start = std::chrono::system_clock::now();
blaze::CompressedMatrix<double> M_invD_blaze = BlazeTest::ConvertMatrix(M_invD);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load M_invD Blaze: " << elapsed.count() << std::endl;
blaze::DynamicVector<double> gamma_blaze = BlazeTest::ConvertVector(gamma);
{
std::cout << "Blaze Test:\n";
BlazeTest blaze_test;
start = std::chrono::system_clock::now();
blaze_test.RunSPMV(D_T_blaze, M_invD_blaze, gamma_blaze);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Blaze Time: " << elapsed.count() / RUNS << std::endl;
}
std::cout << "Eigen Triplet:\n";
// Convert the COO into Eigen triplets
// Timing this part isn't important, in practice you would not need to do this
std::vector<Eigen::Triplet<double> > D_T_triplet = EigenTest::ConvertCOO(D_T);
std::vector<Eigen::Triplet<double> > M_invD_triplet = EigenTest::ConvertCOO(M_invD);
std::cout << "Eigen Convert:\n";
Eigen::SparseMatrix<double> D_T_eigen(D_T.num_rows, D_T.num_cols);
D_T_eigen.reserve(Eigen::VectorXi::Constant(D_T.num_cols, 12));
Eigen::SparseMatrix<double> M_invD_eigen(M_invD.num_rows, M_invD.num_cols);
start = std::chrono::system_clock::now();
EigenTest::ConvertMatrix(D_T_triplet, D_T, D_T_eigen);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Eigen: " << elapsed.count() << std::endl;
start = std::chrono::system_clock::now();
EigenTest::ConvertMatrix(M_invD_triplet, M_invD, M_invD_eigen);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Eigen: " << elapsed.count() << std::endl;
Eigen::VectorXd gamma_eigen = EigenTest::ConvertVector(gamma);
{
std::cout << "Eigen Test:\n";
start = std::chrono::system_clock::now();
EigenTest::RunSPMV(D_T_eigen, M_invD_eigen, gamma_eigen);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Eigen Time: " << elapsed.count() / RUNS << std::endl;
}
//
// {
// VexCLTest vexcl_test;
// vexcl_test.CreateContext();
// vexcl_test.WarmUp();
// CSR D_T_csr = BlazeTest::ConvertSparse(D_T_blaze);
// CSR M_invD_csr = BlazeTest::ConvertSparse(M_invD_blaze);
// vex::SpMat<double> D_T_vex = vexcl_test.ConvertMatrix(D_T_csr);
// vex::SpMat<double> M_invD_vex = vexcl_test.ConvertMatrix(M_invD_csr);
// vex::vector<double> gamma_vex = vexcl_test.ConvertVector(gamma);
//
// start = std::chrono::system_clock::now();
// vexcl_test.RunSPMV(D_T_vex, M_invD_vex, gamma_vex);
// end = std::chrono::system_clock::now();
// vexcl_time = end - start;
// }
//
// // Compute some metrics and print them out
// num_rows = D_T_blaze.rows();
// num_cols = D_T_blaze.columns();
// num_nonzeros = D_T_blaze.nonZeros();
// printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: Memory\n");
// printf("%d, %d, %d, %d, %d, %d, %d, %d %f\n", num_rows, num_cols, num_nonzeros, M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros(), gamma_blaze.size(), rhs_blaze.size(),
// ((num_nonzeros + M_invD_blaze.nonZeros() + gamma_blaze.size() + rhs_blaze.size()) / double(GFLOP)) * sizeof(double) );
//
// // printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
// // printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
// // printf("gamma: size: %d\n", gamma_blaze.size());
// // printf("b: size: %d\n", rhs_blaze.size());
//
// {
// ViennaCLTest viennacl_test;
// viennacl_test.WarmUp();
//
// viennacl::compressed_matrix<double> D_T_vcl = viennacl_test.ConvertMatrix(D_T_csr);
// viennacl::compressed_matrix<double> M_invD_vcl = viennacl_test.ConvertMatrix(M_invD_csr);
// viennacl::vector<double> gamma_vcl = viennacl_test.ConvertVector(gamma_blaze);
//
// start = std::chrono::system_clock::now();
// viennacl_test.RunSPMV(D_T_vcl, M_invD_vcl, gamma_vcl);
// end = std::chrono::system_clock::now();
// vcl_time = end - start;
// }
//
//
// // Two Spmv each with 2*nnz operations
// uint operations = 2 * 2 * num_nonzeros;
// uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);
//
// double blaze_single = blaze_time.count() / RUNS;
// double vex_single = vexcl_time.count() / RUNS;
// double vcl_single = vcl_time.count() / RUNS;
// // double eig_single = eigen_time.count() / RUNS;
//
// printf("Blaze: %f %f %f", blaze_single, operations / blaze_single / GFLOP, moved / blaze_single / GFLOP);
// printf("VexCL: %f %f %f", vex_single, operations / vex_single / GFLOP, moved / vex_single / GFLOP);
// printf("VCL: %f %f %f", vcl_single, operations / vcl_single / GFLOP, moved / vcl_single / GFLOP);
//
// // printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
// // printf("%f, %f, %f, %f, %f, %f, %f\n", blaze_single, vex_single, blaze_single / vex_single, operations / blaze_single / GFLOP, operations / vex_single / GFLOP, moved / blaze_single / GFLOP,
// // moved / vex_single / GFLOP);
// // //
// // printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
// // printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
// // printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
// // printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
// //
// // printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
// // printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);
return 0;
}
<commit_msg>Output timing for transposing a matrix<commit_after>#include "main.h"
#include <chrono>
int num_rows;
int num_cols;
int num_nonzeros;
std::chrono::duration<double> blaze_time;
std::chrono::duration<double> vcl_time;
std::chrono::duration<double> vexcl_time;
std::chrono::duration<double> elapsed;
std::chrono::time_point<std::chrono::system_clock> start, end;
#include "utils.h"
void ReadSparse(COO& data, const std::string filename) {
std::cout << "Reading: " << filename << std::endl;
std::stringstream ss(ReadFileAsString(filename));
size_t i, j;
double v;
while (true) {
ss >> i;
// Make sure that after reading things are still valid
// If so then the line is good and continue
if (ss.fail() == true) {
break;
}
ss >> j >> v;
data.row.push_back(i);
data.col.push_back(j);
data.val.push_back(v);
}
data.update();
}
void ReadVector(std::vector<double>& data, const std::string filename) {
std::cout << "Reading: " << filename << std::endl;
std::stringstream ss(ReadFileAsString(filename));
double v;
while (true) {
ss >> v;
// Make sure that after reading things are still valid
// If so then the line is good and continue
if (ss.fail() == true) {
break;
}
data.push_back(v);
}
}
int main(int argc, char* argv[]) {
COO D_T, M_invD;
std::vector<double> gamma;
std::cout << "Read in data to sparse COO structure: \n";
start = std::chrono::system_clock::now();
ReadSparse(D_T, "D_T_" + std::string(argv[1]) + ".mat");
ReadSparse(M_invD, "M_invD_" + std::string(argv[1]) + ".mat");
ReadVector(gamma, "gamma_" + std::string(argv[1]) + ".mat");
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to read data from file: " << elapsed.count() << std::endl;
start = std::chrono::system_clock::now();
blaze::CompressedMatrix<double> D_T_blaze = BlazeTest::ConvertMatrix(D_T);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Blaze: " << elapsed.count() << std::endl;
start = std::chrono::system_clock::now();
blaze::CompressedMatrix<double> M_invD_blaze = BlazeTest::ConvertMatrix(M_invD);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load M_invD Blaze: " << elapsed.count() << std::endl;
blaze::DynamicVector<double> gamma_blaze = BlazeTest::ConvertVector(gamma);
{
std::cout << "Blaze Test:\n";
BlazeTest blaze_test;
start = std::chrono::system_clock::now();
blaze_test.RunSPMV(D_T_blaze, M_invD_blaze, gamma_blaze);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Blaze Time: " << elapsed.count() / RUNS << std::endl;
start = std::chrono::system_clock::now();
blaze::CompressedMatrix<double> Transposed = blaze::trans(D_T_blaze);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Blaze Transpose Time: " << elapsed.count() / RUNS << std::endl;
}
std::cout << "Eigen Triplet:\n";
// Convert the COO into Eigen triplets
// Timing this part isn't important, in practice you would not need to do this
std::vector<Eigen::Triplet<double> > D_T_triplet = EigenTest::ConvertCOO(D_T);
std::vector<Eigen::Triplet<double> > M_invD_triplet = EigenTest::ConvertCOO(M_invD);
std::cout << "Eigen Convert:\n";
Eigen::SparseMatrix<double> D_T_eigen(D_T.num_rows, D_T.num_cols);
D_T_eigen.reserve(Eigen::VectorXi::Constant(D_T.num_cols, 12));
Eigen::SparseMatrix<double> M_invD_eigen(M_invD.num_rows, M_invD.num_cols);
start = std::chrono::system_clock::now();
EigenTest::ConvertMatrix(D_T_triplet, D_T, D_T_eigen);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Eigen: " << elapsed.count() << std::endl;
start = std::chrono::system_clock::now();
EigenTest::ConvertMatrix(M_invD_triplet, M_invD, M_invD_eigen);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Time to load D_T Eigen: " << elapsed.count() << std::endl;
Eigen::VectorXd gamma_eigen = EigenTest::ConvertVector(gamma);
{
std::cout << "Eigen Test:\n";
start = std::chrono::system_clock::now();
EigenTest::RunSPMV(D_T_eigen, M_invD_eigen, gamma_eigen);
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Eigen Time: " << elapsed.count() / RUNS << std::endl;
start = std::chrono::system_clock::now();
Eigen::SparseMatrix<double> Transposed(D_T_eigen.transpose());
end = std::chrono::system_clock::now();
elapsed = end - start;
std::cout << "Eigen Transpose Time: " << elapsed.count() / RUNS << std::endl;
}
//
// {
// VexCLTest vexcl_test;
// vexcl_test.CreateContext();
// vexcl_test.WarmUp();
// CSR D_T_csr = BlazeTest::ConvertSparse(D_T_blaze);
// CSR M_invD_csr = BlazeTest::ConvertSparse(M_invD_blaze);
// vex::SpMat<double> D_T_vex = vexcl_test.ConvertMatrix(D_T_csr);
// vex::SpMat<double> M_invD_vex = vexcl_test.ConvertMatrix(M_invD_csr);
// vex::vector<double> gamma_vex = vexcl_test.ConvertVector(gamma);
//
// start = std::chrono::system_clock::now();
// vexcl_test.RunSPMV(D_T_vex, M_invD_vex, gamma_vex);
// end = std::chrono::system_clock::now();
// vexcl_time = end - start;
// }
//
// // Compute some metrics and print them out
// num_rows = D_T_blaze.rows();
// num_cols = D_T_blaze.columns();
// num_nonzeros = D_T_blaze.nonZeros();
// printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: Memory\n");
// printf("%d, %d, %d, %d, %d, %d, %d, %d %f\n", num_rows, num_cols, num_nonzeros, M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros(), gamma_blaze.size(), rhs_blaze.size(),
// ((num_nonzeros + M_invD_blaze.nonZeros() + gamma_blaze.size() + rhs_blaze.size()) / double(GFLOP)) * sizeof(double) );
//
// // printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
// // printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
// // printf("gamma: size: %d\n", gamma_blaze.size());
// // printf("b: size: %d\n", rhs_blaze.size());
//
// {
// ViennaCLTest viennacl_test;
// viennacl_test.WarmUp();
//
// viennacl::compressed_matrix<double> D_T_vcl = viennacl_test.ConvertMatrix(D_T_csr);
// viennacl::compressed_matrix<double> M_invD_vcl = viennacl_test.ConvertMatrix(M_invD_csr);
// viennacl::vector<double> gamma_vcl = viennacl_test.ConvertVector(gamma_blaze);
//
// start = std::chrono::system_clock::now();
// viennacl_test.RunSPMV(D_T_vcl, M_invD_vcl, gamma_vcl);
// end = std::chrono::system_clock::now();
// vcl_time = end - start;
// }
//
//
// // Two Spmv each with 2*nnz operations
// uint operations = 2 * 2 * num_nonzeros;
// uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);
//
// double blaze_single = blaze_time.count() / RUNS;
// double vex_single = vexcl_time.count() / RUNS;
// double vcl_single = vcl_time.count() / RUNS;
// // double eig_single = eigen_time.count() / RUNS;
//
// printf("Blaze: %f %f %f", blaze_single, operations / blaze_single / GFLOP, moved / blaze_single / GFLOP);
// printf("VexCL: %f %f %f", vex_single, operations / vex_single / GFLOP, moved / vex_single / GFLOP);
// printf("VCL: %f %f %f", vcl_single, operations / vcl_single / GFLOP, moved / vcl_single / GFLOP);
//
// // printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
// // printf("%f, %f, %f, %f, %f, %f, %f\n", blaze_single, vex_single, blaze_single / vex_single, operations / blaze_single / GFLOP, operations / vex_single / GFLOP, moved / blaze_single / GFLOP,
// // moved / vex_single / GFLOP);
// // //
// // printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
// // printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
// // printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
// // printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
// //
// // printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
// // printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);
return 0;
}
<|endoftext|> |
<commit_before>4621437e-5216-11e5-a683-6c40088e03e4<commit_msg>46283418-5216-11e5-92e0-6c40088e03e4<commit_after>46283418-5216-11e5-92e0-6c40088e03e4<|endoftext|> |
<commit_before>daf5f899-2d3e-11e5-b8de-c82a142b6f9b<commit_msg>db64cd40-2d3e-11e5-914a-c82a142b6f9b<commit_after>db64cd40-2d3e-11e5-914a-c82a142b6f9b<|endoftext|> |
<commit_before>#include <SDL.h>
#include <vector>
#include "opengl.h"
int Abs(int num) {
return num > 0 ? num : -num;
}
int PingPong(int num, int length) {
return length - Abs((num % (length * 2)) - length);
}
int main() {
const int WindowWidth = 720;
const int WindowHeight = 720;
if (SDL_Init(SDL_INIT_EVERYTHING)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
return 1;
}
SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
return 1;
}
//// OpenGL Setup
// Options
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
// Connect window
SDL_GLContext context = SDL_GL_CreateContext(window);
if (!context) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
return 1;
}
OpenGL_Init();
{
int value = 0;
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value);
SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value);
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value);
SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value);
}
int r = 0;
int g = 0;
int b = 0;
glViewport(0, 0, WindowWidth, WindowHeight);
glClearColor(0.39f, 0.58f, 0.92f, 1.0f);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Shaders
const GLchar* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"layout (location = 1) in vec2 texCoord;\n"
"out vec2 TexCoord;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"TexCoord = texCoord;\n"
"}\0";
const GLchar* fragmentShaderSource = "#version 330 core\n"
"in vec2 TexCoord;\n"
"out vec4 color;\n"
"uniform sampler2D ourTexture;\n"
"void main()\n"
"{\n"
"color = texture(ourTexture, TexCoord);\n"
"}\n\0";
GLint success;
GLchar logBuffer[512];
// Vertex
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer);
}
// Fragment
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer);
}
// Program
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer);
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
GLfloat vertices[] = {
// Positions // Colors // Texture Coords
0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // Top Right
0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // Bottom Right
-0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Bottom Left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // Top Left
};
GLuint indices[] = {
0, 1, 3,
1, 2, 3,
};
GLuint VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
{
// Now the VBO..
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Finally the EBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// Vertex Attributes
glVertexAttribPointer(0, // Layout
3, // Size
GL_FLOAT, // Type
GL_FALSE, // Normalised
8 * sizeof(GLfloat), // Stride
(void*) 0); // Array Buffer Offset
glEnableVertexAttribArray(0);
// glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
// glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
}
glBindVertexArray(0);
// Texture loading
SDL_Surface* image = SDL_LoadBMP("texture.bmp");
if (!image) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load texture.bmp! %s", SDL_GetError());
return 1;
}
GLuint texture = 0;
glGenTextures(1, &texture);
{
glBindTexture(GL_TEXTURE_2D, texture); // All texture functions will now operate on this texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // X wrapping
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Y wrapping
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Far away
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Close up
// Use GL_BGR because bitmaps are silly
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->w, image->h, 0, GL_BGR, GL_UNSIGNED_BYTE, image->pixels);
SDL_FreeSurface(image);
}
glBindTexture(GL_TEXTURE_2D, 0); // Unbind
for(GLenum err; (err = glGetError()) != GL_NO_ERROR;) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "OpenGL Init: 0x%x", err);
}
bool running = true;
SDL_Event event;
float current = SDL_GetTicks();
float last = current;
float interval = 1000 / 60;
while (running) {
// Limit frame rate
current = SDL_GetTicks();
float dt = current - last;
if (dt < interval) {
SDL_Delay(interval - dt);
continue;
}
last = current;
// Input
while(SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
break;
}
if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
int x = event.window.data1;
int y = event.window.data2;
glViewport(0, 0, x, y);
}
}
r = (r + 2) % (255 * 2);
g = (g + 4) % (255 * 2);
b = (b + 8) % (255 * 2);
//Rendering
glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw Triangle
glUseProgram(shaderProgram);
// Bind texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(glGetUniformLocation(shaderProgram, "ourTexture"), 0);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
SDL_GL_SwapWindow(window);
}
// Properly de-allocate all resources once they've outlived their purpose
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
return 0;
}<commit_msg>Colours are properly working.<commit_after>#include <SDL.h>
#include <vector>
#include "opengl.h"
int Abs(int num) {
return num > 0 ? num : -num;
}
int PingPong(int num, int length) {
return length - Abs((num % (length * 2)) - length);
}
int main() {
const int WindowWidth = 720;
const int WindowHeight = 720;
if (SDL_Init(SDL_INIT_EVERYTHING)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
return 1;
}
SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
return 1;
}
//// OpenGL Setup
// Options
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
// Connect window
SDL_GLContext context = SDL_GL_CreateContext(window);
if (!context) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
return 1;
}
OpenGL_Init();
{
int value = 0;
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value);
SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value);
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value);
SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value);
}
int r = 0;
int g = 0;
int b = 0;
glViewport(0, 0, WindowWidth, WindowHeight);
glClearColor(0.39f, 0.58f, 0.92f, 1.0f);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Shaders
const GLchar* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"layout (location = 1) in vec3 color;\n"
"layout (location = 2) in vec2 texCoord;\n"
"out vec3 ourColor;\n"
"out vec2 TexCoord;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"TexCoord = texCoord;\n"
"ourColor = color;\n"
"}\0";
const GLchar* fragmentShaderSource = "#version 330 core\n"
"in vec3 ourColor;\n"
"in vec2 TexCoord;\n"
"out vec4 color;\n"
"uniform sampler2D ourTexture;\n"
"void main()\n"
"{\n"
"color = texture(ourTexture, TexCoord);\n"
"color.rgb *= ourColor;\n"
"}\n\0";
GLint success;
GLchar logBuffer[512];
// Vertex
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer);
}
// Fragment
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer);
}
// Program
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer);
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
GLfloat vertices[] = {
// Positions // Colors // Texture Coords
0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // Top Right
0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // Bottom Right
-0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Bottom Left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f // Top Left
};
GLuint indices[] = {
0, 1, 3,
1, 2, 3,
};
GLuint VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
{
// Now the VBO..
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Finally the EBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// Vertex Attributes
glVertexAttribPointer(0, // Layout
3, // Size
GL_FLOAT, // Type
GL_FALSE, // Normalised
8 * sizeof(GLfloat), // Stride
(void*) 0); // Array Buffer Offset
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
}
glBindVertexArray(0);
// Texture loading
SDL_Surface* image = SDL_LoadBMP("texture.bmp");
if (!image) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load texture.bmp! %s", SDL_GetError());
return 1;
}
GLuint texture = 0;
glGenTextures(1, &texture);
{
glBindTexture(GL_TEXTURE_2D, texture); // All texture functions will now operate on this texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // X wrapping
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Y wrapping
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Far away
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Close up
// Use GL_BGR because bitmaps are silly
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->w, image->h, 0, GL_BGR, GL_UNSIGNED_BYTE, image->pixels);
SDL_FreeSurface(image);
}
glBindTexture(GL_TEXTURE_2D, 0); // Unbind
for(GLenum err; (err = glGetError()) != GL_NO_ERROR;) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "OpenGL Init: 0x%x", err);
}
bool running = true;
SDL_Event event;
float current = SDL_GetTicks();
float last = current;
float interval = 1000 / 60;
while (running) {
// Limit frame rate
current = SDL_GetTicks();
float dt = current - last;
if (dt < interval) {
SDL_Delay(interval - dt);
continue;
}
last = current;
// Input
while(SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
break;
}
if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
int x = event.window.data1;
int y = event.window.data2;
glViewport(0, 0, x, y);
}
}
r = (r + 2) % (255 * 2);
g = (g + 4) % (255 * 2);
b = (b + 8) % (255 * 2);
//Rendering
glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw Triangle
glUseProgram(shaderProgram);
// Bind texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(glGetUniformLocation(shaderProgram, "ourTexture"), 0);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
SDL_GL_SwapWindow(window);
}
// Properly de-allocate all resources once they've outlived their purpose
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
return 0;
}<|endoftext|> |
<commit_before>8e9bbfc7-4b02-11e5-821d-28cfe9171a43<commit_msg>Stuff changed<commit_after>8ea62402-4b02-11e5-83df-28cfe9171a43<|endoftext|> |
<commit_before>e53c1273-327f-11e5-9c3a-9cf387a8033e<commit_msg>e54237d9-327f-11e5-8edf-9cf387a8033e<commit_after>e54237d9-327f-11e5-8edf-9cf387a8033e<|endoftext|> |
<commit_before>7946522c-2d53-11e5-baeb-247703a38240<commit_msg>7946da1c-2d53-11e5-baeb-247703a38240<commit_after>7946da1c-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>67e9c526-5216-11e5-8260-6c40088e03e4<commit_msg>67f100a2-5216-11e5-9c78-6c40088e03e4<commit_after>67f100a2-5216-11e5-9c78-6c40088e03e4<|endoftext|> |
<commit_before>ac14d1c0-2e4f-11e5-9ac7-28cfe91dbc4b<commit_msg>ac1ba894-2e4f-11e5-b0a3-28cfe91dbc4b<commit_after>ac1ba894-2e4f-11e5-b0a3-28cfe91dbc4b<|endoftext|> |
<commit_before>9363befa-2d14-11e5-af21-0401358ea401<commit_msg>9363befb-2d14-11e5-af21-0401358ea401<commit_after>9363befb-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>92323acc-2d14-11e5-af21-0401358ea401<commit_msg>92323acd-2d14-11e5-af21-0401358ea401<commit_after>92323acd-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>c5aca66b-327f-11e5-bb7e-9cf387a8033e<commit_msg>c5b3f9d9-327f-11e5-82b3-9cf387a8033e<commit_after>c5b3f9d9-327f-11e5-82b3-9cf387a8033e<|endoftext|> |
<commit_before>/*
* noice - ...
* Copyright (C) 2016 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
// --------------------------------------------------------------------------------------------------------------------
#include "devices/guitarhero.hpp"
#include "devices/ps3.hpp"
#include "devices/ps4.hpp"
// --------------------------------------------------------------------------------------------------------------------
static const int kJoystickAnalogStart = 0;
static const int kJoystickAnalogEnd = 7;
static const int kJoystickButtonStart = 8;
static const int kJoystickButtonEnd = 63;
static const int kJoystickMaxAnalog = kJoystickAnalogEnd-kJoystickAnalogStart;
static const int kJoystickMaxButton = kJoystickButtonEnd-kJoystickButtonStart;
// --------------------------------------------------------------------------------------------------------------------
struct js_event {
unsigned int time; /* event timestamp in milliseconds */
short value; /* value */
unsigned char type; /* event type */
unsigned char number; /* axis/button number */
};
JackData::JackData() noexcept
: joystick(false),
device(kNull),
fd(-1),
nr(-1),
thread(0),
client(nullptr),
midiport(nullptr)
{
pthread_mutex_init(&mutex, nullptr);
std::memset(buf, 0, kBufSize);
std::memset(oldbuf, 0, kBufSize);
}
JackData::~JackData()
{
if (client != nullptr)
{
jack_deactivate(client);
jack_client_close(client);
}
if (fd >= 0)
close(fd);
pthread_mutex_destroy(&mutex);
}
// --------------------------------------------------------------------------------------------------------------------
static void shutdown_callback(void* const arg)
{
JackData* const jackdata = (JackData*)arg;
jackdata->client = nullptr;
}
static int process_callback(const jack_nframes_t frames, void* const arg)
{
JackData* const jackdata = (JackData*)arg;
// try lock asap, not fatal yet
bool locked = pthread_mutex_trylock(&jackdata->mutex) == 0;
// stack data
unsigned char tmpbuf[JackData::kBufSize];
// get jack midi port buffer
void* const midibuf = jack_port_get_buffer(jackdata->midiport, frames);
jack_midi_clear_buffer(midibuf);
// try lock again
if (! locked)
{
locked = pthread_mutex_trylock(&jackdata->mutex) == 0;
// could not try-lock until here, stop
if (! locked)
return 0;
}
// copy buf data into a temp location so we can release the lock
std::memcpy(tmpbuf, jackdata->buf, jackdata->nr);
pthread_mutex_unlock(&jackdata->mutex);
switch (jackdata->device)
{
case JackData::kNull:
break;
case JackData::kDualShock3:
PS3::process(jackdata, midibuf, tmpbuf);
break;
case JackData::kDualShock4:
PS4::process(jackdata, midibuf, tmpbuf);
break;
case JackData::kGuitarHero:
GuitarHero::process(jackdata, midibuf, tmpbuf);
break;
}
// cache current buf for comparison on next call
std::memcpy(jackdata->oldbuf, tmpbuf, jackdata->nr);
return 0;
}
// --------------------------------------------------------------------------------------------------------------------
static bool noice_init(JackData* const jackdata, const char* const device)
{
if (device == nullptr || device[0] == '\0')
return false;
int nr;
unsigned char buf[JackData::kBufSize];
jackdata->joystick = strncmp(device, "/dev/input/js", 13) == 0;
if ((jackdata->fd = open(device, O_RDONLY)) < 0)
{
fprintf(stderr, "noice::open(\"%s\") - failed to open hidraw device\n", device);
return false;
}
const char* const deviceNum = device+(strlen(device)-1);
if ((nr = read(jackdata->fd, buf, jackdata->joystick ? sizeof(js_event) : JackData::kBufSize)) < 0)
{
fprintf(stderr, "noice::read(%i) - failed to read from device\n", jackdata->fd);
return false;
}
printf("noice::read(%i) - nr = %d\n", jackdata->fd, nr);
if (jackdata->joystick)
{
if (nr != sizeof(js_event))
{
fprintf(stderr, "noice::read(%i) - failed to read device (nr = %d)\n", jackdata->fd, nr);
return false;
}
memset(buf, 0, JackData::kBufSize);
// TODO - ask joystick to know what it is
jackdata->device = JackData::kGuitarHero;
jackdata->nr = 9;
}
else
{
switch (nr)
{
case 49:
jackdata->device = JackData::kDualShock3;
break;
case 64:
jackdata->device = JackData::kDualShock4;
break;
default:
fprintf(stderr, "noice::read(%i) - unsuppported device (nr = %d)\n", jackdata->fd, nr);
return false;
}
jackdata->nr = nr;
}
char tmpName[32];
std::strcpy(tmpName, "noice");
std::strcat(tmpName, deviceNum);
if (jackdata->client == nullptr)
{
jackdata->client = jack_client_open(tmpName, JackNoStartServer, nullptr);
if (jackdata->client == nullptr)
{
fprintf(stderr, "noice:: failed to register jack client\n");
return false;
}
}
std::strcpy(tmpName, "noice_capture_");
std::strcat(tmpName, deviceNum);
jackdata->midiport = jack_port_register(jackdata->client, tmpName, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput|JackPortIsPhysical|JackPortIsTerminal, 0);
if (jackdata->midiport == nullptr)
{
fprintf(stderr, "noice:: failed to register jack midi port\n");
return false;
}
switch (jackdata->device)
{
case JackData::kNull:
break;
case JackData::kDualShock3:
jack_port_set_alias(jackdata->midiport, "PS3 DualShock");
break;
case JackData::kDualShock4:
jack_port_set_alias(jackdata->midiport, "PS4 DualShock");
break;
case JackData::kGuitarHero:
jack_port_set_alias(jackdata->midiport, "Guitar Hero");
break;
}
std::memcpy(jackdata->buf, buf, jackdata->nr);
jack_on_shutdown(jackdata->client, shutdown_callback, jackdata);
jack_set_process_callback(jackdata->client, process_callback, jackdata);
jack_activate(jackdata->client);
return true;
}
static bool noice_idle(JackData* const jackdata, unsigned char buf[JackData::kBufSize])
{
if (jackdata->client == nullptr)
return false;
if (jackdata->joystick)
{
js_event ev;
const int nr = read(jackdata->fd, &ev, sizeof(js_event));
if (nr != sizeof(js_event))
{
fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
jack_deactivate(jackdata->client);
return false;
}
// ignore synthetic events
ev.type &= ~0x80;
// put data into buf to simulate a raw device
switch (ev.type)
{
case 1: { // button
if (ev.number > kJoystickMaxButton)
break;
if (jackdata->device == JackData::kGuitarHero && ev.number > 5)
--ev.number;
const int mask = 1 << ev.number;
const int offs = kJoystickButtonStart + (ev.number / 8);
if (ev.value)
buf[offs] |= mask;
else
buf[offs] &= ~mask;
break;
}
case 2: { // axis
if (ev.number > kJoystickMaxAnalog)
break;
const int offs = kJoystickAnalogStart + ev.number;
buf[offs] = (ev.value + 32767) / 256;
break;
}
}
}
else
{
const int nr = read(jackdata->fd, buf, jackdata->nr);
if (nr != jackdata->nr)
{
fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
jack_deactivate(jackdata->client);
return false;
}
}
pthread_mutex_lock(&jackdata->mutex);
std::memcpy(jackdata->buf, buf, jackdata->nr);
pthread_mutex_unlock(&jackdata->mutex);
#if 0
printf("\n==========================================\n");
for (int j=0; j<jackdata->nr; j++)
{
printf("%02X ", buf[j]);
if ((j+1) % 16 == 0)
printf("\n");
}
#endif
return true;
}
// --------------------------------------------------------------------------------------------------------------------
static volatile bool gRunning;
static void signalHandler(int)
{
gRunning = false;
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Usage: %s /dev/hidrawX|/dev/input/jsX\n", argv[0]);
return 1;
}
JackData jackdata;
if (! noice_init(&jackdata, argv[1]))
return 1;
gRunning = true;
struct sigaction sig;
sig.sa_handler = signalHandler;
sig.sa_flags = SA_RESTART;
sig.sa_restorer = nullptr;
sigemptyset(&sig.sa_mask);
sigaction(SIGINT, &sig, nullptr);
sigaction(SIGTERM, &sig, nullptr);
unsigned char buf[JackData::kBufSize];
memset(buf, 0, JackData::kBufSize);
while (gRunning && noice_idle(&jackdata, buf)) {}
return 0;
}
// --------------------------------------------------------------------------------------------------------------------
static void* gInternalClientRun(void* arg)
{
JackData* const jackdata = (JackData*)arg;
unsigned char buf[JackData::kBufSize];
memset(buf, 0, JackData::kBufSize);
while (noice_idle(jackdata, buf)) {}
return nullptr;
}
extern "C" __attribute__ ((visibility("default")))
int jack_initialize(jack_client_t* client, const char* load_init);
int jack_initialize(jack_client_t* client, const char* load_init)
{
JackData* const jackdata = new JackData();
jackdata->client = client;
if (! noice_init(jackdata, load_init))
return 1;
pthread_create(&jackdata->thread, nullptr, gInternalClientRun, jackdata);
return 0;
}
extern "C" __attribute__ ((visibility("default")))
void jack_finish(void* arg);
void jack_finish(void* arg)
{
if (arg == nullptr)
return;
JackData* const jackdata = (JackData*)arg;
jackdata->client = nullptr;
pthread_join(jackdata->thread, nullptr);
delete jackdata;
}
// --------------------------------------------------------------------------------------------------------------------
<commit_msg>Prevent conflicts between js and hidraw used at the same time<commit_after>/*
* noice - ...
* Copyright (C) 2016 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
// --------------------------------------------------------------------------------------------------------------------
#include "devices/guitarhero.hpp"
#include "devices/ps3.hpp"
#include "devices/ps4.hpp"
// --------------------------------------------------------------------------------------------------------------------
static const int kJoystickAnalogStart = 0;
static const int kJoystickAnalogEnd = 7;
static const int kJoystickButtonStart = 8;
static const int kJoystickButtonEnd = 63;
static const int kJoystickMaxAnalog = kJoystickAnalogEnd-kJoystickAnalogStart;
static const int kJoystickMaxButton = kJoystickButtonEnd-kJoystickButtonStart;
// --------------------------------------------------------------------------------------------------------------------
struct js_event {
unsigned int time; /* event timestamp in milliseconds */
short value; /* value */
unsigned char type; /* event type */
unsigned char number; /* axis/button number */
};
JackData::JackData() noexcept
: joystick(false),
device(kNull),
fd(-1),
nr(-1),
thread(0),
client(nullptr),
midiport(nullptr)
{
pthread_mutex_init(&mutex, nullptr);
std::memset(buf, 0, kBufSize);
std::memset(oldbuf, 0, kBufSize);
}
JackData::~JackData()
{
if (client != nullptr)
{
jack_deactivate(client);
jack_client_close(client);
}
if (fd >= 0)
close(fd);
pthread_mutex_destroy(&mutex);
}
// --------------------------------------------------------------------------------------------------------------------
static void shutdown_callback(void* const arg)
{
JackData* const jackdata = (JackData*)arg;
jackdata->client = nullptr;
}
static int process_callback(const jack_nframes_t frames, void* const arg)
{
JackData* const jackdata = (JackData*)arg;
// try lock asap, not fatal yet
bool locked = pthread_mutex_trylock(&jackdata->mutex) == 0;
// stack data
unsigned char tmpbuf[JackData::kBufSize];
// get jack midi port buffer
void* const midibuf = jack_port_get_buffer(jackdata->midiport, frames);
jack_midi_clear_buffer(midibuf);
// try lock again
if (! locked)
{
locked = pthread_mutex_trylock(&jackdata->mutex) == 0;
// could not try-lock until here, stop
if (! locked)
return 0;
}
// copy buf data into a temp location so we can release the lock
std::memcpy(tmpbuf, jackdata->buf, jackdata->nr);
pthread_mutex_unlock(&jackdata->mutex);
switch (jackdata->device)
{
case JackData::kNull:
break;
case JackData::kDualShock3:
PS3::process(jackdata, midibuf, tmpbuf);
break;
case JackData::kDualShock4:
PS4::process(jackdata, midibuf, tmpbuf);
break;
case JackData::kGuitarHero:
GuitarHero::process(jackdata, midibuf, tmpbuf);
break;
}
// cache current buf for comparison on next call
std::memcpy(jackdata->oldbuf, tmpbuf, jackdata->nr);
return 0;
}
// --------------------------------------------------------------------------------------------------------------------
static bool noice_init(JackData* const jackdata, const char* const device)
{
if (device == nullptr || device[0] == '\0')
return false;
int nr;
unsigned char buf[JackData::kBufSize];
jackdata->joystick = strncmp(device, "/dev/input/js", 13) == 0;
if ((jackdata->fd = open(device, O_RDONLY)) < 0)
{
fprintf(stderr, "noice::open(\"%s\") - failed to open hidraw device\n", device);
return false;
}
int deviceNum = atoi(device+(strlen(device)-1));
if ((nr = read(jackdata->fd, buf, jackdata->joystick ? sizeof(js_event) : JackData::kBufSize)) < 0)
{
fprintf(stderr, "noice::read(%i) - failed to read from device\n", jackdata->fd);
return false;
}
printf("noice::read(%i) - nr = %d\n", jackdata->fd, nr);
if (jackdata->joystick)
{
if (nr != sizeof(js_event))
{
fprintf(stderr, "noice::read(%i) - failed to read device (nr = %d)\n", jackdata->fd, nr);
return false;
}
memset(buf, 0, JackData::kBufSize);
// TODO - ask joystick to know what it is
jackdata->device = JackData::kGuitarHero;
jackdata->nr = 9;
deviceNum += 20;
}
else
{
switch (nr)
{
case 49:
jackdata->device = JackData::kDualShock3;
break;
case 64:
jackdata->device = JackData::kDualShock4;
break;
default:
fprintf(stderr, "noice::read(%i) - unsuppported device (nr = %d)\n", jackdata->fd, nr);
return false;
}
jackdata->nr = nr;
}
char tmpName[32];
std::snprintf(tmpName, 32, "noice%i", deviceNum);
if (jackdata->client == nullptr)
{
jackdata->client = jack_client_open(tmpName, JackNoStartServer, nullptr);
if (jackdata->client == nullptr)
{
fprintf(stderr, "noice:: failed to register jack client\n");
return false;
}
}
std::snprintf(tmpName, 32, "noice_capture_%i", deviceNum);
jackdata->midiport = jack_port_register(jackdata->client, tmpName, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput|JackPortIsPhysical|JackPortIsTerminal, 0);
if (jackdata->midiport == nullptr)
{
fprintf(stderr, "noice:: failed to register jack midi port\n");
return false;
}
switch (jackdata->device)
{
case JackData::kNull:
break;
case JackData::kDualShock3:
jack_port_set_alias(jackdata->midiport, "PS3 DualShock");
break;
case JackData::kDualShock4:
jack_port_set_alias(jackdata->midiport, "PS4 DualShock");
break;
case JackData::kGuitarHero:
jack_port_set_alias(jackdata->midiport, "Guitar Hero");
break;
}
std::memcpy(jackdata->buf, buf, jackdata->nr);
jack_on_shutdown(jackdata->client, shutdown_callback, jackdata);
jack_set_process_callback(jackdata->client, process_callback, jackdata);
jack_activate(jackdata->client);
return true;
}
static bool noice_idle(JackData* const jackdata, unsigned char buf[JackData::kBufSize])
{
if (jackdata->client == nullptr)
return false;
if (jackdata->joystick)
{
js_event ev;
const int nr = read(jackdata->fd, &ev, sizeof(js_event));
if (nr != sizeof(js_event))
{
fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
jack_deactivate(jackdata->client);
return false;
}
// ignore synthetic events
ev.type &= ~0x80;
// put data into buf to simulate a raw device
switch (ev.type)
{
case 1: { // button
if (ev.number > kJoystickMaxButton)
break;
if (jackdata->device == JackData::kGuitarHero && ev.number > 5)
--ev.number;
const int mask = 1 << ev.number;
const int offs = kJoystickButtonStart + (ev.number / 8);
if (ev.value)
buf[offs] |= mask;
else
buf[offs] &= ~mask;
break;
}
case 2: { // axis
if (ev.number > kJoystickMaxAnalog)
break;
const int offs = kJoystickAnalogStart + ev.number;
buf[offs] = (ev.value + 32767) / 256;
break;
}
}
}
else
{
const int nr = read(jackdata->fd, buf, jackdata->nr);
if (nr != jackdata->nr)
{
fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
jack_deactivate(jackdata->client);
return false;
}
}
pthread_mutex_lock(&jackdata->mutex);
std::memcpy(jackdata->buf, buf, jackdata->nr);
pthread_mutex_unlock(&jackdata->mutex);
#if 0
printf("\n==========================================\n");
for (int j=0; j<jackdata->nr; j++)
{
printf("%02X ", buf[j]);
if ((j+1) % 16 == 0)
printf("\n");
}
#endif
return true;
}
// --------------------------------------------------------------------------------------------------------------------
static volatile bool gRunning;
static void signalHandler(int)
{
gRunning = false;
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Usage: %s /dev/hidrawX|/dev/input/jsX\n", argv[0]);
return 1;
}
JackData jackdata;
if (! noice_init(&jackdata, argv[1]))
return 1;
gRunning = true;
struct sigaction sig;
sig.sa_handler = signalHandler;
sig.sa_flags = SA_RESTART;
sig.sa_restorer = nullptr;
sigemptyset(&sig.sa_mask);
sigaction(SIGINT, &sig, nullptr);
sigaction(SIGTERM, &sig, nullptr);
unsigned char buf[JackData::kBufSize];
memset(buf, 0, JackData::kBufSize);
while (gRunning && noice_idle(&jackdata, buf)) {}
return 0;
}
// --------------------------------------------------------------------------------------------------------------------
static void* gInternalClientRun(void* arg)
{
JackData* const jackdata = (JackData*)arg;
unsigned char buf[JackData::kBufSize];
memset(buf, 0, JackData::kBufSize);
while (noice_idle(jackdata, buf)) {}
return nullptr;
}
extern "C" __attribute__ ((visibility("default")))
int jack_initialize(jack_client_t* client, const char* load_init);
int jack_initialize(jack_client_t* client, const char* load_init)
{
JackData* const jackdata = new JackData();
jackdata->client = client;
if (! noice_init(jackdata, load_init))
return 1;
pthread_create(&jackdata->thread, nullptr, gInternalClientRun, jackdata);
return 0;
}
extern "C" __attribute__ ((visibility("default")))
void jack_finish(void* arg);
void jack_finish(void* arg)
{
if (arg == nullptr)
return;
JackData* const jackdata = (JackData*)arg;
jackdata->client = nullptr;
pthread_join(jackdata->thread, nullptr);
delete jackdata;
}
// --------------------------------------------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>5ae7ec27-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ec28-2d16-11e5-af21-0401358ea401<commit_after>5ae7ec28-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>248e0066-2f67-11e5-8c15-6c40088e03e4<commit_msg>2494d6c0-2f67-11e5-a481-6c40088e03e4<commit_after>2494d6c0-2f67-11e5-a481-6c40088e03e4<|endoftext|> |
<commit_before>#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
static void error_callback(int error, const char* description)
{
fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
int main(void)
{
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
glewInit();
while (!glfwWindowShouldClose(window))
{
float ratio;
int width, height;
glfwGetFramebufferSize(window, &width, &height);
ratio = width / (float) height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);
glBegin(GL_TRIANGLES);
glColor3f(1.f, 0.f, 0.f);
glVertex3f(-0.6f, -0.4f, 0.f);
glColor3f(0.f, 1.f, 0.f);
glVertex3f(0.6f, -0.4f, 0.f);
glColor3f(0.f, 0.f, 1.f);
glVertex3f(0.f, 0.6f, 0.f);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
<commit_msg>sfml main<commit_after>#include <SFML/Graphics.hpp>
//#include <GL/glew.h>
int main()
{
// glewinit();
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
}
<|endoftext|> |
<commit_before>7914865c-2d53-11e5-baeb-247703a38240<commit_msg>79150438-2d53-11e5-baeb-247703a38240<commit_after>79150438-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>ff7c6235-2747-11e6-a85a-e0f84713e7b8<commit_msg>Deal with it<commit_after>ff8e486e-2747-11e6-8dc8-e0f84713e7b8<|endoftext|> |
<commit_before>81cf0e3e-2d15-11e5-af21-0401358ea401<commit_msg>81cf0e3f-2d15-11e5-af21-0401358ea401<commit_after>81cf0e3f-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>78e6305e-2d53-11e5-baeb-247703a38240<commit_msg>78e6b074-2d53-11e5-baeb-247703a38240<commit_after>78e6b074-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>5fb84a66-2e4f-11e5-b96e-28cfe91dbc4b<commit_msg>5fc00485-2e4f-11e5-817b-28cfe91dbc4b<commit_after>5fc00485-2e4f-11e5-817b-28cfe91dbc4b<|endoftext|> |
<commit_before>8d512c0c-2e4f-11e5-adcd-28cfe91dbc4b<commit_msg>8d58a721-2e4f-11e5-8b30-28cfe91dbc4b<commit_after>8d58a721-2e4f-11e5-8b30-28cfe91dbc4b<|endoftext|> |
<commit_before>814a79e3-2e4f-11e5-9749-28cfe91dbc4b<commit_msg>81515e0f-2e4f-11e5-a3e1-28cfe91dbc4b<commit_after>81515e0f-2e4f-11e5-a3e1-28cfe91dbc4b<|endoftext|> |
<commit_before>6bc1f1d4-2fa5-11e5-8196-00012e3d3f12<commit_msg>6bc39f82-2fa5-11e5-aa63-00012e3d3f12<commit_after>6bc39f82-2fa5-11e5-aa63-00012e3d3f12<|endoftext|> |
<commit_before>7907679c-2d53-11e5-baeb-247703a38240<commit_msg>7907e71c-2d53-11e5-baeb-247703a38240<commit_after>7907e71c-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>decc08eb-4b02-11e5-b187-28cfe9171a43<commit_msg>Boyaaah!<commit_after>ded8feeb-4b02-11e5-99a3-28cfe9171a43<|endoftext|> |
<commit_before>#include <sys/mman.h>
#include "asmtest.h"
#include "Operand-x86_64.h"
#include "Assembler-x86_64.h"
using namespace x86_64;
template<typename X, typename Y>
void print_mem(X* start, Y* end) {
unsigned char* i = (unsigned char*)start;
unsigned char* j = (unsigned char*)end;
for (; i < j; ++i) {
printf("0x%.2x ", *i);
}
puts("");
}
void say_hello() {
printf("HELLO WORLD!\n");
}
int main (int argc, char const *argv[])
{
Assembler masm;
#define __ masm.
__ enter();
__ call("say_hello");
__ call("count_up");
__ inc(rax);
__ leave();
__ ret();
__ define_symbol("count_up");
__ enter();
__ bin_xor(rax, rax);
__ mov(Immediate(200), rbx);
Assembler::Label loop_cond, loop_exit;
__ bind(loop_cond);
__ cmp(rax, rbx);
__ j(CC_EQUAL, loop_exit);
__ inc(rax);
__ jmp(loop_cond);
__ bind(loop_exit);
__ leave();
__ ret();
unsigned char* code = (unsigned char*)valloc(masm.length());
Assembler::SymbolTable table;
table["say_hello"] = Assembler::Symbol((void*)say_hello);
masm.compile_to(code, table);
mprotect(code, masm.length(), PROT_EXEC);
int(*func)(int a, int b) = (int(*)(int, int))code;
printf("add: %d\n", func(6772, 2123));
return 0;
}
<commit_msg>test relative offset call<commit_after>#include <sys/mman.h>
#include "asmtest.h"
#include "Operand-x86_64.h"
#include "Assembler-x86_64.h"
using namespace x86_64;
template<typename X, typename Y>
void print_mem(X* start, Y* end) {
unsigned char* i = (unsigned char*)start;
unsigned char* j = (unsigned char*)end;
for (; i < j; ++i) {
printf("0x%.2x ", *i);
}
puts("");
}
void say_hello() {
printf("HELLO WORLD!\n");
}
int main (int argc, char const *argv[])
{
Assembler masm;
#define __ masm.
__ enter();
__ call("say_hello");
__ call("count_up");
__ inc(rax);
__ leave();
__ ret();
Assembler::Symbol s = __ define_symbol("do_the_count_up");
__ enter();
__ bin_xor(rax, rax);
__ mov(Immediate(200), rbx);
Assembler::Label loop_cond, loop_exit;
__ bind(loop_cond);
__ cmp(rax, rbx);
__ j(CC_EQUAL, loop_exit);
__ inc(rax);
__ jmp(loop_cond);
__ bind(loop_exit);
__ leave();
__ ret();
__ define_symbol("count_up");
__ enter();
__ call(s);
__ leave();
__ ret();
unsigned char* code = (unsigned char*)valloc(masm.length());
Assembler::SymbolTable table;
table["say_hello"] = Assembler::Symbol((void*)say_hello);
masm.compile_to(code, table);
mprotect(code, masm.length(), PROT_EXEC);
int(*func)(int a, int b) = (int(*)(int, int))code;
printf("add: %d\n", func(6772, 2123));
return 0;
}
<|endoftext|> |
<commit_before>d64082a8-4b02-11e5-a4ce-28cfe9171a43<commit_msg>My Backup<commit_after>d650c391-4b02-11e5-af9e-28cfe9171a43<|endoftext|> |
<commit_before>7801a65a-2d53-11e5-baeb-247703a38240<commit_msg>780226c0-2d53-11e5-baeb-247703a38240<commit_after>780226c0-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>d2be228a-585a-11e5-85af-6c40088e03e4<commit_msg>d2c69eec-585a-11e5-becc-6c40088e03e4<commit_after>d2c69eec-585a-11e5-becc-6c40088e03e4<|endoftext|> |
<commit_before>8e22af0f-2e4f-11e5-9358-28cfe91dbc4b<commit_msg>8e2984bd-2e4f-11e5-80d7-28cfe91dbc4b<commit_after>8e2984bd-2e4f-11e5-80d7-28cfe91dbc4b<|endoftext|> |
<commit_before>a804d06b-4b02-11e5-bb61-28cfe9171a43<commit_msg>My Backup<commit_after>a814673d-4b02-11e5-af45-28cfe9171a43<|endoftext|> |
<commit_before>708fd78c-2749-11e6-b2b1-e0f84713e7b8<commit_msg>my cat is cute<commit_after>709ed94f-2749-11e6-80ee-e0f84713e7b8<|endoftext|> |
<commit_before>57dad30a-5216-11e5-88c3-6c40088e03e4<commit_msg>57e1a928-5216-11e5-b345-6c40088e03e4<commit_after>57e1a928-5216-11e5-b345-6c40088e03e4<|endoftext|> |
<commit_before>e3772478-585a-11e5-b4f9-6c40088e03e4<commit_msg>e37def24-585a-11e5-9ddb-6c40088e03e4<commit_after>e37def24-585a-11e5-9ddb-6c40088e03e4<|endoftext|> |
<commit_before>e81133b3-327f-11e5-95e1-9cf387a8033e<commit_msg>e816f221-327f-11e5-9598-9cf387a8033e<commit_after>e816f221-327f-11e5-9598-9cf387a8033e<|endoftext|> |
<commit_before>81cf0e01-2d15-11e5-af21-0401358ea401<commit_msg>81cf0e02-2d15-11e5-af21-0401358ea401<commit_after>81cf0e02-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <irrlicht/irrlicht.h>
#include <irrlicht/driverChoice.h>
#include "controlterm.cpp"
const char* disp = ":1";
//#pragma comment(lib, "Irrlicht.lib")
using namespace irr;
//using namespace core;
//using namespace scene;
//using namespace video;
//using namespace io;
//using namespace gui;
//
enum {
ID_IsNotPickable = 0,
IDFlag_IsSolid = 1 << 0,
IDFlag_IsInteractable = 1 << 1
};
X11Display xdisp(disp);
class VREventReceiver : public IEventReceiver {
public:
virtual bool OnEvent(const SEvent& event){
if(event.EventType == irr::EET_KEY_INPUT_EVENT){
if(IsModKey(event.KeyInput.Key)){
if(event.KeyInput.PressedDown){
CurrentMod |= mapKeyCode(event.KeyInput.Key);
} else {
CurrentMod &= ~mapKeyCode(event.KeyInput.Key);
}
} else {
KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
xdisp.sendKeyEvent(mapKeyCode(event.KeyInput.Key), event.KeyInput.PressedDown, CurrentMod);
}
}
return false;
}
virtual bool IsKeyDown(EKEY_CODE keyCode) const {
return KeyIsDown[keyCode];
}
private:
bool KeyIsDown[KEY_KEY_CODES_COUNT];
// FIXME: can initialise to nonzero
int CurrentMod;
};
int main() {
// Uses driverChoiceConsole() from driverChoice.h
VREventReceiver receiver;
IrrlichtDevice *device = createDevice(driverChoiceConsole(), core::dimension2d<u32>(512, 384), 16, false, false, false, &receiver);
device->setWindowCaption(L"Grimmware VRHackspace::Mk I");
// set up video driver, scene manager and gui environment
video::IVideoDriver* driver = device->getVideoDriver();
scene::ISceneManager* smgr = device->getSceneManager();
gui::IGUIEnvironment* guienv = device->getGUIEnvironment();
video::SMaterial selectMaterial;
selectMaterial.Wireframe = true;
selectMaterial.Lighting = false;
scene::IBillboardSceneNode * bill = smgr->addBillboardSceneNode();
bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
bill->setMaterialTexture(0, driver->getTexture("media/particle.jpg"));
bill->setMaterialFlag(video::EMF_LIGHTING, false);
bill->setMaterialFlag(video::EMF_ZBUFFER, false);
bill->setSize(core::dimension2d<f32>(20.0f, 20.0f));
bill->setID(ID_IsNotPickable); // This ensures that we don't accidentally ray-pick it
scene::IMeshSceneNode *cube = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(10,-10,10), core::vector3df(0,0,0), core::vector3df(4, 4, 1));
cube->setMaterialFlag(video::EMF_LIGHTING, true);
if(cube){
scene::ITriangleSelector* selector = smgr->createTriangleSelectorFromBoundingBox( cube );
cube->setTriangleSelector( selector );
selector->drop();
}
scene::ITriangleSelector* cubeSelector = cube->getTriangleSelector();
// Create the level and the collision levelSelector
device->getFileSystem()->addFileArchive("models/map-20kdm2.pk3");
scene::IAnimatedMesh* levelMesh = smgr->getMesh("20kdm2.bsp");
scene::IMeshSceneNode* levelNode = 0;
scene::ITriangleSelector* levelSelector = 0;
scene::IMetaTriangleSelector* cameraCollisionSelector =
smgr->createMetaTriangleSelector();
if (levelMesh) {
levelNode = smgr->addOctreeSceneNode(levelMesh->getMesh(0), 0, IDFlag_IsSolid);
// node = smgr->addMeshSceneNode(mesh->getMesh(0));
if(levelNode){
levelNode->setPosition(core::vector3df(-1350,-130,-1400));
levelSelector = smgr->createOctreeTriangleSelector(
levelNode->getMesh(), levelNode, 128);
cameraCollisionSelector->addTriangleSelector(levelSelector);
cameraCollisionSelector->addTriangleSelector(cubeSelector);
levelNode->setTriangleSelector(levelSelector);
}
}
//Create camera and pin it to the floor
scene::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS(0, 100.0f, .3f, ID_IsNotPickable, 0, 0, true, 3.f);
camera->setPosition(core::vector3df(50,50,-60));
//Add collision to the camera
if (levelSelector) {
scene::ISceneNodeAnimator* levelAnim = smgr->createCollisionResponseAnimator(
cameraCollisionSelector, camera, core::vector3df(30,50,30),
core::vector3df(0,-10,0), core::vector3df(0,30,0));
levelSelector->drop(); // As soon as we're done with the levelSelector, drop it.
camera->addAnimator(levelAnim);
levelAnim->drop(); // And likewise, drop the animator when we're done referring to it.
}
device->getCursorControl()->setVisible(false);
//camera->setTarget(cube->getAbsolutePosition());
int lastFPS = -1;
video::ITexture * texture;
while(device->run()) {
device->getVideoDriver()->removeTexture(texture);
texture = driver->getTexture("/tmp/vrhs/shot.png");
cube->setMaterialTexture(0, texture);
// Make the pointy pointer thingy
core::line3d<f32> ray;
ray.start = camera->getPosition();
ray.end = ray.start + (camera->getTarget() - ray.start).normalize() * 1000.0f;
scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();
core::vector3df intersection;
core::triangle3df hitTriangle;
driver->beginScene(true, true, video::SColor(255,100,101,140));
scene::ISceneNode * selectedSceneNode =
collMan->getSceneNodeAndCollisionPointFromRay(
ray,
intersection,
hitTriangle,
IDFlag_IsInteractable,
0);
if(selectedSceneNode)
{
bill->setPosition(intersection);
driver->setTransform(video::ETS_WORLD, core::matrix4());
driver->setMaterial(selectMaterial);
driver->draw3DTriangle(hitTriangle, video::SColor(0, 255, 0, 0));
}
smgr->drawAll();
guienv->drawAll();
driver->endScene();
}
device->drop();
return 0;
}
<commit_msg>Some weird shit<commit_after>#include <irrlicht/irrlicht.h>
#include <irrlicht/driverChoice.h>
#include "controlterm.cpp"
const char* disp = ":1";
//#pragma comment(lib, "Irrlicht.lib")
using namespace irr;
//using namespace core;
//using namespace scene;
//using namespace video;
//using namespace io;
//using namespace gui;
//
enum {
ID_IsNotPickable = 0,
IDFlag_IsSolid = 1 << 0,
IDFlag_IsInteractable = 1 << 1
};
X11Display xdisp(disp);
class VREventReceiver : public IEventReceiver {
public:
virtual bool OnEvent(const SEvent& event){
if(event.EventType == irr::EET_KEY_INPUT_EVENT){
if(IsModKey(event.KeyInput.Key)){
if(event.KeyInput.PressedDown){
//FIXME: shit sometimes gets weird here
CurrentMod |= mapKeyCode(event.KeyInput.Key);
} else {
CurrentMod &= ~mapKeyCode(event.KeyInput.Key);
}
} else {
KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
xdisp.sendKeyEvent(mapKeyCode(event.KeyInput.Key), event.KeyInput.PressedDown, CurrentMod);
}
}
return false;
}
virtual bool IsKeyDown(EKEY_CODE keyCode) const {
return KeyIsDown[keyCode];
}
private:
bool KeyIsDown[KEY_KEY_CODES_COUNT];
// FIXME: can initialise to nonzero
int CurrentMod;
};
int main() {
// Uses driverChoiceConsole() from driverChoice.h
VREventReceiver receiver;
IrrlichtDevice *device = createDevice(driverChoiceConsole(), core::dimension2d<u32>(512, 384), 16, false, false, false, &receiver);
device->setWindowCaption(L"Grimmware VRHackspace::Mk I");
// set up video driver, scene manager and gui environment
video::IVideoDriver* driver = device->getVideoDriver();
scene::ISceneManager* smgr = device->getSceneManager();
gui::IGUIEnvironment* guienv = device->getGUIEnvironment();
video::SMaterial selectMaterial;
selectMaterial.Wireframe = true;
selectMaterial.Lighting = false;
scene::IBillboardSceneNode * bill = smgr->addBillboardSceneNode();
bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
bill->setMaterialTexture(0, driver->getTexture("media/particle.jpg"));
bill->setMaterialFlag(video::EMF_LIGHTING, false);
bill->setMaterialFlag(video::EMF_ZBUFFER, false);
bill->setSize(core::dimension2d<f32>(20.0f, 20.0f));
bill->setID(ID_IsNotPickable); // This ensures that we don't accidentally ray-pick it
// Set up terminal
scene::IMeshSceneNode *cube = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(10,-10,10), core::vector3df(0,0,0), core::vector3df(4, 4, 1));
cube->setMaterialFlag(video::EMF_LIGHTING, true);
if(cube){
scene::ITriangleSelector* selector = smgr->createTriangleSelectorFromBoundingBox( cube );
cube->setTriangleSelector( selector );
selector->drop();
}
scene::ITriangleSelector* cubeSelector = cube->getTriangleSelector();
// Add lighting
scene::ISceneNode* light = smgr->addLightSceneNode(0, core::vector3df(10,20,20),
video::SColorf(1.0f, 0.6f, 0.7f, 1.0f), 800.0f);
scene::IMeshSceneNode *room = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(10,-10,10), core::vector3df(0,0,0), core::vector3df(30, 30, 30));
smgr->getMeshManipulator()->flipSurfaces(room->getMesh());
room->setMaterialFlag(video::EMF_LIGHTING, false);
room->setMaterialTexture(0, driver->getTexture("media/texture.jpg"));
room->setTriangleSelector(smgr->createTriangleSelector( room->getMesh(), room ));
bool yesLevel = true;
int collideablesNumber = 3;
scene::ITriangleSelector* collideables[collideablesNumber];
collideables[0] = cubeSelector;
collideables[1] = room->getTriangleSelector();
scene::IMetaTriangleSelector* cameraCollisionSelector =
smgr->createMetaTriangleSelector();
if(yesLevel){
// Create the level and the collision levelSelector
device->getFileSystem()->addFileArchive("models/map-20kdm2.pk3");
scene::IAnimatedMesh* levelMesh = smgr->getMesh("20kdm2.bsp");
scene::IMeshSceneNode* levelNode = 0;
scene::ITriangleSelector* levelSelector = 0;
if (levelMesh) {
levelNode = smgr->addOctreeSceneNode(levelMesh->getMesh(0), 0, IDFlag_IsSolid);
// node = smgr->addMeshSceneNode(mesh->getMesh(0));
if(levelNode){
levelNode->setMaterialFlag(video::EMF_LIGHTING, true);
levelNode->setPosition(core::vector3df(-1350,-130,-1400));
levelSelector = smgr->createOctreeTriangleSelector(
levelNode->getMesh(), levelNode, 128);
collideables[2] = levelSelector;
levelNode->setTriangleSelector(levelSelector);
levelSelector->drop(); // As soon as we're done with the levelSelector, drop it.
}
}
} else {
collideablesNumber = 2;
}
for(int i=0; i<collideablesNumber; i++){
cameraCollisionSelector->addTriangleSelector(collideables[i]);
}
//Create camera and pin it to the floor
scene::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS(0, 100.0f, .3f, ID_IsNotPickable, 0, 0, true, 3.f);
camera->setPosition(core::vector3df(50,50,-60));
//Add collision to the camera
scene::ISceneNodeAnimator* levelAnim = smgr->createCollisionResponseAnimator(
cameraCollisionSelector, camera, core::vector3df(30,50,30),
core::vector3df(0,-10,0), core::vector3df(0,30,0));
camera->addAnimator(levelAnim);
levelAnim->drop(); // And likewise, drop the animator when we're done referring to it.
device->getCursorControl()->setVisible(false);
//camera->setTarget(cube->getAbsolutePosition());
int lastFPS = -1;
video::ITexture * texture;
scene::ISceneNode* lastSelectedSceneNode = NULL;
while(device->run()) {
device->getVideoDriver()->removeTexture(texture);
texture = driver->getTexture("/tmp/vrhs/shot.png");
cube->setMaterialTexture(0, texture);
// Make the pointy pointer thingy
core::line3d<f32> ray;
ray.start = camera->getPosition();
ray.end = ray.start + (camera->getTarget() - ray.start).normalize() * 1000.0f;
scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();
core::vector3df intersection;
core::triangle3df hitTriangle;
driver->beginScene(true, true, video::SColor(255,100,101,140));
scene::ISceneNode * selectedSceneNode =
collMan->getSceneNodeAndCollisionPointFromRay(
ray,
intersection,
hitTriangle,
IDFlag_IsInteractable,
0);
if(lastSelectedSceneNode) lastSelectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, true);
if(selectedSceneNode)
{
bill->setPosition(intersection);
driver->setTransform(video::ETS_WORLD, core::matrix4());
driver->setMaterial(selectMaterial);
driver->draw3DTriangle(hitTriangle, video::SColor(0, 255, 0, 0));
selectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, false);
lastSelectedSceneNode = selectedSceneNode;
}
smgr->drawAll();
guienv->drawAll();
driver->endScene();
}
device->drop();
return 0;
}
<|endoftext|> |
<commit_before>a33e9019-2e4f-11e5-bce6-28cfe91dbc4b<commit_msg>a345addc-2e4f-11e5-8d0e-28cfe91dbc4b<commit_after>a345addc-2e4f-11e5-8d0e-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <bits/stl_algo.h>
#include <bitset>
#include <fstream>
#include <chrono>
using namespace std;
typedef struct GraphTree {
unsigned char symbol;
unsigned char symbolExtended;
unsigned long long int nrOfApp;
GraphTree *parent;
GraphTree *left;
GraphTree *right;
unsigned long long int index;
} ShannonTree;
typedef std::vector<GraphTree *> GraphIndex;
typedef std::map<int, std::pair<GraphTree *, std::string>> MappedSymbols;
typedef std::chrono::duration<int, std::milli> miliseconds_type;
typedef struct GraphSearch {
std::string code;
bool type;
GraphTree *reference;
};
int ENCODE_BITS = 8;
int ESC_VALUE = 257;
int EOS_VALUE = 256;
MappedSymbols symbolMap;
GraphIndex indexedGraph;
auto
cmp = [](std::pair<unsigned char, unsigned long int> const &a, std::pair<unsigned char, unsigned long int> const &b) {
return a.second != b.second ? a.second > b.second : a.first < b.first;
};
GraphTree *initGraph() {
GraphTree *parent, *left, *right;
parent = new GraphTree;
left = new GraphTree;
right = new GraphTree;
parent->symbol = 0;
parent->symbolExtended = 0;
parent->nrOfApp = 2;
parent->parent = NULL;
parent->left = left;
parent->right = right;
parent->index = 1;
indexedGraph.push_back(parent);
left->parent = parent;
right->parent = parent;
left->left = NULL;
left->right = NULL;
right->left = NULL;
right->right = NULL;
left->symbol = 255;
left->symbolExtended = 1;
right->symbol = 255;
right->symbolExtended = 2;
left->nrOfApp = 1;
right->nrOfApp = 1;
left->index = 2;
right->index = 3;
indexedGraph.push_back(left);
indexedGraph.push_back(right);
symbolMap[right->symbol + right->symbolExtended].first = right;
symbolMap[right->symbol + right->symbolExtended].second = "1";
symbolMap[left->symbol + left->symbolExtended].first = left;
symbolMap[left->symbol + left->symbolExtended].second = "0";
return parent;
}
/**
* find symbol in alphabet map, if it is first occurence for symbol return a reference for ESC symbol
*/
GraphSearch findSymbol(unsigned char symbol) {
GraphSearch result;
if (symbolMap.count(symbol) > 0) {
result.code = symbolMap[symbol].second;
result.type = true;
result.reference = symbolMap[symbol].first;
} else {
result.code = symbolMap[ESC_VALUE].second;
result.type = false;
result.reference = symbolMap[ESC_VALUE].first;
}
return result;
}
void updateSymbol(GraphSearch result) {
(result.reference)->nrOfApp = (result.reference)->nrOfApp + 1;
}
void addSymbol(GraphSearch result, unsigned char symbol) {
GraphTree *left, *right;
left = new GraphTree;
left->nrOfApp = 1;
left->right = NULL;
left->left = NULL;
left->symbol = symbol;
left->symbolExtended = 0;
left->parent = result.reference;
left->index = (result.reference)->index + 1;
right = new GraphTree;
right->nrOfApp = 1;
right->right = NULL;
right->left = NULL;
right->symbol = 255;
right->symbolExtended = 2;
right->parent = result.reference;
right->index = (result.reference)->index + 2;
(result.reference)->left = left;
(result.reference)->right = right;
(result.reference)->nrOfApp = 2;
(result.reference)->symbol = 0;
(result.reference)->symbolExtended = 0;
indexedGraph.push_back(left);
indexedGraph.push_back(right);
symbolMap[ESC_VALUE].first = right;
}
void displayIndexedGraph() {
GraphIndex::size_type iterator;
for (iterator = 0; iterator < indexedGraph.size(); ++iterator) {
std::cout << (indexedGraph[iterator])->nrOfApp << " " << (indexedGraph[iterator])->index << " -> " << iterator + 1 << "\n";
}
}
void displayGraph(GraphTree *root) {
if ((root->symbol + root->symbolExtended) == 0) {
std::cout << "Pondere: " << root->nrOfApp << "\n";
displayGraph(root->left);
displayGraph(root->right);
} else {
std::cout << "Simbol: " << (root->symbol + root->symbolExtended) << "\n";
}
}
void balanceGraph(GraphTree *node) {
GraphTree *aux, *changeAux, *parent;
GraphIndex::size_type iterator, auxIndex;
for (iterator = node->index - 1; iterator > 0; iterator--) {
if ((indexedGraph[iterator - 1])->nrOfApp >= node->nrOfApp) {
break;
}
}
if (iterator == node->index - 1) {
node->parent->nrOfApp++;
if (node->parent->parent != NULL) {
balanceGraph(node->parent);
}
return void();
}
if (iterator == node->index - 2) {
(indexedGraph[iterator - 1])->right = indexedGraph[iterator];
(indexedGraph[iterator - 1])->left = node;
indexedGraph[iterator]->index++;
node->index--;
indexedGraph[iterator] = node;
indexedGraph[iterator + 1] = (indexedGraph[iterator - 1])->right;
balanceGraph(node);
return void();
}
if ((iterator - (node->index - 2)) > 0 && node->index - 2 >= 0) {
aux = indexedGraph[iterator - 1];
indexedGraph[iterator - 1] = node;
auxIndex = node->index;
parent = aux->parent;
changeAux = node->parent;
if (iterator % 2 == 0) {
parent->left = node;
} else {
parent->right = node;
}
node->parent = parent;
indexedGraph[auxIndex - 1] = aux;
if (auxIndex % 2 == 0) {
changeAux->left = node;
} else {
changeAux->right = node;
}
balanceGraph(indexedGraph[iterator - 1]);
//return void();
}
//return void();
}
void encodeSymbol(unsigned char symbol, GraphTree *parent) {
GraphSearch result;
result = findSymbol(symbol);
if (result.type == true) {
updateSymbol(result);
} else {
addSymbol(result, symbol);
}
balanceGraph(result.reference);
}
void swapChild(GraphTree *root) {
GraphTree *aux;
aux = root->left;
root->left = root->right;
root->right = aux;
}
void balanceTree(GraphTree *root) {
if ((root->symbol + root->symbolExtended) == 0) {
if (root->left->nrOfApp < root->right->nrOfApp) {
swapChild(root);
}
}
}
void encodeFile() {
}
void compressFile(std::string fileName) {
GraphTree *huffmanTree;
huffmanTree = initGraph();
encodeSymbol('a', huffmanTree);
encodeSymbol('b', huffmanTree);
displayIndexedGraph();
std::cout << "\n\n";
displayGraph(huffmanTree);
// balanceTree(huffmanTree);
// encodeSymbol('b', huffmanTree);
// balanceTree(huffmanTree);
// std::cout << "\n\n";
// displayGraph(huffmanTree);
}
void uncompressFile(std::string fileName) {
}
void displayOptions() {
std::cout << "Alege fisierul!" << "\n\n Audio:\n";
std::cout << "\t1.)instr_01.wav\n";
std::cout << "\t2.)sound_01.wav\n";
std::cout << "\t3.)speech_01.wav\n";
std::cout << "\nDocuments:\n";
std::cout << "\t4.)Documentatie_UMAPID.doc\n";
std::cout << "\t5.)Documentatie_UMAPID.pdf\n";
std::cout << "\t6.)Prefata_Undine.txt\n";
std::cout << "\t7.)show_audio.m\n";
std::cout << "\t8.)Y04.M\n";
std::cout << "\nExecutables:\n";
std::cout << "\t9.)KARMA_DATA482#1_5_V7.mat\n";
std::cout << "\t10.)quartz.dll\n";
std::cout << "\t11.)WinRar.exe\n";
std::cout << "\t12.)WINZIP32.EXE\n";
}
std::ifstream::pos_type filesize(std::string fileName) {
std::ifstream in(fileName.c_str(), std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
void displayInformations(std::string fileName) {
std::ifstream::pos_type compressedFileSize, fileSize, uncompressedFileSize;
std::string compressedFileName, uncompressedFileName;
compressedFileName = fileName + ".psh";
uncompressedFileName = fileName + ".pshu";
compressedFileSize = filesize(compressedFileName);
fileSize = filesize(fileName);
uncompressedFileSize = filesize(uncompressedFileName);
std::cout << "Norma: " << (fileSize - uncompressedFileSize) * (fileSize - uncompressedFileSize) << "\n";
std::cout << "Rata compresie: " << (1 - ((float) compressedFileSize) / ((float) uncompressedFileSize)) * 100 << "%\n";
std::cout << "Factor compresie: " << (((float) compressedFileSize) / ((float) fileSize)) * 100 << "%\n";
}
int main() {
std::vector<std::string> files = {
".\\audio\\instr_01.wav",
".\\audio\\sound_01.wav",
".\\audio\\speech_01.wav",
".\\documents\\Documentatie_UMAPID.doc",
".\\documents\\Documentatie_UMAPID.pdf",
".\\documents\\Prefata_Undine.txt",
".\\documents\\show_audio.m",
".\\documents\\Y04.M",
".\\executables\\KARMA_DATA482#1_5_V7.mat",
".\\executables\\quartz.dll",
".\\executables\\WinRar.exe",
".\\executables\\WINZIP32.EXE",
".\\documents\\input.txt",
"D:\\input.txt",
};
int option;
//displayOptions();
//std::cout << "Select file!..\n";
//std::cin >> option;
// if (option < 1 && option > 14) {
// std::cout << "Invalid option!";
// return 0;
// }
auto startC = std::chrono::high_resolution_clock::now();
compressFile(files[2]);
auto endC = std::chrono::high_resolution_clock::now();
auto timeC = endC - startC;
std::cout << "Compressed time: " << std::chrono::duration_cast<miliseconds_type>(timeC).count() << " miliseconds.\n";
auto startU = std::chrono::high_resolution_clock::now();
// uncompressFile(files[option - 1]);
auto endU = std::chrono::high_resolution_clock::now();
auto timeU = endU - startU;
std::cout << "Uncompressed time: " << std::chrono::duration_cast<miliseconds_type>(timeU).count() << " miliseconds.\n";
// displayInformations(files[option - 1]);
//std::cin >> option;
return 0;
}<commit_msg>update encodeSymbol method to work for "abc" string<commit_after>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <bits/stl_algo.h>
#include <bitset>
#include <fstream>
#include <chrono>
using namespace std;
typedef struct GraphTree {
unsigned char symbol;
unsigned char symbolExtended;
unsigned long long int nrOfApp;
GraphTree *parent;
GraphTree *left;
GraphTree *right;
unsigned long long int index;
} ShannonTree;
typedef std::vector<GraphTree *> GraphIndex;
typedef std::map<int, std::pair<GraphTree *, std::string>> MappedSymbols;
typedef std::chrono::duration<int, std::milli> miliseconds_type;
typedef struct GraphSearch {
std::string code;
bool type;
GraphTree *reference;
};
int ENCODE_BITS = 8;
int ESC_VALUE = 257;
int EOS_VALUE = 256;
MappedSymbols symbolMap;
GraphIndex indexedGraph;
auto
cmp = [](std::pair<unsigned char, unsigned long int> const &a, std::pair<unsigned char, unsigned long int> const &b) {
return a.second != b.second ? a.second > b.second : a.first < b.first;
};
GraphTree *initGraph() {
GraphTree *parent, *left, *right;
parent = new GraphTree;
left = new GraphTree;
right = new GraphTree;
parent->symbol = 0;
parent->symbolExtended = 0;
parent->nrOfApp = 2;
parent->parent = NULL;
parent->left = left;
parent->right = right;
parent->index = 1;
indexedGraph.push_back(parent);
left->parent = parent;
right->parent = parent;
left->left = NULL;
left->right = NULL;
right->left = NULL;
right->right = NULL;
left->symbol = 255;
left->symbolExtended = 1;
right->symbol = 255;
right->symbolExtended = 2;
left->nrOfApp = 1;
right->nrOfApp = 1;
left->index = 2;
right->index = 3;
indexedGraph.push_back(left);
indexedGraph.push_back(right);
symbolMap[right->symbol + right->symbolExtended].first = right;
symbolMap[right->symbol + right->symbolExtended].second = "1";
symbolMap[left->symbol + left->symbolExtended].first = left;
symbolMap[left->symbol + left->symbolExtended].second = "0";
return parent;
}
/**
* find symbol in alphabet map, if it is first occurence for symbol return a reference for ESC symbol
*/
GraphSearch findSymbol(unsigned char symbol) {
GraphSearch result;
if (symbolMap.count(symbol) > 0) {
result.code = symbolMap[symbol].second;
result.type = true;
result.reference = symbolMap[symbol].first;
} else {
result.code = symbolMap[ESC_VALUE].second;
result.type = false;
result.reference = symbolMap[ESC_VALUE].first;
}
return result;
}
void updateSymbol(GraphSearch result) {
(result.reference)->nrOfApp = (result.reference)->nrOfApp + 1;
}
void addSymbol(GraphSearch result, unsigned char symbol) {
GraphTree *left, *right;
left = new GraphTree;
left->nrOfApp = 1;
left->right = NULL;
left->left = NULL;
left->symbol = symbol;
left->symbolExtended = 0;
left->parent = result.reference;
left->index = (result.reference)->index + 1;
right = new GraphTree;
right->nrOfApp = 1;
right->right = NULL;
right->left = NULL;
right->symbol = 255;
right->symbolExtended = 2;
right->parent = result.reference;
right->index = (result.reference)->index + 2;
(result.reference)->left = left;
(result.reference)->right = right;
(result.reference)->nrOfApp = 2;
(result.reference)->symbol = 0;
(result.reference)->symbolExtended = 0;
indexedGraph.push_back(left);
indexedGraph.push_back(right);
symbolMap[ESC_VALUE].first = right;
}
void displayIndexedGraph() {
GraphIndex::size_type iterator;
for (iterator = 0; iterator < indexedGraph.size(); ++iterator) {
std::cout << ((indexedGraph[iterator])->symbol + (indexedGraph[iterator])->symbolExtended) << " " << (indexedGraph[iterator])->index << " -> " << iterator + 1 << " " << (indexedGraph[iterator])->nrOfApp << "\n";
}
std::cout << "\n\n";
}
void displayGraph(GraphTree *root) {
if ((root->symbol + root->symbolExtended) == 0) {
std::cout << "Pondere: " << root->nrOfApp << "\n";
displayGraph(root->left);
displayGraph(root->right);
} else {
std::cout << "Simbol: " << (root->symbol + root->symbolExtended) << "\n";
}
}
void balanceGraph(GraphTree *node) {
GraphTree *aux, *changeAux, *parent;
GraphIndex::size_type iterator, auxIndex;
for (iterator = node->index - 1; iterator > 0; iterator--) {
if ((indexedGraph[iterator - 1])->nrOfApp >= node->nrOfApp) {
break;
}
}
if (iterator == node->index - 1) {
node->parent->nrOfApp++;
if (node->parent->parent != NULL) {
balanceGraph(node->parent);
}
return void();
}
if (iterator == node->index - 2) {
(indexedGraph[iterator - 1])->right = indexedGraph[iterator];
(indexedGraph[iterator - 1])->left = node;
indexedGraph[iterator]->index++;
node->index--;
indexedGraph[iterator] = node;
indexedGraph[iterator + 1] = (indexedGraph[iterator - 1])->right;
balanceGraph(node);
return void();
}
if ((iterator - (node->index - 2)) > 0 && node->index - 2 >= 0) {
aux = indexedGraph[iterator];
auxIndex = node->index;
node->index = aux->index;
aux->index = auxIndex;
indexedGraph[iterator] = node;
parent = aux->parent;
changeAux = node->parent;
if (iterator % 2 == 1) {
parent->left = node;
} else {
parent->right = node;
}
node->parent = parent;
indexedGraph[auxIndex - 1] = aux;
if (auxIndex % 2 == 0) {
changeAux->left = aux;
} else {
changeAux->right = aux;
}
balanceGraph(indexedGraph[iterator]);
//return void();
}
//return void();
}
/**
* Update symbol map
*/
void updateMap() {
int symbol;
GraphIndex::size_type iterator;
for (iterator = 0; iterator < indexedGraph.size(); iterator++) {
symbol = indexedGraph[iterator]->symbolExtended + indexedGraph[iterator]->symbol;
if (symbol > 0) {
symbolMap[symbol].first = indexedGraph[iterator];
}
}
}
void encodeSymbol(unsigned char symbol, GraphTree *parent) {
GraphSearch result;
result = findSymbol(symbol);
if (result.type == true) {
updateSymbol(result);
} else {
addSymbol(result, symbol);
}
balanceGraph(result.reference);
updateMap();
}
void swapChild(GraphTree *root) {
GraphTree *aux;
aux = root->left;
root->left = root->right;
root->right = aux;
}
void balanceTree(GraphTree *root) {
if ((root->symbol + root->symbolExtended) == 0) {
if (root->left->nrOfApp < root->right->nrOfApp) {
swapChild(root);
}
}
}
void encodeFile() {
}
void compressFile(std::string fileName) {
GraphTree *huffmanTree;
huffmanTree = initGraph();
encodeSymbol('a', huffmanTree);
encodeSymbol('b', huffmanTree);
encodeSymbol('c', huffmanTree);
encodeSymbol('a', huffmanTree);
// encodeSymbol('e', huffmanTree);
// encodeSymbol('f', huffmanTree);
// encodeSymbol('g', huffmanTree);
displayIndexedGraph();
displayGraph(huffmanTree);
}
void uncompressFile(std::string fileName) {
}
void displayOptions() {
std::cout << "Alege fisierul!" << "\n\n Audio:\n";
std::cout << "\t1.)instr_01.wav\n";
std::cout << "\t2.)sound_01.wav\n";
std::cout << "\t3.)speech_01.wav\n";
std::cout << "\nDocuments:\n";
std::cout << "\t4.)Documentatie_UMAPID.doc\n";
std::cout << "\t5.)Documentatie_UMAPID.pdf\n";
std::cout << "\t6.)Prefata_Undine.txt\n";
std::cout << "\t7.)show_audio.m\n";
std::cout << "\t8.)Y04.M\n";
std::cout << "\nExecutables:\n";
std::cout << "\t9.)KARMA_DATA482#1_5_V7.mat\n";
std::cout << "\t10.)quartz.dll\n";
std::cout << "\t11.)WinRar.exe\n";
std::cout << "\t12.)WINZIP32.EXE\n";
}
std::ifstream::pos_type filesize(std::string fileName) {
std::ifstream in(fileName.c_str(), std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
void displayInformations(std::string fileName) {
std::ifstream::pos_type compressedFileSize, fileSize, uncompressedFileSize;
std::string compressedFileName, uncompressedFileName;
compressedFileName = fileName + ".psh";
uncompressedFileName = fileName + ".pshu";
compressedFileSize = filesize(compressedFileName);
fileSize = filesize(fileName);
uncompressedFileSize = filesize(uncompressedFileName);
std::cout << "Norma: " << (fileSize - uncompressedFileSize) * (fileSize - uncompressedFileSize) << "\n";
std::cout << "Rata compresie: " << (1 - ((float) compressedFileSize) / ((float) uncompressedFileSize)) * 100 << "%\n";
std::cout << "Factor compresie: " << (((float) compressedFileSize) / ((float) fileSize)) * 100 << "%\n";
}
int main() {
std::vector<std::string> files = {
".\\audio\\instr_01.wav",
".\\audio\\sound_01.wav",
".\\audio\\speech_01.wav",
".\\documents\\Documentatie_UMAPID.doc",
".\\documents\\Documentatie_UMAPID.pdf",
".\\documents\\Prefata_Undine.txt",
".\\documents\\show_audio.m",
".\\documents\\Y04.M",
".\\executables\\KARMA_DATA482#1_5_V7.mat",
".\\executables\\quartz.dll",
".\\executables\\WinRar.exe",
".\\executables\\WINZIP32.EXE",
".\\documents\\input.txt",
"D:\\input.txt",
};
int option;
//displayOptions();
//std::cout << "Select file!..\n";
//std::cin >> option;
// if (option < 1 && option > 14) {
// std::cout << "Invalid option!";
// return 0;
// }
auto startC = std::chrono::high_resolution_clock::now();
compressFile(files[2]);
auto endC = std::chrono::high_resolution_clock::now();
auto timeC = endC - startC;
std::cout << "Compressed time: " << std::chrono::duration_cast<miliseconds_type>(timeC).count() << " miliseconds.\n";
auto startU = std::chrono::high_resolution_clock::now();
// uncompressFile(files[option - 1]);
auto endU = std::chrono::high_resolution_clock::now();
auto timeU = endU - startU;
std::cout << "Uncompressed time: " << std::chrono::duration_cast<miliseconds_type>(timeU).count() << " miliseconds.\n";
// displayInformations(files[option - 1]);
//std::cin >> option;
return 0;
}<|endoftext|> |
<commit_before>//90% finished
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <mach/mach_traps.h>
#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach.h>
#include <mach-o/dyld_images.h>
#include <mach-o/loader.h>
#include <libproc.h>
#include <sys/stat.h>
#include <string>
#include <sstream>
using namespace std;
mach_port_t task;
uint64_t Client, SizeClient;
uint8_t * buffer;
////
// define global patterns
////
string LocalPlayer = "4839DF74??4885FF74??4889DEE8????????EB??";
string EntityList = "554889E54156534889FBBE??000000E8????????8B??????????83F8FF";
string Glow = "48C7????e?2E05????????488D??????????488D??????????E8";
////
// copy client.dylib to our program memory
////
int GetCSpid() {
int csgopid ;
int numberOfProcesses = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
pid_t pids[numberOfProcesses];
bzero(pids, sizeof(pids));
proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
for (int i = 0; i < numberOfProcesses; ++i) {
if (pids[i] == 0) { continue; }
char pathBuffer[PROC_PIDPATHINFO_MAXSIZE];
bzero(pathBuffer, PROC_PIDPATHINFO_MAXSIZE);
proc_pidpath(pids[i], pathBuffer, sizeof(pathBuffer));
char nameBuffer[256];
int position = strlen(pathBuffer);
while(position >= 0 && pathBuffer[position] != '/')
{
position--;
}
strcpy(nameBuffer, pathBuffer + position + 1);
if (strcmp(nameBuffer, "csgo_osx64")==0) {
return pids[i];
}
}
return 0;
}
void ClientToBuffer() {
kern_return_t kret;
mach_vm_address_t address;
int csgopid = GetCSpid();
kret = task_for_pid(mach_task_self(), csgopid, &task);
if (kret!=KERN_SUCCESS)
{
printf("task_for_pid() failed with message %s!\n",mach_error_string(kret));
exit(0);
}
struct task_dyld_info dyld_info;
mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
if (task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count) == KERN_SUCCESS)
{
address = dyld_info.all_image_info_addr;
}
mach_msg_type_number_t size = sizeof(struct dyld_all_image_infos);
vm_offset_t readMem;
vm_read(task,address,size,&readMem,&size);
struct dyld_all_image_infos* infos = (struct dyld_all_image_infos *) readMem;
size = sizeof(struct dyld_image_info) * infos->infoArrayCount;
vm_read(task,(mach_vm_address_t) infos->infoArray,size,&readMem,&size);
struct dyld_image_info* info = (struct dyld_image_info*) readMem;
mach_msg_type_number_t sizeMax=512;
for (int i=0; i < infos->infoArrayCount; i++) {
vm_read(task,(mach_vm_address_t) info[i].imageFilePath,sizeMax,&readMem,&sizeMax);
char *path = (char *) readMem ;
if(strstr(path, "/client.dylib") != NULL){
Client = (mach_vm_address_t)info[i].imageLoadAddress ;
struct stat st;
stat(path, &st);
printf("client: 0x%llx %lld\n", Client, st.st_size);
uint8_t * m_data;
m_data = new uint8_t[st.st_size];
sizeMax = st.st_size;
vm_read(task,(vm_address_t)Client,sizeMax,&readMem,&sizeMax);
uint64_t address = (uint64_t)readMem;
buffer = (uint8_t *)address;
SizeClient = st.st_size;
}
}
}
uint64_t Scan(string s){
stringstream ss;
bool flag = true;
for (int j=0;j<(SizeClient-(s.size())/2 + 1);j++){
flag = true;
for (int i=0; i<(s.size())/2; i++){
string bytechar = s.substr(2*i,2);
if (bytechar.compare("??") != 0){
if (bytechar.substr(1,1).compare("?") == 0){
char byte[2];
int out;
out = sprintf(byte, "%x",buffer[i+j]);
string bytebuffer (byte);
if (bytebuffer.length()==1){
bytebuffer = "0"+bytebuffer;
}
//cout << bytebuffer << endl;
if (bytechar.substr(0,1).compare(bytebuffer.substr(0,1))!=0){
//cout << bytechar << bytebuffer << endl;
flag=false;
break;
}
continue;
}
uint8_t byte = std::stoi(bytechar, NULL,16);
if (byte != buffer[j+i]){
flag = false;
break;
}
}
}
if (flag){
return (Client+j);
}
}
return 0;
}
int main(int argc, const char * argv[]) {
// insert code here...
ClientToBuffer();
printf("%x\n",buffer[0]);
printf("%llx\n",Scan(LocalPlayer));
printf("%llx\n",Scan(EntityList));
printf("%llx\n",Scan(Glow));
uint8_t test = 0x1e ;
string conv = std::to_string(test);
cout << conv << endl;
return 0;
}
<commit_msg>Final commit<commit_after>#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <mach/mach_traps.h>
#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach.h>
#include <mach-o/dyld_images.h>
#include <mach-o/loader.h>
#include <libproc.h>
#include <sys/stat.h>
#include <string>
#include <sstream>
using namespace std;
mach_port_t task;
uint64_t Client, SizeClient;
uint8_t * buffer;
////
// define global patterns
////
string LocalPlayer = "4839DF74??4885FF74??4889DEE8????????EB??";
string EntityList = "554889E54156534889FBBE??000000E8????????8B??????????83F8FF";
string Glow = "48C7????e?2E05????????488D??????????488D??????????E8";
////
// copy client.dylib to our program memory
////
int GetCSpid() {
int csgopid ;
int numberOfProcesses = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
pid_t pids[numberOfProcesses];
bzero(pids, sizeof(pids));
proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
for (int i = 0; i < numberOfProcesses; ++i) {
if (pids[i] == 0) { continue; }
char pathBuffer[PROC_PIDPATHINFO_MAXSIZE];
bzero(pathBuffer, PROC_PIDPATHINFO_MAXSIZE);
proc_pidpath(pids[i], pathBuffer, sizeof(pathBuffer));
char nameBuffer[256];
int position = strlen(pathBuffer);
while(position >= 0 && pathBuffer[position] != '/')
{
position--;
}
strcpy(nameBuffer, pathBuffer + position + 1);
if (strcmp(nameBuffer, "csgo_osx64")==0) {
return pids[i];
}
}
return 0;
}
void ClientToBuffer() {
kern_return_t kret;
mach_vm_address_t address;
int csgopid = GetCSpid();
kret = task_for_pid(mach_task_self(), csgopid, &task);
if (kret!=KERN_SUCCESS)
{
printf("task_for_pid() failed with message %s!\n",mach_error_string(kret));
exit(0);
}
struct task_dyld_info dyld_info;
mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
if (task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count) == KERN_SUCCESS)
{
address = dyld_info.all_image_info_addr;
}
mach_msg_type_number_t size = sizeof(struct dyld_all_image_infos);
vm_offset_t readMem;
vm_read(task,address,size,&readMem,&size);
struct dyld_all_image_infos* infos = (struct dyld_all_image_infos *) readMem;
size = sizeof(struct dyld_image_info) * infos->infoArrayCount;
vm_read(task,(mach_vm_address_t) infos->infoArray,size,&readMem,&size);
struct dyld_image_info* info = (struct dyld_image_info*) readMem;
mach_msg_type_number_t sizeMax=512;
for (int i=0; i < infos->infoArrayCount; i++) {
vm_read(task,(mach_vm_address_t) info[i].imageFilePath,sizeMax,&readMem,&sizeMax);
char *path = (char *) readMem ;
if(strstr(path, "/client.dylib") != NULL){
Client = (mach_vm_address_t)info[i].imageLoadAddress ;
struct stat st;
stat(path, &st);
printf("client: 0x%llx %lld\n", Client, st.st_size);
uint8_t * m_data;
m_data = new uint8_t[st.st_size];
sizeMax = st.st_size;
vm_read(task,(vm_address_t)Client,sizeMax,&readMem,&sizeMax);
uint64_t address = (uint64_t)readMem;
buffer = (uint8_t *)address;
SizeClient = st.st_size;
}
}
}
uint64_t Scan(string s){
stringstream ss;
bool flag = true;
for (int j=0;j<(SizeClient-(s.size())/2 + 1);j++){
flag = true;
for (int i=0; i<(s.size())/2; i++){
string bytechar = s.substr(2*i,2);
if (bytechar.compare("??") != 0){
if (bytechar.substr(1,1).compare("?") == 0){
char byte[2];
int out;
out = sprintf(byte, "%x",buffer[i+j]);
string bytebuffer (byte);
if (bytebuffer.length()==1){
bytebuffer = "0"+bytebuffer;
}
if (bytechar.substr(0,1).compare(bytebuffer.substr(0,1))!=0){
flag=false;
break;
}
continue;
}
uint8_t byte = std::stoi(bytechar, NULL,16);
if (byte != buffer[j+i]){
flag = false;
break;
}
}
}
if (flag){
return (Client+j);
}
}
return 0;
}
int main(int argc, const char * argv[]) {
// insert code here...
ClientToBuffer();
uint64_t LocalPlayerArr=Scan(LocalPlayer);
uint64_t EntityArr=Scan(EntityList);
uint64_t GlowArr=Scan(Glow);
uint32_t int1 = (int)*((int*)(LocalPlayerArr-Client+buffer + 0x17));
LocalPlayerArr = LocalPlayerArr + 0x1F + int1 - Client;
printf("%llx\n",LocalPlayerArr);
uint32_t int2 = (int)*((int*)(EntityArr-Client+buffer + 0x22));
uint64_t int3 = (uint64_t) *(uint64_t *)(EntityArr-Client+buffer + 0x26 + int2);
EntityArr = int3 + 0x8 + 0x20 -Client;
printf("%llx\n",EntityArr);
uint32_t int4 = (int)*((int*)(GlowArr-Client+buffer + 0x2D));
GlowArr = GlowArr + 0x31 + int4 - Client;
printf("%llx\n",GlowArr);
return 0;
}
<|endoftext|> |
<commit_before>b54d774a-327f-11e5-871c-9cf387a8033e<commit_msg>b5540f8a-327f-11e5-bbad-9cf387a8033e<commit_after>b5540f8a-327f-11e5-bbad-9cf387a8033e<|endoftext|> |
<commit_before>0a56f005-2e4f-11e5-ac12-28cfe91dbc4b<commit_msg>0a5db7ae-2e4f-11e5-8ea6-28cfe91dbc4b<commit_after>0a5db7ae-2e4f-11e5-8ea6-28cfe91dbc4b<|endoftext|> |
<commit_before>80649ccc-2e4f-11e5-96b2-28cfe91dbc4b<commit_msg>806cf6b3-2e4f-11e5-9903-28cfe91dbc4b<commit_after>806cf6b3-2e4f-11e5-9903-28cfe91dbc4b<|endoftext|> |
<commit_before>// 2006-2008 (c) Viva64.com Team
// 2008-2016 (c) OOO "Program Verification Systems"
#include "comments.h"
#include "encoding.h"
#include <cstdio>
#include <cstring>
#include <string>
#include <functional>
#include <algorithm>
#include <vector>
#include <cassert>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <experimental/filesystem>
using namespace std;
using namespace std::experimental;
static bool IsSourceFile(const filesystem::path &path)
{
static const vector<string> sourceExtensions = {
".c"
, ".cc"
, ".cpp"
, ".cp"
, ".cxx"
, ".c++"
, ".cs"
};
string ext = path.extension().string();
transform(ext.begin(), ext.end(), ext.begin(), [](char ch){return tolower(ch);});
return find(sourceExtensions.begin(), sourceExtensions.end(), ext) != sourceExtensions.end();
}
class ProgramOptions
{
ProgramOptions() = default;
ProgramOptions(const ProgramOptions& root) = delete;
ProgramOptions& operator=(const ProgramOptions&) = delete;
public:
size_t m_commentType = -1;
vector<string> m_files;
bool m_multiline = false;
bool m_readSymlinks = false;
static ProgramOptions& Instance()
{
static ProgramOptions programOptions;
return programOptions;
}
};
void WriteComment(const filesystem::path &path,
const string &comment,
const string &source,
bool isUnixLineEnding,
Encoding enc,
size_t bomLen)
{
ofstream osrc(path, ios::binary);
if (!osrc.is_open())
{
cerr << "Error: Couldn't open " << path << endl;
return;
}
if (bomLen != 0)
{
osrc.write(source.c_str(), bomLen);
}
ConvertEncoding(osrc, comment, enc, !isUnixLineEnding);
osrc.write(source.c_str() + bomLen, source.length() - bomLen);
}
static void AddCommentsToFile(const filesystem::path &path, const string &comment, const ProgramOptions &options)
{
if (!IsSourceFile(path))
return;
cout << "+ " << path << endl;
ifstream isrc(path, ios::binary);
if (!isrc.is_open())
{
cerr << "Error: Couldn't open " << path << endl;
return;
}
string str;
isrc.seekg(0, ios::end);
str.reserve(isrc.tellg());
isrc.seekg(0, ios::beg);
str.assign((istreambuf_iterator<char>(isrc)), istreambuf_iterator<char>());
isrc.close();
string source = str;
Encoding enc;
size_t bomLen;
ConvertEncoding(str, enc, bomLen);
bool isUnixLineEnding = true;
size_t idx = str.find('\n');
if (idx != string::npos && idx != 0 && str[idx - 1] == '\r')
isUnixLineEnding = false;
PvsStudioFreeComments::CommentsParser parser;
auto itFreeComment = parser.readFreeComment(source.c_str());
const char *beg = parser.freeCommentBegin();
const char *end = parser.freeCommentEnd();
if (itFreeComment != PvsStudioFreeComments::Comments.end())
{
bool needToChangeComment = (!options.m_multiline && beg[0] == '/' && beg[1] == '*')
|| (options.m_multiline && beg[0] == '/' && beg[1] == '/')
|| itFreeComment != PvsStudioFreeComments::Comments.begin() + (ProgramOptions::Instance().m_commentType - 1);
if (needToChangeComment)
{
source.erase(source.begin() + distance(source.c_str(), beg), source.begin() + distance(source.c_str(), end));
WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
}
}
else
{
WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
}
}
static void ProcessFile(filesystem::path path, const string &comment, const ProgramOptions &options)
{
if (options.m_readSymlinks && filesystem::is_symlink(path))
{
std::error_code error;
path = filesystem::canonical(filesystem::read_symlink(path), path.parent_path(), error);
if (error != std::error_code())
{
return;
}
}
if (filesystem::is_regular_file(path))
{
AddCommentsToFile(path, comment, options);
}
}
static void AddComments(const string &path, const string &comment, const ProgramOptions &options)
{
auto fsPath = filesystem::canonical(path);
if (!filesystem::exists(fsPath))
{
cerr << "File not exists: " << path << endl;
return;
}
if (filesystem::is_directory(fsPath))
{
filesystem::directory_options symlink_flag = options.m_readSymlinks
? filesystem::directory_options::follow_directory_symlink
: filesystem::directory_options::none;
for (auto &&p : filesystem::recursive_directory_iterator(fsPath, symlink_flag))
{
ProcessFile(p.path(), comment, options);
}
}
else
{
ProcessFile(fsPath, comment, options);
}
}
static string Format(const string &comment, bool multiline)
{
ostringstream ostream;
istringstream stream(comment);
string line;
if (multiline)
{
ostream << "/*" << endl;
while (getline(stream, line))
{
ostream << "* " << line << endl;
}
ostream << "*/" << endl;
}
else
{
while (getline(stream, line))
{
ostream << "// " << line << endl;
}
}
return ostream.str();
}
static const char Help[] = R"HELP(How to use PVS-Studio for FREE?
You can use PVS-Studio code analyzer for free, if you add special comments
to your source code. Available options are provided below.
Usage:
how-to-use-pvs-studio-free -c <1|2|3> [-m] [-s] [-h] <strings> ...
Options:
-c <1|2|3>, /c <1|2|3>, --comment <1|2|3>
(required) Type of comment prepended to the source file.
-m, /m, --multiline
Use multi-line comments instead of single-line.
-s, /s, --symlinks
Follow the symbolic links and add comment to the files to which symbolic links point (files and directories).
-h, /?, --help
Display usage information and exit.
<string> (accepted multiple times)
(required) Files or directories.
Description:
The utility will add comments to the files located in the specified folders
and subfolders. The comments are added to the beginning of the files with the
extensions .c, .cc, .cpp, .cp, .cxx, .c++, .cs. You don't have to change
header files. If you use files with other extensions, you can customize this
utility for your needs.
Options of comments that will be added to the code (-c NUMBER):
1. Personal academic project;
2. Open source non-commercial project;
3. Independent project of an individual developer.
If you are using PVS-Studio as a Visual Studio plugin, then enter the
following license key:
Name: PVS-Studio Free
Key: FREE-FREE-FREE-FREE
If you are using PVS-Studio for Linux, you do not need to do anything else
besides adding comments to the source code. Just check your code.
In case none of the options suits you, we suggest considering a purchase of a
commercial license for PVS-Studio. We are ready to discuss this and other
questions via e-mail: support@viva64.com.
You can find more details about the free version of PVS-Studio
here: https://www.viva64.com/en/b/0457/
)HELP";
void help()
{
cout << Help;
}
struct Option
{
vector<string> names;
bool hasArg;
function<void(string&&)> found;
};
struct ProgramOptionsError {};
typedef vector<Option> ParsedOptions;
static void ParseProgramOptions(int argc, const char *argv[], const ParsedOptions &options, function<void(string&&)> found)
{
auto findOpt = [&options](const string& arg) {
return find_if(begin(options), end(options), [arg](const Option &o) {
return find(o.names.begin(), o.names.end(), arg) != o.names.end();
});
};
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
auto it = findOpt(arg);
if (it == end(options))
{
found(move(arg));
}
else if (it->hasArg)
{
++i;
if (i == argc)
{
cout << "No argument specified for " << arg << endl;
throw ProgramOptionsError();
}
string val = argv[i];
auto itNext = findOpt(val);
if (itNext != end(options))
{
cout << "No argument specified for " << arg << endl;
throw ProgramOptionsError();
}
it->found(move(val));
}
else
{
it->found(string());
}
}
}
int main(int argc, const char *argv[])
{
auto &progOptions = ProgramOptions::Instance();
ParsedOptions options = {
{ { "-c", "/c", "--comment" }, true, [&](string &&arg) { progOptions.m_commentType = stoull(arg); } },
{ { "-m", "/m", "--multiline" }, false, [&](string &&) { progOptions.m_multiline = true; } },
{ { "-s", "/s", "--symlinks" }, false, [&](string &&) { progOptions.m_readSymlinks = true; } },
{ { "-h", "/?", "--help" }, false, [&](string &&) { throw ProgramOptionsError(); } },
};
try
{
ParseProgramOptions(argc, argv, options, [&files = progOptions.m_files](string &&arg){files.emplace_back(move(arg));});
unsigned long long n = progOptions.m_commentType;
if (n == 0 || n > PvsStudioFreeComments::Comments.size())
{
throw invalid_argument("");
}
string comment = Format(PvsStudioFreeComments::Comments[n - 1].m_text, progOptions.m_multiline);
for (const string &file : progOptions.m_files)
{
AddComments(file, comment, progOptions);
}
}
catch (ProgramOptionsError &)
{
help();
return 1;
}
catch (invalid_argument &)
{
cout << "Invalid comment type specified" << endl;
help();
return 1;
}
return 0;
}
<commit_msg>support java<commit_after>// 2006-2008 (c) Viva64.com Team
// 2008-2016 (c) OOO "Program Verification Systems"
#include "comments.h"
#include "encoding.h"
#include <cstdio>
#include <cstring>
#include <string>
#include <functional>
#include <algorithm>
#include <vector>
#include <cassert>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <experimental/filesystem>
using namespace std;
using namespace std::experimental;
static bool IsSourceFile(const filesystem::path &path)
{
static const vector<string> sourceExtensions = {
".c"
, ".cc"
, ".cpp"
, ".cp"
, ".cxx"
, ".c++"
, ".cs"
, ".java"
};
string ext = path.extension().string();
transform(ext.begin(), ext.end(), ext.begin(), [](char ch){return tolower(ch);});
return find(sourceExtensions.begin(), sourceExtensions.end(), ext) != sourceExtensions.end();
}
class ProgramOptions
{
ProgramOptions() = default;
ProgramOptions(const ProgramOptions& root) = delete;
ProgramOptions& operator=(const ProgramOptions&) = delete;
public:
size_t m_commentType = -1;
vector<string> m_files;
bool m_multiline = false;
bool m_readSymlinks = false;
static ProgramOptions& Instance()
{
static ProgramOptions programOptions;
return programOptions;
}
};
void WriteComment(const filesystem::path &path,
const string &comment,
const string &source,
bool isUnixLineEnding,
Encoding enc,
size_t bomLen)
{
ofstream osrc(path, ios::binary);
if (!osrc.is_open())
{
cerr << "Error: Couldn't open " << path << endl;
return;
}
if (bomLen != 0)
{
osrc.write(source.c_str(), bomLen);
}
ConvertEncoding(osrc, comment, enc, !isUnixLineEnding);
osrc.write(source.c_str() + bomLen, source.length() - bomLen);
}
static void AddCommentsToFile(const filesystem::path &path, const string &comment, const ProgramOptions &options)
{
if (!IsSourceFile(path))
return;
cout << "+ " << path << endl;
ifstream isrc(path, ios::binary);
if (!isrc.is_open())
{
cerr << "Error: Couldn't open " << path << endl;
return;
}
string str;
isrc.seekg(0, ios::end);
str.reserve(isrc.tellg());
isrc.seekg(0, ios::beg);
str.assign((istreambuf_iterator<char>(isrc)), istreambuf_iterator<char>());
isrc.close();
string source = str;
Encoding enc;
size_t bomLen;
ConvertEncoding(str, enc, bomLen);
bool isUnixLineEnding = true;
size_t idx = str.find('\n');
if (idx != string::npos && idx != 0 && str[idx - 1] == '\r')
isUnixLineEnding = false;
PvsStudioFreeComments::CommentsParser parser;
auto itFreeComment = parser.readFreeComment(source.c_str());
const char *beg = parser.freeCommentBegin();
const char *end = parser.freeCommentEnd();
if (itFreeComment != PvsStudioFreeComments::Comments.end())
{
bool needToChangeComment = (!options.m_multiline && beg[0] == '/' && beg[1] == '*')
|| (options.m_multiline && beg[0] == '/' && beg[1] == '/')
|| itFreeComment != PvsStudioFreeComments::Comments.begin() + (ProgramOptions::Instance().m_commentType - 1);
if (needToChangeComment)
{
source.erase(source.begin() + distance(source.c_str(), beg), source.begin() + distance(source.c_str(), end));
WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
}
}
else
{
WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
}
}
static void ProcessFile(filesystem::path path, const string &comment, const ProgramOptions &options)
{
if (options.m_readSymlinks && filesystem::is_symlink(path))
{
std::error_code error;
path = filesystem::canonical(filesystem::read_symlink(path), path.parent_path(), error);
if (error != std::error_code())
{
return;
}
}
if (filesystem::is_regular_file(path))
{
AddCommentsToFile(path, comment, options);
}
}
static void AddComments(const string &path, const string &comment, const ProgramOptions &options)
{
auto fsPath = filesystem::canonical(path);
if (!filesystem::exists(fsPath))
{
cerr << "File not exists: " << path << endl;
return;
}
if (filesystem::is_directory(fsPath))
{
filesystem::directory_options symlink_flag = options.m_readSymlinks
? filesystem::directory_options::follow_directory_symlink
: filesystem::directory_options::none;
for (auto &&p : filesystem::recursive_directory_iterator(fsPath, symlink_flag))
{
ProcessFile(p.path(), comment, options);
}
}
else
{
ProcessFile(fsPath, comment, options);
}
}
static string Format(const string &comment, bool multiline)
{
ostringstream ostream;
istringstream stream(comment);
string line;
if (multiline)
{
ostream << "/*" << endl;
while (getline(stream, line))
{
ostream << "* " << line << endl;
}
ostream << "*/" << endl;
}
else
{
while (getline(stream, line))
{
ostream << "// " << line << endl;
}
}
return ostream.str();
}
static const char Help[] = R"HELP(How to use PVS-Studio for FREE?
You can use PVS-Studio code analyzer for free, if you add special comments
to your source code. Available options are provided below.
Usage:
how-to-use-pvs-studio-free -c <1|2|3> [-m] [-s] [-h] <strings> ...
Options:
-c <1|2|3>, /c <1|2|3>, --comment <1|2|3>
(required) Type of comment prepended to the source file.
-m, /m, --multiline
Use multi-line comments instead of single-line.
-s, /s, --symlinks
Follow the symbolic links and add comment to the files to which symbolic links point (files and directories).
-h, /?, --help
Display usage information and exit.
<string> (accepted multiple times)
(required) Files or directories.
Description:
The utility will add comments to the files located in the specified folders
and subfolders. The comments are added to the beginning of the files with the
extensions .c, .cc, .cpp, .cp, .cxx, .c++, .cs. You don't have to change
header files. If you use files with other extensions, you can customize this
utility for your needs.
Options of comments that will be added to the code (-c NUMBER):
1. Personal academic project;
2. Open source non-commercial project;
3. Independent project of an individual developer.
If you are using PVS-Studio as a Visual Studio plugin, then enter the
following license key:
Name: PVS-Studio Free
Key: FREE-FREE-FREE-FREE
If you are using PVS-Studio for Linux, you do not need to do anything else
besides adding comments to the source code. Just check your code.
In case none of the options suits you, we suggest considering a purchase of a
commercial license for PVS-Studio. We are ready to discuss this and other
questions via e-mail: support@viva64.com.
You can find more details about the free version of PVS-Studio
here: https://www.viva64.com/en/b/0457/
)HELP";
void help()
{
cout << Help;
}
struct Option
{
vector<string> names;
bool hasArg;
function<void(string&&)> found;
};
struct ProgramOptionsError {};
typedef vector<Option> ParsedOptions;
static void ParseProgramOptions(int argc, const char *argv[], const ParsedOptions &options, function<void(string&&)> found)
{
auto findOpt = [&options](const string& arg) {
return find_if(begin(options), end(options), [arg](const Option &o) {
return find(o.names.begin(), o.names.end(), arg) != o.names.end();
});
};
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
auto it = findOpt(arg);
if (it == end(options))
{
found(move(arg));
}
else if (it->hasArg)
{
++i;
if (i == argc)
{
cout << "No argument specified for " << arg << endl;
throw ProgramOptionsError();
}
string val = argv[i];
auto itNext = findOpt(val);
if (itNext != end(options))
{
cout << "No argument specified for " << arg << endl;
throw ProgramOptionsError();
}
it->found(move(val));
}
else
{
it->found(string());
}
}
}
int main(int argc, const char *argv[])
{
auto &progOptions = ProgramOptions::Instance();
ParsedOptions options = {
{ { "-c", "/c", "--comment" }, true, [&](string &&arg) { progOptions.m_commentType = stoull(arg); } },
{ { "-m", "/m", "--multiline" }, false, [&](string &&) { progOptions.m_multiline = true; } },
{ { "-s", "/s", "--symlinks" }, false, [&](string &&) { progOptions.m_readSymlinks = true; } },
{ { "-h", "/?", "--help" }, false, [&](string &&) { throw ProgramOptionsError(); } },
};
try
{
ParseProgramOptions(argc, argv, options, [&files = progOptions.m_files](string &&arg){files.emplace_back(move(arg));});
unsigned long long n = progOptions.m_commentType;
if (n == 0 || n > PvsStudioFreeComments::Comments.size())
{
throw invalid_argument("");
}
string comment = Format(PvsStudioFreeComments::Comments[n - 1].m_text, progOptions.m_multiline);
for (const string &file : progOptions.m_files)
{
AddComments(file, comment, progOptions);
}
}
catch (ProgramOptionsError &)
{
help();
return 1;
}
catch (invalid_argument &)
{
cout << "Invalid comment type specified" << endl;
help();
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>8d6dfd17-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd18-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd18-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>2ac80917-ad5c-11e7-8223-ac87a332f658<commit_msg>updated some files<commit_after>2b21b89e-ad5c-11e7-b143-ac87a332f658<|endoftext|> |
<commit_before>fd01f262-585a-11e5-9dbb-6c40088e03e4<commit_msg>fd08b746-585a-11e5-9296-6c40088e03e4<commit_after>fd08b746-585a-11e5-9296-6c40088e03e4<|endoftext|> |
<commit_before>c497ec34-35ca-11e5-b99a-6c40088e03e4<commit_msg>c49e4b06-35ca-11e5-b17d-6c40088e03e4<commit_after>c49e4b06-35ca-11e5-b17d-6c40088e03e4<|endoftext|> |
<commit_before>5bf67466-2d16-11e5-af21-0401358ea401<commit_msg>5bf67467-2d16-11e5-af21-0401358ea401<commit_after>5bf67467-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>b4f03368-2e4f-11e5-9f89-28cfe91dbc4b<commit_msg>b4f6c9bd-2e4f-11e5-ada4-28cfe91dbc4b<commit_after>b4f6c9bd-2e4f-11e5-ada4-28cfe91dbc4b<|endoftext|> |
<commit_before>979e2ac2-2e4f-11e5-9349-28cfe91dbc4b<commit_msg>97a6b3de-2e4f-11e5-9efe-28cfe91dbc4b<commit_after>97a6b3de-2e4f-11e5-9efe-28cfe91dbc4b<|endoftext|> |
<commit_before>cf953fcc-35ca-11e5-83fe-6c40088e03e4<commit_msg>cfa0461c-35ca-11e5-b086-6c40088e03e4<commit_after>cfa0461c-35ca-11e5-b086-6c40088e03e4<|endoftext|> |
<commit_before>8b3325fb-2d14-11e5-af21-0401358ea401<commit_msg>8b3325fc-2d14-11e5-af21-0401358ea401<commit_after>8b3325fc-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>770c8a3a-2d53-11e5-baeb-247703a38240<commit_msg>770d080c-2d53-11e5-baeb-247703a38240<commit_after>770d080c-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>068b2b97-2748-11e6-935f-e0f84713e7b8<commit_msg>more bug fix<commit_after>06a0aa8f-2748-11e6-9b7e-e0f84713e7b8<|endoftext|> |
<commit_before>6fe03aa3-2749-11e6-a743-e0f84713e7b8<commit_msg>Does anyone even read these anymore???<commit_after>6ff15294-2749-11e6-871c-e0f84713e7b8<|endoftext|> |
<commit_before>b1bcb051-4b02-11e5-8f6a-28cfe9171a43<commit_msg>Now it no longer crashes if X<commit_after>b1c85db0-4b02-11e5-a0b5-28cfe9171a43<|endoftext|> |
<commit_before>a90b7fcf-4b02-11e5-a3b3-28cfe9171a43<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>a91744f8-4b02-11e5-82fe-28cfe9171a43<|endoftext|> |
<commit_before>60bb4783-2d16-11e5-af21-0401358ea401<commit_msg>60bb4784-2d16-11e5-af21-0401358ea401<commit_after>60bb4784-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>e12207f6-585a-11e5-8e35-6c40088e03e4<commit_msg>e12b4a94-585a-11e5-8e48-6c40088e03e4<commit_after>e12b4a94-585a-11e5-8e48-6c40088e03e4<|endoftext|> |
<commit_before>cb6cef6e-327f-11e5-8a43-9cf387a8033e<commit_msg>cb72e93a-327f-11e5-9491-9cf387a8033e<commit_after>cb72e93a-327f-11e5-9491-9cf387a8033e<|endoftext|> |
<commit_before>// $RCSfile: $
// $Revision: $ $Date: $
// Auth: Samson Bonfante (bonfante@steptools.com)
//
// Copyright (c) 1991-2015 by STEP Tools 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.
#include <rose.h>
#include <stp_schema.h>
void main(int argc,char **argv)
{
stplib_init();
RoseDesign * d = ROSE.findDesign("io1-md-214.stp.stp");
RoseCursor cur;
RoseObject * obj;
cur.traverse(d);
cur.domain(ROSE_DOMAIN(stp_product_definition));
while ((obj = cur.next()) != 0){
stp_product_definition * pd = ROSE_CAST(stp_product_definition, obj);
printf("Product Definiton ID #%d \n", pd->id());
}
return;
}<commit_msg>Testing GUID code.<commit_after>// $RCSfile: $
// $Revision: $ $Date: $
// Auth: Samson Bonfante (bonfante@steptools.com)
//
// Copyright (c) 1991-2015 by STEP Tools 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.
#include <rose.h>
#include <stp_schema.h>
#include "GUID.h"
void main(int argc,char **argv)
{
stplib_init();
RoseDesign * d = ROSE.findDesign("io1-md-214.stp.stp");
RoseCursor cur;
RoseObject * obj;
cur.traverse(d);
cur.domain(ROSE_DOMAIN(stp_product_definition));
while ((obj = cur.next()) != 0){
stp_product_definition * pd = ROSE_CAST(stp_product_definition, obj);
unsigned char GUID[16];
get_guid(GUID);
printf("Product Definiton ID #%d \t GUID: %s\n", pd->id(),GUID);
}
return;
}<|endoftext|> |
<commit_before>//Copyright 2015 Adam Smith
//
//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.
// Contact :
// Email : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP
#include "Solaire/Json/Format.hpp"
namespace Solaire {
static bool skipWhitespace(IStream& aStream) {
if(aStream.end()) return true;
char c;
aStream >> c;
while(std::isspace(c)) {
if(aStream.end()) return true;
aStream >> c;
}
aStream.setOffset(aStream.getOffset() - 1);
return true;
}
static bool writeValue(const GenericValue& aValue, OStream& aStream) throw();
static bool writeNull(OStream& aStream) throw() {
aStream << "null";
return true;
}
static bool writeChar(const char aValue, OStream& aStream) throw() {
aStream << '"' << aValue << '"';
return true;
}
static bool writeBool(const bool aValue, OStream& aStream) throw() {
if(aValue) {
aStream << "true";
}else {
aStream << "false";
}
return true;
}
static bool writeUnsigned(const uint64_t aValue, OStream& aStream) throw() {
CString tmp;
tmp += aValue;
aStream << tmp;
return true;
}
static bool writeSigned(const int64_t aValue, OStream& aStream) throw() {
CString tmp;
tmp += aValue;
aStream << tmp;
return true;
}
static bool writeDouble(const double aValue, OStream& aStream) throw() {
CString tmp;
tmp += aValue;
aStream << tmp;
}
static bool writeString(const StringConstant<char>& aValue, OStream& aStream) throw() {
aStream << '"';
aStream << aValue;
aStream << '"';
return true;
}
static bool writeArray(const GenericArray& aValue, OStream& aStream) throw() {
aStream << '[';
const auto end = aValue.end();
for(auto i = aValue.begin(); i != end; ++i) {
if(! writeValue(*i, aStream)) return false;
if(end - i > 1) aStream << ',';
}
aStream << ']';
return true;
}
static bool writeObject(const GenericObject& aValue, OStream& aStream) throw() {
aStream << '{';
const SharedAllocation<StaticContainer<GenericObject::Entry>> entries = aValue.getEntries();
const auto end = entries->end();
for(auto i = entries->begin(); i != end; ++i) {
if(! writeString(i->first, aStream)) return false;
aStream << ':';
if(! writeValue(i->second, aStream)) return false;
if(end - i > 1) aStream << ',';
}
aStream << '}';
return false;
}
static bool writeValue(const GenericValue& aValue, OStream& aStream) throw() {
switch(aValue.getType()) {
case GenericValue::NULL_T:
return writeNull(aStream);
case GenericValue::CHAR_T:
return writeChar(aValue.getChar(), aStream);
case GenericValue::BOOL_T:
return writeBool(aValue.getBool(), aStream);
case GenericValue::UNSIGNED_T:
return writeUnsigned(aValue.getUnsigned(), aStream);
case GenericValue::SIGNED_T:
return writeSigned(aValue.getSigned(), aStream);
case GenericValue::DOUBLE_T:
return writeDouble(aValue.getDouble(), aStream);
case GenericValue::STRING_T:
return writeString(aValue.getString(), aStream);
case GenericValue::ARRAY_T:
return writeArray(aValue.getArray(), aStream);
case GenericValue::OBJECT_T:
return writeObject(aValue.getObject(), aStream);
default:
return false;
}
}
static GenericValue::ValueType getType(IStream& aStream) {
const int32_t offset = aStream.getOffset();
GenericValue::ValueType type = GenericValue::NULL_T;
skipWhitespace(aStream);
if(! aStream.end()) {
char c;
aStream >> c;
switch(c){
case 'n':
type = GenericValue::NULL_T;
break;
case 't':
case 'f':
type = GenericValue::BOOL_T;
break;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
type = GenericValue::DOUBLE_T;
break;
case '"':
type = GenericValue::STRING_T;
break;
case '[':
type = GenericValue::ARRAY_T;
break;
case '{':
type = GenericValue::OBJECT_T;
break;
default:
break;
}
}
aStream.setOffset(offset);
return type;
}
static GenericValue readValue(IStream& aStream);
static GenericValue readNull(IStream& aStream) throw() {
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Null : Could not locate value");
char buffer[4];
aStream.read(buffer, 4);
if(std::memcmp(buffer, "null", 4) != 0) throw std::runtime_error("Json::Null : Value must be either 'null'");
return GenericValue();
}
static GenericValue readBool(IStream& aStream) {
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Bool : Could not locate value");
char buffer[5];
aStream.read(buffer, 4);
switch(buffer[0]){
case 't':
if(std::memcmp(buffer, "true", 4) != 0) throw std::runtime_error("Json::Bool : Value must be either 'true' or 'false'");
return GenericValue(true);
case 'f':
aStream >> buffer[4];
if(std::memcmp(buffer, "false", 5) != 0) throw std::runtime_error("Json::Bool : Value must be either 'true' or 'false'");
return GenericValue(false);
default:
throw std::runtime_error("Json::Bool : Failed to read value");
}
}
static GenericValue readDouble(IStream& aStream) throw() {
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Number : Could not locate value");
CString buffer;
char c;
aStream >> c;
while((c >= '0' && c <= '9') || c == '-' || c == '.' || c == 'e' || c == 'E') {
buffer += c;
aStream >> c;
}
aStream.setOffset(aStream.getOffset() - 1);
return static_cast<int32_t>(buffer); //! \todo readDouble
}
static GenericValue readString(IStream& aStream) {
bool escaped = false;
char c;
aStream >> c;
if(c != '"') throw std::runtime_error("Json::String : String must be opened by '\"'");
GenericValue value;
String<char>& string = value.setString();
while(! aStream.end()){
aStream >> c;
switch(c) {
case '\\':
if(escaped){
string.pushBack('\\');
escaped = false;
}else{
escaped = true;
}
break;
case '"':
if(escaped){
string.pushBack('"');
escaped = false;
}else{
return value;
}
break;
default:
string.pushBack(c);
escaped = false;
break;
}
}
throw std::runtime_error("Json::String : String must be closed by '\"'");
}
static GenericValue readArray(IStream& aStream) {
char c;
aStream >> c;
if(c != '[') throw std::runtime_error("Json::Array : Array must be opened '['");
GenericValue value;
GenericArray& array_ = value.setArray();
// Check for close
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Array : Failed to locate first element");
if(aStream.peek<char>() == ']') return value;
while(! aStream.end()) {
// Read value
array_.pushBack(readValue(aStream));
// Read seperator
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Array : Failed to locate next element");
aStream >> c;
switch(c){
case ']':
return value;
case ',':
break;
default:
#ifdef SOLAIRE_JSON_WHITESPACE_SEPERATORS
aStream.setOffset(aStream.getOffset() -1);
break;
#else
throw std::runtime_error("Json::Array : Array elements must be separated by ','");
#endif
}
}
throw std::runtime_error("Json::Array : Array must be closed by ']'");
}
static GenericValue readObject(IStream& aStream) {
char c;
aStream >> c;
if(c != '{') throw std::runtime_error("Json::Object : Object must be opened by '{'");
GenericValue value;
GenericObject& object = value.setObject();
// Check for close
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Object : Failed to read first member");
if(aStream.peek<char>() == '}') return value;
while(! aStream.end()) {
// Read name
const GenericValue name = readString(aStream);
if(! name.isString()) throw std::runtime_error("Json::Object : Member name must be a string");
// Read divider
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Object : Failed to determine position of member name divider");
aStream >> c;
if(c != ':') throw std::runtime_error("Json::Object : Member name and value must be separated by ':'");
// Read value
object.emplace(name.getString(), readValue(aStream));
// Read seperator
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Object : Failed to determine position of member separator");
aStream >> c;
switch(c){
case '}':
return value;
case ',':
break;
default:
#ifdef SOLAIRE_JSON_WHITESPACE_SEPERATORS
aStream.setOffset(aStream.getOffset() -1);
break;
#else
throw std::runtime_error("Json::Object : Members must be separated by ','");
#endif
}
}
throw std::runtime_error("Json::Object : Object must be closed by '}'");
}
static GenericValue readValue(IStream& aStream) {
switch(getType(aStream)) {
case GenericValue::NULL_T:
return readNull(aStream);
case GenericValue::BOOL_T:
return readBool(aStream);
case GenericValue::DOUBLE_T:
return readDouble(aStream);
case GenericValue::STRING_T:
return readString(aStream);
case GenericValue::ARRAY_T:
return readArray(aStream);
case GenericValue::OBJECT_T:
return readObject(aStream);
default:
throw std::runtime_error("Invalid json type");
}
}
// JsonFormat
SOLAIRE_EXPORT_CALL JsonFormat::~JsonFormat() {
}
GenericValue SOLAIRE_EXPORT_CALL JsonFormat::readValue(IStream& aStream) const throw() {
try{
return Solaire::readValue(aStream);
}catch(std::exception& e) {
std::cerr << e.what() << std::endl;
return GenericValue();
}
}
bool SOLAIRE_EXPORT_CALL JsonFormat::writeValue(const GenericValue& aValue, OStream& aStream) const throw() {
try{
return Solaire::writeValue(aValue, aStream);
}catch(std::exception& e) {
std::cerr << e.what() << std::endl;
return false;
}
}
}
<commit_msg>Fixed double parsing implementation<commit_after>//Copyright 2015 Adam Smith
//
//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.
// Contact :
// Email : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP
#include "Solaire/Json/Format.hpp"
namespace Solaire {
static bool skipWhitespace(IStream& aStream) {
if(aStream.end()) return true;
char c;
aStream >> c;
while(std::isspace(c)) {
if(aStream.end()) return true;
aStream >> c;
}
aStream.setOffset(aStream.getOffset() - 1);
return true;
}
static bool writeValue(const GenericValue& aValue, OStream& aStream) throw();
static bool writeNull(OStream& aStream) throw() {
aStream << "null";
return true;
}
static bool writeChar(const char aValue, OStream& aStream) throw() {
aStream << '"' << aValue << '"';
return true;
}
static bool writeBool(const bool aValue, OStream& aStream) throw() {
if(aValue) {
aStream << "true";
}else {
aStream << "false";
}
return true;
}
static bool writeUnsigned(const uint64_t aValue, OStream& aStream) throw() {
CString tmp;
tmp += aValue;
aStream << tmp;
return true;
}
static bool writeSigned(const int64_t aValue, OStream& aStream) throw() {
CString tmp;
tmp += aValue;
aStream << tmp;
return true;
}
static bool writeDouble(const double aValue, OStream& aStream) throw() {
CString tmp;
tmp += aValue;
aStream << tmp;
return true;
}
static bool writeString(const StringConstant<char>& aValue, OStream& aStream) throw() {
aStream << '"';
aStream << aValue;
aStream << '"';
return true;
}
static bool writeArray(const GenericArray& aValue, OStream& aStream) throw() {
aStream << '[';
const auto end = aValue.end();
for(auto i = aValue.begin(); i != end; ++i) {
if(! writeValue(*i, aStream)) return false;
if(end - i > 1) aStream << ',';
}
aStream << ']';
return true;
}
static bool writeObject(const GenericObject& aValue, OStream& aStream) throw() {
aStream << '{';
const SharedAllocation<StaticContainer<GenericObject::Entry>> entries = aValue.getEntries();
const auto end = entries->end();
for(auto i = entries->begin(); i != end; ++i) {
if(! writeString(i->first, aStream)) return false;
aStream << ':';
if(! writeValue(i->second, aStream)) return false;
if(end - i > 1) aStream << ',';
}
aStream << '}';
return false;
}
static bool writeValue(const GenericValue& aValue, OStream& aStream) throw() {
switch(aValue.getType()) {
case GenericValue::NULL_T:
return writeNull(aStream);
case GenericValue::CHAR_T:
return writeChar(aValue.getChar(), aStream);
case GenericValue::BOOL_T:
return writeBool(aValue.getBool(), aStream);
case GenericValue::UNSIGNED_T:
return writeUnsigned(aValue.getUnsigned(), aStream);
case GenericValue::SIGNED_T:
return writeSigned(aValue.getSigned(), aStream);
case GenericValue::DOUBLE_T:
return writeDouble(aValue.getDouble(), aStream);
case GenericValue::STRING_T:
return writeString(aValue.getString(), aStream);
case GenericValue::ARRAY_T:
return writeArray(aValue.getArray(), aStream);
case GenericValue::OBJECT_T:
return writeObject(aValue.getObject(), aStream);
default:
return false;
}
}
static GenericValue::ValueType getType(IStream& aStream) {
const int32_t offset = aStream.getOffset();
GenericValue::ValueType type = GenericValue::NULL_T;
skipWhitespace(aStream);
if(! aStream.end()) {
char c;
aStream >> c;
switch(c){
case 'n':
type = GenericValue::NULL_T;
break;
case 't':
case 'f':
type = GenericValue::BOOL_T;
break;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
type = GenericValue::DOUBLE_T;
break;
case '"':
type = GenericValue::STRING_T;
break;
case '[':
type = GenericValue::ARRAY_T;
break;
case '{':
type = GenericValue::OBJECT_T;
break;
default:
break;
}
}
aStream.setOffset(offset);
return type;
}
static GenericValue readValue(IStream& aStream);
static GenericValue readNull(IStream& aStream) throw() {
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Null : Could not locate value");
char buffer[4];
aStream.read(buffer, 4);
if(std::memcmp(buffer, "null", 4) != 0) throw std::runtime_error("Json::Null : Value must be either 'null'");
return GenericValue();
}
static GenericValue readBool(IStream& aStream) {
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Bool : Could not locate value");
char buffer[5];
aStream.read(buffer, 4);
switch(buffer[0]){
case 't':
if(std::memcmp(buffer, "true", 4) != 0) throw std::runtime_error("Json::Bool : Value must be either 'true' or 'false'");
return GenericValue(true);
case 'f':
aStream >> buffer[4];
if(std::memcmp(buffer, "false", 5) != 0) throw std::runtime_error("Json::Bool : Value must be either 'true' or 'false'");
return GenericValue(false);
default:
throw std::runtime_error("Json::Bool : Failed to read value");
}
}
static GenericValue readDouble(IStream& aStream) throw() {
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Number : Could not locate value");
CString buffer;
char c;
aStream >> c;
while((c >= '0' && c <= '9') || c == '-' || c == '.' || c == 'e' || c == 'E') {
buffer += c;
aStream >> c;
}
aStream.setOffset(aStream.getOffset() - 1);
return static_cast<double>(buffer);
}
static GenericValue readString(IStream& aStream) {
bool escaped = false;
char c;
aStream >> c;
if(c != '"') throw std::runtime_error("Json::String : String must be opened by '\"'");
GenericValue value;
String<char>& string = value.setString();
while(! aStream.end()){
aStream >> c;
switch(c) {
case '\\':
if(escaped){
string.pushBack('\\');
escaped = false;
}else{
escaped = true;
}
break;
case '"':
if(escaped){
string.pushBack('"');
escaped = false;
}else{
return value;
}
break;
default:
string.pushBack(c);
escaped = false;
break;
}
}
throw std::runtime_error("Json::String : String must be closed by '\"'");
}
static GenericValue readArray(IStream& aStream) {
char c;
aStream >> c;
if(c != '[') throw std::runtime_error("Json::Array : Array must be opened '['");
GenericValue value;
GenericArray& array_ = value.setArray();
// Check for close
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Array : Failed to locate first element");
if(aStream.peek<char>() == ']') return value;
while(! aStream.end()) {
// Read value
array_.pushBack(readValue(aStream));
// Read seperator
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Array : Failed to locate next element");
aStream >> c;
switch(c){
case ']':
return value;
case ',':
break;
default:
#ifdef SOLAIRE_JSON_WHITESPACE_SEPERATORS
aStream.setOffset(aStream.getOffset() -1);
break;
#else
throw std::runtime_error("Json::Array : Array elements must be separated by ','");
#endif
}
}
throw std::runtime_error("Json::Array : Array must be closed by ']'");
}
static GenericValue readObject(IStream& aStream) {
char c;
aStream >> c;
if(c != '{') throw std::runtime_error("Json::Object : Object must be opened by '{'");
GenericValue value;
GenericObject& object = value.setObject();
// Check for close
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Object : Failed to read first member");
if(aStream.peek<char>() == '}') return value;
while(! aStream.end()) {
// Read name
const GenericValue name = readString(aStream);
if(! name.isString()) throw std::runtime_error("Json::Object : Member name must be a string");
// Read divider
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Object : Failed to determine position of member name divider");
aStream >> c;
if(c != ':') throw std::runtime_error("Json::Object : Member name and value must be separated by ':'");
// Read value
object.emplace(name.getString(), readValue(aStream));
// Read seperator
if(! skipWhitespace(aStream)) throw std::runtime_error("Json::Object : Failed to determine position of member separator");
aStream >> c;
switch(c){
case '}':
return value;
case ',':
break;
default:
#ifdef SOLAIRE_JSON_WHITESPACE_SEPERATORS
aStream.setOffset(aStream.getOffset() -1);
break;
#else
throw std::runtime_error("Json::Object : Members must be separated by ','");
#endif
}
}
throw std::runtime_error("Json::Object : Object must be closed by '}'");
}
static GenericValue readValue(IStream& aStream) {
switch(getType(aStream)) {
case GenericValue::NULL_T:
return readNull(aStream);
case GenericValue::BOOL_T:
return readBool(aStream);
case GenericValue::DOUBLE_T:
return readDouble(aStream);
case GenericValue::STRING_T:
return readString(aStream);
case GenericValue::ARRAY_T:
return readArray(aStream);
case GenericValue::OBJECT_T:
return readObject(aStream);
default:
throw std::runtime_error("Invalid json type");
}
}
// JsonFormat
SOLAIRE_EXPORT_CALL JsonFormat::~JsonFormat() {
}
GenericValue SOLAIRE_EXPORT_CALL JsonFormat::readValue(IStream& aStream) const throw() {
try{
return Solaire::readValue(aStream);
}catch(std::exception& e) {
std::cerr << e.what() << std::endl;
return GenericValue();
}
}
bool SOLAIRE_EXPORT_CALL JsonFormat::writeValue(const GenericValue& aValue, OStream& aStream) const throw() {
try{
return Solaire::writeValue(aValue, aStream);
}catch(std::exception& e) {
std::cerr << e.what() << std::endl;
return false;
}
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.