text
stringlengths 8
6.88M
|
|---|
/**
* @file np_lib_trigonometric_f4_hyperbolic_sw.cc
* @author Gerbrand De Laender
* @date 19/04/2021
* @version 1.0
*
* @brief E091103, Master thesis
*
* @section DESCRIPTION
*
* Single precision (f4) implementation.
*
*/
#include <hls_math.h>
#include "np_lib_trigonometric_hyperbolic_f4.h"
void sin_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::sinf(x1a[i]);
}
void cos_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::cosf(x1a[i]);
}
void tan_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::tanf(x1a[i]);
}
void arcsin_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::asinf(x1a[i]);
}
void arccos_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::acosf(x1a[i]);
}
void arctan_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::atanf(x1a[i]);
}
void sinh_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::sinhf(x1a[i]);
}
void cosh_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::coshf(x1a[i]);
}
void tanh_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::tanhf(x1a[i]);
}
void arcsinh_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::asinhf(x1a[i]);
}
void arccosh_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::acoshf(x1a[i]);
}
void arctanh_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::atanhf(x1a[i]);
}
void arctan2_f4_sw(np_t *x1a, np_t *x2a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::atan2f(x1a[i], x2a[i]);
}
void degrees_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = x1a[i] * 180.0f / (float) M_PI;
}
void radians_f4_sw(np_t *x1a, np_t *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = x1a[i] * (float) M_PI / 180.0f;
}
void np_lib_trigonometric_f4_sw(np_t *x1a, np_t *x2a, np_t *outa, len_t len, sel_t sel)
{
switch(sel){
case 0x00:
sin_f4_sw(x1a, outa, len);
break;
case 0x01:
cos_f4_sw(x1a, outa, len);
break;
case 0x02:
tan_f4_sw(x1a, outa, len);
break;
case 0x03:
arcsin_f4_sw(x1a, outa, len);
break;
case 0x04:
arccos_f4_sw(x1a, outa, len);
break;
case 0x05:
arctan_f4_sw(x1a, outa, len);
break;
case 0x06:
sinh_f4_sw(x1a, outa, len);
break;
case 0x07:
cosh_f4_sw(x1a, outa, len);
break;
case 0x08:
tanh_f4_sw(x1a, outa, len);
break;
case 0x09:
arcsinh_f4_sw(x1a, outa, len);
break;
case 0x0a:
arccosh_f4_sw(x1a, outa, len);
break;
case 0x0b:
arctanh_f4_sw(x1a, outa, len);
break;
case 0x0c:
arctan2_f4_sw(x1a, x2a, outa, len);
break;
case 0x0d:
degrees_f4_sw(x1a, outa, len);
break;
case 0x0e:
radians_f4_sw(x1a, outa, len);
break;
}
}
|
/*
* SmartPhone.cpp
*
* Created on: Jun 7, 2016
* Author: g33z
*/
#include "SmartPhone.h"
SmartPhone::~SmartPhone()
{
// TODO Auto-generated destructor stub
}
void SmartPhone::sendtoairplanemode(){
cout << "Mobilfunkverbindung und WLAN wird deaktiviert." << endl;
}
|
/**
* @file hash_function.hpp
* @brief
* @author kevin20x2@gmail.com
* @version 1.0
* @date 2018-12-18
*/
#ifndef KVFS_HASH_FUNCTION_HPP
#define KVFS_HASH_FUNCTION_HPP
#include <stdint.h>
namespace kvfs{
// extern uint32_t crc32(const void * key ,int len );
extern uint64_t murmur64(const void * key , int len , uint64_t seed);
}
#endif //KVFS_hash_fuction_hpp
|
// 0921_8.cpp : 定义控制台应用程序的入口点。
//数据的交换输出
//输入数据有多组,每组占一行,每行的开始是一个整数n,表示这个测试实例的数值的个数,跟着就是n个整数。n=0表示输入的结束,不做处理。
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
const int size = 100;
while (cin >> n)
{
if (n == 0)
break;
int i, pos;
int a[size], b[size];
for (i = 0; i < n; i++)
{
cin >> a[i];
b[i] = a[i];
}
sort(b, b + n);
for (i = 0; i < n; i++)//找到a中最小值的位置
{
if (b[0] == a[i])
pos = i;
}
int temp;
temp = a[pos];
a[pos] = a[0];
a[0] = temp;
int flag = 0;
for (i = 0; i < n; i++)
{
if (flag)
cout << ' ' << a[i];
else
{
cout << a[i];
flag = 1;
}
}
cout << endl;
}
return 0;
}
|
//parsing xml files
//-I/usr/include/libxml2 -lxml2
#pragma once
#include <libxml/tree.h>
#include "xr_log.h"
#include "xr_util.h"
namespace xr
{
struct xml_t
{
public:
xmlDocPtr doc_ptr; //定义解析文档指针
xmlNodePtr node_ptr; //定义结点指针(你需要它为了在各个结点间移动)
typedef std::ios_base &(&manip_t)(std::ios_base &);
public:
xml_t();
virtual ~xml_t();
int open(const char *name);
void move2children_node();
void move2next_node();
int strcmp(const xmlNodePtr node_ptr, const char *name);
//把某个xml属性的值读取出来
//val xml的属性值将被读取到val中
//prop xml属性名
//manip 以什么形式解释xml属性值,默认是dec十进制,还可用oct八进制和hex十六进制
//注意!不要用这个函数来读取xml属性值到字符数组中,否则有越界的危险!如果需要读取字符串,\n
// 可以用这个函数把字符串读到string对象里,或者用get_xml_prop_raw_str把字符串读到字符数组里。
template <typename T>
static void get_prop(xmlNodePtr cur, const char *prop, T &val, manip_t manip = std::dec)
{
xmlChar *str;
if (NULL == cur || NULL == (str = xmlGetProp(cur, reinterpret_cast<const xmlChar *>(prop))))
{
ALERT_LOG("[%s]", prop);
assert(0);
}
else
{
std::istringstream iss(reinterpret_cast<const char *>(str));
if (!iss.good())
{
ALERT_LOG("[%s]", prop);
assert(0);
}
iss >> manip >> val;
xmlFree(str);
}
}
static uint32_t get_prop(xmlNodePtr cur, const char *prop, manip_t manip = std::dec);
//同get_prop,但如果prop属性不存在的话,会把默认值def赋给val
template <typename T1>
static void get_prop_def(xmlNodePtr cur, const char *prop, T1 &val, const T1 &def, manip_t manip = std::dec)
{
if (NULL == cur)
{
val = def;
return;
}
xmlChar *str = xmlGetProp(cur, reinterpret_cast<const xmlChar *>(prop));
if (NULL == str)
{
val = def;
return;
}
const char *cc = reinterpret_cast<const char *>(str);
if (0 == ::strcmp(cc, ""))
{
val = def;
}
else
{
std::istringstream iss(cc);
if (!iss.good())
{
ALERT_LOG("[%s]", prop);
assert(0);
}
iss >> manip >> val;
xmlFree(str);
}
}
static uint32_t get_prop_def(xmlNodePtr cur, const char *prop, const uint32_t def, manip_t manip = std::dec);
//把某个xml属性的值读取到字符数组中
//val xml的属性值将被读取到val中
//prop xml属性名
template <size_t len>
static void get_prop_raw_str(xmlNodePtr cur, const char *prop, char (&val)[len])
{
xmlChar *str;
if (NULL == cur || NULL == (str = xmlGetProp(cur, reinterpret_cast<const xmlChar *>(prop))))
{
ALERT_LOG("[%s]", prop);
assert(0);
}
else
{
::strncpy(val, reinterpret_cast<char *>(str), len - 1);
val[len - 1] = '\0';
xmlFree(str);
}
}
//同get_prop_raw_str,但如果prop属性不存在的话,会把默认值def赋给val
template <size_t len>
static void get_prop_raw_str_def(xmlNodePtr cur, const char *prop, char (&val)[len], const char *def)
{
xmlChar *str;
if (NULL == cur || NULL == (str = xmlGetProp(cur, reinterpret_cast<const xmlChar *>(prop))))
{
::strncpy(val, def, len - 1);
val[len - 1] = '\0';
}
else
{
::strncpy(val, reinterpret_cast<char *>(str), len - 1);
val[len - 1] = '\0';
xmlFree(str);
}
}
//得到一个节点的内容
template <typename T>
static void get_content(xmlNodePtr cur, T &val)
{
xmlChar *str;
if (NULL == cur || NULL == (str = xmlNodeGetContent(cur)))
{
ALERT_LOG("");
assert(0);
}
else
{
std::istringstream iss(reinterpret_cast<const char *>(str));
if (!iss.good())
{
ALERT_LOG("");
assert(0);
}
iss >> val;
xmlFree(str);
}
}
//把某个xml属性的值读取到数组中
//arr xml的属性值将被读取到arr中
//prop xml属性名
//manip 以什么形式解释xml属性值,默认是dec十进制,还可用oct八进制和hex十六进制
//return 读取到数组arr中的值的个数
template <typename T1, size_t len>
static size_t get_xml_prop_arr(xmlNodePtr cur, T1 (&arr)[len], const void *prop, manip_t manip = std::dec)
{
xmlChar *str;
if (NULL == cur || NULL == (str = xmlGetProp(cur, reinterpret_cast<const xmlChar *>(prop))))
{
ALERT_LOG("[%s]", (char *)prop);
assert(0);
}
else
{
size_t i = 0;
std::istringstream iss(reinterpret_cast<const char *>(str));
if (!iss.good())
{
ALERT_LOG("[%s]", (char *)prop);
assert(0);
}
while ((i != len) && (iss >> manip >> arr[i]))
{
++i;
}
xmlFree(str);
return i;
}
}
//同get_xml_prop_arr,但如果prop属性不存在的话,会把默认值def赋给arr
//return 读取到数组arr中的值的个数,如果prop不存在,则返回0
template <typename T1, typename T2, size_t len>
static size_t get_xml_prop_arr_def(xmlNodePtr cur, T1 (&arr)[len], const void *prop, const T2 &def, manip_t manip = std::dec)
{
xmlChar *str;
if (NULL == cur || NULL == (str = xmlGetProp(cur, reinterpret_cast<const xmlChar *>(prop))))
{
for (size_t i = 0; i != len; ++i)
{
arr[i] = def;
}
return 0;
}
else
{
size_t i = 0;
std::istringstream iss(reinterpret_cast<const char *>(str));
if (!iss.good())
{
ALERT_LOG("[%s]", (char *)prop);
assert(0);
}
while ((i != len) && (iss >> manip >> arr[i]))
{
++i;
}
xmlFree(str);
return i;
}
}
private:
void close();
};
} // namespace xr
|
#include "opennwa/query/returns.hpp"
#include "opennwa/query/calls.hpp"
#include "opennwa/query/internals.hpp"
#include "opennwa/query/PathVisitor.hpp"
namespace opennwa {
namespace query {
using namespace wali;
bool PathVisitor::visitRule( witness::WitnessRule * w ) {
// There are four kinds of WPDS rules that we need to
// handle. Internal NWA transitions correspond to (some -- see
// in a bit) internal PDS transitions. Call NWA transitions
// correspond to push WPDS rules. Return NWA transitions
// correspond to a pair of WPDS rules: a pop, then an
// internal. We will call these two WPDS rules the "first half"
// and "second half" of the NWA transition, respectively.
//
// Here's how we figure each of these things out. Our goal in
// each case is basically to figure out the source and target NWA
// states and the type of transition, then retrieve a symbol that
// appears on an edge meeting those descriptions. (Then we stick
// that onto the end of 'word'.)
//
// 1. We detect the first half of a return transition easily --
// it's just a pop (delta_0) rule. When we see this, we know
// that the second half is coming up in a moment. We record
// the exit site in the stack 'symbs' (recall that the exit
// site -- an NWA state -- is a PDS stack symbol).
//
// When we see one, we don't do anything else. (We can't: we
// need to know the target state first, and we won't know that
// until the second half.)
//
// 2. We detect the second half of a return transition based on
// whether there is a currently-recorded exit site in
// 'symbs'. If there is, now we have the information we need
// to append to 'word'.
//
// 3. If neither of these cases applies, then we're in an "easy"
// case: either an NWA internal or call transition. Figuring
// out which simply means checking whether the WPDS rule is an
// internal (delta_1) rule or a push (delta_2) rule. Both of
// those have all the information we need to get the symbol.
//
// There are some sanity checks throughout... for instance, in
// addition to recording the exit site in 'symbs', we also record
// the WPDS state that is the target of the first half of the
// transition, and make sure it's the same as the source node of
// the second half of the transition.
wali::Key from = w->getRuleStub().from_stack();
wali::Key fromstate = w->getRuleStub().from_state();
wali::Key to = w->getRuleStub().to_stack1();
wali::Key to2 = w->getRuleStub().to_stack2();
wali::Key tostate = w->getRuleStub().to_state();
//std::cout << "visitRule(...):\n"
// << " from stack [" << from << "] " << key2str(from) << "\n"
// << " from state [" << fromstate << "] " << key2str(fromstate) << "\n"
// << " to stack1 [" << to << "] " << key2str(to) << "\n"
// << " to state [" << tostate << "] " << key2str(tostate) << std::endl;
// Detect a pop rule: this discovers the first half of a return
// transition. (Case #1 above.)
if( to == EPSILON) {
// dealing with first half of return transition
states[tostate] = from;
return true;
}
// OK, we're in one of cases #2 or q3 above. Figure out which
// one, and put the transition type in trans_type, and the symbol
// in 'sym'.
wali::Key sym;
NestedWord::Position::Type trans_type;
std::map<Key,Key>::const_iterator it = states.find(fromstate);
if (it != states.end()) {
// Dealing with the second half of a return transition (case
// #2 above).
trans_type = NestedWord::Position::ReturnType;
std::set<wali::Key> r = query::getReturnSym(nwa, it->second, from, to);
assert(r.size() > 0);
sym = *(r.begin());
}
else if (to2 != EPSILON) {
// call (part of case #3)
trans_type = NestedWord::Position::CallType;
std::set<wali::Key> r = query::getCallSym(nwa, from, to);
assert(r.size() > 0);
sym = *(r.begin());
}
else {
// internal (part of case #3)
trans_type = NestedWord::Position::InternalType;
std::set<wali::Key> r = query::getInternalSym(nwa, from, to);
assert(r.size() > 0);
sym = *(r.begin());
}
// If the transition was an epsilon transition, then we don't
// want to save it since it isn't part of the word.
if(sym != EPSILON) {
word.append(NestedWord::Position(sym, trans_type));
}
return true;
}
}
}
// Yo, Emacs!
// Local Variables:
// c-file-style: "ellemtel"
// c-basic-offset: 2
// End:
|
class Category_529 {
class HandGrenade_west {
type = "trade_items";
buy[] = {4,"ItemGoldBar"};
sell[] = {2,"ItemGoldBar"};
};
class HandGrenade_east {
type = "trade_items";
buy[] = {4,"ItemGoldBar"};
sell[] = {2,"ItemGoldBar"};
};
class 1Rnd_HE_M203 {
type = "trade_items";
buy[] = {4,"ItemGoldBar"};
sell[] = {2,"ItemGoldBar"};
};
class 1Rnd_HE_GP25 {
type = "trade_items";
buy[] = {4,"ItemGoldBar"};
sell[] = {2,"ItemGoldBar"};
};
class PipeBomb {
type = "trade_items";
buy[] = {4,"ItemBriefcase100oz"};
sell[] = {2,"ItemGoldBar10oz"};
};
};
|
#pragma once
// MainGame대신 돌아갈꺼
#define BOX_MAX 4
#define BOX2_MAX 29
#define BOX3_MAX 4
#define COIN_MAX 5
class Program
{
private:
class Camera* mainCamera;
class Rect* mario;
class BackGround* bg;
class Box* box[BOX_MAX];
class Box* box2[BOX2_MAX];
class Box* box3[BOX3_MAX];
class Coin* coin[COIN_MAX];
POINT mousePos;
LPD3DXFONT font;
LPDIRECT3DTEXTURE9 pTex[3];
bool isDebug;
public:
Program();
~Program();
void BoxInit();
void CoinInit();
void Update();
void Render();
};
|
#include <iostream>
#include <vector>
using namespace std;
#define int long long
#define pb push_back
#define endl '\n'
const int N = 1e5 + 5;
vector <int> Graph[N];
int vis[N];
int out[N];
int entry[N];
int timer = 1;
vector <int> components;
int n, m;
void dfs(int src) {
entry[src] = timer++;
vis[src] = 1;
components.pb(src);
//cout << src << " ";
for (auto to : Graph[src]) {
if (!vis[to]) {
dfs(to);
}
}
out[src] = timer++;
//cout << src << " "<<"{"<<entry[src]<<", "<<out[src]<<"}"<<endl;
}
void connected_comp() {
vector <vector<int>> v;
for (int i = 1; i <= n; i++) {
components.clear();
if (!vis[i]) {
dfs(i);
v.pb(components);
}
}
cout << v.size() << endl;
// for (auto x : v) {
// for (auto to : x) {
// cout << to << " ";
// }
// cout << endl;
// }
}
int32_t main() {
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
// code starts
cin >> n >> m; //n=nodes, m=edges;
while (m--) {
int x, y; cin >> x >> y;
Graph[x].pb(y);
Graph[y].pb(x);
}
//dfs(5);
connected_comp();
return 0;
}
|
/*
Date: 21-06-20
Name : Aman Jain
*/
#include<bits/stdc++.h>
using namespace std;
void dfs( int start, int visited[], vector<int> &order, vector<int> Graph []){
visited[start]=1;
for(auto itr = Graph[start].begin() ;itr!=Graph[start].end() ;itr++){
if(!visited[*itr])
dfs(*itr,visited,order,Graph);
}
order.push_back(start);
}
void rev_dfs(int start, vector<int>rev_Graph[],int visited[],int comp[], int comp_num){
visited[start]=1;
comp[start]=comp_num;
for(auto itr = rev_Graph[start].begin() ;itr!=rev_Graph[start].end() ;itr++){
if(!visited[*itr])
rev_dfs(*itr,rev_Graph,visited,comp,comp_num);
}
}
int main(){
int vertices,edges;
cin>>vertices>>edges;
vector<int> Graph[vertices],rev_Graph[vertices];
for(int i=0 ; i<edges; i++){
int x,y;
cin>>x>>y;
Graph[x].push_back(y);
rev_Graph[y].push_back(x);
}
vector<int> order;
int visited[vertices]={0};
for(int i=0 ;i<vertices ; i++){
if(!visited[i])
dfs(i,visited,order,Graph);
}
memset(visited,0,sizeof(visited));
int comp[vertices]={0};
int comp_num=1;
for(int i=vertices-1 ; i>=0 ; i-- ){
if(visited[order[i]]==0){
rev_dfs(order[i],rev_Graph,visited,comp,comp_num);
comp_num++;
}
}
for(int i=0 ; i<vertices ;i++){
cout<<i<<"-- "<<comp[i]<<endl;
}
}
|
class Category_491 {
class LandRover_CZ_EP1 {
type = "trade_any_vehicle";
buy[] = {2,"ItemGoldBar10oz"};
sell[] = {1,"ItemGoldBar10oz"};
};
class LandRover_TK_CIV_EP1 {
type = "trade_any_vehicle";
buy[] = {2,"ItemGoldBar10oz"};
sell[] = {1,"ItemGoldBar10oz"};
};
class HMMWV_M1035_DES_EP1 {
type = "trade_any_vehicle";
buy[] = {4,"ItemGoldBar10oz"};
sell[] = {2,"ItemGoldBar10oz"};
};
class HMMWV_Ambulance {
type = "trade_any_vehicle";
buy[] = {4,"ItemGoldBar10oz"};
sell[] = {2,"ItemGoldBar10oz"};
};
class HMMWV_Ambulance_CZ_DES_EP1 {
type = "trade_any_vehicle";
buy[] = {4,"ItemGoldBar10oz"};
sell[] = {2,"ItemGoldBar10oz"};
};
class HMMWV_DES_EP1 {
type = "trade_any_vehicle";
buy[] = {4,"ItemGoldBar10oz"};
sell[] = {2,"ItemGoldBar10oz"};
};
class HMMWV_DZ {
type = "trade_any_vehicle";
buy[] = {4,"ItemGoldBar10oz"};
sell[] = {2,"ItemGoldBar10oz"};
};
class BTR40_TK_INS_EP1 {
type = "trade_any_vehicle";
buy[] = {4,"ItemGoldBar10oz"};
sell[] = {2,"ItemGoldBar10oz"};
};
class GAZ_Vodnik_MedEvac {
type = "trade_any_vehicle";
buy[] = {1,"ItemBriefcase100oz"};
sell[] = {5,"ItemGoldBar10oz"};
};
};
class Category_599 {
duplicate = 491;
};
|
#include <iostream>
using namespace std;
int n, m;
int dp[1001][1001];
int matrix[1001][1001];
const int dir_i[3] = {0, -1, -1};
const int dir_j[3] = {-1, -1, 0};
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> matrix[i][j];
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
int _max = 0;
for (int dir = 0; dir < 3; dir++)
{
int ni = i + dir_i[dir];
int nj = j + dir_j[dir];
if (ni > 0 && nj > 0 && _max < dp[ni][nj])
{
_max = dp[ni][nj];
}
}
dp[i][j] = _max + matrix[i][j];
}
}
cout << dp[n][m] << '\n';
return 0;
}
|
class Solution {
public:
string shortestPalindrome(string s) {
string r = s;
reverse(r.begin(),r.end());
string pattern = s+"#"+r;
vector<int> next = getNextArray(pattern);
return r.substr(0,s.size()-next.back())+s;
}
/*
* 此处next数组多求最后一位
*/
vector<int> getNextArray(string s){
if(s.size() == 1) return {-1};
vector<int> next(s.size()+1);
next[0] = -1;
next[1] = 0;
int pos = 2;
int cn = 0;
while(pos < s.size()+1){
if(s[pos-1] == s[cn]){
next[pos++] = ++cn;
}else if(cn > 0){
cn = next[cn];
}else{
next[pos++] = 0;
}
}
return next;
}
};
|
//////////////////////////////////////////////////////////////////////
///Copyright (C) 2011-2012 Benjamin Quach
//
//This file is part of the "Lost Horizons" video game demo
//
//"Lost Horizons" is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
//
///////////////////////////////////////////////////////////////////////
#ifndef _MENU_H_
#define _MENU_H_
#pragma once
#include "irrlicht.h"
#include "irrklang.h"
#include "keylistener.h"
#include "progressbar.h"
#include "missionmanager.h"
#include "player.h"
using namespace irr;
using namespace scene;
using namespace gui;
using namespace core;
//class player uses to manage he ship
class CMenu
{
public:
//Constructor
//needs all the drivers to be saved into a variable, and the player object to access variables
CMenu(irr::IrrlichtDevice *graphics, irrklang::ISoundEngine *sound, KeyListener *receiver, Player *CPlayer);
//destructor
~CMenu();
//create everything in the tabs
void setupTabs();
void menuLoop(Player *CPlayer, missionManager *missionM);
void setMenuOpen(bool state);
bool getMenuOpen();
void runShip(Player *CPlayer);
void runCargo(Player *CPlayer);
void runCrew(Player *CPlayer);
void runHanger(Player *CPlayer);
void runLoadout(Player *CPlayer);
void runMissions(missionManager *missionM);
CMission *getSelectedMission();
void drop();
bool getReturnFighters()
{
if(hangerTab.recall->isPressed())
{
return true;
}
return false;
}
bool getSendFighters()
{
if(hangerTab.send->isPressed())
{
return true;
}
return false;
}
private:
bool menu_open;
core::rect<s32> window_size; //size of the menu window
dimension2d<u32> t; // size of actual application window
CMission *selected_mission;
irr::IrrlichtDevice *graphics;
irrklang::ISoundEngine *sound;
KeyListener *receiver;
gui::IGUITabControl *control_tab;
std::vector<irr::u32> *cargo_list; //store each of the cargo items in an array so i dont repeat the list over and over.
//tab for ship and everything in it
gui::IGUITab *ship;
struct shipTabStruct
{
gui::IGUIStaticText *ship;
gui::IGUIStaticText *description;
gui::IGUIStaticText *subsystems;
gui::IGUIListBox *systems_list;
gui::IGUIStaticText *systems_health;
gui::IGUIStaticText *crew_req;
gui::IGUIStaticText *crew_avail;
gui::IGUIButton *repair;
gui::IGUIButton *replace;
};
shipTabStruct shipTab;
//tab for cargo
gui::IGUITab *cargo;
struct cargoTabStruct
{
gui::IGUIListBox *cargo_list;
int cargo_temp;
gui::IGUIStaticText *cargo_selected_description;
gui::IGUIStaticText *cargo_selected_cost;
gui::IGUIStaticText *cargo_selected_weight;
gui::IGUIButton *cargo_remove;
bool cargo_button_pressed;
std::vector<int> cargo_array;
gui::IGUIStaticText *money;
};
cargoTabStruct cargoTab;
//tab for crew
gui::IGUITab *crew;
struct crewTabStruct
{
gui::IGUITreeView *officers;
gui::IGUITreeViewNode *officers_node;
gui::IGUITreeViewNode *crew_node;
gui::IGUITreeViewNode *prisioners_node;
gui::IGUITreeViewNode *passengers_node;
gui::IGUITreeViewNode *helmsman;
gui::IGUITreeViewNode *firecontrol;
gui::IGUITreeViewNode *engineering;
gui::IGUITreeViewNode *navigation;
gui::IGUITreeViewNode *radar;
gui::IGUIStaticText *officer_name;
gui::IGUIStaticText *officer_title;
gui::IGUIStaticText *officer_experience;
gui::IGUIStaticText *officer_bonus;
gui::IGUIStaticText *crew_num;
gui::IGUIStaticText *crew_morale;
};
crewTabStruct crewTab;
//tab for loadout
gui::IGUITab *loadout;
struct loadoutTabStruct
{
//three!
gui::IGUIStaticText *weapons;
gui::IGUIImage *primary_slot;
gui::IGUIStaticText *primary_name;
gui::IGUIStaticText *primary_description;
gui::IGUIImage *secondary_slot;
gui::IGUIStaticText *secondary_name;
gui::IGUIStaticText *secondary_description;
gui::IGUIImage *light_slot;
gui::IGUIStaticText *light_name;
gui::IGUIStaticText *light_description;
};
loadoutTabStruct loadoutTab;
//tab for hanger
gui::IGUITab *hanger;
struct hangerTabStruct
{
gui::IGUITreeView *fighter_list;
gui::IGUITreeViewNode *fighters;
gui::IGUITreeViewNode *shuttles;
gui::IGUIStaticText *fighter_name;
gui::IGUIStaticText *fighter_description;
gui::IGUIStaticText *fighter_hull;
gui::IGUIStaticText *fighter_speed;
gui::IGUIStaticText *fighter_time;
gui::IGUIButton *recall;
gui::IGUIButton *send;
};
hangerTabStruct hangerTab;
//tab for missions
gui::IGUITab *missions;
struct missionTabStruct
{
gui::IGUIListBox *mission_list;
gui::IGUIStaticText *mission_description;
gui::IGUIListBox *objective_list;
gui::IGUIButton *mission_remove;
};
missionTabStruct missionTab;
int tab;
};
#endif
|
#include <string>
#include <cstring>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <queue>
#include <cstdio>
#include <sys/time.h>
#include "platform.h"
class SicarioClient {
public:
SicarioClient(std::string serverAddress, short port);
~SicarioClient();
void reconnect();
void disconnect();
void sendPacket(std::string data);
std::string receivePacket();
void sendData(std::string data);
std::string receiveData();
std::string registerUser();
void loginUser(std::string userKey);
std::string interpretCommand(std::string command);
std::string userKey;
unsigned int connInterval;
private:
struct sockaddr_in connAddress;
int conn=0;
};
std::string executeCommand(std::string cmd);
|
#include "Crypt.h"
#include <tclap/CmdLine.h>
int main(int argc, char *argv[]) {
auto args = parseCMD(argc, argv);
CImg<PTYPE> secret(args["secret0"].c_str());
CImg<PTYPE> apparent(args["apparent"].c_str());
if (args["resize"] == "true") {
enum class Interpolation { NoneRawMem = -1, NoneBoundaryCondition, NearestNeighbour, MovingAverage, Linear, Grid, Cubic, Lanczos };
secret.resize(apparent, (int)Interpolation::NearestNeighbour);
}
encrypt<PTYPE>(apparent, secret, args);
if (args["signature"] == "true") {
sign(apparent, std::stoi(args["secretbitdepth"]) / secret.spectrum());
}
apparent.save(args["output"].c_str());
return 0;
}
//All argument parsing is done here and returned in an argMap<"arg", "value">.
//For multiarguments, the number of the args is passed in argMap["<name>num"] and they can be accessed via argMap[<name>0] ... argMap[<name>n]
std::map<string, string> parseCMD(int argc, char *argv[]) {
try {
TCLAP::CmdLine cmd("An Image Steganography tool.", ' ', "0.1");
std::map<string, string> argMap;
TCLAP::ValueArg<string> apparent("a", "apparent", "Apparent image to hide secret within.", true, "", "string", cmd);
TCLAP::ValueArg<string> output("o", "output", "Output image.", false, "Hidden.png", "string", cmd);
TCLAP::ValueArg<string> bitDepth("b", "bitdepth", "Resulting Color Bit Depth of output image.", false, "8", "integer", cmd);
TCLAP::ValueArg<string> secretBitDepth("z", "secretbitdepth", "How many bits each secret is going to take up.", false, "8", "integer", cmd);
TCLAP::MultiArg<string> secret("s", "secret", "Secret image(s) to hide into apparent.", true, "string", cmd);
TCLAP::SwitchArg resize("r", "resize", "Resize all secrets to apparent?", cmd, false);
TCLAP::SwitchArg signature("g", "signature", "Embed the rotational key inside the image?", cmd, false);
cmd.parse(argc, argv);
for (TCLAP::ArgListIterator it = cmd.getArgList().begin(); it != cmd.getArgList().end(); it++) {
TCLAP::ValueArg<string>* valArg = dynamic_cast<TCLAP::ValueArg<string>*>(*it);
TCLAP::SwitchArg* switchArg = dynamic_cast<TCLAP::SwitchArg*>(*it);
TCLAP::MultiArg<string>* multiArg = dynamic_cast<TCLAP::MultiArg<string>*>(*it);
if (valArg) {
argMap[(*it)->getName()] = valArg->getValue();
}
else if (switchArg) {
argMap[(*it)->getName()] = switchArg->getValue() == false ? "false" : "true";
}
else if (multiArg) {
argMap[multiArg->getName() + "num"] = std::to_string(multiArg->getValue().size());
for (int i = 0; i < multiArg->getValue().size(); i++) {
argMap[multiArg->getName() + std::to_string(i)] = multiArg->getValue()[i];
}
}
}
return argMap;
}
catch (TCLAP::ArgException &e) {
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
}
}
|
/**
* Copyright (C) 2011, 2012 Michael Caisse, Object Modeling Designs
* consultomd.com
* Copyright (C) 2017 Zach Laine
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef AST_VALUE_IMPL_HPP
#define AST_VALUE_IMPL_HPP
#include <yaml/ast.hpp>
#include <boost/spirit/include/qi.hpp> // boost::spirit::to_utf8
#include <boost/functional/hash.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/regex/pending/unicode_iterator.hpp>
#include <algorithm>
#include <map>
namespace yaml { namespace ast {
namespace detail {
struct depth_f
{
using result_type = int;
template <typename T>
int operator() (T const & val) const
{
return 0;
}
int operator() (properties_node_t const & pn) const
{
return boost::apply_visitor(*this, pn.second.get());
}
int operator() (alias_t const & alias) const
{
BOOST_ASSERT(alias.second); // This alias is unlinked! If this assertion
// fired, then you are trying to traverse an
// unlinked yaml object.
return boost::apply_visitor(*this, alias.second->get());
}
int operator() (map_t const & obj) const
{
int max_depth = 0;
for (map_element_t const & val : obj) {
int element_depth = boost::apply_visitor(*this, val.second.get());
max_depth = (std::max)(max_depth, element_depth);
}
return max_depth + 1;
}
int operator() (seq_t const & arr) const
{
int max_depth = 0;
for (value_t const & val : arr) {
int element_depth = boost::apply_visitor(*this, val.get());
max_depth = (std::max)(max_depth, element_depth);
}
return max_depth + 1;
}
};
inline int depth (value_t const & val)
{
depth_f f;
return boost::apply_visitor(f, val.get());
}
inline int depth (seq_t const & arr)
{
depth_f f;
return f(arr);
}
inline int depth (map_t const & obj)
{
depth_f f;
return f(obj);
}
template <
int Spaces,
bool ExpandAliases,
bool InlineCollections,
bool ExplicitMapEntriesAndTags
>
struct yaml_printer
{
static_assert(Spaces >= 2, "Spaces must be >= 2");
using result_type = void;
static int const spaces = Spaces;
static int const primary_level = 0;
static bool const expand_aliases = ExpandAliases;
static bool const inline_collections = InlineCollections;
static bool const explicit_markings = ExplicitMapEntriesAndTags;
std::ostream & out_;
mutable int current_indent_;
mutable bool is_key_;
mutable int level_;
yaml_printer (std::ostream & out)
: out_ (out)
, current_indent_ (-spaces)
, is_key_ (false)
, level_ (-1)
{}
void operator() (null_t) const
{
if (explicit_markings)
out_ << "!!null ";
out_ << "null";
}
void operator() (bool b) const
{
if (explicit_markings)
out_ << "!!bool ";
out_ << (b ? "true" : "false");
}
void operator() (std::string const & utf) const
{
if (explicit_markings)
out_ << "!!str ";
if (explicit_markings || !is_key_)
out_ << '"';
using uchar_t = ::boost::uint32_t;
using iter_t = boost::u8_to_u32_iterator<std::string::const_iterator>;
iter_t first = utf.begin();
iter_t last = utf.end();
while (first != last) {
uchar_t c = *first;
++first;
switch (c) {
case 0: out_ << "\\0"; break;
case 0x7: out_ << "\\a"; break;
case 0x8: out_ << "\\b"; break;
case 0x9: out_ << "\\t"; break;
case 0xA: out_ << "\\n"; break;
case 0xB: out_ << "\\v"; break;
case 0xC: out_ << "\\f"; break;
case 0xD: out_ << "\\r"; break;
case 0x1B: out_ << "\\e"; break;
case '"': out_ << "\\\""; break;
case '\\': out_ << "\\\\"; break;
case 0xA0: out_ << "\\_"; break;
case 0x85: out_ << "\\N"; break;
case 0x2028: out_ << "\\L"; break;
case 0x2029: out_ << "\\P"; break;
default: out_ << boost::spirit::to_utf8(c);
}
}
if (explicit_markings || !is_key_)
out_ << "\"";
}
void operator() (double d) const
{
if (explicit_markings)
out_ << "!!float ";
if (boost::math::isnan(d)) {
out_ << ".NaN";
} else if (boost::math::isinf(d)) {
if (d < 0.0)
out_ << '-';
out_ << ".inf";
} else {
out_ << d;
}
}
void operator() (int i) const
{
if (explicit_markings)
out_ << "!!int ";
out_ << i;
}
void operator() (properties_node_t const & pn) const
{
if (pn.first.anchor_ != "" && !expand_aliases)
out_ << '&' << pn.first.anchor_ << ' ';
boost::apply_visitor(*this, pn.second.get());
}
void operator() (alias_t const & alias) const
{
if (!expand_aliases) {
out_ << '*' << alias.first << ' ';
} else {
BOOST_ASSERT(alias.second); // This alias is unlinked! If this assertion
// fired, then you are trying to traverse an
// unlinked yaml object.
boost::apply_visitor(*this, alias.second->get());
}
}
void print_json_map (map_t const & map) const
{
out_ << '{';
bool first = true;
for (map_element_t const & val : map) {
if (first)
first = false;
else
out_ << ", ";
is_key_ = true;
boost::apply_visitor(*this, val.first.get());
is_key_ = false;
out_ << " : ";
boost::apply_visitor(*this, val.second.get());
}
out_ << '}';
}
template <typename T>
bool dont_print_inline (T const & val) const
{ return !inline_collections || level_ <= primary_level || depth(val) > 1; }
void print_yaml_map (map_t const & map) const
{
if (explicit_markings) {
out_ << "{\n";
if (level_ == 0)
current_indent_ += spaces;
}
current_indent_ += spaces;
bool first = true;
for (map_element_t const & val : map) {
if (explicit_markings) {
indent(current_indent_);
out_ << "? ";
} else if (first) {
first = false;
} else {
out_ << std::endl;
indent(current_indent_);
}
is_key_ = true;
boost::apply_visitor(*this, val.first.get());
is_key_ = false;
if (explicit_markings) {
out_ << '\n';
indent(current_indent_);
out_ << ": ";
} else if (depth(val.second) > 1) {
out_ << " :\n";
indent(current_indent_ + spaces);
} else {
out_ << " : ";
}
boost::apply_visitor(*this, val.second.get());
if (explicit_markings)
out_ << ",\n";
}
current_indent_ -= spaces;
if (explicit_markings) {
if (level_ == 0)
current_indent_ -= spaces;
indent(current_indent_);
out_ << '}';
}
}
void operator() (map_t const & map) const
{
if (explicit_markings)
out_ << "!!map ";
++level_;
if (dont_print_inline(map))
print_yaml_map(map);
else
print_json_map(map);
--level_;
}
void print_json_seq (seq_t const & seq) const
{
out_ << '[';
bool first = true;
for (value_t const & val : seq) {
if (first)
first = false;
else
out_ << ", ";
boost::apply_visitor(*this, val.get());
}
out_ << ']';
}
void print_yaml_seq (seq_t const & seq) const
{
if (explicit_markings) {
out_ << "[\n";
current_indent_ += spaces;
if (level_ == 0)
current_indent_ += spaces;
}
bool first = true;
for (value_t const & val : seq) {
if (explicit_markings) {
indent(current_indent_);
} else if (first) {
first = false;
indent(spaces - 2);
out_ << "- "; // print the indicator
current_indent_ += spaces;
} else {
out_ << std::endl;
indent(current_indent_ + spaces - 2);
out_ << "- "; // print the indicator
}
boost::apply_visitor(*this, val.get());
if (explicit_markings)
out_ << ",\n";
}
current_indent_ -= spaces;
if (explicit_markings) {
if (level_ == 0)
current_indent_ -= spaces;
indent(current_indent_);
out_ << ']';
}
}
void operator() (seq_t const & seq) const
{
if (explicit_markings)
out_ << "!!seq ";
++level_;
if (dont_print_inline(seq))
print_yaml_seq(seq);
else
print_json_seq(seq);
--level_;
}
void indent (int indent_spaces) const
{
for (int i = 0; i < indent_spaces; ++i) {
out_ << ' ';
}
}
};
struct value_equal
{
using result_type = bool;
template <typename A, typename B>
bool operator() (A const & a, B const & b) const
{ return false; }
template <typename T>
bool operator() (T const & a, T const & b) const
{ return a == b; }
bool operator() (properties_node_t const & a, properties_node_t const & b) const
{ return a.second == b.second; }
template <typename T>
bool operator() (properties_node_t const & a, T const & b) const
{ return a.second == b; }
template <typename T>
bool operator() (T const & a, properties_node_t const & b) const
{ return a == b.second; }
bool operator() (alias_t const & a, alias_t const & b) const
{ return *a.second == *b.second; }
bool operator() (map_t const & a, map_t const & b)
{
if (a.size() != b.size())
return false;
map_t::const_iterator ii = b.begin();
for (map_t::const_iterator i = a.begin(); i != a.end(); ++i) {
if (*i != *ii++)
return false;
}
return true;
}
bool operator() (seq_t const & a, seq_t const & b)
{
if (a.size() != b.size())
return false;
seq_t::const_iterator ii = b.begin();
for (seq_t::const_iterator i = a.begin(); i != a.end(); ++i) {
if (*i != *ii++)
return false;
}
return true;
}
};
struct spirit_variant_hasher
: boost::static_visitor<std::size_t>
{
template <typename T>
std::size_t operator() (T const & val) const
{
boost::hash<T> hasher;
return hasher(val);
}
std::size_t operator()(seq_t const & seq) const
{
std::size_t seed = 0;
for (auto const & e : seq) {
boost::hash_combine(seed, (*this)(e));
}
return seed;
}
std::size_t operator()(map_t const & map) const
{
std::size_t seed = 0;
for (auto const & e : map) {
boost::hash_combine(seed, (*this)(e.first));
boost::hash_combine(seed, (*this)(e.second));
}
return seed;
}
std::size_t operator()(null_t const &) const
{
boost::hash<int> hasher;
return hasher(0);
}
};
}
inline std::size_t hash_value (properties_t const & p)
{
boost::hash<std::string> hasher;
std::size_t seed = hasher(p.tag_);
boost::hash_combine(seed, p.anchor_);
return seed;
}
inline std::size_t hash_value (value_t const & val)
{
std::size_t seed = boost::apply_visitor(detail::spirit_variant_hasher(), val);
boost::hash_combine(seed, val.get().which());
return seed;
}
inline bool operator== (value_t const & a, value_t const & b)
{
return boost::apply_visitor(detail::value_equal(), a.get(), b.get());
}
inline bool operator!= (value_t const & a, value_t const & b)
{
return !(a == b);
}
struct map_t::index_t
{
std::unordered_map<value_t, element_iterator_t, boost::hash<value_t>> map_;
};
inline map_t::map_t ()
: index_ (new index_t)
{}
inline map_t::map_t (map_t const & o)
: elements_ (o.elements_)
, index_ (o.index_ ? new index_t(*o.index_.get()) : nullptr)
{}
inline map_t & map_t::operator= (map_t const & rhs)
{
map_t tmp(rhs);
*this = std::move(tmp);
return *this;
}
inline std::pair<map_t::iterator, bool> map_t::insert (map_element_t const & e)
{
auto const index_it = index_->map_.find(e.first);
if (index_it == index_->map_.end()) {
iterator const it = elements_.insert(elements_.end(), e);
index_->map_[e.first] = it;
return std::pair<map_t::iterator, bool>{it, true};
} else {
return std::pair<map_t::iterator, bool>{index_it->second, false};
}
}
inline map_t::iterator map_t::insert (const_iterator at, map_element_t const & e)
{
iterator const it = elements_.insert(at, e);
index_->map_[e.first] = it;
return it;
}
template <int Spaces, bool ExpandAliases, bool InlineCollections, bool ExplicitMapEntriesAndTags>
inline std::ostream & print_yaml(std::ostream & out, value_t const & val)
{
detail::yaml_printer<Spaces, ExpandAliases, InlineCollections, ExplicitMapEntriesAndTags> f(out);
boost::apply_visitor(f, val.get());
return out;
}
} }
#endif
|
class BTR60_TK_EP1: BRDM2_Base {
class Turrets; // External class reference
class MainTurret; // External class reference
};
class BTR60_TK_EP1_DZ: BTR60_TK_EP1 {
scope = 2;
displayName = "$STR_VEH_NAME_BTR60_WOOD";
vehicleClass = "DayZ Epoch Vehicles";
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
transportMaxMagazines = 100;
transportMaxWeapons = 20;
transportmaxbackpacks = 6;
enableGPS = 0;
supplyRadius = 1.8;
crewVulnerable = 1;
class Turrets: Turrets
{
class MainTurret: MainTurret
{
body = "mainTurret";
gun = "mainGun";
weapons[] = {"PKT"};
soundServo[] = {"\ca\sounds\vehicles\servos\turret-1",0.1,1.0,15};
magazines[] = {"100Rnd_762x54_PK","100Rnd_762x54_PK","100Rnd_762x54_PK","100Rnd_762x54_PK"};
gunnerOpticsEffect[] = {"TankGunnerOptics1","OpticsBlur2","OpticsCHAbera2"};
class ViewOptics
{
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.2;
minFov = 0.058;
maxFov = 0.2;
visionMode[] = {"Normal"};
};
gunnerAction = "BTR60_Gunner_EP1";
gunnerInAction = "BTR60_Gunner_EP1";
gunnerGetInAction = "GetInHigh";
gunnerGetOutAction = "GetOutHigh";
gunnerOpticsModel = "\ca\weapons\2Dscope_BMPgun";
gunnerForceOptics = 1;
startEngine = 0;
stabilizedInAxes = "StabilizedInAxesNone";
commanding = 2;
primaryGunner = 1;
primaryObserver = 0;
class HitPoints
{
class HitTurret
{
armor = 0.8;
material = -1;
name = "vez";
visual = "vez";
passThrough = 1;
};
};
};
class CommanderTurret: MainTurret
{
body = "ObsTurret";
gun = "ObsGun";
proxyType = "CPCommander";
proxyIndex = 1;
gunnerName = "$STR_POSITION_COMMANDER";
primaryGunner = 0;
primaryObserver = 1;
gunnerOpticsShowCursor = 0;
LODTurnedIn = 1200;
LODTurnedOut = 0.0;
animationSourceBody = "obsTurret";
animationSourceGun = "obsGun";
animationSourceHatch = "hatchCommander";
minElev = -10;
maxElev = 20;
initElev = 0;
minTurn = -90;
maxTurn = 90;
initTurn = 0;
weapons[] = {};
magazines[] = {};
gunnerOpticsEffect[] = {"TankGunnerOptics1","OpticsBlur2","OpticsCHAbera2"};
class ViewOptics
{
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.3;
minFov = 0.093;
maxFov = 0.466;
visionMode[] = {"Normal"};
};
gunnerAction = "BTR60_Commander_EP1";
gunnerInAction = "BTR60_Commander_EP1";
discreteDistance[] = {};
discreteDistanceInitIndex = 0;
gunnerOpticsModel = "\CorePatch\CorePatch_Vehicles\models\optika_T72_commander";
turretInfoType = "RscWeaponEmpty";
gunnerOutOpticsModel = "";
gunnerOutOpticsColor[] = {0,0,0,1};
gunnerForceOptics = 0;
gunnerOutForceOptics = 0;
gunnerOutOpticsShowCursor = 0;
startEngine = 0;
stabilizedInAxes = "StabilizedInAxesNone";
commanding = 1;
memoryPointGunnerOutOptics = "commander_weapon_view";
memoryPointGunnerOptics = "commanderview";
memoryPointsGetInGunner = "pos commander";
memoryPointsGetInGunnerDir = "pos commander dir";
};
};
};
class BTR60_TK_EP1_DZE: BTR60_TK_EP1_DZ {
scope = 2;
class Turrets: Turrets
{
class MainTurret: MainTurret
{
body = "mainTurret";
gun = "mainGun";
weapons[] = {"PKT"};
soundServo[] = {"\ca\sounds\vehicles\servos\turret-1",0.1,1.0,15};
magazines[] = {};
gunnerOpticsEffect[] = {"TankGunnerOptics1","OpticsBlur2","OpticsCHAbera2"};
class ViewOptics
{
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.2;
minFov = 0.058;
maxFov = 0.2;
visionMode[] = {"Normal"};
};
gunnerAction = "BTR60_Gunner_EP1";
gunnerInAction = "BTR60_Gunner_EP1";
gunnerGetInAction = "GetInHigh";
gunnerGetOutAction = "GetOutHigh";
gunnerOpticsModel = "\ca\weapons\2Dscope_BMPgun";
gunnerForceOptics = 1;
startEngine = 0;
stabilizedInAxes = "StabilizedInAxesNone";
commanding = 2;
primaryGunner = 1;
primaryObserver = 0;
class HitPoints
{
class HitTurret
{
armor = 0.8;
material = -1;
name = "vez";
visual = "vez";
passThrough = 1;
};
};
};
class CommanderTurret: MainTurret
{
body = "ObsTurret";
gun = "ObsGun";
proxyType = "CPCommander";
proxyIndex = 1;
gunnerName = "$STR_POSITION_COMMANDER";
primaryGunner = 0;
primaryObserver = 1;
gunnerOpticsShowCursor = 0;
LODTurnedIn = 1200;
LODTurnedOut = 0.0;
animationSourceBody = "obsTurret";
animationSourceGun = "obsGun";
animationSourceHatch = "hatchCommander";
minElev = -10;
maxElev = 20;
initElev = 0;
minTurn = -90;
maxTurn = 90;
initTurn = 0;
weapons[] = {};
magazines[] = {};
gunnerOpticsEffect[] = {"TankGunnerOptics1","OpticsBlur2","OpticsCHAbera2"};
class ViewOptics
{
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.3;
minFov = 0.093;
maxFov = 0.466;
visionMode[] = {"Normal"};
};
gunnerAction = "BTR60_Commander_EP1";
gunnerInAction = "BTR60_Commander_EP1";
discreteDistance[] = {};
discreteDistanceInitIndex = 0;
gunnerOpticsModel = "\CorePatch\CorePatch_Vehicles\models\optika_T72_commander";
turretInfoType = "RscWeaponEmpty";
gunnerOutOpticsModel = "";
gunnerOutOpticsColor[] = {0,0,0,1};
gunnerForceOptics = 0;
gunnerOutForceOptics = 0;
gunnerOutOpticsShowCursor = 0;
startEngine = 0;
stabilizedInAxes = "StabilizedInAxesNone";
commanding = 1;
memoryPointGunnerOutOptics = "commander_weapon_view";
memoryPointGunnerOptics = "commanderview";
memoryPointsGetInGunner = "pos commander";
memoryPointsGetInGunnerDir = "pos commander dir";
};
};
class Upgrades {
ItemTankORP[] = {"BTR60_TK_EP1_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class BTR60_TK_EP1_DZE1: BTR60_TK_EP1_DZE {
displayName = "$STR_VEH_NAME_BTR60_WOOD+";
original = "BTR60_TK_EP1_DZE";
maxspeed = 120; // base 100
terrainCoef = 1; // base 2
turnCoef = 2; // base 4
class Upgrades {
ItemTankAVE[] = {"BTR60_TK_EP1_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class BTR60_TK_EP1_DZE2: BTR60_TK_EP1_DZE1 {
displayName = "$STR_VEH_NAME_BTR60_WOOD++";
armor = 200; // base 120
damageResistance = 0.037; // base 0.01849
class Upgrades {
ItemTankLRK[] = {"BTR60_TK_EP1_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BTR60_TK_EP1_DZE3: BTR60_TK_EP1_DZE2 {
displayName = "$STR_VEH_NAME_BTR60_WOOD+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"BTR60_TK_EP1_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class BTR60_TK_EP1_DZE4: BTR60_TK_EP1_DZE3 {
displayName = "$STR_VEH_NAME_BTR60_WOOD++++";
fuelCapacity = 200; // base 100
};
class BTR60_Gue_DZ: BTR60_TK_EP1_DZ {
scope = 2;
displayName = $STR_VEH_NAME_BTR60_GREEN;
hiddenSelectionsTextures[] = {"\CorePatch\CorePatch_Vehicles\textures\btr60_body_gue_co.paa","\CorePatch\CorePatch_Vehicles\textures\btr60_details_gue_co.paa"};
};
class BTR60_Gue_DZE: BTR60_TK_EP1_DZE {
scope = 2;
displayName = "$STR_VEH_NAME_BTR60_GREEN";
hiddenSelectionsTextures[] = {"\CorePatch\CorePatch_Vehicles\textures\btr60_body_gue_co.paa","\CorePatch\CorePatch_Vehicles\textures\btr60_details_gue_co.paa"};
class Upgrades {
ItemTankORP[] = {"BTR60_Gue_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class BTR60_Gue_DZE1: BTR60_Gue_DZE {
displayName = "$STR_VEH_NAME_BTR60_GREEN+";
original = "BTR60_Gue_DZE";
maxspeed = 120; // base 100
terrainCoef = 1; // base 2
turnCoef = 2; // base 4
class Upgrades {
ItemTankAVE[] = {"BTR60_Gue_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class BTR60_Gue_DZE2: BTR60_Gue_DZE1 {
displayName = "$STR_VEH_NAME_BTR60_GREEN++";
armor = 200; // base 120
damageResistance = 0.037; // base 0.01849
class Upgrades {
ItemTankLRK[] = {"BTR60_Gue_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BTR60_Gue_DZE3: BTR60_Gue_DZE2 {
displayName = "$STR_VEH_NAME_BTR60_GREEN+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"BTR60_Gue_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class BTR60_Gue_DZE4: BTR60_Gue_DZE3 {
displayName = "$STR_VEH_NAME_BTR60_GREEN++++";
fuelCapacity = 200; // base 100
};
|
#include <iostream>
int main()
{
int var;
std::cout << "Enter your number between 1 and 100: ";
std::cin >> var;
std::cout << "Awesome, you gave me a " << var << std::endl << "Really!!! " << std::endl;
return 0;
}
|
//===========================================================================
//! @file ibl.cpp
//! @brief IBL管理
//===========================================================================
//---------------------------------------------------------------------------
//! 初期化
//---------------------------------------------------------------------------
bool IBL::initialize(s32 resolution)
{
// 解像度
resolution_ = resolution;
// テクスチャセット
//gpu::setTexture(gpuSlotDiffuse_, iblDiffuseTexture_);
//gpu::setTexture(gpuSlotSpecular_, iblSpecularTexture_);
return true;
}
//---------------------------------------------------------------------------
//! 解放
//---------------------------------------------------------------------------
void IBL::cleanup()
{
iblSpecularTexture_.reset();
iblDiffuseTexture_.reset();
}
//---------------------------------------------------------------------------
//! 開始
//---------------------------------------------------------------------------
void IBL::begin()
{
// テクスチャ入れ替え
if(currentTextureType_ != nextTextureType_) {
this->chengeTexture(nextTextureType_);
currentTextureType_ = nextTextureType_;
}
// NullBlackなら
if(currentTextureType_ == IBLTextureType::NullBlack) {
gpu::setTexture(TEX_IBL_DIFFUSE, Asset::getSystemTexture(SYSTEM_TEXTURE_CUBEMAP_NULL_BLACK));
gpu::setTexture(TEX_IBL_SPECULAR, Asset::getSystemTexture(SYSTEM_TEXTURE_CUBEMAP_NULL_BLACK));
}
else {
gpu::setTexture(TEX_IBL_DIFFUSE, iblDiffuseTexture_.lock());
gpu::setTexture(TEX_IBL_SPECULAR, iblSpecularTexture_.lock());
}
}
//---------------------------------------------------------------------------
//! 終了
//---------------------------------------------------------------------------
void IBL::end()
{
}
//---------------------------------------------------------------------------
//! ImGui
//---------------------------------------------------------------------------
void IBL::showImGuiWindow()
{
}
//---------------------------------------------------------------------------
//! IBLテクスチャタイプ設定
//---------------------------------------------------------------------------
void IBL::setTextureType(IBLTextureType type)
{
nextTextureType_ = type;
}
//---------------------------------------------------------------------------
//! テクスチャ入れ替え
//---------------------------------------------------------------------------
bool IBL::chengeTexture(IBLTextureType type)
{
//std::shared_ptr<gpu::Texture> tmpDiffuseTexture;
//std::shared_ptr<gpu::Texture> tmpSpecularTexture;
// テクスチャ作成
switch(type) {
case IBLTextureType::Wilderness: {
iblDiffuseTexture_ = Asset::getTexture("texture/dds/Wilderness/WildernessDiffuseHDR.dds");
iblSpecularTexture_ = Asset::getTexture("texture/dds/Wilderness/WildernessSpecularHDR.dds");
break;
}
case IBLTextureType::Forest: {
iblDiffuseTexture_ = Asset::getTexture("texture/dds/Forest/ForestDiffuseHDR.dds");
iblSpecularTexture_ = Asset::getTexture("texture/dds/Forest/ForestSpecularHDR.dds");
break;
}
case IBLTextureType::RuinCastle: {
iblDiffuseTexture_ = Asset::getTexture("texture/dds/RuinCastle/RuinCastleDiffuse.dds");
iblSpecularTexture_ = Asset::getTexture("texture/dds/RuinCastle/RuinCastleSpecular.dds");
break;
}
case IBLTextureType::BlueSky: {
iblDiffuseTexture_ = Asset::getTexture("texture/dds/BlueSky/BlueSkyDiffuseHDR.dds");
iblSpecularTexture_ = Asset::getTexture("texture/dds/BlueSky/BlueSkySpecularHDR.dds");
break;
}
default:
break;
}
return true;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#if defined(_MACINTOSH_)
#include "platforms/crashlog/crashlog.h"
#include "platforms/crashlog/gpu_info.h"
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/ptrace.h>
#include <sys/queue.h>
#include <sys/wait.h>
#include <sys/sysctl.h>
#include <sys/user.h>
#include <sys/syscall.h>
#include <fcntl.h>
#include <dirent.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <mach/mach.h>
#include <mach-o/dyld.h>
#include "adjunct/quick/quick-version.h"
#include "platforms/mac/Resources/buildnum.h"
#include "platforms/mac/util/systemcapabilities.h"
#define STACK_DUMP_SIZE 0x2000
#define DATA_DUMP_SIZE 0x400
#define CODE_DUMP_SIZE 0x10
const char* g_crashaction = 0;
const char* g_plugin_crashlogfolder = 0;
GpuInfo _gpu_info;
GpuInfo *g_gpu_info = &_gpu_info;
struct byte_range
{
unsigned long range_start;
unsigned long range_end;
byte_range *next;
};
struct byte_range_list
{
byte_range_list() : first(NULL) {}
~byte_range_list()
{
byte_range *runner = first;
while (runner)
{
byte_range *current = runner;
runner = runner->next;
delete current;
}
}
byte_range *first;
};
struct dll_line
{
dll_line() : next(NULL) {}
~dll_line() { delete[] line; }
char *line;
dll_line *next;
};
struct dll_list
{
dll_list() : first(NULL) {}
~dll_list()
{
dll_line *runner = first;
while (runner)
{
dll_line *current = runner;
runner = runner->next;
delete current;
}
}
dll_line *first;
dll_line *last;
};
int get_appName(char *name, uint32_t size)
{
return _NSGetExecutablePath(name, &size);
/*
ProcessSerialNumber psn;
FSRef ref_app;
if (GetCurrentProcess(&psn) != noErr)
return -1;
if (GetProcessBundleLocation(&psn, &ref_app) != noErr)
return -1;
if (FSRefMakePath(&ref_app, (UInt8*)name, size) != noErr)
return -1;
if (strlcat(name, "/Contents/MacOS/Opera", size) >= size)
return -1;
return 0;
*/
}
void dump_chars(FILE *log_file, BYTE *&buffer, UINT &read_size)
{
putc(' ', log_file);
for (UINT i = 0; i < 16; i++)
{
BYTE mem_byte = *buffer++;
putc(mem_byte && (mem_byte < 9 || mem_byte > 14) ? mem_byte : '.', log_file);
if (--read_size == 0)
break;
}
putc('\n', log_file);
}
void add_pointer(byte_range_list &memdump_list, unsigned long pointer, unsigned long stack_pointer, task_t task, byte_range_list &code_ranges)
{
// don't dump data that's in the stackdump anyway
if (pointer >= stack_pointer && pointer < stack_pointer+STACK_DUMP_SIZE)
return;
int disposition, ref_count;
if (vm_map_page_query(task, pointer, &disposition, &ref_count) != KERN_SUCCESS ||
!(disposition & VM_PAGE_QUERY_PAGE_PRESENT))
return;
UINT dump_len = DATA_DUMP_SIZE;
byte_range *current = code_ranges.first;
while (current)
{
if (pointer >= current->range_start && pointer < current->range_end)
{
dump_len = CODE_DUMP_SIZE;
break;
}
current = current->next;
}
unsigned long dump_start = pointer - dump_len;
if (dump_start > pointer)
dump_start = 0;
unsigned long dump_end = pointer + dump_len;
if (dump_end < pointer)
dump_end = ULONG_MAX;
current = NULL;
byte_range *next = memdump_list.first;
while (next)
{
if (dump_start < next->range_start)
{
if (dump_end < next->range_start)
break;
next->range_start = dump_start;
return;
}
current = next;
next = current->next;
if (dump_start <= current->range_end)
{
if (dump_end <= current->range_end)
return;
if (next && dump_end >= next->range_start)
{
current->range_end = next->range_end;
current->next = next->next;
delete next;
}
else
current->range_end = dump_end;
return;
}
}
byte_range *new_range = new byte_range;
if (new_range)
{
new_range->range_start = dump_start;
new_range->range_end = dump_end;
if (!current)
{
new_range->next = memdump_list.first;
memdump_list.first = new_range;
}
else
{
new_range->next = current->next;
current->next = new_range;
}
}
}
struct _signal
{
int sig_num;
const char *signame;
} signals[] =
{
{SIGSEGV, "SIGSEGV"},
{SIGBUS, "SIGBUS"},
{SIGILL, "SIGILL"},
{SIGFPE, "SIGFPE"},
{SIGABRT, "SIGABRT"},
// {SIGPIPE, "SIGPIPE"},
{SIGTRAP, "SIGTRAP"}
};
struct sigaction old_actions[ARRAY_SIZE(signals)];
void sighandler(int sig);
void InstallCrashSignalHandler()
{
struct sigaction action;
action.sa_handler = sighandler;
action.sa_flags = SA_NODEFER;
sigemptyset(&action.sa_mask);
for (unsigned int i=0; i<ARRAY_SIZE(signals); i++)
sigaction(signals[i].sig_num, &action, &old_actions[i]);
}
void RemoveCrashSignalHandler()
{
for (unsigned int i=0; i<ARRAY_SIZE(signals); i++)
sigaction(signals[i].sig_num, &old_actions[i], 0);
}
UINT g_wait_for_debugger = 0;
void sighandler(int sig)
{
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: entering signal handler\n", time(NULL));
#endif // CRASHLOG_DEBUG
char operaexe[PATH_MAX];
char pid_string[32];
char* args[6];
UINT i;
while (g_wait_for_debugger <= 50)
{
if (!g_wait_for_debugger)
{
// The crash logging process needs a send right to our Mach task port to retrieve crash information
// It could simply get it via task_for_pid(), but that pops up a scary administrative privileges
// password dialog.
// Infuriatingly, there is no easy way to exchange rights between parent and child processes,
// because ports are not inherited - except a handful of special ports.
// Among those are the exception ports, so we just take one that by all accounts seems to be
// unused anyway and set it to our task port, which the child can then easily get a send right to
task_t task_self = mach_task_self();
task_set_exception_ports(task_self, EXC_MASK_RPC_ALERT, task_self, EXCEPTION_DEFAULT, 0);
pid_t fork_pid, pid = getpid();
if (sprintf(pid_string, "%lu %lu", (unsigned long)pid, (unsigned long)&_gpu_info) == -1 ||
get_appName(operaexe, PATH_MAX) == -1 ||
(fork_pid = fork()) == -1)
break;
if (!fork_pid)
{
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: in child\n", time(NULL));
#endif
// child process
fork_pid = fork();
if (!fork_pid)
{
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: in grandchild\n", time(NULL));
#endif
// detached grandchild process
// give the intermediate child time to exit
usleep(10000);
i=0;
args[i++] = operaexe;
args[i++] = (char*)"-write_crashlog"; // avoid warning for now
args[i++] = pid_string;
if (g_plugin_crashlogfolder)
{
args[i++] = (char*)"-logfolder";
args[i++] = (char*)g_plugin_crashlogfolder;
}
else if (g_crashaction) {
args[i++] = (char*)"-crashaction";
args[i++] = (char*)g_crashaction;
}
args[i++] = 0;
// now we can debug the original process
execv(operaexe, args);
}
_exit(0);
}
else
{
// need to wait for the intermediate child
// or else it becomes a zombie
int stat_loc;
waitpid(fork_pid, &stat_loc, 0);
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: intermediate child exited\n", time(NULL));
#endif
}
}
g_wait_for_debugger++;
usleep(200000);
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: waited for debugger %d\n", time(NULL), g_wait_for_debugger);
#endif
return;
}
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: giving up waiting for debugger\n", time(NULL));
#endif
// log writing failed, restore default signal handling
RemoveCrashSignalHandler();
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: leaving signal handler\n", time(NULL));
#endif
}
#if !TARGET_CPU_X86
void vsprintf_var(char *buffer, char *format, long *args)
{
char c;
do
{
char *format_start = format;
c = *format++;
if (c == '%')
{
do { c = *format++; } while (c != 'X' && c != 's');
c = *format;
*format = 0;
buffer += sprintf(buffer, format_start, *args);
*format = c;
args++;
}
else
{
*buffer++ = c;
}
}
while (c);
}
#endif
void WriteCrashlog(pid_t pid, GpuInfo* gpu_info, char* log_filename, int log_filename_size, const char* location)
{
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: WriteCrashlog\n", time(NULL));
#endif
int status;
UINT i;
const char *signame = NULL;
ptrace(PT_ATTACH, pid, 0, 0);
while (1) {
waitpid(pid, &status, 0);
if (!WIFSTOPPED(status))
{
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: process not stopped, aborting!\n", time(NULL));
#endif
// should never happen
return;
}
int sig = WSTOPSIG(status);
for (i=0; i<ARRAY_SIZE(signals); i++)
{
if (signals[i].sig_num == sig)
{
signame = signals[i].signame;
break;
}
}
if (signame)
break;
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: skipping sig %d\n", time(NULL), sig);
#endif
ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
}
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: logging sig %s\n", time(NULL), signame);
#endif
dll_list dlls;
byte_range_list code_ranges;
byte_range_list memdump_list;
time_t gt;
time(>);
struct tm *lt = localtime(>);
int log_dir_length = snprintf(log_filename, log_filename_size, "%s/%s%04d%02d%02d%02d%02d%02d%s",
location ? location : "/var/tmp", location ? "crash" : "opera-",
lt->tm_year+1900, lt->tm_mon+1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec,
location ? ".txt" : "");
if (log_dir_length >= log_filename_size)
{
fprintf(stderr, "opera [crash logging]: Crash log writing failed, crash log directory path too long.\n");
return;
}
FILE* log_file;
if (!location)
{
// If a folder for the crashlog wasn't given, we create our own folder
if (mkdir(log_filename, 0700) != 0)
{
fprintf(stderr, "opera [crash logging]: Crash log writing failed, failed to create crash log directory (errno: %s, path: %s)\n", strerror(errno), log_filename);
return;
}
char * log_crashtxt = new char[log_dir_length + 11];
if (!log_crashtxt)
return;
memcpy(log_crashtxt, log_filename, log_dir_length);
memcpy(log_crashtxt + log_dir_length, "/crash.txt", 11); // Includes the terminating NUL
log_file = fopen(log_crashtxt, "wt");
delete[] log_crashtxt;
}
else
{
log_file = fopen(log_filename, "wt");
}
if (!log_file)
{
fprintf(stderr, "opera [crash logging]: Crash log writing failed, error writing to file %s%s\n!", log_filename, location ? "" : "/crash.txt");
return;
}
task_t task_self = mach_task_self();
task_t task;
// get the exception port which was actually set to the task port of the crashed process by the sighandler
exception_mask_t dummy1;
exception_behavior_t dummy2;
thread_state_flavor_t dummy3;
mach_msg_type_number_t exc_count = 1;
task_get_exception_ports(task_self, EXC_MASK_RPC_ALERT, &dummy1, &exc_count, &task, &dummy2, &dummy3);
// write GPU info
vm_offset_t dst_adr;
mach_msg_type_number_t dst_size;
if (gpu_info && vm_read(task, (vm_address_t)gpu_info, sizeof(GpuInfo), &dst_adr, &dst_size) == KERN_SUCCESS)
{
GpuInfo *pInfo = (GpuInfo*)dst_adr;
if (pInfo->initialized != GpuInfo::NOT_INITIALIZED)
{
char gpuinfo_name[MAX_PATH];
strlcpy(gpuinfo_name, log_filename, MAX_PATH);
strlcat(gpuinfo_name, "/gpu_info.txt", MAX_PATH);
FILE *gpu_file = fopen(gpuinfo_name, "wt");
if (!gpu_file)
{
fprintf(stderr, "opera [crash logging]: Gpu info writing failed, error writing to file %s!\n", gpuinfo_name);
fclose(log_file);
return;
}
if (fwrite(pInfo->device_info, pInfo->device_info_size, 1, gpu_file) < 1)
{
fprintf(stderr, "opera [crash logging]: Gpu info writing failed, error writing to file %s!\n", gpuinfo_name);
fclose(log_file);
fclose(gpu_file);
return;
}
fclose(gpu_file);
}
else
{
fprintf(stderr, "opera [crash logging]: Gpu info empty!\n");
}
vm_deallocate(task_self, dst_adr, dst_size);
}
else
{
fprintf(stderr, "opera [crash logging]: No Gpu info.\n");
}
char *exe_name = NULL;
vm_address_t vmaddr = 0;
vm_size_t vmsize;
uint32_t nesting_depth = 0;
struct vm_region_submap_info_64 region_info;
while (1)
{
mach_msg_type_number_t info_count = VM_REGION_SUBMAP_INFO_COUNT_64;
if (vm_region_recurse_64(task, &vmaddr, &vmsize, &nesting_depth,
(vm_region_recurse_info_t)®ion_info, &info_count) != KERN_SUCCESS)
{
break;
}
if (region_info.is_submap)
{
nesting_depth++;
continue;
}
/* char buffer[PATH_MAX];
int ret_val = proc_regionfilename(pid, vmaddr, buffer, PATH_MAX);
buffer[ret_val] = 0;*/
struct proc_regionwithpathinfo {
char dummy[0xF8]; // struct proc_regioninfo + struct vnode_info;
char vip_path[MAXPATHLEN];
} path_info;
char *obj_name = NULL;
path_info.vip_path[0] = 0;
#define PROC_PIDREGIONPATHINFO 8
syscall(SYS_proc_info, 2, pid, PROC_PIDREGIONPATHINFO, (uint64_t)vmaddr, &path_info, sizeof(path_info));
if (path_info.vip_path[0])
obj_name = path_info.vip_path;
/********************/
if (obj_name)
{
if (!exe_name)
exe_name = strdup(obj_name);
#if TARGET_CPU_X86
unsigned int line_len = strlen(obj_name)+12+2*8;
#else
unsigned int line_len = strlen(obj_name)+12+2*12;
#endif
char *line_text = new char[line_len];
if (line_text)
{
#if TARGET_CPU_X86
sprintf(line_text, "%08X-%08X %c%c%c %s\n", vmaddr, vmaddr+vmsize,
#else
sprintf(line_text, "%012lX-%012lX %c%c%c %s\n", vmaddr, vmaddr+vmsize,
#endif
(region_info.protection & VM_PROT_READ) ?'r':'-',
(region_info.protection & VM_PROT_WRITE)?'w':'-',
(region_info.protection & VM_PROT_EXECUTE)?'x':'-',
obj_name);
dll_line *new_dll = new dll_line;
if (new_dll)
{
new_dll->line = line_text;
if (!dlls.first)
dlls.first = new_dll;
else
dlls.last->next = new_dll;
dlls.last = new_dll;
}
}
}
if ((region_info.protection & VM_PROT_EXECUTE) && !(region_info.protection & VM_PROT_WRITE))
{
byte_range *range = new byte_range;
if (range)
{
range->range_start = vmaddr;
range->range_end = vmaddr+vmsize;
range->next = code_ranges.first;
code_ranges.first = range;
}
}
/********************/
vmaddr += vmsize;
}
thread_act_array_t threads;
mach_msg_type_number_t thread_count;
if (task_threads(task, &threads, &thread_count) != KERN_SUCCESS)
{
fprintf(stderr, "opera [crash logging]: Error getting thread list!\n");
fclose(log_file);
return;
}
thread_act_t crashed_thread = 0;
UINT crashed_thread_num = 0;
for (i = 0; i < thread_count; i++)
{
thread_act_t cur_thread = threads[i];
#if TARGET_CPU_X86
x86_exception_state32_t exc_state;
mach_msg_type_number_t state_count = x86_EXCEPTION_STATE32_COUNT;
if (!crashed_thread &&
thread_get_state(cur_thread, x86_EXCEPTION_STATE32, (thread_state_t)&exc_state, &state_count) == KERN_SUCCESS &&
#else
x86_exception_state64_t exc_state;
mach_msg_type_number_t state_count = x86_EXCEPTION_STATE64_COUNT;
if (!crashed_thread &&
thread_get_state(cur_thread, x86_EXCEPTION_STATE64, (thread_state_t)&exc_state, &state_count) == KERN_SUCCESS &&
#endif
exc_state.__trapno)
{
crashed_thread = cur_thread;
crashed_thread_num = i;
}
if (i)
mach_port_deallocate(task_self, cur_thread);
}
crashed_thread = threads[0];
vm_deallocate(task_self, (vm_address_t)threads, thread_count * sizeof(thread_act_t));
if (!crashed_thread)
{
fprintf(stderr, "opera [crash logging]: Error getting thread state!\n");
fclose(log_file);
return;
}
#ifndef _DEBUG
#if TARGET_CPU_X86
fprintf(log_file, "OPERA-CRASHLOG V1 desktop %s %d mac\n", VER_NUM_STR, crashed_thread_num ? 9999 : VER_BUILD_NUMBER);
#else
fprintf(log_file, "OPERA-CRASHLOG V1 desktop %s %d mac x64\n", VER_NUM_STR, crashed_thread_num ? 9999 : VER_BUILD_NUMBER);
#endif
#endif // !_DEBUG
#if TARGET_CPU_X86
struct CONTEXT
{
x86_thread_state32_t regs;
x86_float_state32_t fpregs;
} context;
mach_msg_type_number_t state_count = x86_THREAD_STATE32_COUNT;
mach_msg_type_number_t fl_state_count = x86_FLOAT_STATE32_COUNT;
kern_return_t ret1 = thread_get_state(crashed_thread, x86_THREAD_STATE32, (thread_state_t)&context.regs, &state_count);
kern_return_t ret2 = thread_get_state(crashed_thread, x86_FLOAT_STATE32, (thread_state_t)&context.fpregs, &fl_state_count);
#else
struct CONTEXT
{
x86_thread_state64_t regs;
x86_float_state64_t fpregs;
} context;
mach_msg_type_number_t state_count = x86_THREAD_STATE64_COUNT;
mach_msg_type_number_t fl_state_count = x86_FLOAT_STATE64_COUNT;
kern_return_t ret1 = thread_get_state(crashed_thread, x86_THREAD_STATE64, (thread_state_t)&context.regs, &state_count);
kern_return_t ret2 = thread_get_state(crashed_thread, x86_FLOAT_STATE64, (thread_state_t)&context.fpregs, &fl_state_count);
#endif
mach_port_deallocate(task_self, crashed_thread);
if (ret1 != KERN_SUCCESS || ret2 != KERN_SUCCESS)
{
fprintf(stderr, "opera [crash logging]: Error getting thread state!\n");
fclose(log_file);
return;
}
#define float_reg(x) offsetof(CONTEXT, fpregs.x)
#define cpu_reg(x) offsetof(CONTEXT, regs.x)
#if TARGET_CPU_X86
static unsigned char register_offsets[] =
{
cpu_reg(__eax), cpu_reg(__ebx), cpu_reg(__ecx), cpu_reg(__edx), cpu_reg(__esi),
cpu_reg(__edi), cpu_reg(__ebp), cpu_reg(__esp), cpu_reg(__eip), cpu_reg(__eflags),
cpu_reg(__cs), cpu_reg(__ds), cpu_reg(__ss), cpu_reg(__es), cpu_reg(__fs), cpu_reg(__gs),
(float_reg(__fpu_stmm7)+8) | 1, float_reg(__fpu_stmm7)+4, float_reg(__fpu_stmm7),
(float_reg(__fpu_stmm6)+8) | 1, float_reg(__fpu_stmm6)+4, float_reg(__fpu_stmm6),
(float_reg(__fpu_stmm5)+8) | 1, float_reg(__fpu_stmm5)+4, float_reg(__fpu_stmm5),
(float_reg(__fpu_stmm4)+8) | 1, float_reg(__fpu_stmm4)+4, float_reg(__fpu_stmm4),
(float_reg(__fpu_stmm3)+8) | 1, float_reg(__fpu_stmm3)+4, float_reg(__fpu_stmm3),
(float_reg(__fpu_stmm2)+8) | 1, float_reg(__fpu_stmm2)+4, float_reg(__fpu_stmm2),
(float_reg(__fpu_stmm1)+8) | 1, float_reg(__fpu_stmm1)+4, float_reg(__fpu_stmm1),
(float_reg(__fpu_stmm0)+8) | 1, float_reg(__fpu_stmm0)+4, float_reg(__fpu_stmm0),
float_reg(__fpu_fsw) | 1, float_reg(__fpu_fcw) | 1
};
int args[ARRAY_SIZE(register_offsets) + 3];
args[0] = exe_name ? (int)exe_name : (int)"<no name>";
args[1] = (int)signame;
args[2] = context.regs.__eip;
for (UINT i=0; i<ARRAY_SIZE(register_offsets); i++)
{
UINT offset = register_offsets[i];
BYTE *reg = (BYTE *)&context + (offset & ~1);
UINT reg_value = (offset & 1) ? *(unsigned short*)reg : *(unsigned int *)reg;
args[i+3] = reg_value;
if (i <= 8)
add_pointer(memdump_list, reg_value, context.regs.__esp, task, code_ranges);
}
static char header_txt[] =
"%s got signal %s at address %08X\n\n"
"Registers:\n"
"EAX=%08X EBX=%08X ECX=%08X EDX=%08X ESI=%08X\n"
"EDI=%08X EBP=%08X ESP=%08X EIP=%08X FLAGS=%08X\n"
"CS=%04X DS=%04X SS=%04X ES=%04X FS=%04X GS=%04X\n"
"FPU stack:\n"
"%04X%08X%08X %04X%08X%08X %04X%08X%08X\n"
"%04X%08X%08X %04X%08X%08X %04X%08X%08X\n"
"%04X%08X%08X %04X%08X%08X SW=%04X CW=%04X\n\n"
"Stack dump:\n";
// %s %08X
char *register_text = new char[op_strlen((char*)args[0]) + op_strlen(signame) + ARRAY_SIZE(header_txt)-4 + 27*4];
if (!register_text)
return;
vsprintf(register_text, header_txt, (va_list)args);
#else
static unsigned short register_offsets[] =
{
cpu_reg(__rax), cpu_reg(__rbx), cpu_reg(__rcx), cpu_reg(__rdx), cpu_reg(__rsi),
cpu_reg(__rdi), cpu_reg(__r8), cpu_reg(__r9), cpu_reg(__r10), cpu_reg(__r11),
cpu_reg(__r12), cpu_reg(__r13), cpu_reg(__r14), cpu_reg(__r15), cpu_reg(__rbp),
cpu_reg(__rsp), cpu_reg(__rip), cpu_reg(__rflags) | 2,
(float_reg(__fpu_stmm0)+ 8) | 1, float_reg(__fpu_stmm0),
(float_reg(__fpu_stmm1)+ 8) | 1, float_reg(__fpu_stmm1),
(float_reg(__fpu_stmm2)+ 8) | 1, float_reg(__fpu_stmm2),
(float_reg(__fpu_stmm3)+ 8) | 1, float_reg(__fpu_stmm3),
(float_reg(__fpu_stmm4)+ 8) | 1, float_reg(__fpu_stmm4),
(float_reg(__fpu_stmm5)+ 8) | 1, float_reg(__fpu_stmm5),
(float_reg(__fpu_stmm6)+ 8) | 1, float_reg(__fpu_stmm6),
(float_reg(__fpu_stmm7)+ 8) | 1, float_reg(__fpu_stmm7),
float_reg(__fpu_fsw) | 1, float_reg(__fpu_fcw) | 1,
float_reg(__fpu_xmm0)+ 8, float_reg(__fpu_xmm0),
float_reg(__fpu_xmm1)+ 8, float_reg(__fpu_xmm1),
float_reg(__fpu_xmm2)+ 8, float_reg(__fpu_xmm2),
float_reg(__fpu_xmm3)+ 8, float_reg(__fpu_xmm3),
float_reg(__fpu_xmm4)+ 8, float_reg(__fpu_xmm4),
float_reg(__fpu_xmm5)+ 8, float_reg(__fpu_xmm5),
float_reg(__fpu_xmm6)+ 8, float_reg(__fpu_xmm6),
float_reg(__fpu_xmm7)+ 8, float_reg(__fpu_xmm7),
float_reg(__fpu_xmm8)+ 8, float_reg(__fpu_xmm8),
float_reg(__fpu_xmm9)+ 8, float_reg(__fpu_xmm9),
float_reg(__fpu_xmm10)+ 8, float_reg(__fpu_xmm10),
float_reg(__fpu_xmm11)+ 8, float_reg(__fpu_xmm11),
float_reg(__fpu_xmm12)+ 8, float_reg(__fpu_xmm12),
float_reg(__fpu_xmm13)+ 8, float_reg(__fpu_xmm13),
float_reg(__fpu_xmm14)+ 8, float_reg(__fpu_xmm14),
float_reg(__fpu_xmm15)+ 8, float_reg(__fpu_xmm15),
};
long args[ARRAY_SIZE(register_offsets) + 3];
args[0] = exe_name ? (long)exe_name : (long)"<no name>";
args[1] = (long)signame;
args[2] = context.regs.__rip;
for (UINT i=0; i<ARRAY_SIZE(register_offsets); i++)
{
unsigned long offset = register_offsets[i];
BYTE *reg = (BYTE *)&context + (offset & ~3);
unsigned long reg_value = (offset & 1) ? *(unsigned short *)reg :
(offset & 2) ? *(unsigned int *)reg : *(unsigned long *)reg;
args[i+3] = reg_value;
if (i <= 16)
add_pointer(memdump_list, reg_value, context.regs.__rsp, task, code_ranges);
}
static char header_txt[] =
"%s got signal %s at address %012lX\n\n"
"Registers:\n"
"RAX=%016lX RBX=%016lX RCX=%016lX\n"
"RDX=%016lX RSI=%016lX RDI=%016lX\n"
" R8=%016lX R9=%016lX R10=%016lX\n"
"R11=%016lX R12=%016lX R13=%016lX\n"
"R14=%016lX R15=%016lX RBP=%016lX\n"
"RSP=%016lX RIP=%016lX FLAGS=%08X\n"
"FPU stack:\n"
"st(0)=%04X%016lX st(1)=%04X%016lX st(2)=%04X%016lX\n"
"st(3)=%04X%016lX st(4)=%04X%016lX st(5)=%04X%016lX\n"
"st(6)=%04X%016lX st(7)=%04X%016lX SW=%04X CW=%04X\n"
" XMM0=%016lX%016lX XMM1=%016lX%016lX\n"
" XMM2=%016lX%016lX XMM3=%016lX%016lX\n"
" XMM4=%016lX%016lX XMM5=%016lX%016lX\n"
" XMM6=%016lX%016lX XMM7=%016lX%016lX\n"
" XMM8=%016lX%016lX XMM9=%016lX%016lX\n"
"XMM10=%016lX%016lX XMM11=%016lX%016lX\n"
"XMM12=%016lX%016lX XMM13=%016lX%016lX\n"
"XMM14=%016lX%016lX XMM15=%016lX%016lX\n\n"
"Stack dump:\n";
// %s %08X %012lX %016lX
char *register_text = new char[op_strlen((char*)args[0]) + op_strlen(signame) + ARRAY_SIZE(header_txt)-4 + 4 + 6 + 57*10];
if (!register_text)
return;
vsprintf_var(register_text, header_txt, args);
#endif
free(exe_name);
if (fputs(register_text, log_file) == EOF)
{
fprintf(stderr, "opera [crash logging]: Crash log writing failed, error writing to file %s!\n", log_filename);
fclose(log_file);
return;
}
#if TARGET_CPU_X86
UINT stack_pos = context.regs.__esp & ~3;
UINT frame_pointer = context.regs.__ebp;
#else
unsigned long stack_pos = context.regs.__rsp & ~3;
unsigned long frame_pointer = context.regs.__rbp;
#endif
for (UINT stack_pages = 0; stack_pages < STACK_DUMP_SIZE / 0x1000; stack_pages++)
{
UINT read_size = 0x1000;
vm_offset_t dst_adr;
mach_msg_type_number_t dst_size;
if (vm_read(task, stack_pos, read_size, &dst_adr, &dst_size) != KERN_SUCCESS)
{
read_size -= (stack_pos & 0xFFF);
if (vm_read(task, stack_pos, read_size, &dst_adr, &dst_size) != KERN_SUCCESS)
break;
}
BYTE *stack_buf_pos = (BYTE *)dst_adr;
read_size = dst_size;
do
{
#if TARGET_CPU_X86
fprintf(log_file, "%08X ", stack_pos);
#else
fprintf(log_file, "%012lX ", stack_pos);
#endif
UINT dump_len = read_size;
BYTE *dump_stack_pos = stack_buf_pos;
#if TARGET_CPU_X86
for (UINT stack_words = 0; stack_words < 4; stack_words++)
{
if (dump_len < 4)
fputs(" ", log_file);
#else
for (UINT stack_words = 0; stack_words < 2; stack_words++)
{
if (dump_len < 8)
fputs(" ", log_file);
#endif
else
{
unsigned long stack_word = *(unsigned long *)dump_stack_pos;
#if TARGET_CPU_X86
add_pointer(memdump_list, stack_word, context.regs.__esp, task, code_ranges);
#else
add_pointer(memdump_list, stack_word, context.regs.__rsp, task, code_ranges);
#endif
if (stack_pos == frame_pointer)
{
frame_pointer = stack_word;
putc('>', log_file);
}
else
putc(' ', log_file);
#if TARGET_CPU_X86
fprintf(log_file, "%08lX ", stack_word);
dump_stack_pos += 4;
stack_pos += 4;
dump_len -= 4;
#else
fprintf(log_file, "%016lX ", stack_word);
dump_stack_pos += 8;
stack_pos += 8;
dump_len -= 8;
#endif
}
}
dump_chars(log_file, stack_buf_pos, read_size);
} while (read_size);
vm_deallocate(task_self, dst_adr, dst_size);
}
if (fputs("\nUsed Libraries:\n", log_file) == EOF)
{
fprintf(stderr, "opera [crash logging]: Crash log writing failed, error writing to file %s!\n", log_filename);
fclose(log_file);
return;
}
dll_line *current_dll = dlls.first;
while (current_dll)
{
fputs(current_dll->line, log_file);
current_dll = current_dll->next;
}
if (fputs("\nMemory dumps:", log_file) == EOF)
{
fprintf(stderr, "opera [crash logging]: Crash log writing failed, error writing to file %s!\n", log_filename);
fclose(log_file);
return;
}
byte_range *current_mem = memdump_list.first;
while (current_mem)
{
unsigned long dump_start = current_mem->range_start;
unsigned long dump_end = current_mem->range_end;
int disposition, ref_count;
if (vm_map_page_query(task, dump_start, &disposition, &ref_count) != KERN_SUCCESS ||
!(disposition & VM_PAGE_QUERY_PAGE_PRESENT))
dump_start = (dump_start | 0xFFF) + 1;
if (vm_map_page_query(task, dump_end, &disposition, &ref_count) != KERN_SUCCESS ||
!(disposition & VM_PAGE_QUERY_PAGE_PRESENT))
dump_end = (dump_end & ~0xFFF);
UINT read_size = dump_end - dump_start;
vm_offset_t dst_adr;
mach_msg_type_number_t dst_size = 0;
vm_read(task, dump_start, read_size, &dst_adr, &dst_size);
BYTE *mem_buf_pos = (BYTE *)dst_adr;
read_size = dst_size;
putc('\n', log_file);
while (read_size)
{
#if TARGET_CPU_X86
fprintf(log_file, "%08lX", dump_start);
#else
fprintf(log_file, "%012lX", dump_start);
#endif
UINT dump_len = read_size;
BYTE *dump_mem_pos = mem_buf_pos;
for (UINT mem_bytes = 0; mem_bytes < 16; mem_bytes++)
{
putc(' ', log_file);
if (!(mem_bytes & 3))
putc(' ', log_file);
if (!dump_len)
{
fputs(" ", log_file);
}
else
{
fprintf(log_file, "%02X", *dump_mem_pos);
dump_mem_pos++;
dump_start++;
dump_len--;
}
}
dump_chars(log_file, mem_buf_pos, read_size);
}
vm_deallocate(task_self, dst_adr, dst_size);
current_mem = current_mem->next;
}
fclose(log_file);
/*
char *first_line_end = register_text;
do { first_line_end++; } while (*first_line_end != '\n');
*first_line_end = 0;
fprintf(stderr, "opera [crash logging]: CRASH!!\n%s\n\nLog was created here:\r\n%s\n", register_text, log_filename);
delete[] register_text;
*/
#ifdef CRASHLOG_DEBUG
errno = 0;
#endif
ptrace(PT_KILL, pid, 0, 0);
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: killing crashed instance: %d\n", time(NULL), errno);
#endif
}
#endif // defined(_MACINTOSH_)
|
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <set>
#include <bitset>
#define BUG '#'
#define MTY '.'
using namespace std;
ifstream fin("input.txt");
typedef pair<int, int> coord;
const coord directions[] = {
{-1,0}, //0 up
{1, 0}, //1 down
{0, -1}, //2 left
{0, 1} //3 right
};
inline bool checkBounds(int x) {
return x < 5 && x >= 0;
}
bool checkBounds(coord x) {
return checkBounds(x.first) && checkBounds(x.second);
}
coord operator+(const coord& lhs, const coord& rhs) {
return { lhs.first + rhs.first,lhs.second + rhs.second };
}
//This code used to be broken but still worked for my input somehow, lol
struct level
{
bitset<24> cells;
level* above, * below;
const coord center = { 2,2 };
level() {
above = 0;
below = 0;
}
level(level* creator, bool aboveCreator) {
if (aboveCreator)
{
above = 0;
below = creator;
}
else
{
above = creator;
below = 0;
}
}
void createUp() {
above = new level(this, true);
}
void createDown() {
below = new level(this, false);
}
auto operator[](const coord& pos) {
if (pos == center) {
throw;
}
int i = pos.first * 5 + pos.second;
if (i > 12) i--;
return cells[i];
}
//get neighbors from the lower level given the direction of the cell that is checking from the upper level
size_t getDownNeighbors(size_t dir) {
if (!below) {
return 0;
}
//the microoptimisation is big with this one!
int i,
j = (dir % 2) ? 0 : 4, // true: dir is down/right so we must check up/left, false: vice-versa
* a, * b;
//I'm using pointers so I can easily flip diagonally
if (dir / 2) { //true:dir is on horizontal axis
a = &i;
b = &j;
}
else { //false: dir is on vertical axis
a = &j;
b = &i;
}
size_t neighbors = 0;
//now I can cover all cases with just one for! Nice!
for (i = 0; i < 5; i++)
{
neighbors += (*below)[{*a, * b}];
}
return neighbors;
}
void tick(bool up, bool down) {
if (!above) {
for (int i = 0; i < 5; i++)
{
if ((*this)[{ 0, i }] || (*this)[{ 4, i }]) {
createUp();
goto done;
}
}
for (int j = 1; j < 4; j++)
{
if ((*this)[{ j, 0 }] || (*this)[{ j, 4 }]) {
createUp();
break;
}
}
}
done:
level nextcells;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
coord pos = { i,j };
if (pos == center)
{
if (!below) {
for (auto& dir : directions)
{
if ((*this)[pos + dir]) {
createDown();
break;
}
}
}
continue;
}
size_t neighbors = 0;
for (size_t dir = 0; dir < 4; dir++)
{
auto checkpos = pos + directions[dir];
if (!checkBounds(checkpos)) {
neighbors += above ? (*above)[center + directions[dir]] : 0;
}
else if (checkpos == center) {
neighbors += getDownNeighbors(dir);
}
else
{
neighbors += (*this)[checkpos];
}
}
if (neighbors == 1 || (neighbors == 2 && !(*this)[pos]))
{
nextcells[pos] = true;
}
}
}
if (up && above)
above->tick(true, false);
if (down && below)
below->tick(false, true);
cells = nextcells.cells;
}
void tick() {
tick(true, true);
}
size_t count(bool up) {
auto nr = cells.count();
if (up) {
if (above) {
nr += above->count(true);
}
}
else
{
if (below) {
nr += below->count(false);
}
}
return nr;
}
auto count() {
return count(true) + (below ? below->count(false) : 0);
}
void print() {
/*for (size_t i = 0; i < 12; i++)
{
if (i % 5 == 0)
cout << endl;
cout << (cells[i] ? BUG : MTY);
}
cout << ' ';
for (size_t i = 12; i < 24; i++)
{
if (i % 5 == 4)
cout << endl;
cout << (cells[i] ? BUG : MTY);
}*/
for (size_t i = 0; i < 5; i++)
{
for (size_t j = 0; j < 5; j++)
{
coord pos = { i,j };
if (pos == center) {
cout << ' ';
}
else {
cout << (operator[](pos) ? BUG : MTY);
}
}
cout << endl;
}
}
void printall() {
int lvl = 0;
level* ptr = this;
while (ptr->below)
{
ptr = ptr->below;
lvl--;
}
for (; ptr ; ptr = ptr->above, lvl++ )
{
cout << "Depth " << lvl << ":\n";
ptr->print();
}
}
};
int main() {
char c;
level area;
for (size_t i = 0; i < 5; i++)
{
for (size_t j = 0; j < 5; j++)
{
fin >> c;
if (c == BUG) {
area[{ i, j }] = true;
}
}
}
//area.printall();
for (size_t i = 0; i < 200; i++)
{
area.tick();
/*cout << "\nMin " << i + 1 << ":\n";
area.printall();
cout << area.count();
cin.get();*/
}
cout << area.count();
}
|
#include <string>
#include <fstream>
#include <iostream>
#include <cstdlib> // for exit()
#include <array>
#include <map>
#include "weight.h"
using namespace std;
// this function scores a single word created on an existing board
//the word parameter must include all the letters of the word formed by the length of the placed letters
//the xaxis parameter provides the direction of that word: true if horizontal, false if vertical
int scoreword(bool sevenLettersUsed, char &board[][], string word, bool xaxis, int xstart, int, ystart){
//FIXME change parameters and the below to use Words struct
int length = word.length();
char tile; // the boardgame representation of that spot on the baord
int totalscore = 0; //ongoing return accumulator
bool triple = false;
bool doobel = false;
int letterVal; // to contain the letter weight
for (int i = 0; i < length; i++){
if (xaxis){ tile = board[ystart][xstart+i];} //FIXME check that this works right
else { tile = board[ystart+i][xstart]; } // and this
letterVal = weight(word[i]);
switch (tile){
case '9':
triple = true;
totalscore += letterVal;
break;
case '4':
doobel = true;
totalscore += letterVal;
break;
case '3':
totalscore += (3 * letterVal);
break;
case '2':
totalscore += (2 * letterVal);
break;
default:
totalscore += letterVal;
}
}
if (triple){totalscore *= 3;}
if (doobel){totalscore *= 2;}
if (sevenLettersUsed){totalscore += 50;}
return totalscore;
}
|
//
// channeltest.hpp
// AutoCaller
//
// Created by Micheal Chen on 2017/7/18.
//
//
#ifndef channeltest_hpp
#define channeltest_hpp
#include "cocos2d.h"
#include "testbase/BaseTest.h"
DEFINE_TEST_SUITE(ChannelTests);
class LoginTest : public TestCase
{
public:
LoginTest();
~LoginTest();
CREATE_FUNC(LoginTest);
virtual void onEnter() override;
virtual std::string subtitle() const override{
return "Login Test";
}
virtual std::string title() const override {
return "Channel Test";
}
};
class ChannelTest : public TestCase
{
public:
ChannelTest();
~ChannelTest();
CREATE_FUNC(ChannelTest);
virtual std::string title() const override {
return "Channel Test";
}
virtual std::string subtitle() const override {
return "Channel Enter Test";
}
void onEnter() override;
void onEnterRoom(cocos2d::Ref* psender);
void onLeaveRoom(cocos2d::Ref *pSender);
private:
cocos2d::Label * _label;
};
class ChannelLeaveTest : public TestCase
{
public:
ChannelLeaveTest();
~ChannelLeaveTest();
CREATE_FUNC(ChannelLeaveTest);
virtual std::string title() const override {
return "Channel Test";
}
virtual std::string subtitle() const override {
return "Channel Leave Test";
}
private:
};
#endif /* channeltest_hpp */
|
//---------------------------------------------------------
//
// Project: dada
// Module: geometry
// File: Vector3fUtils.h
// Author: Viacheslav Pryshchepa
//
// Description: Utilities for three-element vector of floats
//
//---------------------------------------------------------
#ifndef DADA_GEOMETRY_VECTOR3FUTILS_H
#define DADA_GEOMETRY_VECTOR3FUTILS_H
#include "dada/geometry/Vector3f.h"
namespace dada
{
float length(const Vector3f& v);
float lengthSq(const Vector3f& v);
void normalize(Vector3f& v);
void negate(Vector3f& v);
void operator += (Vector3f& a, const Vector3f& b);
void operator -= (Vector3f& a, const Vector3f& b);
void operator *= (Vector3f& a, float b);
void operator /= (Vector3f& a, float b);
float dot(const Vector3f& a, const Vector3f& b);
void cross(Vector3f& res, const Vector3f& a, const Vector3f& b);
inline float lengthSq(const Vector3f& v)
{
return v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
}
inline void normalize(Vector3f& v)
{
const float len = length(v);
if (len != 0.0f)
{
v /= len;
}
}
inline void negate(Vector3f& v)
{
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
}
inline void operator += (Vector3f& a, const Vector3f& b)
{
a[0] += b[0];
a[1] += b[1];
a[2] += b[2];
}
inline void operator -= (Vector3f& a, const Vector3f& b)
{
a[0] -= b[0];
a[1] -= b[1];
a[2] -= b[2];
}
inline void operator *= (Vector3f& a, float b)
{
a[0] *= b;
a[1] *= b;
a[2] *= b;
}
inline void operator /= (Vector3f& a, float b)
{
a[0] /= b;
a[1] /= b;
a[2] /= b;
}
inline float dot(const Vector3f& a, const Vector3f& b)
{
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
inline void cross(Vector3f& res, const Vector3f& a, const Vector3f& b)
{
res[0] = a[1] * b[2] - a[2] * b[1];
res[1] = a[2] * b[0] - a[0] * b[2];
res[2] = a[0] * b[1] - a[1] * b[0];
}
} // dada
#endif // DADA_GEOMETRY_VECTOR3FUTILS_H
|
#include "LobyState.h"
#include "PlayState.h"
#include "Play2State.h"
#include "Play3State.h"
#include "TitleState.h"
#include "OptionState.h"
using namespace Ogre;
LobyState LobyState::mLobyState;
void LobyState::enter(void)
{
iCount1 = 0;
iCount2 = 0;
iCount3 = 0;
mRoot = Root::getSingletonPtr();
mRoot->getAutoCreatedWindow()->resetStatistics();
mSceneMgr = mRoot->getSceneManager("main");
mCamera = mSceneMgr->getCamera("main");
mCamera->setPosition(Ogre::Vector3::ZERO);
_drawGridPlane();
_setLights();
_drawScene();
_drawGroundPlane();
mInformationOverlay = OverlayManager::getSingleton().getByName("Overlay/Information");
mInformationOverlay->show();
mCharacterRoot = mSceneMgr->getRootSceneNode()->createChildSceneNode("ProfessorRoot");
mCharacterYaw = mCharacterRoot->createChildSceneNode("ProfessorYaw");
mCameraYaw = mCharacterRoot->createChildSceneNode("CameraYaw", Vector3(0.0f, 120.0f, 0.0f));
mCameraPitch = mCameraYaw->createChildSceneNode("CameraPitch");
mCameraHolder = mCameraPitch->createChildSceneNode("CameraHolder", Vector3(0.0f, 80.0f, 500.0f));
mCameraYaw->yaw(Degree(180));
mCameraYaw->setInheritOrientation(false);
mCharacterEntity = mSceneMgr->createEntity("Professor", "DustinBody.mesh");
mCharacterYaw->attachObject(mCharacterEntity);
mCharacterEntity->setCastShadows(true);
mCameraHolder->attachObject(mCamera);
mCamera->lookAt(mCameraYaw->getPosition());
mCharacterDirection = Ogre::Vector3::ZERO;
mIdleState = mCharacterEntity->getAnimationState("Idle");
mRunState = mCharacterEntity->getAnimationState("Run");
mIdleState->setLoop(true);
mRunState->setLoop(true);
mIdleState->setEnabled(true);
mRunState->setEnabled(false);
// Sound
//soundInit();
//mAnimationState = mCharacterEntity->getAnimationState("Run");
//mAnimationState->setLoop(true);
//mAnimationState->setEnabled(true);
}
void LobyState::exit(void)
{
// Fill Here -----------------------------
mSceneMgr->clearScene();
mInformationOverlay->hide();
// ---------------------------------------
}
void LobyState::pause(void)
{
}
void LobyState::resume(void)
{
}
bool LobyState::frameStarted(GameManager* game, const FrameEvent& evt)
{
//mAnimationState->addTime(evt.timeSinceLastFrame);
if (mCharacterDirection != Vector3::ZERO)
{
mCharacterRoot->setOrientation(mCameraYaw->getOrientation());
Quaternion quat = Vector3(Vector3::UNIT_Z).getRotationTo(mCharacterDirection);
mCharacterYaw->setOrientation(quat);
mCharacterRoot->translate(mCharacterDirection.normalisedCopy() * 600 * evt.timeSinceLastFrame
, Node::TransformSpace::TS_LOCAL);
if (!mRunState->getEnabled())
{
mRunState->setEnabled(true);
mIdleState->setEnabled(false);
}
mRunState->addTime(evt.timeSinceLastFrame);
}
else
{
if (!mIdleState->getEnabled())
{
mIdleState->setEnabled(true);
mRunState->setEnabled(false);
}
mIdleState->addTime(evt.timeSinceLastFrame);
}
if (mCharacterRoot->getPosition().x >= 450.0f && mCharacterRoot->getPosition().x <= 750.0f
&& mCharacterRoot->getPosition().z >= 450.0f && mCharacterRoot->getPosition().z <= 750.0f)
{
if (iCount1 < 1)
iCount1 = 0;
iCount1 += 1;
if (iCount1 == 1)
{
soundInit();
FMOD_System_PlaySound(g_System, FMOD_CHANNEL_FREE, g_Sound[SD_1], 0, &g_Channel[SD_1]);
//FMOD_Sound_Release(g_Sound[SD_2]);
//FMOD_Sound_Release(g_Sound[SD_3]);
}
}
else
{
if (iCount1 > 1)
iCount1 = 1;
iCount1 -= 1;
if(iCount1 == 0)
Release();
/*FMOD_Sound_Release(g_Sound[SD_1]);
FMOD_Sound_Release(g_Sound[SD_2]);
FMOD_Sound_Release(g_Sound[SD_3]);*/
}
if (mCharacterRoot->getPosition().x >= -200.0f && mCharacterRoot->getPosition().x <= 200.0f
&& mCharacterRoot->getPosition().z >= 450.0f && mCharacterRoot->getPosition().z <= 750.0f)
{
if (iCount2 < 1)
iCount2 = 0;
iCount2 += 1;
if (iCount2 == 1)
{
soundInit();
FMOD_System_PlaySound(g_System, FMOD_CHANNEL_FREE, g_Sound[SD_2], 0, &g_Channel[SD_2]);
//FMOD_Sound_Release(g_Sound[SD_2]);
//FMOD_Sound_Release(g_Sound[SD_3]);
}
}
else
{
if (iCount2 > 1)
iCount2 = 1;
iCount2 -= 1;
if (iCount2 == 0)
Release();
/*FMOD_Sound_Release(g_Sound[SD_1]);
FMOD_Sound_Release(g_Sound[SD_2]);
FMOD_Sound_Release(g_Sound[SD_3]);*/
}
if (mCharacterRoot->getPosition().x >= -750.0f && mCharacterRoot->getPosition().x <= -450.0f
&& mCharacterRoot->getPosition().z >= 450.0f && mCharacterRoot->getPosition().z <= 750.0f)
{
if (iCount3 < 1)
iCount3 = 0;
iCount3 += 1;
if (iCount3 == 1)
{
soundInit();
FMOD_System_PlaySound(g_System, FMOD_CHANNEL_FREE, g_Sound[SD_3], 0, &g_Channel[SD_3]);
//FMOD_Sound_Release(g_Sound[SD_2]);
//FMOD_Sound_Release(g_Sound[SD_3]);
}
}
else
{
if (iCount3 > 1)
iCount3 = 1;
iCount3 -= 1;
if (iCount3 == 0)
Release();
/*FMOD_Sound_Release(g_Sound[SD_1]);
FMOD_Sound_Release(g_Sound[SD_2]);
FMOD_Sound_Release(g_Sound[SD_3]);*/
}
return true;
}
bool LobyState::frameEnded(GameManager* game, const FrameEvent& evt)
{
static Ogre::DisplayString currFps = L"현재 FPS: ";
static Ogre::DisplayString avgFps = L"평균 FPS: ";
static Ogre::DisplayString bestFps = L"최고 FPS: ";
static Ogre::DisplayString worstFps = L"최저 FPS: ";
OverlayElement* guiAvg = OverlayManager::getSingleton().getOverlayElement("AverageFps");
OverlayElement* guiCurr = OverlayManager::getSingleton().getOverlayElement("CurrFps");
OverlayElement* guiBest = OverlayManager::getSingleton().getOverlayElement("BestFps");
OverlayElement* guiWorst = OverlayManager::getSingleton().getOverlayElement("WorstFps");
const RenderTarget::FrameStats& stats = mRoot->getAutoCreatedWindow()->getStatistics();
guiAvg->setCaption(avgFps + StringConverter::toString(stats.avgFPS));
guiCurr->setCaption(currFps + StringConverter::toString(stats.lastFPS));
guiBest->setCaption(bestFps + StringConverter::toString(stats.bestFPS));
guiWorst->setCaption(worstFps + StringConverter::toString(stats.worstFPS));
return true;
}
bool LobyState::keyReleased(GameManager* game, const OIS::KeyEvent &e)
{
switch (e.key)
{
case OIS::KC_W: case OIS::KC_UP: mCharacterDirection.z -= -600.0f; break;
case OIS::KC_S: case OIS::KC_DOWN: mCharacterDirection.z -= 600.0f; break;
case OIS::KC_A: case OIS::KC_LEFT: mCharacterDirection.x -= -600.0f; break;
case OIS::KC_D: case OIS::KC_RIGHT: mCharacterDirection.x -= 600.0f; break;
}
return true;
}
bool LobyState::keyPressed(GameManager* game, const OIS::KeyEvent &e)
{
// Fill Here -------------------------------------------
switch (e.key)
{
case OIS::KC_SPACE:
Release();
if (mCharacterRoot->getPosition().x >= 450.0f && mCharacterRoot->getPosition().x <= 750.0f
&& mCharacterRoot->getPosition().z >= 450.0f && mCharacterRoot->getPosition().z <= 750.0f)
game->changeState(PlayState::getInstance());
if (mCharacterRoot->getPosition().x >= -200.0f && mCharacterRoot->getPosition().x <= 200.0f
&& mCharacterRoot->getPosition().z >= 450.0f && mCharacterRoot->getPosition().z <= 750.0f)
game->changeState(Play2State::getInstance());
if (mCharacterRoot->getPosition().x >= -750.0f && mCharacterRoot->getPosition().x <= -450.0f
&& mCharacterRoot->getPosition().z >= 450.0f && mCharacterRoot->getPosition().z <= 750.0f)
game->changeState(Play3State::getInstance());
break;
case OIS::KC_O:
game->pushState(OptionState::getInstance());
case OIS::KC_W: case OIS::KC_UP: mCharacterDirection.z += -600.0f; break;
case OIS::KC_S: case OIS::KC_DOWN: mCharacterDirection.z += 600.0f; break;
case OIS::KC_A: case OIS::KC_LEFT: mCharacterDirection.x += -600.0f; break;
case OIS::KC_D: case OIS::KC_RIGHT: mCharacterDirection.x += 600.0f; break;
break;
}
// -----------------------------------------------------
return true;
}
bool LobyState::mousePressed(GameManager* game, const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
return true;
}
bool LobyState::mouseReleased(GameManager* game, const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
return true;
}
bool LobyState::mouseMoved(GameManager* game, const OIS::MouseEvent &e)
{
return true;
}
void LobyState::_drawScene(void)
{
//mSceneMgr->setSkyBox(true, "3D-Diggers/SkyBox", 5000);
}
void LobyState::_setLights(void)
{
mSceneMgr->setAmbientLight(ColourValue(0.7f, 0.7f, 0.7f));
mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE);
mLightD = mSceneMgr->createLight("LightD");
mLightD->setType(Light::LT_DIRECTIONAL);
mLightD->setDirection(Vector3(1, -2.0f, -1));
mLightD->setVisible(true);
}
void LobyState::_drawGroundPlane(void)
{
mTitaniumNode = (SceneNode*)malloc(sizeof(SceneNode*));
Plane plane(Vector3::UNIT_Y, 0);
MeshManager::getSingleton().createPlane(
"LobyGround",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
plane,
1500, 1500,
1, 1,
true, 1, 5, 5,
Vector3::NEGATIVE_UNIT_Z
);
Entity* groundEntity = mSceneMgr->createEntity("LobyGroundPlane", "LobyGround");
mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity);
groundEntity->setMaterialName("KPU_LOGO");
groundEntity->setCastShadows(false);
Plane plane11(Vector3::UNIT_Y, -1000);
MeshManager::getSingleton().createPlane(
"ClubGround",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
plane11,
4000, 2000,
1, 1,
true, 1, 1, 1,
Vector3::NEGATIVE_UNIT_Z
);
Entity* groundEntity11 = mSceneMgr->createEntity("ClubGroundPlane", "ClubGround");
//mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity11);
mTitaniumNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("ClubGroundPlane");
mTitaniumNode->setPosition(0.0f, 0.0f, 300.0f);
mTitaniumNode->pitch(Degree(90), Ogre::Node::TS_WORLD);
mTitaniumNode->yaw(Degree(-180), Ogre::Node::TS_WORLD);
mTitaniumNode->attachObject(groundEntity11);
groundEntity11->setMaterialName("CLUB");
groundEntity11->setCastShadows(false);
Plane plane1(Vector3::UNIT_Y, -1000);
MeshManager::getSingleton().createPlane(
"TitanuimImage",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
plane1,
500, 500,
1, 1,
true, 1, 1, 1,
Vector3::NEGATIVE_UNIT_Z
);
Entity* groundEntity1 = mSceneMgr->createEntity("TitanuimPlane", "TitanuimImage");
//mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity);
mTitaniumNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("TitanuimPlane");
mTitaniumNode->setPosition(750.0f, 100.0f, 0.0f);
mTitaniumNode->pitch(Degree(-90), Ogre::Node::TS_WORLD);
mTitaniumNode->attachObject(groundEntity1);
groundEntity1->setMaterialName("KPU_TITANIUM");
groundEntity1->setCastShadows(false);
Plane plane2(Vector3::UNIT_Y, -1000);
MeshManager::getSingleton().createPlane(
"WaitImage",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
plane1,
500, 500,
1, 1,
true, 1, 1, 1,
Vector3::NEGATIVE_UNIT_Z
);
Entity* groundEntity2 = mSceneMgr->createEntity("WaitPlane", "WaitImage");
//mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity);
mTitaniumNode2 = mSceneMgr->getRootSceneNode()->createChildSceneNode("WaitPlane");
mTitaniumNode2->setPosition(-750.0f, 100.0f, 0.0f);
mTitaniumNode2->pitch(Degree(-90), Ogre::Node::TS_WORLD);
mTitaniumNode2->attachObject(groundEntity2);
groundEntity2->setMaterialName("KPU_WAIT");
groundEntity2->setCastShadows(false);
Plane plane3(Vector3::UNIT_Y, -1000);
MeshManager::getSingleton().createPlane(
"TiestoImage",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
plane1,
500, 500,
1, 1,
true, 1, 1, 1,
Vector3::NEGATIVE_UNIT_Z
);
Entity* groundEntity3 = mSceneMgr->createEntity("TiestoPlane", "TiestoImage");
//mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity);
mTitaniumNode3 = mSceneMgr->getRootSceneNode()->createChildSceneNode("TiestoPlane");
mTitaniumNode3->setPosition(0.0f, 100.0f, 0.0f);
mTitaniumNode3->pitch(Degree(-90), Ogre::Node::TS_WORLD);
mTitaniumNode3->attachObject(groundEntity3);
groundEntity3->setMaterialName("KPU_TIESTO");
groundEntity3->setCastShadows(false);
}
void LobyState::_drawGridPlane(void)
{
// 좌표축 표시
/*Ogre::Entity* mAxesEntity = mSceneMgr->createEntity("Axes", "axes.mesh");
mSceneMgr->getRootSceneNode()->createChildSceneNode("AxesNode", Ogre::Vector3(0, 0, 0))->attachObject(mAxesEntity);
mSceneMgr->getSceneNode("AxesNode")->setScale(5, 5, 5);*/
/*Ogre::ManualObject* gridPlane = mSceneMgr->createManualObject("GridPlane");
Ogre::SceneNode* gridPlaneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("GridPlaneNode");
Ogre::MaterialPtr gridPlaneMaterial = Ogre::MaterialManager::getSingleton().create("GridPlanMaterial", "General");
gridPlaneMaterial->setReceiveShadows(false);
gridPlaneMaterial->getTechnique(0)->setLightingEnabled(true);
gridPlaneMaterial->getTechnique(0)->getPass(0)->setDiffuse(1, 1, 1, 0);
gridPlaneMaterial->getTechnique(0)->getPass(0)->setAmbient(1, 1, 1);
gridPlaneMaterial->getTechnique(0)->getPass(0)->setSelfIllumination(1, 1, 1);
gridPlane->begin("GridPlaneMaterial", Ogre::RenderOperation::OT_LINE_LIST);
for (int i = 0; i<21; i++)
{
gridPlane->position(-500.0f, 0.0f, 500.0f - i * 50);
gridPlane->position(500.0f, 0.0f, 500.0f - i * 50);
gridPlane->position(-500.f + i * 50, 0.f, 500.0f);
gridPlane->position(-500.f + i * 50, 0.f, -500.f);
}
gridPlane->end();
gridPlaneNode->attachObject(gridPlane);*/
}
void LobyState::soundInit()/*
그냥 내가 만든 함수이니까 너네 마음대로 바꿔서 쓰면됨
배경음은 CreateStream 으로 하는게 메모리를 덜 잡아먹는데 참고하시길.
우리는 Sound파일을 다 SD_Opening.mp3 이런식으로 이름 다바꿔서 Sound폴더에서 관리해. 절대경로로. 그래서 저렇게 불러오면됨
*/
{
FMOD_System_Create(&g_System);
FMOD_System_Init(g_System, 10, FMOD_INIT_NORMAL, NULL);
//배경음
FMOD_System_CreateStream(g_System, "Sound/Sound1.mp3", FMOD_LOOP_NORMAL, 0, &g_Sound[SD_1]);
FMOD_System_CreateStream(g_System, "Sound/Sound2.mp3", FMOD_LOOP_NORMAL, 0, &g_Sound[SD_2]);
FMOD_System_CreateStream(g_System, "Sound/Sound3.mp3", FMOD_LOOP_NORMAL, 0, &g_Sound[SD_3]);
// 형식은 : g_system에, 경로, 재생 방식(계속 음악끝나면 반복), 사운드 설정 해주고
//효과음
//FMOD_System_CreateSound(g_System, "Sound/효과음.wav", FMOD_DEFAULT, 0, &g_Sound[SD_Effect]);
}
void LobyState::Release() //마지막으로 음악 다 재생 되면 이런식으로 릴리즈해줘야 해.
{
for (int i = 0; i < SD_3; ++i)
{
FMOD_Sound_Release(g_Sound[i]);
}
/*FMOD_Sound_Release(g_Sound[0]);
FMOD_Sound_Release(g_Sound[1]);*/
FMOD_System_Close(g_System);
FMOD_System_Release(g_System);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2011-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#include "modules/network/op_request.h"
#include "modules/network/src/op_request_impl.h"
OP_STATUS OpRequest::Make(OpRequest *&req, OpRequestListener *requestListener, OpURL url, URL_CONTEXT_ID context_id, OpURL referrer)
{
return OpRequestImpl::Make(req, requestListener, url, context_id, referrer);
}
|
#ifndef QUEUE_HPP
#define QUEUE_HPP
#include <iostream>
class Queue {
public:
Queue();
Queue(const int size);
void push(const int value);
void pop();
void print();
~Queue();
private:
int* arr;
int size;
int count;
};
#endif
|
#include "core.h"
template<typename Type>
Type EntElement(Type T) {
Type num;
while (true)
{
cin >> num;
if (cin.fail())
{
cin.clear();
cin.ignore(32767, '\n');
cout << "Entered value is not number. Please, repeat your last response: ";
}
else
return num;
}
}
|
#pragma once
#include <QWidget>
#include <QScopedPointer>
#include "Entities/Key/PartOfKey/PartOfKey.h"
class AddPartOfKeyForm : public QWidget {
Q_OBJECT
public:
explicit AddPartOfKeyForm(QWidget *parent = nullptr);
virtual ~AddPartOfKeyForm() noexcept = default;
virtual void setPartOfKey(const PartOfKey &partOfKey) = 0;
signals:
void editingFinished(const PartOfKey &partOfkey);
protected:
QScopedPointer<PartOfKey> m_partOfKey;
};
|
#include<iostream>
using namespace std;
int hammingDistance(string first_word, string second_word) {
int count = 0;
if (first_word.size() != second_word.size()) {
return -1;
}
for (int i = 0; i < first_word.size(); i++) {
if (first_word[i] != second_word[i]) {
count++;
}
}
return count;
}
int main() {
string first_word, second_word;
cout << "Enter the first word: ";
cin >> first_word;
cout << "Enter the second word: ";
cin >> second_word;
cout << "The hamming distance between " << first_word << " and " << second_word << " is: " << hammingDistance(first_word, second_word) << endl;
return 0;
}
|
#ifndef UAD_WIN32FRAMEWORK_H
#define UAD_WIN32FRAMEWORK_H
#include "Core.h"
#include "BaseDriver.h"
#include <memory>
#include "InputsInfo.h"
#ifdef USING_OGL
#include <SFML\Graphics.hpp>
#include <GL\glew.h>
#else
#include <SDL/SDL.h>
#endif
class Win32Framework : public RootFramework {
public:
Win32Framework( AppBase *pBaseApp ) :
RootFramework( pBaseApp ),
bMousePosFixed{ false }
{
pBaseApp->SetParentFramework(this);
}
void InitGlobalVars();
void OnCreateApplication();
void OnDestroyApplication();
void OnInterruptApplication();
void OnResumeApplication();
void UpdateApplication();
void ProcessInput();
void ResetApplication();
void SetMousePosFixed( bool bFixed );
void SetMouseCursorHidden( bool bHide );
virtual ~Win32Framework() { }
private:
#ifdef USING_OGL
void ProcessKeyDown( const sf::Keyboard::Key& key, sf::Uint32& inputs, bool bDown );
#else
void ProcessKeyDown( const SDL_keysym& key, sf::Uint32& inputs, bool bDown );
#endif
private:
sf::Uint32 inputs;
InputsInfo inputsInfo;
bool bMousePosFixed;
};
#endif
|
#include "OtherUnderscore.hpp"
#include "OtherUnderscoreExtra.hpp"
#include "OtherUnderscore_p.hpp"
class OtherUnderscoreLocal : public QObject
{
Q_OBJECT
public:
OtherUnderscoreLocal();
~OtherUnderscoreLocal();
};
OtherUnderscoreLocal::OtherUnderscoreLocal()
{
}
OtherUnderscoreLocal::~OtherUnderscoreLocal()
{
}
OtherUnderscorePrivate::OtherUnderscorePrivate()
{
OtherUnderscoreLocal localObj;
OtherUnderscoreExtra extraObj;
}
OtherUnderscorePrivate::~OtherUnderscorePrivate()
{
}
OtherUnderscore::OtherUnderscore()
: d(new OtherUnderscorePrivate)
{
}
OtherUnderscore::~OtherUnderscore()
{
delete d;
}
// For OtherUnderscoreLocal
#include "OtherUnderscore.moc"
// - Not the own header
#include "moc_OtherUnderscoreExtra.cpp"
|
#include "Q04.h"
void merge_sort(int *data, int start, int end, int *result)
{
if(0 == end - start) // 只有一个元素
return;
else if(1 == end - start) // 有两个元素
{
if(data[end] < data[start])
{
int temp = data[end];
data[end] = data[start];
data[start] = temp;
}
}
else
{
//继续划分子区间,分别对左右子区间进行排序
int left=(end-start+1)/2, right=(end-start+1)/2+1;
merge_sort(data, start, start+left, result);
merge_sort(data, start+right, end, result);
//开始归并已经排好序的start到end之间的数据
merge(data, start, end, result);
//把排序后的区间数据复制到原始数据中去 // end = length-1
for(int i=start; i<=end; i++)
data[i] = result[i];
}
}
void merge(int *data, int start, int end, int *result)
{
int left_length = (end - start + 1) / 2 + 1;
int left_index = start;
int right_index = start + left_length;
int result_index = start;
while(left_index < start + left_length && right_index < end+1)
{
if(data[left_index] < data[right_index])
result[result_index++] = data[left_index++];
else
result[result_index++] = data[right_index++];
}
while(left_index < start + left_length)
result[result_index++] = data[left_index++];
while(right_index < end)
result[result_index++] = data[right_index++];
}
|
#include "mumuserver.h"
#include <iostream>
#include <QDir>
#include <QTcpSocket>
MumuServer* MumuServer::instance = NULL;
MumuServer* MumuServer::getInstance(int port, QObject * parent)
{
if(instance == NULL){
instance = new MumuServer(port, parent);
}
return instance;
}
/** Constructor */
MumuServer::MumuServer(int port, QObject *parent) : QTcpServer(parent)
{
this->blackListFile;
this->blackListFile << "." << "..";
this->totalSplit = 3;
/* First - Look for a files in the homeapp/file and split it*/
this->openAndSplitFile();
this->databaseManager = DatabaseManager::getInstance();
if(this->listen(QHostAddress::Any, port)){
std::cout<<"The MumuServer is listening any ip address on port " << this->serverPort() << std::endl;
}
if(this->isListening()){
Util::logMessage("The server is listening");
}
connect(this, SIGNAL(newConnection()),this,SLOT(clientConnecting()));
Util::logMessage("Constructor done!.");
}
void MumuServer::clientConnecting()
{
Util::logMessage("Client wants connect!");
std::cout << "Total clients connected = " << connections.size() << std::endl;
}
void MumuServer::sendFile(QString path)
{
this->filePath = path;
}
void MumuServer::openAndSplitFile()
{
QString path = QDir::currentPath();
this->openFiles();
/* Split the file */
if(QDir::setCurrent(FileHandle::getUserHome())){
for(MumuFile * file : files){
QDir::current().mkdir(file->fileName());
QDir blockDir(QDir::currentPath() +"/" + file->fileName());
int countBlock = 1;
QList<MumuBlock> blocks = file->getBlocks();
for(QByteArray block : blocks){
Util::saveBlockLikeFile(blockDir, block, QString::number(countBlock));
countBlock++;
}
std::cout << file->fileName().toStdString() << ". Block ready! " << std::endl;
}
}
QDir::setCurrent(path);
}
void MumuServer::openFiles()
{
if(QDir::setCurrent(FileHandle::getPublicUserHome().path() + "/file")){ // there is files directory in the application home dir
QDir fileDir(QDir::currentPath());
QStringList filesList = fileDir.entryList();
for(int index = 0; index < filesList.size(); index++){
QString fileName = filesList.at(index);
if(this->blackListFile.contains(fileName)){
continue;
}
std::cout << fileName.toStdString() << std::endl;
MumuFile * file = new MumuFile(fileName);
if(file->exists()){
files.append(file);
}
file->getFile()->close();
fileDir.remove(fileName);
}
std::cout << this->files.size() << " files found" << std::endl;
QDir::setCurrent(FileHandle::getDirUserHome().path());
}
}
void MumuServer::incomingConnection(int socketDescription)
{
Util::logMessage("Incoming connection...");
MumuConnection * connection = new MumuConnection(socketDescription,&(this->files),this);
Util::logMessage("connection created");
connection->setId("TESTE");
connections.append(connection);
Util::logMessage("Leaving incoming connection...");
}
void MumuServer::showErrorMessage(QAbstractSocket::SocketError socketError)
{
std::cout<<"ERROR: "<<socketError<<std::endl;
}
void MumuServer::socketStateChanged(QAbstractSocket::SocketState state)
{
std::cout<<"Socket state = "<<state<<std::endl;
}
int MumuServer::getNumberOfParts()
{
int parts = 0;
for (MumuFile *file : files)
parts += file->getSize();
return parts;
}
bool MumuServer::insertNewProcess(QString ip, QString file)
{
this->openAndSplitFile();
for(MumuFile * mumuFile : this->files){
if(mumuFile->fileName() == file){
return this->databaseManager->insertNewProcess(ip, file, "S", mumuFile->getTotalBlocksCount());
}
}
qDebug() << "Nenhum arquivo com esse nome encontrado";
return false;
}
|
#pragma once
#include "libOTe/config.h"
#if defined(ENABLE_MRR) || defined(ENABLE_MRR_TWIST)
#include <cryptoTools/Common/Defines.h>
#include <cryptoTools/Crypto/PRNG.h>
#include <cryptoTools/Crypto/RandomOracle.h>
namespace osuCrypto
{
class FeistelMulPopf
{
public:
struct PopfFunc
{
Block256 t;
Block256 s;
};
typedef bool PopfIn;
typedef Block256 PopfOut;
FeistelMulPopf(const RandomOracle& ro_) : ro(ro_) {}
FeistelMulPopf(RandomOracle&& ro_) : ro(ro_) {}
PopfOut eval(PopfFunc f, PopfIn x) const
{
mulXor(f, x);
xorH(f, x);
return f.t;
}
PopfFunc program(PopfIn x, PopfOut y, PRNG& prng) const
{
PopfFunc f;
f.t = y;
prng.get(&f.s, 1);
xorH(f, x);
mulXor(f, x);
return f;
}
private:
void xorH(PopfFunc &f, PopfIn x) const
{
RandomOracle h = ro;
h.Update(x);
Block256 hOut;
h.Update(f.s);
h.Final(hOut);
for (int i = 0; i < 2; i++)
f.t[i] = f.t[i] ^ hOut[i];
}
void mulXor(PopfFunc &f, PopfIn x) const
{
uint64_t mask64 = -(uint64_t) x;
block mask(mask64, mask64);
for (int i = 0; i < 2; i++)
f.s[i] = f.s[i] ^ (mask & f.t[i]);
}
RandomOracle ro;
};
class DomainSepFeistelMulPopf: public RandomOracle
{
using RandomOracle::Final;
using RandomOracle::outputLength;
public:
typedef FeistelMulPopf ConstructedPopf;
const static size_t hashLength = sizeof(Block256);
DomainSepFeistelMulPopf() : RandomOracle(hashLength) {}
ConstructedPopf construct()
{
return FeistelMulPopf(*this);
}
};
}
#else
// Allow unit tests to use DomainSepFeistelMulPopf as a template argument.
namespace osuCrypto
{
class DomainSepFeistelMulPopf;
}
#endif
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#include "gtdocrange.h"
#include "gtdocmessage.pb.h"
#include "gtdocpage.h"
#include "gtserialize.h"
#include <QtCore/QDebug>
GT_BEGIN_NAMESPACE
QPoint GtDocRange::intersectedText(GtDocPage *page) const
{
GtDocument *document = page->document();
int beginText = m_begin.text(document, false);
int endText = m_end.text(document, false);
if (-1 == beginText || -1 == endText)
return QPoint();
int beginIndex = m_begin.page();
int endIndex = m_end.page();
int index = page->index();
if (index < beginIndex || index > endIndex)
return QPoint();
if (index == beginIndex) {
if (index == endIndex) {
if (endText > beginText)
return QPoint(beginText, endText);
return QPoint(endText, beginText);
}
return QPoint(beginText, page->length());
}
if (index == endIndex)
return QPoint(0, endText);
return QPoint(0, page->length());
}
void GtDocRange::serialize(GtDocRangeMsg &msg) const
{
msg.set_type(m_type);
msg.set_begin_page(m_begin.page());
msg.set_begin_x(m_begin.x());
msg.set_begin_y(m_begin.y());
msg.set_end_page(m_end.page());
msg.set_end_x(m_end.x());
msg.set_end_y(m_end.y());
}
bool GtDocRange::deserialize(const GtDocRangeMsg &msg)
{
GtDocPoint begin(msg.begin_page(), msg.begin_x(), msg.begin_y());
GtDocPoint end(msg.end_page(), msg.end_x(), msg.end_y());
switch (msg.type()) {
case GtDocRange::TextRange:
case GtDocRange::GeomRange:
setType((GtDocRange::RangeType)msg.type());
setRange(begin, end);
return true;
default:
break;
}
return false;
}
#ifndef QT_NO_DATASTREAM
QDataStream &operator<<(QDataStream &s, const GtDocRange &r)
{
return GtSerialize::serialize<GtDocRange, GtDocRangeMsg>(s, r);
}
QDataStream &operator>>(QDataStream &s, GtDocRange &r)
{
return GtSerialize::deserialize<GtDocRange, GtDocRangeMsg>(s, r);
}
#endif // QT_NO_DATASTREAM
GT_END_NAMESPACE
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <quic/client/handshake/ClientHandshake.h>
#include <quic/client/handshake/ClientTransportParametersExtension.h>
#include <quic/client/state/ClientStateMachine.h>
#include <quic/fizz/client/handshake/QuicPskCache.h>
#include <quic/state/QuicStreamFunctions.h>
namespace quic {
ClientHandshake::ClientHandshake(QuicClientConnectionState* conn)
: conn_(conn) {}
void ClientHandshake::connect(
folly::Optional<std::string> hostname,
std::shared_ptr<ClientTransportParametersExtension> transportParams) {
transportParams_ = std::move(transportParams);
folly::Optional<CachedServerTransportParameters> cachedServerTransportParams =
connectImpl(std::move(hostname));
throwOnError();
if (conn_->zeroRttWriteCipher) {
if (conn_->qLogger) {
conn_->qLogger->addTransportStateUpdate(kZeroRttAttempted);
}
// If zero rtt write cipher is derived, it means the cached psk was valid
DCHECK(cachedServerTransportParams);
cacheServerInitialParams(
*conn_,
cachedServerTransportParams->initialMaxData,
cachedServerTransportParams->initialMaxStreamDataBidiLocal,
cachedServerTransportParams->initialMaxStreamDataBidiRemote,
cachedServerTransportParams->initialMaxStreamDataUni,
cachedServerTransportParams->initialMaxStreamsBidi,
cachedServerTransportParams->initialMaxStreamsUni,
cachedServerTransportParams->knobFrameSupport);
updateTransportParamsFromCachedEarlyParams(
*conn_, *cachedServerTransportParams);
}
}
void ClientHandshake::doHandshake(
std::unique_ptr<folly::IOBuf> data,
EncryptionLevel encryptionLevel) {
if (!data) {
return;
}
// TODO: deal with clear text alert messages. It's possible that a MITM who
// mucks with the finished messages could cause the decryption to be invalid
// on the server, which would result in a cleartext close or a cleartext
// alert. We currently switch to 1-rtt ciphers immediately for reads and
// throw away the cleartext cipher for reads, this would result in us
// dropping the alert and timing out instead.
if (phase_ == Phase::Initial) {
// This could be an HRR or a cleartext alert.
handshakeInitiated();
}
// First add it to the right read buffer.
switch (encryptionLevel) {
case EncryptionLevel::Initial:
initialReadBuf_.append(std::move(data));
break;
case EncryptionLevel::Handshake:
handshakeReadBuf_.append(std::move(data));
break;
case EncryptionLevel::EarlyData:
case EncryptionLevel::AppData:
appDataReadBuf_.append(std::move(data));
break;
default:
LOG(FATAL) << "Unhandled EncryptionLevel";
}
// Get the current buffer type the transport is accepting.
waitForData_ = false;
while (!waitForData_) {
switch (getReadRecordLayerEncryptionLevel()) {
case EncryptionLevel::Initial:
processSocketData(initialReadBuf_);
break;
case EncryptionLevel::Handshake:
processSocketData(handshakeReadBuf_);
break;
case EncryptionLevel::EarlyData:
case EncryptionLevel::AppData:
processSocketData(appDataReadBuf_);
break;
default:
LOG(FATAL) << "Unhandled EncryptionLevel";
}
throwOnError();
}
}
void ClientHandshake::handshakeConfirmed() {
phase_ = Phase::Established;
}
ClientHandshake::Phase ClientHandshake::getPhase() const {
return phase_;
}
const folly::Optional<ServerTransportParameters>&
ClientHandshake::getServerTransportParams() {
return transportParams_->getServerTransportParams();
}
folly::Optional<bool> ClientHandshake::getZeroRttRejected() {
return zeroRttRejected_;
}
void ClientHandshake::computeCiphers(CipherKind kind, folly::ByteRange secret) {
std::unique_ptr<Aead> aead;
std::unique_ptr<PacketNumberCipher> packetNumberCipher;
std::tie(aead, packetNumberCipher) = buildCiphers(kind, secret);
switch (kind) {
case CipherKind::HandshakeWrite:
conn_->handshakeWriteCipher = std::move(aead);
conn_->handshakeWriteHeaderCipher = std::move(packetNumberCipher);
break;
case CipherKind::HandshakeRead:
conn_->readCodec->setHandshakeReadCipher(std::move(aead));
conn_->readCodec->setHandshakeHeaderCipher(std::move(packetNumberCipher));
break;
case CipherKind::OneRttWrite:
conn_->oneRttWriteCipher = std::move(aead);
conn_->oneRttWriteHeaderCipher = std::move(packetNumberCipher);
break;
case CipherKind::OneRttRead:
conn_->readCodec->setOneRttReadCipher(std::move(aead));
conn_->readCodec->setOneRttHeaderCipher(std::move(packetNumberCipher));
break;
case CipherKind::ZeroRttWrite:
getClientConn()->zeroRttWriteCipher = std::move(aead);
getClientConn()->zeroRttWriteHeaderCipher = std::move(packetNumberCipher);
break;
default:
// Report error?
break;
}
}
void ClientHandshake::raiseError(folly::exception_wrapper error) {
error_ = std::move(error);
}
void ClientHandshake::throwOnError() {
if (error_) {
error_.throw_exception();
}
}
void ClientHandshake::waitForData() {
waitForData_ = true;
}
void ClientHandshake::writeDataToStream(
EncryptionLevel encryptionLevel,
Buf data) {
if (encryptionLevel == EncryptionLevel::AppData) {
// Don't write 1-rtt handshake data on the client.
return;
}
auto cryptoStream = getCryptoStream(*conn_->cryptoState, encryptionLevel);
writeDataToQuicStream(*cryptoStream, std::move(data));
}
void ClientHandshake::handshakeInitiated() {
CHECK(phase_ == Phase::Initial);
phase_ = Phase::Handshake;
}
void ClientHandshake::computeZeroRttCipher() {
VLOG(10) << "Computing Client zero rtt keys";
earlyDataAttempted_ = true;
}
void ClientHandshake::computeOneRttCipher(bool earlyDataAccepted) {
// The 1-rtt handshake should have succeeded if we know that the early
// write failed. We currently treat the data as lost.
// TODO: we need to deal with HRR based rejection as well, however we don't
// have an API right now.
if (earlyDataAttempted_ && !earlyDataAccepted) {
if (matchEarlyParameters()) {
zeroRttRejected_ = true;
} else {
// TODO: support app retry of zero rtt data.
error_ = folly::make_exception_wrapper<QuicInternalException>(
"Changing parameters when early data attempted not supported",
LocalErrorCode::EARLY_DATA_REJECTED);
return;
}
} else if (earlyDataAttempted_ && earlyDataAccepted) {
zeroRttRejected_ = false;
}
// After a successful handshake we should send packets with the type of
// ClientCleartext. We assume that by the time we get the data for the QUIC
// stream, the server would have also acked all the client initial packets.
CHECK(phase_ == Phase::Handshake);
phase_ = Phase::OneRttKeysDerived;
}
QuicClientConnectionState* ClientHandshake::getClientConn() {
return conn_;
}
const QuicClientConnectionState* ClientHandshake::getClientConn() const {
return conn_;
}
const std::shared_ptr<ClientTransportParametersExtension>&
ClientHandshake::getClientTransportParameters() const {
return transportParams_;
}
void ClientHandshake::setZeroRttRejectedForTest(bool rejected) {
zeroRttRejected_ = rejected;
}
} // namespace quic
|
#include "test_precomp.hpp"
CV_TEST_MAIN("cv")
|
#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > adys(100007);
stack<int> pila;
vector<bool> inStack(100007);
vector<bool> visit(100007);
long long int costos[100007];
unsigned long long int total,posis=1;
int discTempo[100007];
int minTempo[100007];
int minimos;
int cuantos;
int N,M,u,v,T=1,C=1;
void saca(int nodo){
int tope;
minimos = INT_MAX;
cuantos = 1;
do{
tope = pila.top();
pila.pop();
inStack[tope] = false;
if(costos[tope] < minimos){
minimos = costos[tope];
cuantos = 1;
}else if(costos[tope] == minimos){
cuantos++;
}
}while(tope != nodo);
posis*= cuantos;
posis%= 1000000007;
total+= minimos;
C++;
}
void Tarjan(int nodo){
if(visit[nodo]) return;
visit[nodo] = true;
minTempo[nodo] = discTempo[nodo] = T++;
pila.push(nodo);
inStack[nodo] = true;
for(int next : adys[nodo]){
Tarjan(next);
if(inStack[next]){
minTempo[nodo] = min(minTempo[next],minTempo[nodo]);
}
}
if(inStack[nodo]){
if(minTempo[nodo] == discTempo[nodo]){
saca(nodo);
}
}
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> N;
for(int i=1; i<=N;i++){
cin >> costos[i];
}
cin >> M;
for(int i=1;i<=M;i++){
cin >> u >> v;
adys[u].push_back(v);
}
for(int i=1;i<=N;i++){
Tarjan(i);
}
cout << total << " " << posis << '\n';
return 0;
}
|
/* XMRig
* Copyright 2010 Jeff Garzik <jgarzik@pobox.com>
* Copyright 2012-2014 pooler <pooler@litecoinpool.org>
* Copyright 2014 Lucas Jones <https://github.com/lucasjones>
* Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet>
* Copyright 2016 Jay D Dee <jayddee246@gmail.com>
* Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt>
* Copyright 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XMRIG_BASECLIENT_H
#define XMRIG_BASECLIENT_H
#include <map>
#include "base/kernel/interfaces/IClient.h"
#include "base/net/stratum/Job.h"
#include "base/net/stratum/Pool.h"
#include "base/tools/Chrono.h"
namespace xmrig {
class IClientListener;
class SubmitResult;
class BaseClient : public IClient
{
public:
BaseClient(int id, IClientListener *listener);
protected:
inline bool isEnabled() const override { return m_enabled; }
inline const char *tag() const override { return m_tag.c_str(); }
inline const Job &job() const override { return m_job; }
inline const Pool &pool() const override { return m_pool; }
inline const String &ip() const override { return m_ip; }
inline int id() const override { return m_id; }
inline int64_t sequence() const override { return m_sequence; }
inline void setAlgo(const Algorithm &algo) override { m_pool.setAlgo(algo); }
inline void setEnabled(bool enabled) override { m_enabled = enabled; }
inline void setProxy(const ProxyUrl &proxy) override { m_pool.setProxy(proxy); }
inline void setQuiet(bool quiet) override { m_quiet = quiet; }
inline void setRetries(int retries) override { m_retries = retries; }
inline void setRetryPause(uint64_t ms) override { m_retryPause = ms; }
void setPool(const Pool &pool) override;
protected:
enum SocketState {
UnconnectedState,
HostLookupState,
ConnectingState,
ConnectedState,
ClosingState,
ReconnectingState
};
struct SendResult
{
inline SendResult(Callback &&callback) : callback(callback), ts(Chrono::steadyMSecs()) {}
Callback callback;
const uint64_t ts;
};
inline bool isQuiet() const { return m_quiet || m_failures >= m_retries; }
virtual bool handleResponse(int64_t id, const rapidjson::Value &result, const rapidjson::Value &error);
bool handleSubmitResponse(int64_t id, const char *error = nullptr);
bool m_quiet = false;
IClientListener *m_listener;
int m_id;
int m_retries = 5;
int64_t m_failures = 0;
Job m_job;
Pool m_pool;
SocketState m_state = UnconnectedState;
std::map<int64_t, SendResult> m_callbacks;
std::map<int64_t, SubmitResult> m_results;
std::string m_tag;
String m_ip;
String m_password;
String m_rigId;
String m_user;
uint64_t m_retryPause = 5000;
static int64_t m_sequence;
private:
bool m_enabled = true;
};
} /* namespace xmrig */
#endif /* XMRIG_BASECLIENT_H */
|
/*
* File: PoseOperationTest.cpp
* Author: azamat
*
* Created on Jan 24, 2013, 2:05:58 PM
*/
#include "poseOperationTest.hpp"
CPPUNIT_TEST_SUITE_REGISTRATION(PoseOperationTest);
PoseOperationTest::PoseOperationTest()
{
}
PoseOperationTest::~PoseOperationTest()
{
}
void PoseOperationTest::setUp()
{
KDL::Joint testJoint = KDL::Joint("TestJoint", KDL::Joint::RotZ, 1, 0, 0.01);
KDL::Frame testFrame(KDL::Rotation::RPY(0.0, 0.0, 0.0), KDL::Vector(0.0, -0.4, 0.0));
KDL::Segment testSegment = KDL::Segment("TestSegment", testJoint, testFrame);
KDL::RotationalInertia testRotInerSeg(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); //around symmetry axis of rotation
double pointMass = 0.25; //in kg
KDL::RigidBodyInertia testInerSegment(pointMass, KDL::Vector(0.0, -0.4, 0.0), testRotInerSeg);
testSegment.setInertia(testInerSegment);
testTree.addSegment(testSegment,"root");
a_segmentState = kdle::SegmentState();
a_jointState = kdle::JointState();
}
void PoseOperationTest::tearDown()
{
}
void PoseOperationTest::testTransformPose()
{
kdle::SegmentState a_segmentState1;
KDL::SegmentMap::const_iterator segmentId = testTree.getSegment("TestSegment");
kdle::transform<kdle::kdl_tree_iterator, kdle::pose> a_operation;
std::cout << std::endl;
printf("initial pose x %f\n",a_segmentState.X.p[0]);
printf("initial pose y %f\n",a_segmentState.X.p[1]);
printf("initial pose z %f\n",a_segmentState.X.p[2]);
a_segmentState1 = a_operation(segmentId, a_jointState, a_segmentState);
printf("updated pose x %f\n",a_segmentState1.X.p[0]);
printf("updated pose y %f\n",a_segmentState1.X.p[1]);
printf("updated pose z %f\n",a_segmentState1.X.p[2]);
CPPUNIT_ASSERT(a_segmentState != a_segmentState1);
}
void PoseOperationTest::testFailedTransformPose()
{
kdle::SegmentState a_segmentState1;
KDL::SegmentMap::const_iterator segmentId = testTree.getSegment("TestSegment");
kdle::transform<kdle::kdl_tree_iterator, kdle::pose> a_operation;
a_jointState.q = KDL::PI/3.0;
std::cout << std::endl;
printf("initial pose x %f\n",a_segmentState.X.p[0]);
printf("initial pose y %f\n",a_segmentState.X.p[1]);
printf("initial pose z %f\n",a_segmentState.X.p[2]);
a_segmentState1 = a_operation(segmentId, a_jointState, a_segmentState);
printf("updated pose x %f\n",a_segmentState1.X.p[0]);
printf("updated pose y %f\n",a_segmentState1.X.p[1]);
printf("updated pose z %f\n",a_segmentState1.X.p[2]);
CPPUNIT_ASSERT(a_segmentState == a_segmentState1);
}
|
#include "floorgrass.h"
FloorGrass::FloorGrass(QObject *parent) : Ground(parent)
{}
FloorGrass::FloorGrass(int x, int y, int width, int height, QObject *parent)
: Ground(x,
y,
width,
height,
":/images/terrain/ground/images/terrain/ground/floorGrass.png",
parent)
{}
|
//
// Tenta.hpp
// final_sketch2
//
// Created by Kris Li on 12/1/16.
//
//
#pragma once
#include "ofMain.h"
class Tenta {
public:
Tenta();
void init(ofPoint pos);
void update();
void draw();
ofPolyline hand;
ofPolyline handS;
ofPoint pos;
private:
int size;
float angle;
float angleCons;
int res;
float length;
float width;
int smooth;
float step;
float stepAdd;
};
|
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
char infix[55], pseudoinfix[55], postfix[55];
double integers[26];
double result = 0;
struct Result // To calculate result
{
double x;
Result *next;
} *Topr = NULL;
struct Stack // to convert infix to pseudoinfix
{
char Operator;
Stack *next;
} *Top = NULL;
void pushr(double ch)// to push in result
{
Result *newresult = new Result;
if (Topr == NULL)
{
newresult->next = NULL;
Topr = newresult;
newresult->x = ch;
}
else
{
newresult->next = Topr;
Topr = newresult;
newresult->x = ch;
}
}
double popr()// to pop from result
{
double ret;
Result *temp = new Result;
if (Topr != NULL)
{
temp = Topr;
ret = temp->x;
Topr = temp->next;
}
delete temp;
return ret;
}
void push(char ch)// to push in stack
{
Stack *newStack = new Stack;
if (Top == NULL)
{
newStack->next = NULL;
Top = newStack;
newStack->Operator = ch;
}
else
{
newStack->next = Top;
Top = newStack;
newStack->Operator = ch;
}
}
char pop()// to pop from stack
{
char ret;
Stack *temp = new Stack;
if (Top != NULL)
{
temp = Top;
ret = temp->Operator;
Top = temp->next;
return ret;
}
else
{
return '#';
}
delete temp;
}
char Topelement()// top element of stack
{
char ch;
if (Top != NULL)
ch = Top->Operator;
else
ch = '#';
return ch;
}
int braces(char *pseudoinfix)// to count no of braces
{
int leftbr, rightbr;
leftbr = rightbr = 0;
for (int i = 0; pseudoinfix[i] != '\0'; i++)
{
if (pseudoinfix[i] == '(')
leftbr++;
else if (pseudoinfix[i] == ')')
rightbr++;
}
if (leftbr == rightbr)
return 0;
else if (leftbr < rightbr)
return 1;
else
return -1;
}
int precendence(char ch)// returns precendence of operator to apply bodmas
{
switch (ch)
{
case '^':
return 5;
case '/':
return 4;
case '*':
return 4;
case '+':
return 3;
case '-':
return 3;
default:
return 0;
}
}
void To_postfix() // to convert pseudoinfix to postfix
{
char topelement, infixelement, poped_element;
int precendence_of_infix, precendence_of_topelement, j = 0;
strcpy(postfix, " ");
for (int i = 0; pseudoinfix[i] != '\0'; i++)
{
if (pseudoinfix[i] != '(' && pseudoinfix[i] != ')' && pseudoinfix[i] != '*' && pseudoinfix[i] != '/' && pseudoinfix[i] != '+' && pseudoinfix[i] != '-' && pseudoinfix[i] != '^')
postfix[j++] = pseudoinfix[i];
else if (pseudoinfix[i] == '(')
{
infixelement = pseudoinfix[i];
push(infixelement);
}
else if (pseudoinfix[i] == ')')
{
while ((poped_element = pop()) != '(')
{
postfix[j++] = poped_element;
}
}
else
{
infixelement = pseudoinfix[i];
precendence_of_infix = precendence(infixelement);
topelement = Topelement();
precendence_of_topelement = precendence(topelement);
if (precendence_of_infix > precendence_of_topelement)
{
push(infixelement);
}
else
{
while (precendence_of_topelement >= precendence_of_infix)
{
if (topelement == '#')
break;
poped_element = pop();
topelement = Topelement();
postfix[j++] = poped_element;
precendence_of_topelement = precendence(topelement);
}
push(infixelement);
}
}
}
while ((poped_element = pop()) != '#')
postfix[j++] = poped_element;
postfix[j] = '\0';
}
double numeric_value(char ch)// to get numerical value
{
switch (ch)
{
case '0':
return 0.0;
case '1':
return 1.0;
case '2':
return 2.0;
case '3':
return 3.0;
case '4':
return 4.0;
case '5':
return 5.0;
case '6':
return 6.0;
case '7':
return 7.0;
case '8':
return 8.0;
case '9':
return 9.0;
}
return -1;
}
int check_operator(char a)
{
if (a == '+' || a == '-' || a == '*' || a == '/' || a == '(' || a == ')' || a == '^')
{
if (a == '(')
{
return 1;
}
else
{
return 2;
}
}
return 0;
}
void Topseudoinfix()// to convert a expression in pseudoinfix eg: (23+ 4) as (a+b)
{
bool decimal_encountered = false;
double temp = 0;
int j = 0, k = 0, decimal_count = 0;
char ch = 'a';
for (int i = 0; infix[i] != '\0'; i++)
{
if (check_operator(infix[i]) == 0)
{
if (infix[i] == '.')
{
decimal_encountered = true;
}
else
{
temp = (temp * 10) + numeric_value(infix[i]);
}
if (decimal_encountered)// to measure decimal point numbers
{
decimal_count = decimal_count + 1;
}
}
else if (check_operator(infix[i]) == 2)
{
pseudoinfix[k++] = ch++;
pseudoinfix[k++] = infix[i];
while (infix[i] == ')')
{
i++;
pseudoinfix[k++] = infix[i];
}
if (decimal_count > 0)
{
temp = temp / pow(10, decimal_count - 1);
}
decimal_encountered = false;
decimal_count = 0;
integers[j++] = temp;
temp = 0;
}
else if (check_operator(infix[i]) == 1)
{
decimal_encountered = false;
decimal_count = 0;
pseudoinfix[k++] = infix[i];
}
}
if (decimal_count > 0)
{
temp = temp / pow(10, decimal_count - 1);
}
integers[j++] = temp;
pseudoinfix[k++] = ch;
}
double corresponding_value(char ch)
{
switch (ch)
{
case 'a':
return integers[0];
case 'b':
return integers[1];
case 'c':
return integers[2];
case 'd':
return integers[3];
case 'e':
return integers[4];
case 'f':
return integers[5];
case 'g':
return integers[6];
case 'h':
return integers[7];
case 'i':
return integers[8];
case 'j':
return integers[9];
case 'k':
return integers[10];
case 'l':
return integers[11];
case 'm':
return integers[12];
case 'n':
return integers[13];
case 'o':
return integers[14];
case 'p':
return integers[15];
case 'q':
return integers[16];
case 'r':
return integers[17];
case 's':
return integers[18];
case 't':
return integers[19];
case 'u':
return integers[20];
case 'v':
return integers[21];
case 'w':
return integers[22];
case 'x':
return integers[23];
case 'y':
return integers[24];
case 'z':
return integers[25];
case 'R':
return result;
}
return 0;
}
void calculate() // to calculate
{
double num1 = 0, num2 = 0;
for (int i = 0; postfix[i] != '\0'; i++)
{
if (postfix[i] != '+' && postfix[i] != '-' && postfix[i] != '*' && postfix[i] != '/'
&& postfix[i] != '^')
{
pushr(corresponding_value(postfix[i]));
}
else if (postfix[i] == '+')
{
num1 = popr();
num2 = popr();
result = num1 + num2;
pushr(result);
}
else if (postfix[i] == '-')
{
num1 = popr();
num2 = popr();
result = num2 - num1;
pushr(result);
}
else if (postfix[i] == '*')
{
num1 = popr();
num2 = popr();
result = num1 * num2;
pushr(result);
}
else if (postfix[i] == '/')
{
num1 = popr();
num2 = popr();
result = (num2 / num1);
if(num1 == 0){
cout << "Error: Denominator Can't be Zero\n";
system("pause");
exit(1);
}
pushr(result);
}
else if (postfix[i] == '^')
{
num1 = popr();
num2 = popr();
result = pow(num2,num1);
pushr(result);
}
}
cout << endl
<< "Result: " << result << endl;
}
int main()
{
char choice = 'y';
int chk;
system("cls");
while (tolower(choice) != 'n')
{
if (tolower(choice) == 'y')
{
system("cls");
cout << "\t\t\tCalculator by Himanshu Sharma \n";
cout << "Enter expression: "
<< "\n";
cin >> infix;
chk = braces(infix);
if (chk != 0)
{
cout << "Unbalanced No of Braces\n";
if (chk == 1)
{
cout << "Extra Right Braces\n";
}
else
{
cout << "Extra Left Braces\n";
}
}
Topseudoinfix();
To_postfix();
calculate();
cout << "enter Y to continue, N to exit\n";
cin >> choice;
}
}
return 0;
}
|
#pragma once
#include <string>
#include <vector>
#include <sstream>
using namespace std;
struct Element {
virtual ~Element() = default;
virtual void printHTML(ostringstream& oss) const = 0;
// If you want extend it to e.g. markdown printing you need a separate method,
// Violates the Open-Closed Principle:
// virtual void printMarkdown(ostringstream& oss) const = 0;
};
struct TextElement : Element {
string text;
explicit TextElement(const string& text) : text(text) {}
};
struct Paragraph : TextElement {
explicit Paragraph(const string& text) : TextElement(text) {}
void printHTML(ostringstream& oss) const override {
oss << "<p>" << text << "</p>\n";
}
};
struct ListItem : TextElement{
explicit ListItem(const string& text) : TextElement(text){}
void printHTML(ostringstream& oss) const override {
oss << "<li>" << text << "</li>\n";
}
};
struct List : vector<ListItem>, Element {
List(const initializer_list<value_type>& _Ilist) : vector<ListItem>(_Ilist) {}
void printHTML(ostringstream& oss) const override {
oss << "<ul>\n";
for (auto& li : *this)
li.printHTML(oss);
oss << "</ul>\n";
}
};
|
//
// Error.h
// Lab6Progr
//
// Created by Дмитрий Богомолов on 14.11.14.
// Copyright (c) 2014 Дмитрий Богомолов. All rights reserved.
//
#ifndef Lab6Progr_Error_h
#define Lab6Progr_Error_h
class Error {
public:
class MemoryAllocError{};
class IOError{};
class OutOfBounds{};
class NullPointerException {};
};
#endif
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <new> // For placement new
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Renderer
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Abstract memory allocator interface
*
* @note
* - The implementation must be multi-threading safe since the renderer is allowed to internally use multiple threads
* - The interface design is basing on "Nicholas Frechette's Blog Raw bits" - "A memory allocator interface" - http://nfrechette.github.io/2015/05/11/memory_allocator_interface/
*/
class IAllocator
{
//[-------------------------------------------------------]
//[ Public static methods ]
//[-------------------------------------------------------]
public:
template<typename Type>
inline static Type* constructN(Type* basePointer, size_t count)
{
for (size_t i = 0; i < count; ++i)
{
new ((void*)(basePointer + i)) Type();
}
return basePointer;
}
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
inline void* reallocate(void* oldPointer, size_t oldNumberOfBytes, size_t newNumberOfBytes, size_t alignment);
//[-------------------------------------------------------]
//[ Protected definitions ]
//[-------------------------------------------------------]
protected:
typedef void* (*ReallocateFuntion)(IAllocator&, void*, size_t, size_t, size_t);
//[-------------------------------------------------------]
//[ Protected methods ]
//[-------------------------------------------------------]
protected:
inline explicit IAllocator(ReallocateFuntion reallocateFuntion);
inline virtual ~IAllocator();
explicit IAllocator(const IAllocator&) = delete;
IAllocator& operator=(const IAllocator&) = delete;
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
ReallocateFuntion mReallocateFuntion;
};
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
//[-------------------------------------------------------]
//[ Macros & definitions ]
//[-------------------------------------------------------]
// Malloc and free
#define RENDERER_MALLOC(context, newNumberOfBytes) (context).getAllocator().reallocate(nullptr, 0, newNumberOfBytes, 1)
#define RENDERER_MALLOC_TYPED(context, type, newNumberOfElements) reinterpret_cast<type*>((context).getAllocator().reallocate(nullptr, 0, sizeof(type) * (newNumberOfElements), 1))
#define RENDERER_FREE(context, oldPointer) (context).getAllocator().reallocate(oldPointer, 0, 0, 1)
// New and delete
// - Using placement new and explicit destructor call
// - See http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ - "2. Wrap your macros in do { … } while(0)." for background information about the do-while wrap
#define RENDERER_NEW(context, type) new ((context).getAllocator().reallocate(nullptr, 0, sizeof(type), 1)) type
#define RENDERER_DELETE(context, type, oldPointer) \
do \
{ \
if (nullptr != oldPointer) \
{ \
oldPointer->~type(); \
(context).getAllocator().reallocate(oldPointer, 0, 0, 1); \
} \
} while (0)
// New and delete of arrays
// - Using placement new and explicit destructor call, not using the array version since it's using an undocumented additional amount of memory
// - See http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ - "2. Wrap your macros in do { … } while(0)." for background information about the do-while wrap
#define RENDERER_NEW_ARRAY(context, type, count) Renderer::IAllocator::constructN(static_cast<type*>(((context).getAllocator().reallocate(nullptr, 0, sizeof(type) * (count), 1))), count)
#define RENDERER_DELETE_ARRAY(context, type, oldPointer, count) \
do \
{ \
if (nullptr != oldPointer) \
{ \
for (size_t allocatorArrayIndex = 0; allocatorArrayIndex < count; ++allocatorArrayIndex) \
{ \
(oldPointer)[allocatorArrayIndex].~type(); \
} \
(context).getAllocator().reallocate(oldPointer, 0, 0, 1); \
} \
} while (0)
//[-------------------------------------------------------]
//[ Implementation ]
//[-------------------------------------------------------]
#include "Renderer/IAllocator.inl"
|
#include <stdio.h>
#include "heapfileLib.h"
int main(int argc, char *argv[])
{
if (argc < 3) {
printf("Usage: scan <heapfile> <page_size>\n");
return 0;
}
Heapfile *heapFile;
Record heapRecord;
FILE* dataFile = fopen(argv[1], "r+");
int pageSize = atoi(argv[2]);
heapFile = (Heapfile *) malloc(sizeof(Heapfile));
heapFile->file_ptr = dataFile;
heapFile->page_size = pageSize;
RecordIterator r = RecordIterator(heapFile);
while(r.hasNext()){
heapRecord = r.next();
for (int i = 0; i < heapRecord.size(); i++){
printf("%s", heapRecord[i]);
if (i < heapRecord.size() - 1) {
printf(",");
}
}
printf("\n\n");
free_record(&heapRecord);
}
free(heapFile);
return 0;
}
|
#include <iberbar/Utility/Xml/RapidXml.h>
#include <iberbar/Utility/String.h>
#include <iostream>
#include <rapidxml.hpp>
#include <rapidxml_print.hpp>
#include <rapidxml_utils.hpp>
namespace iberbar
{
namespace Xml
{
typedef rapidxml::xml_node< char > RapidNodeContextA;
typedef rapidxml::file< char > RapidFileContextA;
typedef rapidxml::xml_document< char > RapidDocumentContextA;
class CRapidDocumentA : public CDocumentA
{
public:
CRapidDocumentA();
virtual ~CRapidDocumentA();
public:
virtual CResult Create( const char* rootnode ) override;
virtual CResult LoadFromFile( const char* filepath ) override;
virtual CResult Load( const char* source ) override;
virtual CResult Save( const char* filepath ) override;
virtual void GetRoot( CNodeA** ppRootNode ) override;
private:
RapidFileContextA* m_file;
RapidDocumentContextA* m_doc;
};
class CRapidNodeA : public CNodeA
{
public:
CRapidNodeA( CRapidDocumentA* document, RapidNodeContextA* nodeContext );
virtual ~CRapidNodeA();
virtual void SelectSingleNode( const char* tagName, CNodeA** ppNode ) override;
virtual void SelectNodes( const char* tagName, CNodeListA** ppNodeList ) override;
virtual void AppendChild( const char* tagName, CNodeA** ppNode ) override;
virtual void DeleteChild( CNodeA* pNode ) override;
virtual void SetAttribute( const char* attrName, const char* attrValue ) override;
virtual const char* GetAttribute( const char* attrName ) override;
virtual void SetValueText( const char* value ) override;
virtual const char* GetValueText() override;
virtual const char* NameText() override;
private:
CRapidDocumentA* m_document;
RapidNodeContextA* m_nodeContext;
};
class CRapidNodeListA : public CNodeListA
{
public:
CRapidNodeListA( CRapidDocumentA* document );
virtual ~CRapidNodeListA();
public:
virtual void GetNodeAt( int index, CNodeA** ppNode ) override;
virtual int GetNodeCount() override;
void AddNode( CRapidNodeA* pNode );
private:
CRapidDocumentA* m_document;
std::vector< CRapidNodeA* > m_nodes;
};
}
}
iberbar::Xml::PTR_CDocumentA iberbar::Xml::CreateRapidXmlDocumentA()
{
PTR_CDocumentA document;
document.attach( new CRapidDocumentA() );
return document;
}
iberbar::Xml::CRapidDocumentA::CRapidDocumentA()
: CDocumentA()
, m_file( nullptr )
, m_doc( nullptr )
{
}
iberbar::Xml::CRapidDocumentA::~CRapidDocumentA()
{
SAFE_DELETE( m_file );
SAFE_DELETE( m_doc );
}
iberbar::CResult iberbar::Xml::CRapidDocumentA::Create( const char* rootNodeName )
{
return CResult();
}
iberbar::CResult iberbar::Xml::CRapidDocumentA::LoadFromFile( const char* filepath )
{
try
{
m_file = new RapidFileContextA( filepath );
m_doc = new RapidDocumentContextA();
m_doc->parse<0>( m_file->data() );
}
catch ( std::exception exception )
{
return MakeResult( ResultCode::Bad, "Exception of parsing: %s", exception.what() );
}
return CResult();
}
iberbar::CResult iberbar::Xml::CRapidDocumentA::Load( const char* source )
{
return CResult( ResultCode::Bad, "NotImplements" );
}
iberbar::CResult iberbar::Xml::CRapidDocumentA::Save( const char* filepath )
{
return CResult( ResultCode::Bad, "NotImplements" );
}
void iberbar::Xml::CRapidDocumentA::GetRoot( CNodeA** ppRootNode )
{
RapidNodeContextA* node_context = this->m_doc->first_node();
PTR_CNodeA node;
if ( node_context )
node.attach( new CRapidNodeA( this, node_context ) );
if ( ppRootNode )
{
if ( *ppRootNode )
(*ppRootNode)->Release();
(*ppRootNode) = node;
if ( *ppRootNode )
(*ppRootNode)->AddRef();
}
}
iberbar::Xml::CRapidNodeA::CRapidNodeA( CRapidDocumentA* document, RapidNodeContextA* nodeContext )
: CNodeA()
, m_document( document )
, m_nodeContext( nodeContext )
{
this->m_document->AddRef();
}
iberbar::Xml::CRapidNodeA::~CRapidNodeA()
{
UNKNOWN_SAFE_RELEASE_NULL( this->m_document );
}
void iberbar::Xml::CRapidNodeA::SelectSingleNode( const char* tagName, CNodeA** ppNode )
{
assert( StringIsNullOrEmpty( tagName ) == false );
RapidNodeContextA* nodeContext = m_nodeContext->first_node( tagName );
PTR_CNodeA node = nullptr;
if ( nodeContext != nullptr )
{
node.attach( new CRapidNodeA( this->m_document, nodeContext ) );
}
if ( ppNode )
{
if ( *ppNode )
(*ppNode)->Release();
(*ppNode) = node;
if ( *ppNode )
(*ppNode)->AddRef();
}
}
void iberbar::Xml::CRapidNodeA::SelectNodes( const char* tagName, CNodeListA** ppNodeList )
{
assert( StringIsNullOrEmpty( tagName ) == false );
if ( ppNodeList )
UNKNOWN_SAFE_RELEASE_NULL( *ppNodeList );
RapidNodeContextA* nodeContext = m_nodeContext->first_node( tagName );
if ( nodeContext != nullptr )
{
PTR_CNodeListA nodelist;
nodelist.attach( new CRapidNodeListA( this->m_document ) );
CRapidNodeListA* nodelist_ptr = (CRapidNodeListA*)((CNodeListA*)nodelist);
while ( nodeContext )
{
nodelist_ptr->AddNode( new CRapidNodeA( this->m_document, nodeContext ) );
nodeContext = nodeContext->next_sibling( tagName );
}
if ( ppNodeList )
{
(*ppNodeList) = nodelist;
(*ppNodeList)->AddRef();
}
}
}
void iberbar::Xml::CRapidNodeA::AppendChild( const char* tagName, CNodeA** ppNode )
{
}
void iberbar::Xml::CRapidNodeA::DeleteChild( CNodeA* node )
{
}
void iberbar::Xml::CRapidNodeA::SetAttribute( const char* attrName, const char* attrValue )
{
}
const char* iberbar::Xml::CRapidNodeA::GetAttribute( const char* attrName )
{
rapidxml::xml_attribute< char >* attr_context = m_nodeContext->first_attribute( attrName );
if ( attr_context == nullptr )
return nullptr;
return attr_context->value();
}
void iberbar::Xml::CRapidNodeA::SetValueText( const char* value )
{
}
const char* iberbar::Xml::CRapidNodeA::GetValueText()
{
return m_nodeContext->value();
}
const char* iberbar::Xml::CRapidNodeA::NameText()
{
return m_nodeContext->name();
}
iberbar::Xml::CRapidNodeListA::CRapidNodeListA( CRapidDocumentA* document )
: CNodeListA()
, m_document( document )
{
if ( m_document )
m_document->AddRef();
}
iberbar::Xml::CRapidNodeListA::~CRapidNodeListA()
{
auto iter = m_nodes.begin();
auto end = m_nodes.end();
for ( ; iter != end; iter++ )
UNKNOWN_SAFE_RELEASE_NULL( *iter );
UNKNOWN_SAFE_RELEASE_NULL( m_document );
}
void iberbar::Xml::CRapidNodeListA::GetNodeAt( int index, CNodeA** ppNode )
{
assert( index >= 0 && index < this->GetNodeCount() );
assert( ppNode );
if ( *ppNode )
(*ppNode)->Release();
(*ppNode) = m_nodes[index];
(*ppNode)->AddRef();
}
int iberbar::Xml::CRapidNodeListA::GetNodeCount()
{
return (int)m_nodes.size();
}
void iberbar::Xml::CRapidNodeListA::AddNode( CRapidNodeA* pNode )
{
m_nodes.push_back( pNode );
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
int n;
char s[111][111];
void Right(int x, int y, int& nx, int& ny) {
nx = x;
ny = y + 1;
}
void UpRight(int x, int y, int& nx, int& ny) {
if (y & 1) {
nx = x - 1;
ny = y - 1;
} else {
nx = x;
ny = y + 1;
}
}
void UpLeft(int x, int y, int& nx, int& ny) {
if (y & 1) {
nx = x - 1;
ny = y - 1;
} else {
nx = x;
ny = y - 1;
}
}
void RightR(int x, int y, int& nx, int& ny) {
nx = x;
ny = y - 1;
}
void UpRightR(int x, int y, int& nx, int& ny) {
if (y & 1) {
nx = x;
ny = y - 1;
} else {
nx = x + 1;
ny = y + 1;
}
}
void UpLeftR(int x, int y, int& nx, int& ny) {
if (y & 1) {
nx = x;
ny = y + 1;
} else {
nx = x + 1;
ny = y + 1;
}
}
int main() {
freopen("puzzle.in", "r", stdin);
freopen("puzzle.out", "w", stdout);
int it = 0;
while (true) {
++it;
scanf("%d\n", &n);
if (n == 0) break;
for (int i = 0; i < n; ++i) {
gets(s[i]);
}
bool ok[6][2] = {{true, true}, {true, true}, {true, true},{true, true}, {true, true}, {true, true}};
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i + i + 1; ++j) {
int nx, ny;
Right(i, j, nx, ny);
if (nx >= 0 && nx < n && ny >= 0 && ny < nx + nx + 1 && s[nx][ny] != s[i][j]) {
ok[0][s[i][j] - 48] = false;
}
UpRight(i, j, nx, ny);
if (nx >= 0 && nx < n && ny >= 0 && ny < nx + nx + 1 && s[nx][ny] != s[i][j]) {
ok[1][s[i][j] - 48] = false;
}
UpLeft(i, j, nx, ny);
if (nx >= 0 && nx < n && ny >= 0 && ny < nx + nx + 1 && s[nx][ny] != s[i][j]) {
ok[2][s[i][j] - 48] = false;
}
RightR(i, j, nx, ny);
if (nx >= 0 && nx < n && ny >= 0 && ny < nx + nx + 1 && s[nx][ny] != s[i][j]) {
ok[3][s[i][j] - 48] = false;
}
UpRightR(i, j, nx, ny);
if (nx >= 0 && nx < n && ny >= 0 && ny < nx + nx + 1 && s[nx][ny] != s[i][j]) {
ok[4][s[i][j] - 48] = false;
}
UpLeftR(i, j, nx, ny);
if (nx >= 0 && nx < n && ny >= 0 && ny < nx + nx + 1 && s[nx][ny] != s[i][j]) {
ok[5][s[i][j] - 48] = false;
}
}
}
if (it > 1) puts("");
printf("Puzzle %d\n", it);
bool good = false;
for (int i = 0; i < 6; ++i) {
if (ok[(i >= 3) ? (i - 3) : (i + 3)][1] && ok[i][0]) {
good = true;
}
}
if (good) {
puts("Parts can be separated");
} else
puts("Parts cannot be separated");
}
return 0;
}
|
#pragma once
#ifndef AVL_GL_API_H
#define AVL_GL_API_H
#include "glfw_app.hpp"
#include "file_io.hpp"
#include "stb/stb_image.h"
// Todo: supported extensions
// Todo: glMultiDrawElementsIndirect
// Todo: occlusionQuery
// Todo: timerQuery
// Todo: computeShaders (glDispatchCompute)
// Todo: blit/multisample?
// Todo: mapped buffers
// Todo: transform feedback
// Todo: pixel buffers / sync
namespace
{
inline void compile_shader(GLuint program, GLenum type, const char * source)
{
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, nullptr);
glCompileShader(shader);
GLint status, length;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
std::vector<GLchar> buffer(length);
glGetShaderInfoLog(shader, (GLsizei)buffer.size(), nullptr, buffer.data());
glDeleteShader(shader);
std::cerr << "GL Compile Error: " << buffer.data() << std::endl;
std::cerr << "Source: " << source << std::endl;
throw std::runtime_error("GLSL Compile Failure");
}
glAttachShader(program, shader);
glDeleteShader(shader);
}
std::string gl_src_to_str(GLenum source)
{
switch (source)
{
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "WINDOW_SYSTEM";
case GL_DEBUG_SOURCE_SHADER_COMPILER: return "SHADER_COMPILER";
case GL_DEBUG_SOURCE_THIRD_PARTY: return "THIRD_PARTY";
case GL_DEBUG_SOURCE_APPLICATION: return "APPLICATION";
case GL_DEBUG_SOURCE_OTHER: return "OTHER";
case GL_DEBUG_SOURCE_API: return "API";
default: return "UNKNOWN";
}
}
std::string gl_enum_to_str(GLenum type)
{
switch (type)
{
case GL_DEBUG_TYPE_ERROR: return "ERROR";
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "DEPRECATION";
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "UNDEFINED_BEHAVIOR";
case GL_DEBUG_TYPE_PORTABILITY: return "PORTABILITY";
case GL_DEBUG_TYPE_PERFORMANCE: return "PERFORMANCE";
case GL_DEBUG_TYPE_OTHER: return "OTHER";
default: return "UNKNOWN";
}
}
std::string gl_severity_to_str(GLenum severity)
{
switch (severity)
{
case GL_DEBUG_SEVERITY_LOW: return "LOW";
case GL_DEBUG_SEVERITY_MEDIUM: return "MEDIUM";
case GL_DEBUG_SEVERITY_HIGH: return "HIGH";
default: return "UNKNOWN";
}
}
static bool gEnableGLDebugOutputErrorBreakpoints = false;
static void APIENTRY gl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar * message, GLvoid * userParam)
{
if (type != GL_DEBUG_TYPE_ERROR) return;
auto sourceStr = gl_src_to_str(source);
auto typeStr = gl_enum_to_str(type);
auto severityStr = gl_severity_to_str(severity);
std::cout << "gl_debug_callback: " << sourceStr << ", " << severityStr << ", " << typeStr << " , " << id << ", " << message << std::endl;
if ((type == GL_DEBUG_TYPE_ERROR) && (gEnableGLDebugOutputErrorBreakpoints)) __debugbreak();
}
inline void gl_check_error(const char * file, int32_t line)
{
#ifdef _DEBUG
GLint error = glGetError();
if (error)
{
const char * errorStr = 0;
switch (error)
{
case GL_INVALID_ENUM: errorStr = "GL_INVALID_ENUM"; break;
case GL_INVALID_VALUE: errorStr = "GL_INVALID_VALUE"; break;
case GL_INVALID_OPERATION: errorStr = "GL_INVALID_OPERATION"; break;
case GL_OUT_OF_MEMORY: errorStr = "GL_OUT_OF_MEMORY"; break;
default: errorStr = "unknown error"; break;
}
printf("GL error : %s, line %d : %s\n", file, line, errorStr);
error = 0;
}
#endif
}
inline size_t gl_size_bytes(GLenum type)
{
switch (type)
{
case GL_UNSIGNED_BYTE: return sizeof(uint8_t);
case GL_UNSIGNED_SHORT: return sizeof(uint16_t);
case GL_UNSIGNED_INT: return sizeof(uint32_t);
default: throw std::logic_error("unknown element type"); break;
}
}
}
namespace avl
{
template<typename factory_t>
class GlObject
{
mutable GLuint handle = 0;
std::string n;
public:
GlObject() {}
GlObject(GLuint h) : handle(g) {}
~GlObject() { if (handle) factory_t::destroy(handle); }
GlObject(const GlObject & r) = delete;
GlObject & operator = (GlObject && r) { std::swap(handle, r.handle); std::swap(n, r.n); return *this; }
GlObject(GlObject && r) { *this = std::move(r); }
operator GLuint () const { if (!handle) factory_t::create(handle); return handle; }
GlObject & operator = (GLuint & other) { handle = other; return *this; }
void set_name(const std::string & newName) { n = newName; }
std::string name() const { return n; }
GLuint id() const { return handle; };
};
struct GlBufferFactory { static void create(GLuint & x) { glGenBuffers(1, &x); }; static void destroy(GLuint x) { glDeleteBuffers(1, &x); }; };
struct GlTextureFactory { static void create(GLuint & x) { glGenTextures(1, &x); }; static void destroy(GLuint x) { glDeleteTextures(1, &x); }; };
struct GlVertexArrayFactory { static void create(GLuint & x) { glGenVertexArrays(1, &x); }; static void destroy(GLuint x) { glDeleteVertexArrays(1, &x); }; };
struct GlRenderbufferFactory { static void create(GLuint & x) { glGenRenderbuffers(1, &x); }; static void destroy(GLuint x) { glDeleteRenderbuffers(1, &x); }; };
struct GlFramebufferFactory { static void create(GLuint & x) { glGenFramebuffers(1, &x); }; static void destroy(GLuint x) { glDeleteFramebuffers(1, &x); }; };
struct GlQueryFactory { static void create(GLuint & x) { glGenQueries(1, &x); }; static void destroy(GLuint x) { glDeleteQueries(1, &x); }; };
struct GlSamplerFactory { static void create(GLuint & x) { glGenSamplers(1, &x); }; static void destroy(GLuint x) { glDeleteSamplers(1, &x); }; };
struct GlTransformFeedbacksFactory { static void create(GLuint & x) { glGenTransformFeedbacks(1, &x); }; static void destroy(GLuint x) { glDeleteTransformFeedbacks(1, &x); }; };
typedef GlObject<GlBufferFactory> GlBufferObject;
typedef GlObject<GlTextureFactory> GlTextureObject;
typedef GlObject<GlVertexArrayFactory> GlVertexArrayObject;
typedef GlObject<GlRenderbufferFactory> GlRenderbufferObject;
typedef GlObject<GlFramebufferFactory> GlFramebufferObject;
typedef GlObject<GlQueryFactory> GlQueryObject;
typedef GlObject<GlSamplerFactory> GlSamplerObject;
typedef GlObject<GlTransformFeedbacksFactory> GlTransformFeedbacksObject;
//////////////////
// GlBuffer //
//////////////////
struct GlBuffer : public GlBufferObject
{
GLsizeiptr size;
GlBuffer() {}
void set_buffer_data(const GLsizeiptr size, const GLvoid * data, const GLenum usage) { glNamedBufferDataEXT(*this, size, data, usage); this->size = size; }
void set_buffer_data(const std::vector<GLubyte> & bytes, const GLenum usage) { set_buffer_data(bytes.size(), bytes.data(), usage); }
};
////////////////////////
// GlRenderbuffer //
////////////////////////
struct GlRenderbuffer : public GlRenderbufferObject
{
int2 size;
GlRenderbuffer() {};
GlRenderbuffer(int2 size) : size(size) {}
};
///////////////////////
// GlFramebuffer //
///////////////////////
struct GlFramebuffer : public GlFramebufferObject
{
float3 size;
GlFramebuffer() {}
GlFramebuffer(float2 s) : size(s.x, s.y, 0) {}
GlFramebuffer(float3 s) : size(s) {}
void check_complete() { if (glCheckNamedFramebufferStatusEXT(*this, GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw std::runtime_error("fbo incomplete"); }
};
///////////////////
// GlTexture //
///////////////////
struct GlTexture2D : public GlTextureObject
{
int2 size;
GlTexture2D() {}
GlTexture2D(int2 sz) : size(sz) {}
void setup(GLsizei width, GLsizei height, GLenum internal_fmt, GLenum format, GLenum type, const GLvoid * pixels, bool createMipmap = false)
{
glTextureImage2DEXT(*this, GL_TEXTURE_2D, 0, internal_fmt, width, height, 0, format, type, pixels);
if (createMipmap) glGenerateTextureMipmapEXT(*this, GL_TEXTURE_2D);
glTextureParameteriEXT(*this, GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteriEXT(*this, GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, createMipmap ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
glTextureParameteriEXT(*this, GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteriEXT(*this, GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
size = { width, height };
}
};
inline GlTexture2D load_image(const std::string & path)
{
auto binaryFile = read_file_binary(path);
int width, height, nBytes;
auto data = stbi_load_from_memory(binaryFile.data(), (int)binaryFile.size(), &width, &height, &nBytes, 0);
GlTexture2D tex;
switch (nBytes)
{
case 3: tex.setup(width, height, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, data, true); break;
case 4: tex.setup(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, data, true); break;
default: throw std::runtime_error("supported number of channels");
}
tex.set_name(path);
stbi_image_free(data);
return tex;
}
/////////////////////
// GlTexture3D //
/////////////////////
// As either a 3D texture or 2D array
struct GlTexture3D : public GlTextureObject
{
int3 size;
GlTexture3D() {}
GlTexture3D(int3 sz) : size(sz) {}
void setup(GLenum target, GLsizei width, GLsizei height, GLsizei depth, GLenum internal_fmt, GLenum format, GLenum type, const GLvoid * pixels)
{
glTextureImage3DEXT(*this, target, 0, internal_fmt, width, height, depth, 0, format, type, pixels);
glTextureParameteriEXT(*this, target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteriEXT(*this, target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteriEXT(*this, target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteriEXT(*this, target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTextureParameteriEXT(*this, target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
};
//////////////////
// GlShader //
//////////////////
class GlShader : public Noncopyable
{
GLuint program;
bool enabled = false;
void check() const { if (!enabled) throw std::runtime_error("shader not enabled"); };
public:
GlShader() : program() {}
GlShader(const std::string & vertexShader, const std::string & fragmentShader, const std::string & geometryShader = "")
{
program = glCreateProgram();
compile_shader(program, GL_VERTEX_SHADER, vertexShader.c_str());
compile_shader(program, GL_FRAGMENT_SHADER, fragmentShader.c_str());
if (geometryShader.length() != 0)
::compile_shader(program, GL_GEOMETRY_SHADER, geometryShader.c_str());
glLinkProgram(program);
GLint status;
GLint length;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
std::vector<GLchar> buffer(length);
glGetProgramInfoLog(program, (GLsizei)buffer.size(), nullptr, buffer.data());
std::cerr << "GL Link Error: " << buffer.data() << std::endl;
throw std::runtime_error("GLSL Link Failure");
}
}
~GlShader() { if (program) glDeleteProgram(program); }
GlShader(GlShader && r) : GlShader() { *this = std::move(r); }
GLuint handle() const { return program; }
GLint get_uniform_location(const std::string & name) const { return glGetUniformLocation(program, name.c_str()); }
GlShader & operator = (GlShader && r) { std::swap(program, r.program); return *this; }
void reflect_debug_print()
{
GLint count;
glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &count);
for (GLuint i = 0; i < static_cast<GLuint>(count); ++i)
{
char buffer[1024]; GLenum type; GLsizei length; GLint size, block_index;
glGetActiveUniform(program, i, sizeof(buffer), &length, &size, &type, buffer);
glGetActiveUniformsiv(program, 1, &i, GL_UNIFORM_BLOCK_INDEX, &block_index);
if (block_index != -1) continue;
GLint loc = glGetUniformLocation(program, buffer);
}
}
void uniform(const std::string & name, int scalar) const { check(); glUniform1i(get_uniform_location(name), scalar); }
void uniform(const std::string & name, float scalar) const { check(); glUniform1f(get_uniform_location(name), scalar); }
void uniform(const std::string & name, const float2 & vec) const { check(); glUniform2fv(get_uniform_location(name), 1, &vec.x); }
void uniform(const std::string & name, const float3 & vec) const { check(); glUniform3fv(get_uniform_location(name), 1, &vec.x); }
void uniform(const std::string & name, const float4 & vec) const { check(); glUniform4fv(get_uniform_location(name), 1, &vec.x); }
void uniform(const std::string & name, const float3x3 & mat) const { check(); glUniformMatrix3fv(get_uniform_location(name), 1, GL_FALSE, &mat.x.x); }
void uniform(const std::string & name, const float4x4 & mat) const { check(); glUniformMatrix4fv(get_uniform_location(name), 1, GL_FALSE, &mat.x.x); }
void uniform(const std::string & name, const int elements, const std::vector<int> & scalar) const { check(); glUniform1iv(get_uniform_location(name), elements, scalar.data()); }
void uniform(const std::string & name, const int elements, const std::vector<float> & scalar) const { check(); glUniform1fv(get_uniform_location(name), elements, scalar.data()); }
void uniform(const std::string & name, const int elements, const std::vector<float2> & vec) const { check(); glUniform2fv(get_uniform_location(name), elements, &vec[0].x); }
void uniform(const std::string & name, const int elements, const std::vector<float3> & vec) const { check(); glUniform3fv(get_uniform_location(name), elements, &vec[0].x); }
void uniform(const std::string & name, const int elements, const std::vector<float3x3> & mat) const { check(); glUniformMatrix3fv(get_uniform_location(name), elements, GL_FALSE, &mat[0].x.x); }
void uniform(const std::string & name, const int elements, const std::vector<float4x4> & mat) const { check(); glUniformMatrix4fv(get_uniform_location(name), elements, GL_FALSE, &mat[0].x.x); }
void texture(GLint loc, GLenum target, int unit, GLuint tex) const
{
check();
glBindMultiTextureEXT(GL_TEXTURE0 + unit, target, tex);
glProgramUniform1i(program, loc, unit);
}
void texture(const char * name, int unit, GLuint tex, GLenum target) const { texture(get_uniform_location(name), target, unit, tex); }
void bind() { if (program > 0) enabled = true; glUseProgram(program); }
void unbind() { enabled = false; glUseProgram(0); }
};
////////////////
// GlMesh //
////////////////
class GlMesh
{
GlVertexArrayObject vao;
GlBuffer vertexBuffer, instanceBuffer, indexBuffer;
GLenum drawMode = GL_TRIANGLES;
GLenum indexType = 0;
GLsizei vertexStride = 0, instanceStride = 0, indexCount = 0;
public:
GlMesh() {}
GlMesh(GlMesh && r) { *this = std::move(r); }
GlMesh(const GlMesh & r) = delete;
GlMesh & operator = (GlMesh && r)
{
char buffer[sizeof(GlMesh)];
memcpy(buffer, this, sizeof(buffer));
memcpy(this, &r, sizeof(buffer));
memcpy(&r, buffer, sizeof(buffer));
return *this;
}
GlMesh & operator = (const GlMesh & r) = delete;
~GlMesh() {};
void set_non_indexed(GLenum newMode)
{
drawMode = newMode;
indexBuffer = {};
indexType = 0;
indexCount = 0;
}
void draw_elements(int instances = 0) const
{
if (vertexBuffer.size)
{
glBindVertexArray(vao);
if (indexCount)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
if (instances) glDrawElementsInstanced(drawMode, indexCount, indexType, 0, instances);
else glDrawElements(drawMode, indexCount, indexType, nullptr);
}
else
{
if (instances) glDrawArraysInstanced(drawMode, 0, static_cast<GLsizei>(vertexBuffer.size / vertexStride), instances);
else glDrawArrays(drawMode, 0, static_cast<GLsizei>(vertexBuffer.size / vertexStride));
}
glBindVertexArray(0);
}
}
void set_vertex_data(GLsizeiptr size, const GLvoid * data, GLenum usage) { vertexBuffer.set_buffer_data(size, data, usage); }
void set_instance_data(GLsizeiptr size, const GLvoid * data, GLenum usage) { instanceBuffer.set_buffer_data(size, data, usage); }
void set_index_data(GLenum mode, GLenum type, GLsizei count, const GLvoid * data, GLenum usage)
{
size_t size = gl_size_bytes(type);
indexBuffer.set_buffer_data(size * count, data, usage);
drawMode = mode;
indexType = type;
indexCount = count;
}
void set_attribute(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid * offset)
{
glEnableVertexArrayAttribEXT(vao, index);
glVertexArrayVertexAttribOffsetEXT(vao, vertexBuffer, index, size, type, normalized, stride, (GLintptr)offset);
vertexStride = stride;
}
void set_instance_attribute(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid * offset)
{
glEnableVertexArrayAttribEXT(vao, index);
glVertexArrayVertexAttribOffsetEXT(vao, instanceBuffer, index, size, type, normalized, stride, (GLintptr)offset);
glVertexArrayVertexAttribDivisorEXT(vao, index, 1);
instanceStride = stride;
}
void set_indices(GLenum mode, GLsizei count, const uint8_t * indices, GLenum usage) { set_index_data(mode, GL_UNSIGNED_BYTE, count, indices, usage); }
void set_indices(GLenum mode, GLsizei count, const uint16_t * indices, GLenum usage) { set_index_data(mode, GL_UNSIGNED_SHORT, count, indices, usage); }
void set_indices(GLenum mode, GLsizei count, const uint32_t * indices, GLenum usage) { set_index_data(mode, GL_UNSIGNED_INT, count, indices, usage); }
template<class T> void set_vertices(size_t count, const T * vertices, GLenum usage) { set_vertex_data(count * sizeof(T), vertices, usage); }
template<class T> void set_vertices(const std::vector<T> & vertices, GLenum usage) { set_vertices(vertices.size(), vertices.data(), usage); }
template<class T, int N> void set_vertices(const T(&vertices)[N], GLenum usage) { set_vertices(N, vertices, usage); }
template<class V>void set_attribute(GLuint index, float V::*field) { set_attribute(index, 1, GL_FLOAT, GL_FALSE, sizeof(V), &(((V*)0)->*field)); }
template<class V, int N> void set_attribute(GLuint index, linalg::vec<float, N> V::*field) { set_attribute(index, N, GL_FLOAT, GL_FALSE, sizeof(V), &(((V*)0)->*field)); }
template<class T> void set_elements(GLsizei count, const linalg::vec<T, 2> * elements, GLenum usage) { set_indices(GL_LINES, count * 2, &elements->x, GL_STATIC_DRAW); }
template<class T> void set_elements(GLsizei count, const linalg::vec<T, 3> * elements, GLenum usage) { set_indices(GL_TRIANGLES, count * 3, &elements->x, GL_STATIC_DRAW); }
template<class T> void set_elements(GLsizei count, const linalg::vec<T, 4> * elements, GLenum usage) { set_indices(GL_QUADS, count * 4, &elements->x, GL_STATIC_DRAW); }
template<class T> void set_elements(const std::vector<T> & elements, GLenum usage) { set_elements((GLsizei)elements.size(), elements.data(), usage); }
template<class T, int N> void set_elements(const T(&elements)[N], GLenum usage) { set_elements(N, elements, usage); }
};
}
#endif // end AVL_GL_API_H
|
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ClangPluginCheck.h"
#include "ClangPluginRegistry.h"
#include "clang/AST/Decl.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include <string>
using namespace clang;
namespace {
using namespace clang::ast_matchers;
class NoThreadLocalDeclCallback : public MatchFinder::MatchCallback {
public:
void run(const MatchFinder::MatchResult &Result) override {
DiagnosticsEngine &Diagnostics = Result.Context->getDiagnostics();
if (const VarDecl *D = Result.Nodes.getNodeAs<VarDecl>("decl")) {
unsigned ID = Diagnostics.getDiagnosticIDs()->getCustomDiagID(
DiagnosticIDs::Error,
"[system-c++] Thread local storage is disallowed");
Diagnostics.Report(D->getLocStart(), ID);
}
}
};
NoThreadLocalDeclCallback NoThreadLocalDecl;
class NoThreadLocalDeclCheck : public ClangPluginCheck {
public:
void add(ast_matchers::MatchFinder &Finder) override {
// Using thread-local storage is disallowed.
Finder.addMatcher(varDecl(hasThreadStorageDuration()).bind("decl"),
&NoThreadLocalDecl);
}
};
} // namespace
static ClangPluginRegistry::Add<NoThreadLocalDeclCheck>
X("no-thread-local-decl", "Disallow C++ thread_local storage");
|
#include "TTrie.h"
TNode::TNode() : suffLink(nullptr), exitLink(nullptr), leaf(false) {}
void addPattern(TNode* root, vector<uint32_t>& pat, size_t patSize) {
TNode* curNode = root;
for (auto it : pat) {
if (curNode->child.find(it) == curNode->child.end())
curNode->child.insert(make_pair(it, new TNode()));
curNode = curNode->child.find(it)->second;
}
curNode->leaf = true;
curNode->patSize.push_back(patSize);
}
void CreateLinks(TNode* root, TNode* parent, TNode* node, uint32_t symToNode) {
TNode* link = parent->suffLink;
auto findChild = link->child.find(symToNode);
while (link != root && findChild == link->child.end()) {
link = link->suffLink;
findChild = link->child.find(symToNode);
}
if (findChild == link->child.end())
node->suffLink = root;
else {
node->suffLink = findChild->second;
link = node->suffLink;
if (link->leaf)
node->exitLink = link;
else if (link->exitLink)
node->exitLink = link->exitLink;
}
}
void processTrie(TNode* root, TNode* node, size_t lvl) {
if (lvl != 1)
for (auto it : node->child)
processTrie(root, it.second, lvl - 1);
else
for (auto it : node->child)
CreateLinks(root, node, it.second, it.first);
}
void processTrie(TNode* root, size_t maxLen) {
root->suffLink = root;
for (auto it : root->child)
it.second->suffLink = root;
for (size_t i = 1; i < maxLen; i++)
for (auto it : root->child)
processTrie(root, it.second, i);
}
void Search(TNode* root, vector< pair<int32_t, pair<size_t, size_t> > >& text, size_t patLen, size_t patCount) {
size_t textSize = text.size();
vector<size_t> patInd(textSize, 0);
TNode* curNode = root;
TNode* link;
for (int i = 0; i < (int)textSize; i++) {
auto findChild = curNode->child.find(text[i].first);
if (findChild != curNode->child.end())
curNode = findChild->second;
else {
curNode = curNode->suffLink;
findChild = curNode->child.find(text[i].first);
while (curNode->suffLink != root && findChild == curNode->child.end()) {
curNode = curNode->suffLink;
findChild = curNode->child.find(text[i].first);
}
if (findChild != curNode->child.end())
curNode = findChild->second;
else curNode = root;
}
if (curNode->leaf)
for (auto it : curNode->patSize)
if (i - (int)it + 1 >= 0)
patInd[i - (int)it + 1]++;
link = curNode->exitLink;
while (link) {
for (auto it : link->patSize)
if (i - (int)it + 1 >= 0)
patInd[i - (int)it + 1]++;
link = link->exitLink;
}
if (!curNode->child.size()) {
if (curNode->exitLink)
curNode = curNode->exitLink;
else
curNode = curNode->suffLink;
}
}
for (int i = 0; i < (int)textSize - (int)patLen + 1; i++)
if (patInd[i] == patCount)
cout << text[i].second.first << ", " << text[i].second.second << endl;
}
void DeleteTrie(TNode* node) {
for (auto it : node->child)
DeleteTrie(it.second);
delete node;
}
|
#include "PropFactory.h"
#include "Base.h"
#include "Health.h"
using namespace uth;
using namespace pmath;
uth::GameObject* PropFactory::CreateBase()
{
GameObject* go = new GameObject();
go->AddTags({ "Props", "Base" });
go->AddComponent(new Health(0, 100));
go->AddComponent(new uth::Sprite("Base.png"));
go->AddComponent(new Base());
go->transform.SetPosition(0,140);
go->transform.ScaleToSize(300, 150);
// Possibly do some scaling for the texture later, maybe, ok? ok.
return go;
}
uth::GameObject* PropFactory::CreateBackground()
{
GameObject* go = new GameObject();
go->AddTags({ "Props", "Background" });
go->AddComponent(new uth::Sprite("BackGround.png"));
go->transform.ScaleToSize(uthEngine.GetWindow().GetCamera().GetSize());
return go;
}
uth::GameObject* PropFactory::CreateMenuBackground()
{
GameObject* go = new GameObject();
go->AddTags({ "Props", "Background" });
go->AddComponent(new uth::Sprite("Menu/BackGround.png"));
go->transform.ScaleToSize(uthEngine.GetWindow().GetCamera().GetSize());
return go;
}
uth::GameObject* PropFactory::CreateGameOverBackground()
{
GameObject* go = new GameObject();
go->AddTags({ "Props", "Background" });
go->AddComponent(new uth::Sprite("GameOver/GameOver.png"));
go->transform.ScaleToSize(uthEngine.GetWindow().GetCamera().GetSize());
return go;
}
|
/*
* Copyright (c) 2009 Joel de Vahl
* 2009 Markus Ålind
* see LICENSE file for more info
*/
#ifndef INC_SIMD_IMPLEMENTATION_HPP
#define INC_SIMD_IMPLEMENTATION_HPP
#include "intrinsics.hpp"
/*-----------------------------------------------------------------*\
| Complex bit and byte twiddling
\*-----------------------------------------------------------------*/
FORCE_INLINE v128 vCross3(v128 v1, v128 v2);
FORCE_INLINE void mTranspose(const v128 &_rvS0,const v128 &_rvS1, const v128 &_rvS2, const v128 &_rvS3, v128 &_rvD0, v128 &_rvD1, v128 &_rvD2, v128 &_rvD3);
FORCE_INLINE void mTranspose(v128 &_rv0, v128 &_rv1, v128 &_rv2, v128 &_rv3);
FORCE_INLINE void mTranspose(const v128 *_rvSrc, v128 &_rv0, v128 &_rv1, v128 &_rv2, v128 &_rv3);
//FORCE_INLINE void mTranspose(v128 *_rvSrc, v128 *_rvDst);
FORCE_INLINE v128 mMulV(const v128 &_rvMS0, const v128 &_rvMS1, const v128 &_rvMS2, const v128 &_rvMS3, const v128 &_rvVS);
FORCE_INLINE v128 mMulVT(const v128 &_rvMS0, const v128 &_rvMS1, const v128 &_rvMS2, const v128 &_rvMS3, const v128 &_rvVS);
FORCE_INLINE void mMulM(const v128 &_rvM1S0, const v128 &_rvM1S1, const v128 &_rvM1S2, const v128 &_rvM1S3,
const v128 &_rvM2S0, const v128 &_rvM2S1, const v128 &_rvM2S2, const v128 &_rvM2S3,
v128 &_rvMD0, v128 &_rvMD1, v128 &_rvMD2, v128 &_rvMD3);
void FORCE_INLINE mFromPosFwdUp_Slow(const v128& _rvPos, const v128& _rvFwd, const v128& _rvUp,
v128& _rM0Dst, v128& _rM1Dst, v128& _rM2Dst, v128& _rM3Dst);
void FORCE_INLINE mFromVectors_Slow(const v128& _rvTrans, const v128& _rvX, const v128& _rvY, const v128& _rvZ,
v128& _rM0Dst, v128& _rM1Dst, v128& _rM2Dst, v128& _rM3Dst);
/*-----------------------------------------------------------------*\
| Math utility functions
\*-----------------------------------------------------------------*/
FORCE_INLINE v128 vAddH(v128 _v);
FORCE_INLINE v128 vAddH3(v128 _v);
FORCE_INLINE v128 vAddH4x4(v128 _v0, v128 _v1, v128 _v2, v128 _v3);
FORCE_INLINE v128 vAddH4x3(v128 _v0, v128 _v1, v128 _v2, v128 _v3);
FORCE_INLINE v128 vNormalize(v128 _v);
FORCE_INLINE void vNormalize4x3(v128 _v0, v128 _v1, v128 _v2, v128 _v3);
FORCE_INLINE void vNormalize4x4(v128 _v0, v128 _v1, v128 _v2, v128 _v3);
FORCE_INLINE v128 vNormalize3(v128 _v);
/*-----------------------------------------------------------------*\
| THE IMPLEMENTATION
\*-----------------------------------------------------------------*/
/*
Function: vCross3
Cross product (vector product) of the first 3 elements of two vectors.
Parameters:
v1 - first vector
v2 - second vector
Returns:
Cross product vector, w is carried from v1.
*/
FORCE_INLINE v128 vCross3(v128 v1, v128 v2)
{
v128 v1yzxw = vShuffle1(v1, 1, 2, 0, 3);
v128 v2zxyw = vShuffle1(v2, 2, 0, 1, 3);
v128 vRes0 = vMul(v1yzxw, v2zxyw);
v128 v1zxyw = vShuffle1(v1, 2, 0, 1, 3);
v128 v2yzxw = vShuffle1(v2, 1, 2, 0, 3);
v128 vRes1 = vMul(v1zxyw, v2yzxw);
v128 vFin = vSub(vRes0, vRes1);
return vMskW(vFin, v1);
}
FORCE_INLINE void mTranspose(const v128 &_rvS0,const v128 &_rvS1, const v128 &_rvS2, const v128 &_rvS3, v128 &_rvD0, v128 &_rvD1, v128 &_rvD2, v128 &_rvD3)
{
const v128 v0 = _rvS0;
const v128 v1 = _rvS1;
const v128 v2 = _rvS2;
const v128 v3 = _rvS3;
const v128 vTmp0 = vMergeHigh(v0, v2);
const v128 vTmp1 = vMergeLow(v0, v2);
const v128 vTmp2 = vMergeHigh(v1, v3);
const v128 vTmp3 = vMergeLow(v1, v3);
const v128 vTrans3 = vMergeLow(vTmp1, vTmp3);
const v128 vTrans2 = vMergeHigh(vTmp1, vTmp3);
const v128 vTrans1 = vMergeLow(vTmp0, vTmp2);
const v128 vTrans0 = vMergeHigh(vTmp0, vTmp2);
_rvD0 = vTrans0;
_rvD1 = vTrans1;
_rvD2 = vTrans2;
_rvD3 = vTrans3;
}
FORCE_INLINE void mTranspose(v128 &_rv0, v128 &_rv1, v128 &_rv2, v128 &_rv3)
{
mTranspose(_rv0, _rv1, _rv2, _rv3, _rv0, _rv1, _rv2, _rv3);
}
FORCE_INLINE void mTranspose(const v128 *_rvSrc, v128 &_rv0, v128 &_rv1, v128 &_rv2, v128 &_rv3)
{
const v128 vS0 = _rvSrc[0];
const v128 vS1 = _rvSrc[1];
const v128 vS2 = _rvSrc[2];
const v128 vS3 = _rvSrc[3];
mTranspose(vS0, vS1, vS2, vS3, _rv0, _rv1, _rv2, _rv3);
}
/*
FORCE_INLINE void mTranspose (v128 *_rvSrc, v128 *_rvDst)
{
#if defined(SIMD_ALTIVEC)
#elif defined(SIMD_SPU)
#elif defined(SIMD_SSE)
const __m64* __restrict__ src = reinterpret_cast<const __m64* __restrict__>(_rvSrc);
__m128 tmp1 = _mm_loadh_pi(_mm_loadl_pi(tmp1, src), &src[2]);
__m128 row1 = _mm_loadh_pi(_mm_loadl_pi(row1, &src[4]), &src[6]);
__m128 row0 = _mm_shuffle_ps(tmp1, row1, 0x88);
row1 = _mm_shuffle_ps(row1, tmp1, 0xDD);
tmp1 = _mm_loadh_pi(_mm_loadl_pi(tmp1, &src[1]), &src[3]);
__m128 row3 = _mm_loadh_pi(_mm_loadl_pi(row3, &src[5]), &src[7]);
__m128 row2 = _mm_shuffle_ps(tmp1, row3, 0x88);
row3 = _mm_shuffle_ps(row3, tmp1, 0xDD);
#else
#endif
} */
FORCE_INLINE v128 mMulV(const v128 &_rvMS0, const v128 &_rvMS1, const v128 &_rvMS2, const v128 &_rvMS3, const v128 &_rvVS)
{
v128 t0, t1, t2, t3;
mTranspose(_rvMS0, _rvMS1, _rvMS2, _rvMS3, t0, t1, t2, t3);
return mMulVT(t0, t1, t2, t3, _rvVS);
}
FORCE_INLINE v128 mMulVT(const v128 &_rvMS0, const v128 &_rvMS1, const v128 &_rvMS2, const v128 &_rvMS3, const v128 &_rvVS)
{
v128 vVD = vMul(vSplat(_rvVS, 0), _rvMS0);
vVD = vMAdd(vSplat(_rvVS, 1), _rvMS1, vVD);
vVD = vMAdd(vSplat(_rvVS, 2), _rvMS2, vVD);
vVD = vMAdd(vSplat(_rvVS, 3), _rvMS3, vVD);
return vVD;
}
FORCE_INLINE void mMulM(const v128 &_rvM1S0, const v128 &_rvM1S1, const v128 &_rvM1S2, const v128 &_rvM1S3,
const v128 &_rvM2S0, const v128 &_rvM2S1, const v128 &_rvM2S2, const v128 &_rvM2S3,
v128 &_rvMD0, v128 &_rvMD1, v128 &_rvMD2, v128 &_rvMD3)
{
_rvMD0 = vMAdd(vSplat(_rvM1S0, 0), _rvM2S0, vZero());
_rvMD1 = vMAdd(vSplat(_rvM1S1, 0), _rvM2S0, vZero());
_rvMD2 = vMAdd(vSplat(_rvM1S2, 0), _rvM2S0, vZero());
_rvMD3 = vMAdd(vSplat(_rvM1S3, 0), _rvM2S0, vZero());
_rvMD0 = vMAdd(vSplat(_rvM1S0, 1), _rvM2S1, _rvMD0);
_rvMD1 = vMAdd(vSplat(_rvM1S1, 1), _rvM2S1, _rvMD1);
_rvMD2 = vMAdd(vSplat(_rvM1S2, 1), _rvM2S1, _rvMD2);
_rvMD3 = vMAdd(vSplat(_rvM1S3, 1), _rvM2S1, _rvMD3);
_rvMD0 = vMAdd(vSplat(_rvM1S0, 2), _rvM2S2, _rvMD0);
_rvMD1 = vMAdd(vSplat(_rvM1S1, 2), _rvM2S2, _rvMD1);
_rvMD2 = vMAdd(vSplat(_rvM1S2, 2), _rvM2S2, _rvMD2);
_rvMD3 = vMAdd(vSplat(_rvM1S3, 2), _rvM2S2, _rvMD3);
_rvMD0 = vMAdd(vSplat(_rvM1S0, 3), _rvM2S3, _rvMD0);
_rvMD1 = vMAdd(vSplat(_rvM1S1, 3), _rvM2S3, _rvMD1);
_rvMD2 = vMAdd(vSplat(_rvM1S2, 3), _rvM2S3, _rvMD2);
_rvMD3 = vMAdd(vSplat(_rvM1S3, 3), _rvM2S3, _rvMD3);
}
void FORCE_INLINE mFromVectors_Slow(const v128& _rvTrans, const v128& _rvX, const v128& _rvY, const v128& _rvZ,
v128& _rM0Dst, v128& _rM1Dst, v128& _rM2Dst, v128& _rM3Dst)
{
float* rfTrans = (float*)&_rvTrans;
float* rfX = (float*)&_rvX;
float* rfY = (float*)&_rvY;
float* rfZ = (float*)&_rvZ;
/*matrix.M11 = x_axis.X;
matrix.M12 = x_axis.Y;
matrix.M13 = x_axis.Z;
matrix.M21 = y_axis.X;
matrix.M22 = y_axis.Y;
matrix.M23 = y_axis.Z;
matrix.M31 = z_axis.X;
matrix.M32 = z_axis.Y;
matrix.M33 = z_axis.Z;*/
_rM0Dst = vLoad(rfX[0], rfY[0], rfZ[0], rfTrans[0]);
_rM1Dst = vLoad(rfX[1], rfY[1], rfZ[1], rfTrans[1]);
_rM2Dst = vLoad(rfX[2], rfY[2], rfZ[2], rfTrans[2]);
_rM3Dst = vLoad(0.0f, 0.0f, 0.0f, 1.0f);
}
void FORCE_INLINE mFromPosFwdUp_Slow(const v128& _rvPos, const v128& _rvFwd, const v128& _rvUp,
v128& _rM0Dst, v128& _rM1Dst, v128& _rM2Dst, v128& _rM3Dst)
{
// vDebugPrint(_rvUp);
// vDebugPrint(_rvFwd);
v128 vX = vCross3(_rvUp, _rvFwd);
// vDebugPrint(vX);
mFromVectors_Slow(_rvPos, vX, _rvUp, _rvFwd, _rM0Dst, _rM1Dst, _rM2Dst, _rM3Dst);
}
/*-----------------------------------------------------------------*\
| Math utility functions
\*-----------------------------------------------------------------*/
FORCE_INLINE v128 vAddH(v128 _v)
{
v128 v0 = vSplat(_v, 0);
v128 v1 = vSplat(_v, 1);
v128 v2 = vSplat(_v, 2);
v128 v3 = vSplat(_v, 3);
return vAdd(vAdd(v0, v1), vAdd(v2, v3));
}
FORCE_INLINE v128 vAddH3(v128 _v)
{
v128 v0 = vSplat(_v, 0);
v128 v1 = vSplat(_v, 1);
v128 v2 = vSplat(_v, 2);
return vAdd(vAdd(v0, v1), v2);
}
FORCE_INLINE v128 vAddH4x4(v128 _v0, v128 _v1, v128 _v2, v128 _v3)
{
mTranspose(_v0, _v1, _v2, _v3);
return vAdd(vAdd(_v0, _v1), vAdd(_v2, _v3));
}
FORCE_INLINE v128 vAddH4x3(v128 _v0, v128 _v1, v128 _v2, v128 _v3)
{
mTranspose(_v0, _v1, _v2, _v3);
return vAdd(vAdd(_v0, _v1), _v3);
}
FORCE_INLINE v128 vNormalize(v128 _v)
{
v128 vLen2 = vAddH(vMul(_v, _v));
v128 vRcp = vRc(vLen2);
return vMul(vRcp, _v);
}
FORCE_INLINE void vNormalize4x3(v128 _v0, v128 _v1, v128 _v2, v128 _v3)
{
mTranspose(_v0, _v1, _v2, _v3);
v128 vLen2 = vAdd(vAdd(vMul(_v0, _v0), vMul(_v1, _v1)), vAdd(vMul(_v2, _v2), vMul(_v3, _v3)));
v128 vLenRc = vRsq(vLen2);
_v0 = vMskW(vMul(vLenRc, _v0), _v0);
_v1 = vMskW(vMul(vLenRc, _v1), _v1);
_v2 = vMskW(vMul(vLenRc, _v2), _v2);
_v3 = vMskW(vMul(vLenRc, _v3), _v3);
}
FORCE_INLINE void vNormalize4x4(v128 _v0, v128 _v1, v128 _v2, v128 _v3)
{
mTranspose(_v0, _v1, _v2, _v3);
v128 vLen2 = vAdd(vAdd(vMul(_v0, _v0), vMul(_v1, _v1)), vMul(_v2, _v2));
v128 vLenRc = vRsq(vLen2);
_v0 = vMul(vLenRc, _v0);
_v1 = vMul(vLenRc, _v1);
_v2 = vMul(vLenRc, _v2);
_v3 = vMul(vLenRc, _v3);
}
FORCE_INLINE v128 vNormalize3(v128 _v)
{
v128 vLen2 = vAddH3(vMul(_v, _v));
v128 vLenRc = vRsq(vLen2);
return vMskW(vMul(vLenRc, _v), _v);
}
#endif //INC_SIMD_IMPL_HPP
|
#ifndef DATA_MANAGER_HPP
#define DATA_MANAGER_HPP
#include "../Common/Configuration.hpp"
#include "../Common/Math.hpp"
#include "../Common/Vector2.hpp"
#include "../Services/Input.hpp"
#include "../Services/Window.hpp"
#include "../Services/ImmediateRenderer2D.hpp"
#include <Box2D/Box2D.h>
#include <tuple>
#include <unordered_map>
#include <vector>
#include <array>
using MeshManager = std::unordered_map<u32, std::vector<vec2>>;
u32 generateID()
{
static u32 id = 0;
return ++id;
}
#endif // DATA_MANAGER_HPP
|
#include "CSceneGame.h"
//OpenGL
#include "glut.h"
//
#include "CCamera.h"
//
#include "CText.h"
//
#include "CRes.h"
//スマートポインタの生成
std::shared_ptr<CTexture> TextureExp(new CTexture());
CSceneGame::~CSceneGame() {
}
void CSceneGame::Init() {
//3Dモデルファイルの読み込み
CRes::sModelX.Load(MODEL_FILE);
//テキストフォントの読み込みと設定
CText::mFont.Load("FontG.tga");
CText::mFont.SetRowCol(1, 4096 / 64);
//モデルファイルの入力
CRes::sBackGround.Load("sky.obj", "sky.mtl");
}
void CSceneGame::Update() {
//カメラのパラメータを作成する
CVector e, c, u;//視点、注視点、上方向
//視点を求める
e = CVector(-2.0f, 10.0f, -30.0f);
//注視点を求める
c = CVector();
//上方向を求める
u = CVector(0.0f, 1.0f, 0.0f);
//カメラクラスの設定
Camera.Set(e, c, u);
Camera.Render();
CRes::sBackGround.Render(CMatrix());
//2D描画開始
Start2D(0, 800, 0, 600);
CText::DrawString("PLAYER DAMAGE ", 20, 50, 10, 12);
CText::DrawString("AIRBASE DAMAGE", 20, 20, 10, 12);
//2D描画終了
End2D();
return;
}
//2D描画スタート
//Start2D(左座標, 右座標, 下座標, 上座標)
void CSceneGame::Start2D(float left, float right, float bottom, float top) {
//モデルビュー行列の退避
glPushMatrix();
//モデルビュー行列の初期化
glLoadIdentity();
//モデルビュー行列から
//プロジェクション行列へ切り替え
glMatrixMode(GL_PROJECTION);
//プロジェクション行列の退避
glPushMatrix();
//プロジェクション行列の初期化
glLoadIdentity();
//2D描画の設定
gluOrtho2D(left, right, bottom, top);
//Depthテストオフ
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glColor3f(1.0f, 1.0f, 1.0f);
}
//2D描画終了
void CSceneGame::End2D() {
//プロジェクション行列を戻す
glPopMatrix();
//モデルビューモードへ切り替え
glMatrixMode(GL_MODELVIEW);
//モデルビュー行列を戻す
glPopMatrix();
//Depthテストオン
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "InteractableActor.h"
#include "Components/BoxComponent.h"
// Sets default values
AInteractableActor::AInteractableActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AInteractableActor::BeginPlay()
{
Super::BeginPlay();
this->Tags.Add(FName(TEXT("Interactor")));
LoadMesh();
AttachCollider();
}
// Called when interacted with
bool AInteractableActor::Interact(UObjectInfo* info)
{
return InteractorComponent->InteractWith(info);
}
// Called when tried to be picked up with
bool AInteractableActor::PickUp()
{
return InteractorComponent->PickUp();
}
void AInteractableActor::LoadMesh() {
if (!MeshComponent && !Info->MeshReference.Equals("")) {
UStaticMeshComponent* SMeshComponent = NewObject<UStaticMeshComponent>(this, UStaticMeshComponent::StaticClass(), TEXT("MeshComponent"));
UStaticMesh* Mesh = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, *Info->MeshReference));
if (Mesh)
{
SMeshComponent->SetStaticMesh(Mesh);
}
MeshComponent = SMeshComponent;
if (SMeshComponent) {
SMeshComponent->RegisterComponent();
SMeshComponent->SetRelativeLocation(FVector(0, 0, 0));
SMeshComponent->SetRelativeRotation(FRotator());
SMeshComponent->AttachTo(RootComponent, NAME_None, EAttachLocation::KeepRelativeOffset);
}
}
}
void AInteractableActor::AttachCollider() {
if (MeshComponent) {
/*
UBoxComponent* BoxComponent = NewObject<UBoxComponent>(this, UBoxComponent::StaticClass(), TEXT("BoxComponent"));
if (BoxComponent) {
BoxComponent->RegisterComponent();
BoxComponent->SetRelativeLocation(FVector());
BoxComponent->SetRelativeRotation(FRotator());
BoxComponent->AttachToComponent(MeshComponent, FAttachmentTransformRules::KeepRelativeTransform);
}*/
}
}
void AInteractableActor::PlaySound(FString soundName, FVector location) {
}
|
#pragma once
class BinkManager {
public:
static void Render();
static void Close();
};
|
#include "GameController.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <random>
#include <algorithm>
#define STATUS_OK 0
#define STATUS_INVALID 1
#define STATUS_QUIT 2
#define STATUS_TERMINATE 3
Game::Game()
: m_nRows(6)
, m_nCols(6)
, m_nCurrentPlayer(0)
{
}
Game::~Game()
{
}
void Game::Start()
{
PrintWelcome();
int select = Menu();
while (select)
{
if (select == 1)
{
NewGame();
RunGame();
select = 0;
}
else if (select == 2)
{
if (LoadGame())
{
RunGame();
select = 0;
}
else
{
select = Menu();
}
}
else if (select == 3)
{
ShowStudentInfo();
select = Menu();
}
else if (select == 4)
{
Quit();
select = 0;
}
else if (select == 5)
{
NewGameAI();
RunGame();
select = 0;
}
}
}
void Game::RunGame()
{
int status = STATUS_OK;
while (status == STATUS_OK)
{
status = Round();
}
if (status == STATUS_TERMINATE) EndGame();
Quit();
}
void Game::PrintWelcome()
{
std::cout << "Welcome to Qwirkle!\n---------------------\n" << std::endl;
}
std::string Game::UserPrompt()
{
std::cout << "> ";
std::string str;
std::getline(std::cin, str);
std::cout << std::endl;
return str;
}
void Game::PrintInvalid()
{
std::cout << "Invalid Input" << std::endl;
}
int Game::Menu()
{
std::cout << "Menu\n----\n1. New Game\n2. Load Game\n3. Show student information\n4. Quit\n5. Play with AI\n" << std::endl;
int select = 0;
while (!select)
{
std::string num = UserPrompt();
select = atoi(num.c_str());
if (select < 1 || select>5)
{
if (num.compare("^D") == 0 ) {
int status = STATUS_QUIT;
return status;
}
PrintInvalid();
select = 0;
}
}
return select;
}
void Game::NewGame()
{
for (int i = 0; i < m_nRows; i++)
{
std::vector<Tile> row;
for (int j = 0; j < m_nCols; j++)
{
Tile tile; tile.colour = 0; tile.shape = 0;
row.push_back(tile);
}
m_board.push_back(row);
}
std::cout << "Starting a New Game\n" << std::endl;
for (int i = 0; i < 2; i++)
{
Player player; player.score = 0;
bool legal = false;
while (!legal)
{
legal = true;
std::cout << "Enter a name for player " << i + 1 << " (uppercase characters only)" << std::endl;
player.name = UserPrompt();
if (player.name.compare("^D") == 0) {
Quit();
return;
}
if (player.name.empty()) legal = false;
else
{
for (auto c : player.name)
{
if (c<'A' || c>'Z')
legal = false;
}
}
if (!legal) PrintInvalid();
}
m_players.push_back(player);
}
std::cout << "\nLet's Play!\n" << std::endl;
Shuffle();
for (int i = 0; i < 2; i++)
{
m_players[i].ClearHand();
m_players[i].Drawn(&m_bag, 6);
}
}
//Gao,Player name
void Game::NewGameAI()
{
for (int i = 0; i < m_nRows; i++)
{
std::vector<Tile> row;
for (int j = 0; j < m_nCols; j++)
{
Tile tile; tile.colour = 0; tile.shape = 0;
row.push_back(tile);
}
m_board.push_back(row);
}
std::cout << "Starting a New Game\n" << std::endl;
//create human
{
Player player; player.score = 0;
bool legal = false;
while (!legal)
{
legal = true;
std::cout << "Enter your name(uppercase characters only)" << std::endl;
player.name = UserPrompt();
if (player.name.compare("^D") == 0) {
Quit();
return;
}
if (player.name.empty()) legal = false;
else
{
for (auto c : player.name)
{
if (c<'A' || c>'Z')
legal = false;
}
}
if (!legal) PrintInvalid();
}
m_players.push_back(player);
}
//create computer
{
Player player; player.score = 0; player.name = "COMPUTER"; player.m_isAI = true;
m_players.push_back(player);
}
std::cout << "\nLet's Play!\n" << std::endl;
Shuffle();
for (int i = 0; i < 2; i++)
{
m_players[i].ClearHand();
m_players[i].Drawn(&m_bag, 6);
}
}
// Gao, Create AI base on rule
bool Game::LoadGame()
{
std::cout << "Enter the filename from which load a game" << std::endl;
std::string file = UserPrompt();
file.erase(0, file.find_first_not_of(" "));
file.erase(file.find_last_not_of(" ") + 1);
std::ifstream is; is.open(file);
if (!is)
{
std::cout << "Can not load the game!\n" << std::endl;
return false;
}
else
{
std::string line;
m_players.clear();
for (int i = 0; i < 2; i++)
{
Player player; m_players.push_back(player);
}
for (int i = 0; i < 2; i++)
{
std::getline(is, m_players[i].name);
std::getline(is, line); m_players[i].score = atoi(line.c_str());
std::string strHand; std::getline(is, strHand);
size_t left = 0;
while (left < strHand.length())
{
std::string strTile = strHand.substr(left, 2);
m_players[i].hand.AddTail(strTile[0], strTile[1] - '0');
left += 3;
}
}
std::getline(is, line); std::getline(is, line);
bool reading_board = true;
int i = 0;
while (reading_board)
{
std::getline(is, line);
size_t index = line.find("|");
if ((int)index == -1) reading_board = false;
else
{
int j = 0;
std::vector<Tile> row;
while (index + 2 < line.length())
{
Tile tile; tile.colour = 0; tile.shape = 0;
if (line[index + 1] != ' ')
{
tile.colour = line[index + 1];
tile.shape = line[index + 2] - '0';
}
row.push_back(tile);
j++; index += 3;
}
m_board.push_back(row);
}
i++;
}
if (m_board.size())
{
m_nRows = m_board.size();
m_nCols = m_board[0].size();
}
size_t index = 0;
while (index < line.length())
{
m_bag.AddTail(line[index], line[index + 1] - '0');
index += 3;
}
std::getline(is, line);
for (size_t i = 0; i < m_players.size(); i++)
{
if (m_players[i].name.compare(line) == 0)
m_nCurrentPlayer = i;
}
std::cout << "Qwirkle game successfully loaded\n" << std::endl;
return true;
}
}
void Game::ShowStudentInfo()
{
struct Student
{
std::string m_name, m_studentID, m_email;
Student(std::string Name, std::string StudentID, std::string Email) { m_name = Name; m_studentID = StudentID; m_email = Email; }
void Print() { std::cout << "Name:" << m_name << "\nStudent ID:" << m_studentID << "\nEmail:" << m_email << std::endl; }
};
std::vector<Student> students;
students.push_back(Student("Oscar", "3562697", "s3562697@student.rmit.edu.au"));
students.push_back(Student("Jack", "3661033", "s3661033@student.rmit.edu.au"));
students.push_back(Student("Cryil", "3579811", "s3579811@student.rmit.edu.au"));
students.push_back(Student("Jason", "3566690", "s3566690@student.rmit.edu.au"));
std::cout << "----------------------------------" << std::endl;
for (size_t i = 0; i < students.size(); i++)
{
students[i].Print();
if (i + 1 < students.size()) std::cout << std::endl;
}
std::cout << "----------------------------------\n" << std::endl;
}
int Game::Quit()
{
std::cout << "Goodbye" << std::endl;
int status = STATUS_QUIT;
return status;
}
int Game::Round()
{
while (m_nCurrentPlayer < m_players.size())
{
Player &p = m_players[m_nCurrentPlayer];
if (p.hand.size() == 0) return STATUS_TERMINATE;
std::cout << p.name << ", it's your turn" << std::endl;
PrintScores();
PrintBoard();
std::cout << "Your hand is" << std::endl;
p.hand.PrintContent();
std::cout << std::endl;
if (p.m_isAI)
{
std::vector<Tile> tiles; p.hand.GetContent(tiles);
Tile tileChoose = tiles[0];
int scoreMax = 0, row = 0, col = 0;
for (unsigned int t = 0; t < tiles.size(); t++)
{
for (int i = 0; i < m_nRows; i++)
{
for (int j = 0; j < m_nCols; j++)
{
if (m_board[i][j].shape == 0)
{
m_board[i][j].colour = tiles[t].colour;
m_board[i][j].shape = tiles[t].shape;
if (PlaceCheck(i, j))
{
bool isqwirkle;
int score = CalcScore(i, j, isqwirkle);
if (scoreMax < score)
{
scoreMax = score;
tileChoose = tiles[t];
row = i;
col = j;
}
}
m_board[i][j].colour = 0;
m_board[i][j].shape = 0;
}
}
}
}
if (scoreMax == 0)
{
std::cout << "COMPUTER replace " << tiles[0].colour << tiles[0].shape << std::endl;
ReplaceTile(p, tiles[0]);
}
else
{
char r = 'A' + row;
std::cout << "COMPUTER place " << tileChoose.colour << tileChoose.shape << " at " << r << col << std::endl << std::endl;
PlaceTile(p, tileChoose, row, col);
}
}
else
{
int status = STATUS_INVALID;
while (status != STATUS_OK)
{
std::string cmd = UserPrompt();
status = ParseCmd(cmd, p);
if (status == STATUS_QUIT || status == STATUS_TERMINATE) return status;
if (status == STATUS_INVALID) PrintInvalid();
}
}
m_nCurrentPlayer++;
}
m_nCurrentPlayer = 0;
return STATUS_OK;
}
void Game::PrintScores()
{
for (size_t i = 0; i < m_players.size(); i++)
{
std::cout << "Score for " << m_players[i].name << ": " << m_players[i].score << std::endl;
}
}
//Gao, display score
void Game::PrintBoard()
{
std::cout << " ";
for (int i = 0; i < m_nCols; i++)
{
if (i < 10)
std::cout << i << " ";
else
std::cout << i << " ";
}
std::cout << std::endl;
for (int i = 0; i < m_nCols + 1; i++)
{
std::cout << "---";
}
std::cout << std::endl;
for (size_t i = 0; i < m_board.size(); i++)
{
char c = 'A' + short(i);
std::cout << c << " |";
for (auto t : m_board[i])
{
if (t.colour)
{
std::cout << t.colour << t.shape << "|";
}
else
{
std::cout << " |";
}
}
std::cout << std::endl;
}
std::cout << std::endl;
}
void Game::SaveBoard(std::ofstream &os)
{
os << " ";
for (size_t i = 0; i < m_board.size(); i++)
{
os << i << " ";
}
os << std::endl;
for (size_t i = 0; i < m_board.size() + 1; i++)
{
os << "---";
}
os << std::endl;
for (size_t i = 0; i < m_board.size(); i++)
{
char c = 'A' + short(i);
os << c << " |";
for (auto t : m_board[i])
{
if (t.colour)
{
os << t.colour << t.shape << "|";
}
else
{
os << " |";
}
}
os << std::endl;
}
}
void Game::Shuffle()
{
char colour[6] = { 'R' ,'O' ,'Y' ,'G' ,'B' ,'P' };
std::vector<Tile> pool;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
Tile tile;
tile.colour = colour[i];
tile.shape = j + 1;
pool.push_back(tile);
pool.push_back(tile);
}
}
m_bag.Clear();
std::default_random_engine e;
std::uniform_int_distribution<unsigned> id(0, 71);
std::random_device device;
e.seed(device());
while (!pool.empty())
{
int index = id(e) % pool.size();
Tile t = pool[index];
m_bag.AddTail(t.colour, t.shape);
pool.erase(pool.begin() + index);
}
}
void Game::EndGame()
{
std::string winner;
int max = 0;
std::cout << "Game over" << std::endl;
for (size_t i = 0; i < m_players.size(); i++)
{
if (max < m_players[i].score)
{
winner = m_players[i].name;
max = m_players[i].score;
}
std::cout << "Score for " << m_players[i].name << ": " << m_players[i].score << std::endl;
}
std::cout << "Player " << winner << " won!\n" << std::endl;
}
int Game::ParseCmd(std::string cmd, Player &player)
{
if (cmd.compare("^D") == 0 ) return STATUS_QUIT;
int index = cmd.find(' ');
if (cmd.find("place ") == 0)
{
int c = cmd.find("at");
if (c == -1) return STATUS_INVALID;
std::string strTile = cmd.substr(index + 1, c - index - 2);
std::string strPlace = cmd.substr(c + 3, cmd.length() - c - 3);
Tile tile; if (!ParseTile(strTile, tile)) return STATUS_INVALID;
int row, col; if (!ParsePlace(strPlace, row, col)) return STATUS_INVALID;
return PlaceTile(player, tile, row, col);
}
else if (cmd.find("replace ") == 0)
{
std::string strTile = cmd.substr(index + 1, cmd.length() - index);
Tile tile; if (!ParseTile(strTile, tile)) return STATUS_INVALID;
return ReplaceTile(player, tile);
}
else if (cmd.find("save ") == 0)
{
std::string fileName = cmd.substr(index + 1, cmd.length() - index);
fileName.erase(0, fileName.find_first_not_of(" "));
fileName.erase(fileName.find_last_not_of(" ") + 1);
std::ofstream os; os.open(fileName);
if (!os) return STATUS_INVALID;
for (size_t i = 0; i < m_players.size(); i++)
{
os << m_players[i].name << std::endl;
os << m_players[i].score << std::endl;
m_players[i].hand.SaveContent(os);
}
SaveBoard(os);
m_bag.SaveContent(os);
os << player.name << std::endl;
os.close();
std::cout << "Game successfully saved\n" << std::endl;
return STATUS_OK;
}
return STATUS_INVALID;
}
bool Game::ParseTile(std::string strTile, Tile& tile)
{
if (strTile.size() != 2) return false;
Colour c = strTile[0];
if (c != 'R'&&c != 'O'&&c != 'Y'&&c != 'G'&&c != 'B'&&c != 'P') return false;
int shape = strTile[1] - '0';
if (shape < 1 || shape>6) return false;
tile.colour = c;
tile.shape = shape;
return true;
}
bool Game::ParsePlace(std::string strPlace, int& row, int& col)
{
row = strPlace[0] - 'A';
if (row < 0 || row > m_nRows) return false;
for (size_t i = 1; i < strPlace.length(); i++)
{
if (strPlace[i]<'0' || strPlace[i]>'9') return false;
}
col = atoi(strPlace.substr(1, strPlace.length() - 1).c_str());
if (col < 0 || col>m_nCols) return false;
return true;
}
int Game::ReplaceTile(Player & player, Tile & tile)
{
if (m_bag.size() == 0) return STATUS_INVALID;
else
{
Node * node = player.hand.Extract(tile.colour, tile.shape);
if(node==nullptr) return STATUS_INVALID;
m_bag.AddTail(node);
player.Drawn(&m_bag, 1);
return STATUS_OK;
}
}
//Gao, change the tile from pBag
int Game::PlaceTile(Player& player, Tile& tile, int row, int col)
{
if (player.hand.size() == 0) return STATUS_TERMINATE;
if (m_board[row][col].colour != 0) return STATUS_INVALID;
m_board[row][col].colour = tile.colour;
m_board[row][col].shape = tile.shape;
if (!PlaceCheck(row, col))
{
m_board[row][col].colour = 0;
m_board[row][col].shape = 0;
return STATUS_INVALID;
}
if (!player.Discard(tile.colour, tile.shape)) return STATUS_INVALID;
else
{
bool qwirkle;
player.score += CalcScore(row, col, qwirkle);
if (qwirkle) std::cout << "QWIRKLE!!!\n" << std::endl;
player.Drawn(&m_bag, 1);
if (row == 0) ExpandBoard(0);
if (row == m_nRows - 1) ExpandBoard(1);
if (col == 0) ExpandBoard(2);
if (col == m_nCols - 1) ExpandBoard(3);
return STATUS_OK;
}
}
//place tile on borad,Gao
bool Game::PlaceCheck(int row, int col)
{
Shape shape = m_board[row][col].shape;
Colour colour = m_board[row][col].colour;
int type = -1;
//type = 0 when above have tile but not same color
if (row - 1 >= 0 && m_board[row - 1][col].shape)
{
type = 0;
//type = 1 when above tile has same color
if (colour == m_board[row - 1][col].colour) type = 1;
}
//type = 0 when below have tile
else if (row + 1 < m_nRows && m_board[row + 1][col].shape)
{
type = 0;
//type = 1 when below have same colour
if (colour == m_board[row + 1][col].colour) type = 1;
}
if (type != -1)
{
//Down to top
int i = row - 1, count = 1;
while (i >= 0 && m_board[i][col].shape)
{
//First or means shape the same and color different with above one, but if same color happen again though out the line above the above one, then return false
//Second or means if above have shape with different color and their shape is defferet as well, return false
if ((m_board[i][col].colour == colour || m_board[i][col].shape != shape) && type == 0) return false;
//Third ir means same color with above one with different shape, but if different color and same shape happen though out the above line, then return false
//Forth or means if above has same shape and same color then return false
if ((m_board[i][col].colour != colour || m_board[i][col].shape == shape) && type == 1) return false;
count++;
i--;
}
i = row + 1;
while (i < m_nRows && m_board[i][col].shape)
{
if ((m_board[i][col].colour == colour || m_board[i][col].shape != shape) && type == 0) return false;
if ((m_board[i][col].colour != colour || m_board[i][col].shape == shape) && type == 1) return false;
count++;
i++;
}
if (count > 6) return false;
}
type = -1;
if (col - 1 >= 0 && m_board[row][col - 1].shape)
{
type = 0;
if (colour == m_board[row][col - 1].colour) type = 1;
}
else if (col + 1 < m_nCols && m_board[row][col + 1].shape)
{
type = 0;
if (colour == m_board[row][col + 1].colour) type = 1;
}
if (type != -1)
{
int i = col - 1, count = 1;
while (i >= 0 && m_board[row][i].shape)
{
if ((m_board[row][i].colour == colour || m_board[row][i].shape != shape) && type == 0) return false;
if ((m_board[row][i].colour != colour || m_board[row][i].shape == shape) && type == 1) return false;
count++;
i--;
}
i = col + 1;
while (i < m_nCols && m_board[row][i].shape)
{
if ((m_board[row][i].colour == colour || m_board[row][i].shape != shape) && type == 0) return false;
if ((m_board[row][i].colour != colour || m_board[row][i].shape == shape) && type == 1) return false;
count++;
i++;
}
if (count > 6) return false;
}
return true;
}
int Game::CalcScore(int row, int col,bool& qwirkle)
{
qwirkle = false;
int score = 0, count = 1, i = row - 1;
while (i >= 0 && m_board[i][col].shape)
{
count++;
i--;
}
i = row + 1;
while (i < m_nRows && m_board[i][col].shape)
{
count++;
i++;
}
if (count > 1)score += count;
if (count == 6) { score += 6; qwirkle = true; }
i = col - 1; count = 1;
while (i >= 0 && m_board[row][i].shape)
{
count++;
i--;
}
i = col + 1;
while (i < m_nCols && m_board[row][i].shape)
{
count++;
i++;
}
if (count > 1)score += count;
if (count == 6) { score += 6; qwirkle = true; }
return score;
}
void Game::ExpandBoard(int direction)
{
std::vector<std::vector<Tile>> copy;
if (direction == 0 && m_nRows<26)
{
std::vector<Tile> row;
for (int j = 0; j < m_nCols; j++)
{
Tile tile; tile.colour = 0; tile.shape = 0;
row.push_back(tile);
}
copy.push_back(row);
for (int i = 0; i < m_nRows; i++)
{
copy.push_back(m_board[i]);
}
m_nRows++;
m_board.swap(copy);
}
else if (direction == 1 && m_nRows<26)
{
for (int i = 0; i < m_nRows; i++)
{
copy.push_back(m_board[i]);
}
std::vector<Tile> row;
for (int j = 0; j < m_nCols; j++)
{
Tile tile; tile.colour = 0; tile.shape = 0;
row.push_back(tile);
}
copy.push_back(row);
m_nRows++;
m_board.swap(copy);
}
else if (direction == 2 && m_nCols<26)
{
for (int i = 0; i < m_nRows; i++)
{
std::vector<Tile> row;
Tile tile; tile.colour = 0; tile.shape = 0;
row.push_back(tile);
for (int j = 0; j < m_nCols; j++)
{
row.push_back(m_board[i][j]);
}
copy.push_back(row);
}
m_nCols++;
m_board.swap(copy);
}
else if (direction == 3 && m_nCols<26)
{
for (int i = 0; i < m_nRows; i++)
{
Tile tile; tile.colour = 0; tile.shape = 0;
m_board[i].push_back(tile);
}
m_nCols++;
}
}
|
#pragma once
#include "ofMain.h"
class Stones
{
public:
Stones();
~Stones();
void init();
void render( std::vector< ofPolyline > closedLines, std::vector< float > transparencies, ofPoint centered );
ofFbo getBuffer();
private:
ofFbo buffer;
};
|
#include "stdafx.h"
#include <iostream>
#include "LT.h"
#include "Error.h"
namespace LT
{
LexTable Create(int size) //Создать ТЛ
{
LexTable* tabl = new LexTable;
if (size > LT_MAXSIZE)///4096
{
throw ERROR_THROW(113); ///Заданное количество строк в ТЛ > 4096
}
tabl->maxsize = size;
tabl->size = 0;
tabl->table = new Entry[size]; ///новая строка ТЛ
return *tabl;
}
void Add(LexTable& lextable, Entry entry) //Добавить строку в ТЛ
{
if (lextable.size + 1 > lextable.maxsize)
{
throw ERROR_THROW(114); ///Превышено количество строк в ТЛ
}
lextable.table[lextable.size] = entry;
lextable.size += 1;
}
Entry GetEntry(LexTable& lextable, int n) //Получить строку по №
{
return lextable.table[n];
}
void Delete(LexTable& lextable) //Удалить ТЛ
{
delete[] lextable.table;
//delete &lextable;
}
};
|
#pragma once
#include<iostream>
using namespace std;
#define MAXSIZE 128 //字符串的最大长度
class Astring
{
public:
Astring();
Astring(const char* init);
Astring(const Astring& ob); //复制构造函数
~Astring();
int Length()const; //返回字符串的长度
Astring operator()(int pos, int len); //指出从pos-1开始到pos+len-1的字符串
int operator==(Astring& ob); //判断两串是否相等
int operator!=(Astring& ob); //判断两串是否不等
Astring& operator=(Astring& ob); //字符串赋值
Astring operator+=(Astring& ob); //把串ob接在串*this后面
Astring operator+(Astring& ob);
char& operator[](int i); //取第i个字符
int Find(Astring& pat)const; //字符串匹配(BF算法)
int find(Astring& pat)const; //字符串匹配(KMP算法)
private:
char* ch; //串存放数组
int charLen; //串的实际长度
int maxSize; //存放数组的最大长度
};
ostream& operator<<(ostream& cout, Astring& ob);//左移运算
//不会利用成员函数重载<<运算符,因为无法实现cout<<在左边
|
#ifndef WALI_WFA_DETERMINIZE_WEIGHT_GEN_HPP
#define WALI_WFA_DETERMINIZE_WEIGHT_GEN_HPP
#include "wali/Key.hpp"
#include "wali/SemElem.hpp"
#include <set>
#include <map>
namespace wali {
namespace wfa {
class WFA;
class ITrans;
class DeterminizeWeightGen
{
public:
typedef std::map<Key, sem_elem_t> AccessibleStateMap;
/// For each state 's' in 'source' and each 't' in 'target', the
/// computed weight spec will hold the net weight from 's' to 't'
/// including the first transition for the symbol in question and any
/// epsilon paths.
typedef std::map<Key, AccessibleStateMap> ComputedWeights;
virtual ~DeterminizeWeightGen() {}
/// Returns the weight for the transition from the source to target
/// state, given as the set of states in the nondeterministic automaton
/// that correspond. Both the original and partial determinized
/// automata are provided.
virtual sem_elem_t getWeight(WFA const & original_wfa,
WFA const & determinized_wfa_so_far,
ComputedWeights const & weight_spec,
std::set<Key> const & source,
Key symbol,
std::set<Key> const & target) const
= 0;
virtual sem_elem_t getAcceptWeight(WFA const & original_wfa,
WFA const & determinized_wfa_so_far,
std::set<Key> const & cell) const
= 0;
virtual sem_elem_t getOne(WFA const & original_wfa) const = 0;
};
/// Provides a class that computes the weight for a determinized
/// transition by creating a KeyedSemElemSet where the key marks the
/// endpoints of the transition.
///
/// The accept weight of a state is the set of accept weights of its
/// constituant states, guarded by the id transition on that state only.
class CreateKeyedSet
: public DeterminizeWeightGen
{
sem_elem_t getWeight(WFA const & original_wfa,
WFA const & UNUSED_PARAMETER(determinized_wfa_so_far),
ComputedWeights const & weight_spec,
std::set<Key> const & sources,
Key symbol,
std::set<Key> const & targets) const;
sem_elem_t getAcceptWeight(WFA const & original_wfa,
WFA const & determinized_wfa_so_far,
std::set<Key> const & cell) const;
sem_elem_t getOne(WFA const & original_wfa) const;
};
/// Provides a class that computes the weight for a determinizied
/// transition as follows. Given a transition from S to T (both sets of
/// states in the nondeterministic WFA), it looks at all edges (in the
/// nondeterministic machine) from any state in S to any state in T with
/// the appropriate symbol, collects up all those weights, calls
/// 'liftWeight' with each of them, and then 'combines' the result.
class LiftCombineWeightGen
: public DeterminizeWeightGen
{
/// Overload to return the lifted weight for a nondeterministic
/// transition.
virtual sem_elem_t liftWeight(WFA const & original_wfa,
Key source,
Key symbol,
Key target,
sem_elem_t weight) const
= 0;
virtual sem_elem_t liftAcceptWeight(WFA const & original_wfa,
Key state,
sem_elem_t original_accept_weight) const
= 0;
virtual sem_elem_t getOne(WFA const & original_wfa) const = 0;
sem_elem_t getWeight(WFA const & original_wfa,
WFA const & UNUSED_PARAMETER(determinized_wfa_so_far),
ComputedWeights const & weight_spec,
std::set<Key> const & sources,
Key symbol,
std::set<Key> const & targets) const;
virtual sem_elem_t getAcceptWeight(WFA const & original_wfa,
WFA const & determinized_wfa_so_far,
std::set<Key> const & cell) const;
};
class AlwaysReturnOneWeightGen
: public DeterminizeWeightGen
{
sem_elem_t const one;
public:
AlwaysReturnOneWeightGen(sem_elem_t some_weight)
: one(some_weight->one())
{}
virtual sem_elem_t getWeight(WFA const & UNUSED_PARAMETER(original_wfa),
WFA const & UNUSED_PARAMETER(determinized_wfa_so_far),
ComputedWeights const & UNUSED_PARAMETER(weight_spec),
std::set<Key> const & UNUSED_PARAMETER(source),
Key UNUSED_PARAMETER(symbol),
std::set<Key> const & UNUSED_PARAMETER(target)) const
{
return one;
}
virtual sem_elem_t getAcceptWeight(WFA const & UNUSED_PARAMETER(original_wfa),
WFA const & UNUSED_PARAMETER(determinized_wfa_so_far),
std::set<Key> const & UNUSED_PARAMETER(cell)) const
{
return one;
}
virtual sem_elem_t getOne(WFA const & UNUSED_PARAMETER(original_wfa)) const
{
return one;
}
};
}
}
// Yo emacs!
// Local Variables:
// c-file-style: "ellemtel"
// c-basic-offset: 2
// indent-tabs-mode: nil
// End:
#endif
|
// SPOJ HIST2
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define oo 1000000000
int A[16];
int DP[16][1<<16];
int cnt[16][1<<16];
int n;
int solve(int c, int mask)
{
if(DP[c][mask]!=-1)return DP[c][mask];
int res = 0;
int ways = 1;
for(int i=0; i<n; i++)
if((mask & (1<<i))==0)
{
int nmask = mask | (1<<i);
if(nmask==(1<<n)-1) //last one
{
int val = abs(A[i]-A[c]) + 2 + A[i];
if(val > res)res=val,ways=1;
else if(val==res)ways++;
}
else
{
int val = abs(A[i]-A[c]) + 2 + solve(i,nmask);
if(val > res)res=val,ways=cnt[i][nmask];
else if(val==res)ways+=cnt[i][nmask];
}
}
cnt[c][mask]=ways;
return DP[c][mask]=res;
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);
while(cin>>n && n>0)
{
for(int i=0; i<n; i++)
cin>>A[i];
for(int i=0; i<n; i++)
for(int j=0; j<(1<<n); j++)
DP[i][j]=-1;
int res = 0, ways = 0;
for(int i=0; i<n; i++)
{
int val = solve(i,(1<<i)) + A[i] + 2;
if(val > res)res=val,ways=cnt[i][(1<<i)];
else if(val==res)ways+=cnt[i][(1<<i)];
}
cout<<res<<" "<<ways<<"\n";
}
}
|
#include <iostream>
#include <GL/glut.h>
#include "Ising_simulator.hpp"
#include "spin.hpp"
#include "Ising_simulator_traits.hpp"
#include "Ising_window_traits.hpp"
#include "Ising_draw_func.hpp"
#include "Ising_model_parameters.hpp"
#include "Ising_global_variable.hpp"
int main(int argc, char *argv[]){
Ising_simulator_ptr = new simulator_type
(random_seed, tempreture, magnetic_flux_density, spin_interaction);
Ising_field_ptr = &(Ising_simulator_ptr->spins_state());
set_canvas<Ising_window_traits>(argc ,argv);
update_canvas(true);
update_roop();
delete Ising_simulator_ptr;
return 0;
}
|
#include <stdio.h>
#include <iostream>
#include "Chaine.hpp"
void annexe(const Chaine &s) {
std::cout << s.taille() << std::endl;
//std::printf("%d\n", s.taille());
}
Chaine print(Chaine s){
s.debug();
return s;
}
void main1(){
Chaine chaine("Une petite");
chaine.debug();
annexe(chaine);
}
void main2(){
Chaine s1("Hello");
Chaine s2(s1);
Chaine s3 = s1; //les donnees pointes à la mm adresse
s1.debug();
s2.debug();
s3.debug();
}
void main3(){
Chaine c("Message");
print(c);
}
int main() {
Chaine s1("hello");
Chaine s2("coucou");
Chaine s3 = s1+s2;
s3.debug();
s2 = s1;
s2.debug();
s1[3] = 'Z';
for(unsigned int i = 0; i<s1.taille(); ++i)
printf("%c ",s1[i]);
printf("\n");
printf("%s\n", (const char*)s3);
return 0;
}
|
#include <QWidget>
#include <CXYVals.h>
class CQXYValsTest;
class CQXYValsCanvas : public QWidget {
Q_OBJECT
public:
CQXYValsCanvas(CQXYValsTest *text);
private:
void paintEvent(QPaintEvent *);
void mousePressEvent (QMouseEvent *me);
void mouseMoveEvent (QMouseEvent *me);
void mouseReleaseEvent(QMouseEvent *me);
void keyPressEvent(QKeyEvent *);
void updatePolygons();
void getPolygons();
QPolygon toQPolygon(const CXYVals::Polygon &polygon) const;
private:
typedef std::vector<QPolygon> Polygons;
struct ValueData {
CXYValsInside xyvals;
CXYValsInside::Polygons ipolygons;
CXYValsInside::Polygons opolygons;
Polygons iqpolygons;
Polygons oqpolygons;
};
CQXYValsTest* test_;
ValueData valueData_;
ValueData valueData1_;
bool pressed_ { false };
QPoint pressPos_;
QPoint releasePos_;
};
class CQXYValsTest : public QWidget {
Q_OBJECT
public:
CQXYValsTest();
private:
CQXYValsCanvas *canvas_;
};
|
#include <iostream>
using namespace std;
unsigned int odd_bits = 0;
unsigned int even_bits = 0;
void init() {
for (int i = 0; i < 32; i++) {
if ((i % 2) == 0) {
even_bits |= (1 << i);
} else {
odd_bits |= (1 << i);
}
}
}
int pairwise_swap(int n) {
return ((n & odd_bits) >> 1) | ((n & even_bits) << 1);
}
int main() {
init();
cout << pairwise_swap(-1) << endl;
cout << pairwise_swap(0) << endl;
cout << pairwise_swap(1) << endl;
cout << pairwise_swap(2) << endl;
cout << pairwise_swap(-2) << endl;
cout << pairwise_swap(-3) << endl;
}
|
#include <maker_robot/robot_hardware_interface.h>
#include <std_msgs/UInt16.h>
//namesapce i2c_ros
ROBOTHardwareInterface::ROBOTHardwareInterface(ros::NodeHandle& nh) : nh_(nh),linear_(1),angular_(2) {
init();
// joy
nh_.param("axis_linear", linear_, linear_);
nh_.param("axis_angular", angular_, angular_);
nh_.param("scale_angular", a_scale_, a_scale_);
nh_.param("scale_linear", l_scale_, l_scale_);
controller_manager_.reset(new controller_manager::ControllerManager(this, nh_));
loop_hz_=10;
ros::Duration update_freq = ros::Duration(1.0/loop_hz_);
right_client = nh_.serviceClient<three_dof_planar_manipulator::Floats_array>("right_joint_states");
left_client = nh_.serviceClient<three_dof_planar_manipulator::Floats_array>("left_joint_states");
pub_right = nh_.advertise<rospy_tutorials::Floats>("/joint_right_to_aurdino",10);
pub_left = nh_.advertise<rospy_tutorials::Floats>("/joint_left_to_aurdino",10);
//pwm_to_arduino = nh_.advertise<std_msgs::UInt16_t>("/pwm_to_arduino",1);
pwm_to_arduino = nh_.advertise<std_msgs::UInt16>("/pwm_to_arduino",10);
non_realtime_loop_ = nh_.createTimer(update_freq, &ROBOTHardwareInterface::update, this);
joy_sub_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &ROBOTHardwareInterface::joyCallback, this);
//move_base_sub_ = nh_.subscribe<move_base_msgs::MoveBaseAction>("move_base/status",10,&ROBOTHardwareInterface::moveBaseCallback, this);
move_base_sub_ = nh.subscribe<actionlib_msgs::GoalStatusArray>("/move_base/status", 10, &ROBOTHardwareInterface::navStatusCallBack,this);
}
ROBOTHardwareInterface::~ROBOTHardwareInterface() {
}
void ROBOTHardwareInterface::init() {
for(int i=0; i< JOINT_NUM; i++)
{
// Create joint state interface
hardware_interface::JointStateHandle jointStateHandle(joint_name_[i], &joint_position_[i], &joint_velocity_[i], &joint_effort_[i]);
joint_state_interface_.registerHandle(jointStateHandle);
// Create velocity joint interface
hardware_interface::JointHandle jointVelocityHandle(jointStateHandle, &joint_velocity_command_[i]);
velocity_joint_interface_.registerHandle(jointVelocityHandle);
// Create Joint Limit interface
joint_limits_interface::JointLimits limits;
joint_limits_interface::getJointLimits(joint_name_[i], nh_, limits);
joint_limits_interface::VelocityJointSaturationHandle jointLimitsHandle(jointVelocityHandle, limits);
velocityJointSaturationInterface.registerHandle(jointLimitsHandle);
}
// Register all joints interfaces
registerInterface(&joint_state_interface_);
registerInterface(&velocity_joint_interface_);
registerInterface(&velocityJointSaturationInterface);
}
void ROBOTHardwareInterface::update(const ros::TimerEvent& e) {
elapsed_time_ = ros::Duration(e.current_real - e.last_real);
read();
controller_manager_->update(ros::Time::now(), elapsed_time_);
write(elapsed_time_);
}
void ROBOTHardwareInterface::read() {
uint8_t rbuff[1];
int x;
right_joint_read.request.req=1.0;
left_joint_read.request.req=1.0;
/*
// left_motor.readBytes(rbuff,1);
x=0;//(int8_t)rbuff[0];
left_motor_pos+=angles::from_degrees((double)x);
joint_position_[0]=left_motor_pos;
right_motor.readBytes(rbuff,1);
x=(int8_t)rbuff[0];
right_motor_pos+=angles::from_degrees((double)x);
joint_position_[1]=right_motor_pos;
*/
//ROS_INFO("pos=%.2f x=%d ",pos,x);
if(right_client.call(right_joint_read))
{
// joint_right_position = angles::from_degrees(right_joint_read.response.res[0]);
// joint_left_velocity = angles::from_degrees(right_joint_read.response.res[1]);
right_motor_pos += angles::from_degrees((double)right_joint_read.response.res[0] );
joint_position_[2]=right_motor_pos ;
joint_position_[3]=right_motor_pos ;
// ROS_INFO("Right Pos: %.2f, %.2f ",right_joint_read.response.res[0],angles::from_degrees(right_joint_read.response.res[0]));
// right_motor_pos+=joint_right_position;
// joint_position_[0] = right_motor_pos;
// joint_position_[1] = joint_right_velocity;
/*
if more than one joint,
get values for joint_position_2, joint_velocity_2,......
*/
}
else
{
// joint_right_position = 0;
// joint_left_position = 0;
}
if(left_client.call(left_joint_read))
{
// joint_right_position = angles::from_degrees(left_joint_read.response.res[0]);
// joint_left_velocity = angles::from_degrees(left_joint_read.response.res[1]);
left_motor_pos += angles::from_degrees((double)left_joint_read.response.res[0] );
joint_position_[0]= left_motor_pos;
joint_position_[1]= left_motor_pos;
// ROS_INFO("Left Pos: %.2f, %.2f ",left_joint_read.response.res[0],left_joint_read.response.res[1]);
// joint_position_[0] = joint_left_position;
// joint_position_[1] = joint_left_velocity;
//
}
else
{
// joint_right_position = 0;
// joint_left_position = 0;
}
}
void ROBOTHardwareInterface::write(ros::Duration elapsed_time) {
velocityJointSaturationInterface.enforceLimits(elapsed_time);
uint8_t wbuff[2];
int velocity,result;
velocity=(int)angles::to_degrees(joint_velocity_command_[0]);
if( is_goal){
velocity =0;
}
wbuff[0]=velocity;
wbuff[1]=velocity >> 8;
// joints_pub.data.clear();
// joints_pub.data.push_back( velocity );
// joints_pub.data.push_back( velocity >> 8);
//ROS_INFO("joint_velocity_command_[0]=%.2f velocity=%d B1=%d B2=%d", joint_velocity_command_[0],velocity,wbuff[0],wbuff[1]);
if(left_prev_cmd!=velocity)
{
pub_left.publish(joints_pub);
result = 0 ;// left_motor.writeData(wbuff,2);
//ROS_INFO("Writen successfully result=%d", result);
left_prev_cmd=velocity;
ROS_INFO("Log1-LEFT wheel command %d , %d" , velocity , velocity>>8 );
}
velocity=(int)angles::to_degrees(joint_velocity_command_[2]);
if( is_goal){
velocity =0;
}
wbuff[0]=velocity;
wbuff[1]=velocity >> 8;
// joints_pub.data.clear();
// joints_pub.data.push_back( velocity );
// joints_pub.data.push_back( velocity >> 8);
//ROS_INFO("joint_velocity_command_[0]=%.2f velocity=%d B1=%d B2=%d", joint_velocity_command_[0],velocity,wbuff[0],wbuff[1]);
if(right_prev_cmd!=velocity)
{
pub_right.publish(joints_pub);
result = 0; // right_motor.writeData(wbuff,2);
//ROS_INFO("Writen successfully result=%d", result);
right_prev_cmd=velocity;
ROS_INFO("Log1-RIGHT wheel command %d , %d" , velocity , velocity>>8 );
}
}
void ROBOTHardwareInterface::joyCallback(const sensor_msgs::Joy::ConstPtr& joy)
{
int velocity;
uint8_t wbuff[2];
wbuff[0]=velocity;
wbuff[1]=velocity >> 8;
velocity=(int)angles::to_degrees(joint_velocity_command_[0]);
// joints_pub.data.clear();
// joints_pub.data.push_back( velocity );
// joints_pub.data.push_back( velocity >> 8);
ROS_INFO("JOY Message %d %d", wbuff[0] , wbuff[1] );
// turtlesim::Velocity vel;
// vel.angular = a_scale_*joy->axes[angular_];
// vel.linear = l_scale_*joy->axes[linear_];
// vel_pub_.publish(vel);
}
void ROBOTHardwareInterface::navStatusCallBack(const actionlib_msgs::GoalStatusArray::ConstPtr &status)
{
int velocity = 255;
int status_id = 0;
uint8_t wbuff[2];
std_msgs::UInt16 msg;
msg.data = 0;
if (!status->status_list.empty()){
actionlib_msgs::GoalStatus goalStatus = status->status_list[0];
status_id = goalStatus.status;
}
if( status_id == 3 ) // The goal was achieved successfully
{
// is_goal = true;
// velocity=(int)angles::to_degrees(joint_velocity_command_[0]);
// wbuff[0]=velocity;
// wbuff[1]=velocity >> 8;
// joints_pub.data.clear();
// joints_pub.data.push_back( velocity );
// joints_pub.data.push_back( velocity >> 8);
// pub_left.publish(joints_pub);
// pub_right.publish(joints_pub);
// pwm_to_arduino.publish(msg);
ROS_INFO("MoveBase -- The goal was achieved successfully");
}
ROS_INFO("MoveBase Action Message %d" , status_id );
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "mobile_robot_hardware_interface");
ros::NodeHandle nh;
//ros::AsyncSpinner spinner(4);
ros::MultiThreadedSpinner spinner(2); // Multiple threads for controller service callback and for the Service client callback used to get the feedback from ardiuno
ROBOTHardwareInterface ROBOT(nh);
//spinner.start();
spinner.spin();
//ros::spin();
return 0;
}
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define N 611111
int n, k, m;
int a[111][111], nx[111][111], ny[111][111], FX, FY;
int ans = 0;
void Calc(int x, int y, int mask, int nmask) {
if (x == FX && y == FY) {
/* for (int i =0; i < n; ++i) {
for (int j = 0; j < m; ++j) cerr << a[i][j] << " ";
cerr << endl;
}
cerr << endl;
*/
++ans;
return;
}
if (a[x][y] != -1) {
if (mask & (1 << a[x][y])) {
if (nx[x][y] == x + 1 && ny[x][y] == y - 1)
Calc(nx[x][y], ny[x][y], mask, nmask | (1 << a[x][y]));else
Calc(nx[x][y], ny[x][y], mask ^ (nmask | (1 << a[x][y])), 0);
}
else
return;
} else {
for (int i = 0; i < k; ++i)
if (mask & (1 << i)) {
// a[x][y] = i;
if (nx[x][y] == x + 1 && ny[x][y] == y - 1)
Calc(nx[x][y], ny[x][y], mask, nmask | (1 << i));else
Calc(nx[x][y], ny[x][y], mask ^ (nmask | (1 << i)), 0);
}
}
}
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
scanf("%d%d%d", &n, &m, &k);
if (n + m - 1 > k) {
puts("0");
return 0;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf("%d", &a[i][j]);
--a[i][j];
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (i + 1 < n && j - 1 >= 0) {
nx[i][j] = i + 1;
ny[i][j] = j - 1;
} else {
int tx = i + j + 1;
for (int ii = 0, f = 0; !f && ii < n; ++ii)
for (int jj = 0; !f && jj < m; ++jj) if (ii + jj == tx) {
nx[i][j] = ii;
ny[i][j] = jj;
f = 1;
break;
}
}
}
}
FX = nx[n - 1][m - 1] = n + 1;
FY = ny[n - 1][m - 1] = m + 1;
Calc(0, 0, (1 << k) - 1, 0);
cout << ans << endl;
return 0;
}
|
#ifndef LOGISTIC_LAYER_H_
#define LOGISTIC_LAYER_H_
#include "Layer.h"
class Logistic_layer: public Layer
{
public:
Logistic_layer(int dimension);
virtual ~Logistic_layer();
protected:
virtual MatrixXd act_func(MatrixXd input);
virtual MatrixXd act_func_g(MatrixXd input);
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef ACCESSIBILITY_TREE_ROOT_NODE_H
#define ACCESSIBILITY_TREE_ROOT_NODE_H
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
#include "modules/accessibility/acctree/AccessibilityTreeNode.h"
class AccessibilityTreeRootNode : public AccessibilityTreeNode
{
public:
AccessibilityTreeRootNode(AccessibleDocument* document);
// AccessibilityTreeNode
virtual OpAccessibleItem* GetAccessibleObject() const;
virtual const AccessibilityTreeNode* GetRoot() const {return this;}
virtual TreeNodeType NodeType() const;
};
#endif // ACCESSIBILITY_EXTENSION_SUPPORT
#endif // ACCESSIBILITY_TREE_ROOT_NODE_H
|
using ll = long long;
//n^kをmで割ったあまりを求める繰り返し二乗法
ll pow_mod(ll n, ll k, ll m){
ll r = 1;
//kの下の桁から処理。右シフトで処理し終わった桁を追い出す。
//ゼロになるまでやる
for(;k>0; k >>= 1){
if(k & 1) r = (r * n) % m; //kの一番下の桁のフラグが立っていたらnをかける
n = (n * n) % m; //次の桁の処理にむけてnを自乗しておく
}
return r;
}
|
#include "myclass.h"
#include <QThread>
#include <qpushbutton.h>
#include <pugixml.hpp>
MyClass::MyClass(QWidget *parent)
: QMainWindow(parent),
snapIndex(0)
{
ui.setupUi(this);
m_emHandler = new DR::EMHandler(this);
m_emHandler->connect();
m_leapHandler = new LeapHander();
m_leapHandler->moveToThread(&leapThread);
connect(this, &MyClass::deleteLeap, m_leapHandler, &QObject::deleteLater, Qt::QueuedConnection);
leapThread.start();
m_leapHandler->connect();
}
MyClass::~MyClass()
{
emit deleteLeap();
leapThread.wait();
}
void MyClass::takeSnapShoot(){
std::cout << "snapShoot" << std::endl;
pugi::xml_document doc;
pugi::xml_node frameNode = doc.append_child("Leap");
pugi::xml_node emNode = doc.append_child("EM");
m_leapHandler->frame(frameNode);
m_emHandler->getDynamicRecording(emNode);
std::stringstream sstm;
sstm << "snap_" << snapIndex << ".xml";
doc.save_file(sstm.str().c_str());
snapIndex++;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef MAC_PLUGIN_CRASHLOG_H
#define MAC_PLUGIN_CRASHLOG_H
/** @brief Implementations related to crash logging from the plugin wrapper
*/
namespace PluginCrashlog
{
/** Setup signals to install the crash handler
* @param pathname Path to the executable we're running
* @param logfolder Path to log to when crashes happen
*/
void InstallHandler(const char* logfolder);
/** Handle a crash happening in another process
* @param pid Process ID of the crashing process
* @param log_location Where to write logs
*/
OP_STATUS HandleCrash(pid_t pid, const char* log_location);
};
#endif // MAC_PLUGIN_CRASHLOG_H
|
#ifndef MENU_H
#define MENU_H
#include <Windows.h>
#include <vector>
#include <string>
#include "MenuItem.h"
class Menu : public MenuItem
{
public:
Menu(std::string itemName, bool popupMenu = false);
virtual ~Menu();
bool takeChild(MenuItem* child, UINT index);
MenuItem* giveChild(UINT index);
bool connect(HWND newOwner);
void disconnect();
bool hasOwner();
static bool dispatchMenuCommand(WPARAM wParam, LPARAM lParam);
static Menu* getMenuFromHandle(HMENU handle);
void onClick();
bool insertControl(HMENU insertInto, UINT index);
bool updateControl(HMENU updateFrom, UINT index);
bool popup(HWND popupFor, UINT xPos, UINT yPos);
private:
Menu();
void removeControl(UINT index);
std::vector<MenuItem*> children;
HWND owner;
HMENU menuHandle;
};
/*
class Menu
{
public:
Menu(std::string text, MenuCallback* callbackType);
virtual ~Menu();
bool takeChild(Menu* newChild, UINT index);
Menu* giveChild(UINT index);
bool connect(HWND connectTo);
void disconnect();
bool isChild();
bool isOwned();
UINT getChildIndex(Menu* child);
private:
bool insertSelf(Menu* into, UINT index);
void removeSelf();
void update(Menu* toUpdate);
std::vector<Menu*> children;
std::string text;
MenuCallback* callback;
Menu* parent;
HMENU menuHandle;
HWND owner;
};
*/
/*
enum ItemType
{
BUTTON,
RADIOBOX,
CHECKBOX
};
class Menu
{
public:
Menu(ItemType setType, std::string text);
virtual ~Menu();
bool connect(HWND connectWith);
void disconnect();
bool connected();
bool takeItem(Menu* child, UINT pos = 0);
Menu* giveItem(UINT pos);
private:
Menu();
void fillMII(MENUITEMINFO* mII);
//recursively store menu objects
Menu* parent;
std::vector<Menu*> children;
std::string text;
// menuHandle for this item
HMENU menuHandle;
// if owner is set this is the parent node
HWND owner;
// what is this menu item?
ItemType type;
};
*/
#endif // MENU_H
|
#include <iostream>
#include <vector>
#include <dirent.h>
#include "vocabulary_creator.h"
#include "fbow.h"
#include "Database.h"
#include <opencv2/opencv.hpp>
#include <opencv2/features2d/features2d.hpp>
using namespace fbow;
using namespace std;
vector<string> readImageFolder(string folderPath){
DIR *dir;
struct dirent *ent;
vector<string> filenames;
char buf[PATH_MAX];
char *inputDir = realpath(folderPath.c_str(), buf);
if ((dir = opendir(inputDir)) != NULL) {
while ((ent = readdir (dir)) != NULL) {
char buf2[PATH_MAX];
memset(buf2, '\0', sizeof(buf2));
strcpy(buf2, inputDir);
buf2[strlen(buf2)] = '/';
if (ent->d_name[0] == '.')
continue;
strcat(buf2, ent->d_name);
filenames.push_back(string(buf2));
}
closedir (dir);
} else {
cerr << "Could not read input folder " << inputDir << endl;
exit(1);
}
sort(filenames.begin(), filenames.end());
return filenames;
}
vector<cv::Mat> loadFeatures(vector<string> path_to_images, int numImages, int numFeatures, int delta) {
//select detector
auto detector = cv::ORB::create(numFeatures, 1.2f, 1, 31, 0, 2, cv::ORB::FAST_SCORE, 31, 10);
vector<cv::Mat> features;
for(size_t i = 0; i < path_to_images.size(); i+=delta){
//cout << "Reading image: "<<path_to_images[i] << endl;
cv::Mat image = cv::imread(path_to_images[i], 0);
if(image.empty()){
cerr << "Could not open image"+path_to_images[i] << endl;
exit(1);
}
vector<cv::KeyPoint> keypoints;
cv::Mat descriptors;
detector->detectAndCompute(image, cv::Mat(), keypoints, descriptors);
features.push_back(descriptors);
if (features.size() >= numImages){
break;
}
}
return features;
}
bool testVocabularyCreator(const vector<cv::Mat> &features, const int k, const int L, string outFile){
const int nThreads = 10;
fbow::VocabularyCreator voc_creator;
fbow::Vocabulary voc;
cout << "Creating a " << k << "^" << L << " vocabulary..." << endl;
voc_creator.create(voc, features, "orb", fbow::VocabularyCreator::Params(k, L, nThreads));
fbow::BowVector v1, v2;
for(size_t i = 0; i < features.size(); i++){
voc.transform(features[i], v1);
auto score = fbow::BowVector::score(v1, v1);
if(std::abs(score - 1.0) > 1e-3){
cerr << "Score " << score << " != 1 for BoW representation of image = " << i << endl;
return false;
}
}
// save the vocabulary to disk
cout << endl << "Saving vocabulary to " << outFile << endl;
voc.saveToFile(outFile);
return true;
}
bool testDBQuery(const vector<cv::Mat > &features, string inFile, string outFile){
fbow::Vocabulary voc;
voc.readFromFile(inFile);
cout << "Creating database from codebook of size " << voc.size() << endl;
Database db(voc, true, 0);
// populate dataset
for(size_t i = 0; i < features.size(); i++){
db.add(features[i]);
}
for(size_t i = 0; i < features.size(); i++){
QueryResults ret;
db.query(features[i], ret, 1);
if (ret.empty()){
cerr << "No results for query with image " << i << endl;
return false;
}
// since we added images to the DB, we should get them themselves
// as closest query results
if (ret[0].Id != i){
cerr << "Query result id = " << ret[0].Id << " doesn't match image id = " << i << endl;
return false;
}
}
cout << "Saving database to " << outFile << endl;
db.save(outFile);
return true;
}
bool testLoadedDB(const vector<cv::Mat > &features, string inFile){
Database db2(inFile);
cout << "Loaded database from " << inFile << endl;
for (size_t i = 0; i < features.size(); i++){
QueryResults ret;
db2.query(features[i], ret, 1);
if (ret.empty()){
cerr << "No result for image " << i << endl;
return false;
}
// since we laoded DB that contains the query images we should get them themselves
// as closest query results
if (ret[0].Id != i){
cerr << "Query result id = " << ret[0].Id << " doesn't match image id = " << i << endl;
return false;
}
}
return true;
}
int main(int argc,char **argv){
if (argc < 1){
cerr << "Usage: " << argv[0] << " [image folder 1] [image folder 2] ..." << endl;
exit(1);
}
auto images = readImageFolder(string(argv[1]));
int delta = 10;
vector< cv::Mat> features = loadFeatures(images, 100, 50, delta);
for (int i = 2; i < argc; i++){
auto imagesI = readImageFolder(string(argv[i]));
auto featuresI = loadFeatures(imagesI, 100, 50, delta);
features.insert(features.end(), featuresI.begin(), featuresI.end());
}
string dbFilename = "orb_voc_kitti.yaml";
int k = 10;
int L = 8;
cout << "Creating a vocabulary with k = " << k << ", L = " << L << std::endl;
if (testVocabularyCreator(features, k, L, dbFilename)){
cout << "testVocabularyCreator() succeeded!" << endl;
} else {
cerr << "testVocabularyCreator() failed!" << endl;
exit(1);
}
cout << "Creating database with vocabulary " << dbFilename << " and querying it" << endl;
if (testDBQuery(features, dbFilename, dbFilename)){
cout << "testDBQuery() succeeded!" << endl;
} else {
cerr << "testDBQuery() failed!" << endl;
exit(1);
}
cout << "Loading database from " << dbFilename << " and querying it" << endl;
if (testLoadedDB(features, dbFilename)){
cout << "testLoadedDB() succeeded!" << endl;
} else {
cerr << "testLoadedDB() failed!" << endl;
exit(1);
}
return 0;
}
|
#ifndef BATTLE_HPP
#define BATTLE_HPP
#include <string>
#include <iostream>
#include <vector>
#include "Engimon.hpp"
#include "Player.hpp"
#include "SkillItem.hpp"
using namespace std;
class Battle
{
private:
Player player;
Engimon engimonPlayer;
Engimon engimonWild;
int levelEngimonPlayer; // Level Engimon Player 1
int levelEngimonWild; // Level Engimon Player 2
float multiplierEngimonPlayer; // Element Advantage Engimon Player 1
float multiplierEngimonWild; // Element Advantage Engimon Player 2
int skillPowerPlayer; // Total skill base power Engimon Player 1
int skillPowerWild; // Total skill base power Engimon Player 2
float totalPowerPlayer;
float totalPowerWild;
string winner;
string loser;
public:
// Constructor & Destructor
Battle(Player player, Engimon engimonPlayer, Engimon engimonWild);
~Battle();
// Get Class Attribute
int getlevelEngimonPlayer();
int getlevelEngimonWild();
int getMultiplierEngimonPlayer();
int getMultiplierEngimonWild();
int getskillPowerPlayer();
int getskillPowerWild();
float getTotalPowerPlayer();
float getTotalPowerWild();
string getWinner();
// Set Class Attribute
void setMultiplierEngimon();
void setSkillPower();
void setTotalPower();
void setElement();
// Fungsi dan Prosedur
float checkMultiplier(string elemen1, string elemen2);
void showTotalPower();
void doBattle();
SkillItem getRandomSkill(vector<SkillItem> fireItems, vector<SkillItem> waterItems, vector<SkillItem> electricItems, vector<SkillItem> groundItems, vector<SkillItem> iceItems);
};
#endif
|
#pragma once
#include "../../Toolbox/Toolbox.h"
#include "Texture.h"
namespace ae
{
class FramebufferAttachement;
/// \ingroup graphics
/// <summary>
/// 3D samplable data that can be link to a shader to be rendered.
/// </summary>
class AERO_CORE_EXPORT Texture3D : public Texture
{
public:
/// <summary>Create an empty texture 3D.</summary>
/// <param name="_Width">The width of the texture.</param>
/// <param name="_Height">The height of the texture.</param>
/// <param name="_Depth">The depth of the texture.</param>
/// <param name="_Format">Format of the texture : channels, type.</param>
Texture3D( Uint32 _Width, Uint32 _Height, Uint32 _Depth, TexturePixelFormat _Format = TexturePixelFormat::DefaultTexture );
/// <summary>Create an empty texture with framebuffer attachement settings..</summary>
/// <param name="_Width">The width of the texture.</param>
/// <param name="_Height">The height of the texture.</param>
/// <param name="_Depth">The depth of the texture.</param>
/// <param name="_FramebufferAttachement">Settings to apply.</param>
Texture3D( Uint32 _Width, Uint32 _Height, Uint32 _Depth, const FramebufferAttachement& _FramebufferAttachement );
/// <summary>Create an empty texture 3D.</summary>
/// <param name="_Width">The width of the texture.</param>
/// <param name="_Height">The height of the texture.</param>
/// <param name="_Depth">The depth of the texture.</param>
/// <param name="_Format">Format of the texture : channels, type.</param>
void Set( Uint32 _Width, Uint32 _Height, Uint32 _Depth, TexturePixelFormat _Format = TexturePixelFormat::DefaultTexture );
/// <summary>Create an empty texture with framebuffer attachement settings..</summary>
/// <param name="_Width">The width of the texture.</param>
/// <param name="_Height">The height of the texture.</param>
/// <param name="_Depth">The depth of the texture.</param>
/// <param name="_FramebufferAttachement">Settings to apply.</param>
void Set( Uint32 _Width, Uint32 _Height, Uint32 _Depth, const FramebufferAttachement& _FramebufferAttachement );
/// <summary>Resize the texture 1D.</summary>
/// <param name="_Width">The width of the texture.</param>
/// <param name="_Height">The height of the texture.</param>
/// <param name="_Depth">The depth of the texture.</param>
void Resize( Uint32 _Width, Uint32 _Height, Uint32 _Depth );
/// <summary>Get the width of the texture.</summary>
/// <returns>Width of the texture.</returns>
Uint32 GetWidth() const;
/// <summary>Get the height of the texture.</summary>
/// <returns>Height of the texture.</returns>
Uint32 GetHeight() const;
/// <summary>Get the depth of the texture.</summary>
/// <returns>Depth of the texture.</returns>
Uint32 GetDepth() const;
/// <summary>Called by the framebuffer to attach the texture to it.</summary>
void AttachToFramebuffer( const FramebufferAttachement& _Attachement ) const override;
/// <summary>
/// Function called by the editor.
/// It allows the class to expose some attributes for user editing.
/// Think to call all inherited class function too when overloading.
/// </summary>
void ToEditor() override;
private:
/// <summary>Create an empty texture.</summary>
virtual void SetupEmpty();
protected:
/// <summary>Width of the texture.</summary>
Uint32 m_Width;
/// <summary>Width of the texture.</summary>
Uint32 m_Height;
/// <summary>Depth of the texture (for 3D texture).</summary>
Uint32 m_Depth;
};
} // ae
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#include "modules/style/src/css_conditional_rule.h"
#include "modules/style/src/css_parser.h"
BOOL
CSS_ConditionalRule::EnterRule(FramesDocument* doc, CSS_MediaType medium)
{
CSS_ConditionalRule* parent = GetConditionalRule();
if (!parent || parent->EnterRule(doc,medium))
return Evaluate(doc, medium);
else
return FALSE;
}
/* virtual */ OP_STATUS
CSS_ConditionalRule::GetCssText(CSS* stylesheet, TempBuffer* buf, unsigned int indent_level)
{
RETURN_IF_ERROR(GetCssTextHeader(stylesheet, buf));
RETURN_IF_ERROR(buf->Append(" {\n"));
CSS_Rule* rule = static_cast<CSS_Rule*>(m_rules.First());
while (rule)
{
for (unsigned int i = 0; i < indent_level + 1; i++)
RETURN_IF_ERROR(buf->Append(" "));
RETURN_IF_ERROR(rule->GetCssText(stylesheet, buf, indent_level + 1));
RETURN_IF_ERROR(buf->Append("\n"));
rule = static_cast<CSS_Rule*>(rule->Suc());
}
for (unsigned int i = 0; i < indent_level; i++)
RETURN_IF_ERROR(buf->Append(" "));
return buf->Append("}");
}
CSS_PARSE_STATUS
CSS_ConditionalRule::InsertRule(HLDocProfile* hld_prof, CSS* stylesheet, const uni_char* text, int len, unsigned int idx)
{
OP_ASSERT(idx <= GetRuleCount());
CSS_Rule* before_rule = GetRule(idx);
return stylesheet->ParseAndInsertRule(hld_prof, before_rule, this, NULL, FALSE, CSS_TOK_DOM_RULE, text, len);
}
BOOL
CSS_ConditionalRule::DeleteRule(HLDocProfile* hld_prof, CSS* stylesheet, unsigned int idx)
{
Link* l = m_rules.First();
while (l && idx-- > 0) l = l->Suc();
if (l)
{
stylesheet->RuleRemoved(hld_prof, static_cast<CSS_Rule*>(l));
l->Out();
OP_DELETE(l);
return TRUE;
}
else
return FALSE;
}
void CSS_ConditionalRule::DeleteRules(HLDocProfile* hld_prof, CSS* stylesheet)
{
Link* l;
while ((l = m_rules.First()))
{
stylesheet->RuleRemoved(hld_prof, static_cast<CSS_Rule*>(l));
l->Out();
OP_DELETE(l);
}
}
|
/*! @file LogVol_SegmentedCrystal_Box.hh
@brief Defines mandatory user class LogVol_SegmentedCrystal_Box.
@date September, 2015
@author Flechas (D. C. Flechas dcflechasg@unal.edu.co)
@version 2.0
In this header file, the 'physical' setup is defined: materials, geometries and positions.
This class defines the experimental hall used in the toolkit.
*/
/* no-geant4 classes*/
#include "LogVol_SegmentedCrystal_Box.hh"
/* units and constants */
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
/* geometric objects */
#include "G4Box.hh"
#include "G4Polycone.hh"
/* logic and physical volume */
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4PVReplica.hh"
/* geant4 materials */
#include "G4NistManager.hh"
/* visualization */
#include "G4VisAttributes.hh"
LogVol_SegmentedCrystal_Box:: LogVol_SegmentedCrystal_Box(G4String fname,
G4double flen, G4double fheight,
G4int fNpixelX, G4int fNpixelY ,
G4Material* fMaterial):
G4LogicalVolume(new G4Box(fname+"_Sol",flen/2.0,flen/2.0,fheight/2.0),
fMaterial, fname+"_Log",0,0,0),Material(fMaterial)
{
/* set variables */
SetName(fname);
SetHeight(fheight);
SetXPixels(fNpixelX);
SetYPixels(fNpixelY);
SetLength(flen);
/* Construct solid volume */
SegmentedCrystal_Box_LogVol=NULL;
ConstructLogVol_SegmentedCrystal_Box();
/* Visualization */
this->SetVisAttributes(G4VisAttributes::GetInvisible());
}
LogVol_SegmentedCrystal_Box::~LogVol_SegmentedCrystal_Box()
{}
void LogVol_SegmentedCrystal_Box::ConstructLogVol_SegmentedCrystal_Box(void)
{
/* Visualization */
G4VisAttributes* yellow_vis
= new G4VisAttributes(true,G4Colour(0.7,0.5,0.2));
yellow_vis->SetForceWireframe(false);
yellow_vis->SetForceSolid(false);
/*!
- Create the "pixels"
- Create a volume that looks like a strip
- Create a volume that looks like a pixel
- The CsI detector is \c X x \c Y CsI replicas (\ref WALL_pixel_log "pixels") and place them into \ref vacuum vacuum container
- To achieve that, we first divide (using the method Replica) the CsI volume into strips
- Once we have the strips, we can divide them in a similar way to the previous step but now creating pixels
*/
/* for now a strip along X*/
G4Box* strip_solid = new G4Box("position_strip_solid",
Length/2.0/XPixelNum, Length/2.0, Height/2.0);
G4LogicalVolume* strip_log = new G4LogicalVolume(strip_solid,
Material,
Name+"position_strip_log", 0,0,0);
strip_log->SetVisAttributes(G4VisAttributes::Invisible); //never show
/* the pixel along Y*/
G4Box* pixel_solid = new G4Box("position_pixel_solid",
Length/2.0/XPixelNum, Length/2.0/YPixelNum, Height/2.0);
G4LogicalVolume* pixel_log = new G4LogicalVolume(pixel_solid,
Material,
Name+"pixel_csi_log", 0,0,0);
pixel_log->SetVisAttributes(yellow_vis);
/*the [Materia] crystal is XxY CsI replicas (pixels) and place them into step 3)*/
/* for now the strips */
G4VPhysicalVolume* Crystal_strip;
Crystal_strip = new G4PVReplica(Name+"position_strip_phy", //name
strip_log, //logical volume
this,//its logical mother
kXAxis, //replication axis
XPixelNum, //number of replicas
Length/XPixelNum); //width
/* strip division into pixels */
G4VPhysicalVolume* Crystal_pixel;
Crystal_pixel = new G4PVReplica(Name+"ArraySegCystal", //name
pixel_log, //logical volume
strip_log, //its logical mother
kYAxis, //replication axis
YPixelNum, //number of replicas
Length/YPixelNum); //width
/*** Main trick here: Set the new solid volume ***/
if(pixel_log)
SegmentedCrystal_Box_LogVol = pixel_log;
}
|
#ifndef LETNODE_H
#define LETNODE_H
#include <vector>
#include <string>
#include <iostream>
#include "Node.hpp"
#include "VariablesTable.hpp"
#include "ClassNode.hpp"
using namespace std;
class LetNode : public Node {
private:
string objectId;
string type;
Node *expr = nullptr;
Node *assign = nullptr;
public:
LetNode(string objectId, string type, Node *expr);
LetNode(string objectId, string type, Node *assign, Node *expr);
string getType() override;
string getName();
void printTree() override;
string printCheck(ClassNode *classNode) override;
};
#endif
|
#ifndef __CGET_NOTICE_H_
#define __CGET_NOTICE_H_
#include <string>
#include "CHttpRequestHandler.h"
class CGetNotice : public CHttpRequestHandler
{
public:
CGetNotice(){}
~CGetNotice(){}
virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out);
private:
bool GetNotice(int pid, Json::Value &info);
};
#endif //end for __CGET_NOTICE_H_
|
#include<bits/stdc++.h>
using namespace std;
const int X[4] = {1,2,2,1},
Y[4] = {-2,-1,1,2};
int a[100][100];
int m, n;
int s;
void input(){
cin >> m >> n;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; j++)
cin >> a[i][j];
}
bool isInside(int x, int y){
return (x >= 0 && x < m && y >= 0 && y < n);
}
void loang(int x, int y){
for (int k = 0; k < 4; k++){
int u = x + X[k], v = y + Y[k];
if(isInside(u,v)){
s += a[u][v];
if(u == m)
break;
else
loang(u,v);
}
}
}
int main(){
freopen("TONGMA.inp", "r", stdin);
freopen("TONGMA.out", "w", stdout);
input();
int sMax = -1000;
for (int j = 0; j < n; ++j){
s = a[0][j];
loang(0,j);
sMax = max(s,sMax);
}
cout << sMax;
return 0;
}
|
#pragma once
#include "global.h"
class CItem
{
public:
CItem(void);
~CItem(void);
void create_item(int xx,int yy,int ttt);
void init_item();
void move();
bool live;
float x,y;
int timer;
};
|
#include "game/LoadingScreen.hpp"
LoadingScreen::LoadingScreen(){
gLoadTextTexture = new LTexture();
loadIcon = new LTexture();
background = new LTexture();
timer = new LTimer();
timer->start();
connecting_to_server = false;
}
LoadingScreen::~LoadingScreen(){
delete(timer);
loadIcon->free();
background->free();
gLoadTextTexture->free();
delete(loadIcon);
delete(background);
delete(gLoadTextTexture);
loadIcon = NULL;
background = NULL;
gLoadTextTexture = NULL;
timer = NULL;
}
void LoadingScreen::render(std::string text){
background->renderBackground(NULL);
loadText.str("");
loadText<<text;
gLoadTextTexture->loadFromRenderedText( loadText.str().c_str(), SDL_Color{0, 0, 0, 255}, gFont);
gLoadTextTexture->render((SCREEN_WIDTH- gLoadTextTexture->getWidth())/2, 10, NULL, 1);
loadIcon->render(SCREEN_WIDTH/2-25, 4*SCREEN_HEIGHT/5-25, NULL, 0.25, (double)((timer->getTicks())%1000)*(0.36));
}
void LoadingScreen::loadMedia(){
gFont = TTF_OpenFont( "media/fonts/Amatic-Bold.ttf", 50);
if( !background->loadFromFile( "media/texture/loadingScreen.png" ) )
{
printf( "Failed to load loadIcon texture!\n" );
}
if( !loadIcon->loadFromFile( "media/texture/loadIcon.png" ) )
{
printf( "Failed to load background texture!\n" );
}
}
|
// IStrokeContainer.h
#pragma once
/*
Copyright © 2006, Drollic
All rights reserved.
http://www.drollic.com
Redistribution of this software in source or binary forms, with or
without modification, is expressly prohibited. You may not reverse-assemble,
reverse-compile, or otherwise reverse-engineer this software in any way.
THIS SOFTWARE ("SOFTWARE") IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "NativeStroke.h"
namespace com
{
namespace drollic
{
namespace graphics
{
namespace painting
{
namespace native
{
namespace processing
{
class IStrokeContainer
{
public:
virtual void AddStroke(const NativeStroke &s) = 0;
};
}
}
}
}
}
}
|
#include "stdafx.h"
#include "Object.h"
Jaraffe::Object::Object()
{
}
Jaraffe::Object::~Object()
{
}
|
/**
* created: 2013-4-8 13:29
* filename: FKFrameAllocator
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#include "../Include/STLTemplate/FKFrameAllocator.h"
//------------------------------------------------------------------------
void mallocState::Init(char *beg, char *end)
{
m_beg=beg;
m_end=end;
m_last=NULL;
m_nMaxSize=m_end-m_beg;
m_cur=m_beg;
m_nMaxFrameAllocation=0;
}
//------------------------------------------------------------------------
void mallocState::Init(char *beg, int nSize)
{
m_beg=beg;
m_nMaxSize=nSize;
m_last=NULL;
m_end=m_beg+m_nMaxSize;
m_cur=m_beg;
m_nMaxFrameAllocation=0;
}
//------------------------------------------------------------------------
void mallocState::Init(mallocState* other)
{
m_beg=other->getbeg();
m_nMaxSize=other->getBufferSize();
m_end=m_beg+m_nMaxSize;
m_cur=m_beg+other->getCurSize();
m_last=other->m_last;
m_nMaxFrameAllocation=other->getUseMaxSize();
}
//------------------------------------------------------------------------
void mallocState::Uninit()
{
g_logger.debug("mallocState log-->[%d/%d]",getUseMaxSize(),getBufferSize());
m_beg=0;
m_end=0;
m_nMaxSize=0;
m_cur=0;
m_last=NULL;
m_nMaxFrameAllocation=0;
}
//------------------------------------------------------------------------
mallocState::mallocState()
{
Uninit();
}
//------------------------------------------------------------------------
mallocState::mallocState(char *beg, char *end)
{
Init(beg,end);
}
//------------------------------------------------------------------------
mallocState::mallocState(char *beg, int nSize)
{
Init(beg,nSize);
}
//------------------------------------------------------------------------
mallocState::mallocState(const mallocState& other)
{
Init((mallocState*)&other);
}
//------------------------------------------------------------------------
void mallocState::reset()
{
m_cur=m_beg;
m_last=NULL;
m_nMaxFrameAllocation=0;
}
//------------------------------------------------------------------------
void* mallocState::alloc(unsigned long allocSize)
{
if(m_beg && ((m_cur+ allocSize) < m_end)){
m_last = m_cur;
m_cur += allocSize;
int nCurSize=m_cur-m_beg;
if (nCurSize > m_nMaxFrameAllocation)
m_nMaxFrameAllocation = nCurSize;
return m_last;
}else{
g_logger.forceLog(zLogger::zFATAL,"[ fatal error ] mallocState is out memory-->[%d/%d](%d) ",getCurSize(),getBufferSize(),allocSize);
return malloc(allocSize);
}
}
//------------------------------------------------------------------------
bool mallocState::issysmalloc(void* p){
return (!(p>=m_beg && p<m_end));
}
//------------------------------------------------------------------------
void mallocState::_free(void* p){
if (p>=m_beg && p<m_end){}
else if(p){free(p);}
}
//------------------------------------------------------------------------
void mallocState::setCurSize(const int waterMark){
if (waterMark>=0 && waterMark<m_nMaxSize){
m_cur=m_beg+waterMark;
}
}
//------------------------------------------------------------------------
int mallocState::getCurSize(){
return (int)(m_cur-m_beg);
}
//------------------------------------------------------------------------
int mallocState::getBufferSize(){
return m_nMaxSize;
}
//------------------------------------------------------------------------
int mallocState::getUseMaxSize(){
return m_nMaxFrameAllocation;
}
//------------------------------------------------------------------------
char* mallocState::getbeg(){
return m_beg;
}
//------------------------------------------------------------------------
void stStackFrameAllocator::init(unsigned long frameSize,bool bocheckthreadobj)
{
frameSize=(frameSize>=1024*256)?(ROUNDNUM2(frameSize,1024*64)):(1024*1024*2);
frameSize=safe_max(frameSize,m_initframeSize);
m_currthread=::GetCurrentThreadId();
if (CLD_ThreadBase::getThreadObj()!=NULL || !bocheckthreadobj){
if (!m_State)
{
m_State=(mallocState*)&Statebuf;
constructInPlace(m_State);
char* p = (char*)malloc(frameSize);
assert((p != NULL) && "Error, malloc memory error");
m_State->Init(p,frameSize);
m_initframeSize=safe_max(frameSize,m_initframeSize);
}
}else{
g_logger.forceLog(zLogger::zFATAL,"[ fatal error ] thread %d init mallocState ",m_currthread);
}
}
//------------------------------------------------------------------------
DWORD getMaxFrameAllocation(){
return (tlsFrameAllocator.m_State!=NULL)?tlsFrameAllocator.m_State->getUseMaxSize():0;
}
//------------------------------------------------------------------------
|
#pragma once
#include "plbase/PluginBase.h"
#include "CAtomicModelInfo.h"
class PLUGIN_API CTimeModelInfo : public CAtomicModelInfo {
public:
tTimeInfo m_timeInfo;
void FindOtherTimeModel(char *modelName);
};
VALIDATE_SIZE(CTimeModelInfo, 0x24);
|
#include "OrthoBuilder.h"
SolInfo::SolInfo()
{
o.resize( EQ_NUM * EQ_NUM, 0.0 );
z1.resize( EQ_NUM );
z2.resize( EQ_NUM );
z3.resize( EQ_NUM );
z4.resize( EQ_NUM );
z5.resize( EQ_NUM );
C.resize( EQ_NUM / 2 );
}
void SolInfo::flushO()
{
for( int i = 0; i < o.size(); ++i )
{
o[i] = 0.0;
}
}
SolInfo::~SolInfo()
{
}
OrthoBuilder::OrthoBuilder()
{
eq_num = EQ_NUM;
}
OrthoBuilder::~OrthoBuilder()
{
}
void OrthoBuilder::flushO( int x )
{
solInfoMap[x].flushO();
}
void OrthoBuilder::setParams( int _Km )
{
Km = _Km;
solInfoMap.resize( Km );
}
void OrthoBuilder::setInitVects( const Matrix<PL_NUM, EQ_NUM, 1> &N1, const Matrix<PL_NUM, EQ_NUM, 1> &N2, const Matrix<PL_NUM, EQ_NUM, 1> &N3, const Matrix<PL_NUM, EQ_NUM, 1> &N4, const Matrix<PL_NUM, EQ_NUM, 1> &N5 )
{
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[0].z1[i] = N1( i );
solInfoMap[0].z2[i] = N2( i );
solInfoMap[0].z3[i] = N3( i );
solInfoMap[0].z4[i] = N4( i );
solInfoMap[0].z5[i] = N5( i );
}
}
void OrthoBuilder::orthogTest( int x )
{
PL_NUM sq1 = 0;
PL_NUM sq2 = 0;
PL_NUM sq3 = 0;
PL_NUM sq4 = 0;
PL_NUM sq5 = 0;
PL_NUM sum1 = 0;
PL_NUM sum2 = 0;
PL_NUM sum3 = 0;
PL_NUM sum4 = 0;
PL_NUM sum5 = 0;
for( int i = 0; i < eq_num; ++i )
{
sq1 += solInfoMap[x].z1[i] * solInfoMap[x].z1[i];
sq2 += solInfoMap[x].z2[i] * solInfoMap[x].z2[i];
sq3 += solInfoMap[x].z3[i] * solInfoMap[x].z3[i];
sq4 += solInfoMap[x].z4[i] * solInfoMap[x].z4[i];
sq5 += solInfoMap[x].z5[i] * solInfoMap[x].z5[i];
}
for( int i = 0; i < eq_num; ++i )
{
sum1 += solInfoMap[x].z1[i] * solInfoMap[x].z2[i];
sum2 += solInfoMap[x].z2[i] * solInfoMap[x].z3[i];
sum3 += solInfoMap[x].z3[i] * solInfoMap[x].z4[i];
sum4 += solInfoMap[x].z4[i] * solInfoMap[x].z5[i];
sum5 += solInfoMap[x].z5[i] * solInfoMap[x].z1[i];
}
//cout << " " << sqrtl( sq1 ) << " " << sqrtl( sq2 ) << " " << sqrtl( sq3 ) << " " << sqrtl( sq4 ) << " " << sqrtl( sq5 ) << endl;
cout << " " << sum1 << " " << sum2 << " " << sum3 << " " << sum4 << " " << sum5 << endl;
}
//void OrthoBuilderGodunov::orthonorm( int baseV, int n, PL_NUM* NtoOrt )
//{
// if( baseV < 1 || baseV > 5 || n < 0 || n > Km - 1 )
// {
// cout << "Error in orthonorm: bad input\n";
// return;
// }
//
// if( baseV == 1 )
// {
// for( int i = 0; i < eq_num; ++i )
// {
// solInfoMap[n + 1].o[0 * eq_num + 0] += (NtoOrt)[i] * (NtoOrt)[i];
// }
// solInfoMap[n + 1].o[0 * eq_num + 0] = sqrtl( solInfoMap[n + 1].o[0 * eq_num + 0] );
// for( int i = 0; i < eq_num; ++i )
// {
// (NtoOrt)[i] = (NtoOrt)[i] / solInfoMap[n + 1].o[0 * eq_num + 0];
// solInfoMap[n + 1].z1[i] = (NtoOrt)[i];
// }
// }
// else if( baseV == 2 )
// {
// for( int i = 0; i < eq_num; ++i )
// {
// solInfoMap[n + 1].o[1 * eq_num + 0] += (NtoOrt)[i] * solInfoMap[n + 1].z1[i];
// solInfoMap[n + 1].o[1 * eq_num + 1] += (NtoOrt)[i] * (NtoOrt)[i];
// }
// solInfoMap[n + 1].o[1 * eq_num + 1] = sqrtl( solInfoMap[n + 1].o[1 * eq_num + 1]
// - solInfoMap[n + 1].o[1 * eq_num + 0] * solInfoMap[n + 1].o[1 * eq_num + 0] );
// for( int i = 0; i < eq_num; ++i )
// {
// (NtoOrt)[i] = ( (NtoOrt)[i] - solInfoMap[n + 1].o[1 * eq_num + 0] * solInfoMap[n + 1].z1[i] )
// / solInfoMap[n + 1].o[1 * eq_num + 1];
// solInfoMap[n + 1].z2[i] = (NtoOrt)[i];
// }
// }
// else if( baseV == 3 )
// {
// for( int i = 0; i < eq_num; ++i )
// {
// solInfoMap[n + 1].o[2 * eq_num + 0] += (NtoOrt)[i] * solInfoMap[n + 1].z1[i];
// solInfoMap[n + 1].o[2 * eq_num + 1] += (NtoOrt)[i] * solInfoMap[n + 1].z2[i];
// solInfoMap[n + 1].o[2 * eq_num + 2] += (NtoOrt)[i] * (NtoOrt)[i];
// }
// solInfoMap[n + 1].o[2 * eq_num + 2] = sqrtl( solInfoMap[n + 1].o[2 * eq_num + 2]
// - solInfoMap[n + 1].o[2 * eq_num + 0] * solInfoMap[n + 1].o[2 * eq_num + 0]
// - solInfoMap[n + 1].o[2 * eq_num + 1] * solInfoMap[n + 1].o[2 * eq_num + 1] );
// for( int i = 0; i < eq_num; ++i )
// {
// (NtoOrt)[i] = ( (NtoOrt)[i] - solInfoMap[n + 1].o[2 * eq_num + 0] * solInfoMap[n + 1].z1[i]
// - solInfoMap[n + 1].o[2 * eq_num + 1] * solInfoMap[n + 1].z2[i] )
// / solInfoMap[n + 1].o[2 * eq_num + 2];
// solInfoMap[n + 1].z3[i] = (NtoOrt)[i];
// }
// }
// else if( baseV == 4 )
// {
// for( int i = 0; i < eq_num; ++i )
// {
// solInfoMap[n + 1].o[3 * eq_num + 0] += (NtoOrt)[i] * solInfoMap[n + 1].z1[i];
// solInfoMap[n + 1].o[3 * eq_num + 1] += (NtoOrt)[i] * solInfoMap[n + 1].z2[i];
// solInfoMap[n + 1].o[3 * eq_num + 2] += (NtoOrt)[i] * solInfoMap[n + 1].z3[i];
// solInfoMap[n + 1].o[3 * eq_num + 3] += (NtoOrt)[i] * (NtoOrt)[i];
// }
// solInfoMap[n + 1].o[3 * eq_num + 3] = sqrtl( solInfoMap[n + 1].o[3 * eq_num + 3]
// - solInfoMap[n + 1].o[3 * eq_num + 0] * solInfoMap[n + 1].o[3 * eq_num + 0]
// - solInfoMap[n + 1].o[3 * eq_num + 1] * solInfoMap[n + 1].o[3 * eq_num + 1]
// - solInfoMap[n + 1].o[3 * eq_num + 2] * solInfoMap[n + 1].o[3 * eq_num + 2] );
// for( int i = 0; i < eq_num; ++i )
// {
// (NtoOrt)[i] = ( (NtoOrt)[i] - solInfoMap[n + 1].o[3 * eq_num + 0] * solInfoMap[n + 1].z1[i]
// - solInfoMap[n + 1].o[3 * eq_num + 1] * solInfoMap[n + 1].z2[i]
// - solInfoMap[n + 1].o[3 * eq_num + 2] * solInfoMap[n + 1].z3[i] )
// / solInfoMap[n + 1].o[3 * eq_num + 3];
// solInfoMap[n + 1].z4[i] = (NtoOrt)[i];
// }
// }
// else if( baseV == 5 )
// {
// for( int i = 0; i < eq_num; ++i )
// {
// solInfoMap[n + 1].o[4 * eq_num + 0] += (NtoOrt)[i] * solInfoMap[n + 1].z1[i];
// solInfoMap[n + 1].o[4 * eq_num + 1] += (NtoOrt)[i] * solInfoMap[n + 1].z2[i];
// solInfoMap[n + 1].o[4 * eq_num + 2] += (NtoOrt)[i] * solInfoMap[n + 1].z3[i];
// solInfoMap[n + 1].o[4 * eq_num + 3] += (NtoOrt)[i] * solInfoMap[n + 1].z4[i];
// solInfoMap[n + 1].o[4 * eq_num + 4] += (NtoOrt)[i] * (NtoOrt)[i];
// }
// for( int i = 0; i < eq_num; ++i )
// {
// (NtoOrt)[i] = (NtoOrt)[i] - solInfoMap[n + 1].o[4 * eq_num + 0] * solInfoMap[n + 1].z1[i]
// - solInfoMap[n + 1].o[4 * eq_num + 1] * solInfoMap[n + 1].z2[i]
// - solInfoMap[n + 1].o[4 * eq_num + 2] * solInfoMap[n + 1].z3[i]
// - solInfoMap[n + 1].o[4 * eq_num + 3] * solInfoMap[n + 1].z4[i];
// solInfoMap[n + 1].z5[i] = (NtoOrt)[i];
// }
// }
// else
// {
// cout << "Error in orthonormalizer: bad value of baseV\n";
// return;
// }
//}
void OrthoBuilderGodunov::buildSolution( vector<VarVect>* _mesh )
{
vector<PL_NUM> M;
vector<PL_NUM> f11;
vector<PL_NUM> L;
vector<PL_NUM> R;
vector<PL_NUM> x1;
int msize = eq_num / 2; //caution here!
M.resize( msize * msize, 0.0 );
f11.resize( msize, 0.0 );
L.resize( msize * msize, 0.0 );
R.resize( msize * msize, 0.0 );
x1.resize( msize, 0.0 );
//simply supported plate NO CURRENT PASSING THROUGH THE BOUNDARY
M[0 * msize + 0] = solInfoMap[Km - 1].z1[0];
M[1 * msize + 0] = solInfoMap[Km - 1].z1[1];
M[2 * msize + 0] = solInfoMap[Km - 1].z1[5];
M[3 * msize + 0] = solInfoMap[Km - 1].z1[6];
M[0 * msize + 1] = solInfoMap[Km - 1].z2[0];
M[1 * msize + 1] = solInfoMap[Km - 1].z2[1];
M[2 * msize + 1] = solInfoMap[Km - 1].z2[5];
M[3 * msize + 1] = solInfoMap[Km - 1].z2[6];
M[0 * msize + 2] = solInfoMap[Km - 1].z3[0];
M[1 * msize + 2] = solInfoMap[Km - 1].z3[1];
M[2 * msize + 2] = solInfoMap[Km - 1].z3[5];
M[3 * msize + 2] = solInfoMap[Km - 1].z3[6];
M[0 * msize + 3] = solInfoMap[Km - 1].z4[0];
M[1 * msize + 3] = solInfoMap[Km - 1].z4[1];
M[2 * msize + 3] = solInfoMap[Km - 1].z4[5];
M[3 * msize + 3] = solInfoMap[Km - 1].z4[6];
f11[0] = -solInfoMap[Km - 1].z5[0];
f11[1] = -solInfoMap[Km - 1].z5[1];
f11[2] = -solInfoMap[Km - 1].z5[5];
f11[3] = -solInfoMap[Km - 1].z5[6];
int posI = 0;
int posJ = 0;
for( int i = 0; i < msize; ++i )
{
int found = 0;
for(int j = 0; j < msize; ++j )
{
if( M[i * msize + j].real() >= 0.0000000001 )
{
found = 1;
posI = i;
posJ = j;
break;
}
}
if( found == 1 )
{
break;
}
}
PL_NUM m0, m1, m2, m3;
m0 = M[posI * msize + 0];
m1 = M[posI * msize + 1];
m2 = M[posI * msize + 2];
m3 = M[posI * msize + 3];
M[posI * msize + 0] = M[0 * msize + 0];
M[posI * msize + 1] = M[0 * msize + 1];
M[posI * msize + 2] = M[0 * msize + 2];
M[posI * msize + 3] = M[0 * msize + 3];
M[0 * msize + 0] = m0;
M[0 * msize + 1] = m1;
M[0 * msize + 2] = m2;
M[0 * msize + 3] = m3;
m0 = M[0 * msize + posJ];
m1 = M[0 * msize + posJ];
m2 = M[0 * msize + posJ];
m3 = M[0 * msize + posJ];
M[0 * msize + posJ] = M[0 * msize + 0];
M[1 * msize + posJ] = M[1 * msize + 0];
M[2 * msize + posJ] = M[2 * msize + 0];
M[3 * msize + posJ] = M[3 * msize + 0];
M[0 * msize + 0] = m0;
M[1 * msize + 0] = m1;
M[2 * msize + 0] = m2;
M[3 * msize + 0] = m3;
m0 = f11[posI];
f11[posI] = f11[0];
f11[0] = m0;
for( int i = 0; i < msize; ++i )
{
L[i * msize + 0] = M[i * msize + 0];
for( int j = i + 1; j < msize; ++j ) //TODO I think this is redundant
{
L[i * msize + j] = 0.0;
R[j * msize + i] = 0.0;
}
}
for( int i = 1; i < msize; ++i )
{
R[0 * msize + i] = M[0 * msize + i] / L[0 * msize + 0];
}
for( int i = 0; i < msize; ++i )
{
R[i * msize + i] = 1.0;
}
for( int i = 1; i < msize; ++i )
{
for( int k = i; k < msize; ++k )
{
L[k * msize + i] = M[k * msize + i];
for( int l = 0; l < i; ++l )
{
L[k * msize + i] -= L[k * msize + l] * R[l * msize + i];
}
}
for( int j = i + 1; j < msize; ++j )
{
R[i * msize + j] = M[i * msize + j];
for( int l = 0; l < i; ++l )
{
R[i * msize + j] -= L[i * msize + l] * R[l * msize + j];
}
R[i * msize + j] /= L[i * msize + i];
}
}
f11[0] = f11[0] / L[0 * msize + 0];
for( int i = 1; i < msize; ++i )
{
for( int j = 0; j < i; ++j )
{
f11[i] -= L[i * msize + j] * f11[j];
}
f11[i] /= L[i * msize + i];
}
x1[msize - 1] = f11[msize - 1];
for( int i = msize - 2; i >= 0; --i )
{
x1[i] = f11[i];
for( int j = i + 1; j < msize; ++j )
{
x1[i] -= R[i * msize + j] * x1[j];
}
}
for( int i = 0; i < msize; ++i )
{
solInfoMap[Km - 1].C[i] = x1[i];
}
m0 = solInfoMap[Km - 1].C[0]; //we changed the order in M matrix, so we must change it in C too
solInfoMap[Km - 1].C[0] = solInfoMap[Km - 1].C[posJ];
solInfoMap[Km - 1].C[posJ] = m0;
for( int j = 0; j < eq_num; ++j )
{
(*_mesh)[Km - 1].Nk1[j] = solInfoMap[Km - 1].C[0] * solInfoMap[Km - 1].z1[j]
+ solInfoMap[Km - 1].C[1] * solInfoMap[Km - 1].z2[j]
+ solInfoMap[Km - 1].C[2] * solInfoMap[Km - 1].z3[j]
+ solInfoMap[Km - 1].C[3] * solInfoMap[Km - 1].z4[j]
+ solInfoMap[Km - 1].z5[j];
}
for( int x = Km - 2; x >= 0; --x ) //calculate the coeeficients at all the other points and restore the solution there
{
solInfoMap[x].C[3] = ( solInfoMap[x + 1].C[3]
- solInfoMap[x + 1].o[4 * eq_num + 3] )
/ solInfoMap[x + 1].o[3 * eq_num + 3];
solInfoMap[x].C[2] = ( solInfoMap[x + 1].C[2]
- solInfoMap[x + 1].o[4 * eq_num + 2]
- solInfoMap[x + 1].o[3 * eq_num + 2] * solInfoMap[x].C[3] )
/ solInfoMap[x + 1].o[2 * eq_num + 2];
solInfoMap[x].C[1] = ( solInfoMap[x + 1].C[1]
- solInfoMap[x + 1].o[4 * eq_num + 1]
- solInfoMap[x + 1].o[3 * eq_num + 1] * solInfoMap[x].C[3]
- solInfoMap[x + 1].o[2 * eq_num + 1] * solInfoMap[x].C[2] )
/ solInfoMap[x + 1].o[1 * eq_num + 1];
solInfoMap[x].C[0] = ( solInfoMap[x + 1].C[0]
- solInfoMap[x + 1].o[4 * eq_num + 0]
- solInfoMap[x + 1].o[3 * eq_num + 0] * solInfoMap[x].C[3]
- solInfoMap[x + 1].o[2 * eq_num + 0] * solInfoMap[x].C[2]
- solInfoMap[x + 1].o[1 * eq_num + 0] * solInfoMap[x].C[1] )
/ solInfoMap[x + 1].o[0 * eq_num + 0];
for( int j = 0; j < eq_num; ++j )
{
(*_mesh)[x].Nk1[j] = solInfoMap[x].C[0] * solInfoMap[x].z1[j]
+ solInfoMap[x].C[1] * solInfoMap[x].z2[j]
+ solInfoMap[x].C[2] * solInfoMap[x].z3[j]
+ solInfoMap[x].C[3] * solInfoMap[x].z4[j]
+ solInfoMap[x].z5[j];
}
}
}
void OrthoBuilderGSh::orthonorm( int baseV, int n, Matrix<PL_NUM, EQ_NUM, 1>* NtoOrt )
{
long double k11 = 1.414213562373095;
PL_NUM norm = 0;
vector<PL_NUM> omega2;
omega2.resize( eq_num * eq_num, 0.0 );
if( baseV < 1 || baseV > 5 || n < 0 || n > Km - 1 )
{
cout << "Error in orthonorm: bad input\n";
return;
}
if( baseV == 1 )
{
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].o[0 * eq_num + 0] += (*NtoOrt)( i ) * (*NtoOrt)( i );
}
solInfoMap[n + 1].o[0 * eq_num + 0] = sqrt( solInfoMap[n + 1].o[0 * eq_num + 0] );
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) = (*NtoOrt)( i ) / solInfoMap[n + 1].o[0 * eq_num + 0];
solInfoMap[n + 1].z1[i] = (*NtoOrt)( i );
}
}
else if( baseV == 2 )
{
for( int i = 0; i < eq_num; ++i )
{
norm += (*NtoOrt)( i ) * (*NtoOrt)( i );
solInfoMap[n + 1].o[1 * eq_num + 0] += (*NtoOrt)( i ) * solInfoMap[n + 1].z1[i];
}
norm = sqrt( norm );
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) = (*NtoOrt)( i ) - solInfoMap[n + 1].o[1 * eq_num + 0] * solInfoMap[n + 1].z1[i];
}
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].o[1 * eq_num + 1] += (*NtoOrt)( i ) * (*NtoOrt)( i );
}
solInfoMap[n + 1].o[1 * eq_num + 1] = sqrt( solInfoMap[n + 1].o[1 * eq_num + 1] );
if( sqrt( ( norm / solInfoMap[n + 1].o[1 * eq_num + 1] ).real() * ( norm / solInfoMap[n + 1].o[1 * eq_num + 1] ).real() +
( norm / solInfoMap[n + 1].o[1 * eq_num + 1] ).imag() * ( norm / solInfoMap[n + 1].o[1 * eq_num + 1] ).imag() ) <= k11 )
{
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) = (*NtoOrt)( i ) / solInfoMap[n + 1].o[1 * eq_num + 1];
solInfoMap[n + 1].z2[i] = (*NtoOrt)( i );
}
}
else
{
for( int i = 0; i < eq_num; ++i )
{
omega2[ 1 * eq_num + 0 ] += (*NtoOrt)( i ) * solInfoMap[n + 1].z1[i];
}
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) -= omega2[ 1 * eq_num + 0 ] * solInfoMap[n + 1].z1[i];
}
for( int i = 0; i < eq_num; ++i )
{
omega2[ 1 * eq_num + 1 ] += (*NtoOrt)( i ) * (*NtoOrt)( i );
}
omega2[ 1 * eq_num + 1 ] = sqrt( omega2[ 1 * eq_num + 1 ] );
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].z2[i] = (*NtoOrt)( i ) / omega2[ 1 * eq_num + 1 ];
(*NtoOrt)( i ) = solInfoMap[n + 1].z2[i];
}
solInfoMap[n + 1].o[1 * eq_num + 0] += omega2[ 1 * eq_num + 0 ];
solInfoMap[n + 1].o[1 * eq_num + 1] = omega2[ 1 * eq_num + 1 ];
}
}
else if( baseV == 3 )
{
for( int i = 0; i < eq_num; ++i )
{
norm += (*NtoOrt)( i ) * (*NtoOrt)( i );
solInfoMap[n + 1].o[2 * eq_num + 0] += (*NtoOrt)( i ) * solInfoMap[n + 1].z1[i];
}
norm = sqrt( norm );
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) = (*NtoOrt)( i ) - solInfoMap[n + 1].o[2 * eq_num + 0] * solInfoMap[n + 1].z1[i];
}
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].o[2 * eq_num + 1] += (*NtoOrt)( i ) * solInfoMap[n + 1].z2[i];
}
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) = (*NtoOrt)( i ) - solInfoMap[n + 1].o[2 * eq_num + 1] * solInfoMap[n + 1].z2[i];
}
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].o[2 * eq_num + 2] += (*NtoOrt)( i ) * (*NtoOrt)( i );
}
solInfoMap[n + 1].o[2 * eq_num + 2] = sqrt( solInfoMap[n + 1].o[2 * eq_num + 2] );
if( sqrt( ( norm / solInfoMap[n + 1].o[2 * eq_num + 2] ).real() * ( norm / solInfoMap[n + 1].o[2 * eq_num + 2] ).real()
+ ( norm / solInfoMap[n + 1].o[2 * eq_num + 2] ).imag() * ( norm / solInfoMap[n + 1].o[2 * eq_num + 2] ).imag() ) <= k11 )
{
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) = (*NtoOrt)( i ) / solInfoMap[n + 1].o[2 * eq_num + 2];
solInfoMap[n + 1].z3[i] = (*NtoOrt)( i );
}
}
else
{
for( int i = 0; i < eq_num; ++i )
{
omega2[ 2 * eq_num + 0 ] += (*NtoOrt)( i ) * solInfoMap[n + 1].z1[i];
}
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) -= omega2[ 2 * eq_num + 0 ] * solInfoMap[n + 1].z1[i];
}
for( int i = 0; i < eq_num; ++i )
{
omega2[ 2 * eq_num + 1 ] += (*NtoOrt)( i ) * solInfoMap[n + 1].z2[i];
}
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) -= omega2[ 2 * eq_num + 1 ] * solInfoMap[n + 1].z2[i];
}
for( int i = 0; i < eq_num; ++i )
{
omega2[ 2 * eq_num + 2 ] += (*NtoOrt)( i ) * (*NtoOrt)( i );
}
omega2[ 2 * eq_num + 2 ] = sqrt( omega2[ 2 * eq_num + 2 ] );
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].z3[i] = (*NtoOrt)( i ) / omega2[ 2 * eq_num + 2 ];
(*NtoOrt)( i ) = solInfoMap[n + 1].z3[i];
}
solInfoMap[n + 1].o[2 * eq_num + 0] += omega2[ 2 * eq_num + 0 ];
solInfoMap[n + 1].o[2 * eq_num + 1] += omega2[ 2 * eq_num + 1 ];
solInfoMap[n + 1].o[2 * eq_num + 2] = omega2[ 2 * eq_num + 2 ];
}
}
else if( baseV == 4 )
{
for( int i = 0; i < eq_num; ++i )
{
norm += (*NtoOrt)( i ) * (*NtoOrt)( i );
solInfoMap[n + 1].o[3 * eq_num + 0] += (*NtoOrt)( i ) * solInfoMap[n + 1].z1[i];
}
norm = sqrt( norm );
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) -= solInfoMap[n + 1].o[3 * eq_num + 0] * solInfoMap[n + 1].z1[i];
}
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].o[3 * eq_num + 1] += (*NtoOrt)( i ) * solInfoMap[n + 1].z2[i];
}
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) -= solInfoMap[n + 1].o[3 * eq_num + 1] * solInfoMap[n + 1].z2[i];
}
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].o[3 * eq_num + 2] += (*NtoOrt)( i ) * solInfoMap[n + 1].z3[i];
}
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) -= solInfoMap[n + 1].o[3 * eq_num + 2] * solInfoMap[n + 1].z3[i];
}
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].o[3 * eq_num + 3] += (*NtoOrt)( i ) * (*NtoOrt)( i );
}
solInfoMap[n + 1].o[3 * eq_num + 3] = sqrt( solInfoMap[n + 1].o[3 * eq_num + 3] );
if( sqrt( ( norm / solInfoMap[n + 1].o[3 * eq_num + 3] ).real() * ( norm / solInfoMap[n + 1].o[3 * eq_num + 3] ).real()
+ ( norm / solInfoMap[n + 1].o[3 * eq_num + 3] ).imag() * ( norm / solInfoMap[n + 1].o[3 * eq_num + 3] ).imag() ) <= k11 )
{
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) = (*NtoOrt)( i ) / solInfoMap[n + 1].o[3 * eq_num + 3];
solInfoMap[n + 1].z4[i] = (*NtoOrt)( i );
}
}
else
{
//cout << "N4 > k11\n";
for( int i = 0; i < eq_num; ++i )
{
omega2[ 3 * eq_num + 0 ] += (*NtoOrt)( i ) * solInfoMap[n + 1].z1[i];
}
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) -= omega2[ 3 * eq_num + 0 ] * solInfoMap[n + 1].z1[i];
}
for( int i = 0; i < eq_num; ++i )
{
omega2[ 3 * eq_num + 1 ] += (*NtoOrt)( i ) * solInfoMap[n + 1].z2[i];
}
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) -= omega2[ 3 * eq_num + 1 ] * solInfoMap[n + 1].z2[i];
}
for( int i = 0; i < eq_num; ++i )
{
omega2[ 3 * eq_num + 2 ] += (*NtoOrt)( i ) * solInfoMap[n + 1].z3[i];
}
for( int i = 0; i < eq_num; ++i )
{
(*NtoOrt)( i ) -= omega2[ 3 * eq_num + 2 ] * solInfoMap[n + 1].z3[i];
}
for( int i = 0; i < eq_num; ++i )
{
omega2[ 3 * eq_num + 3 ] += (*NtoOrt)( i ) * (*NtoOrt)( i );
}
omega2[ 3 * eq_num + 3 ] = sqrt( omega2[ 3 * eq_num + 3 ] );
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].z4[i] = (*NtoOrt)( i ) / omega2[ 3 * eq_num + 3 ];
(*NtoOrt)( i ) = solInfoMap[n + 1].z4[i];
}
solInfoMap[n + 1].o[3 * eq_num + 0] += omega2[ 3 * eq_num + 0 ];
solInfoMap[n + 1].o[3 * eq_num + 1] += omega2[ 3 * eq_num + 1 ];
solInfoMap[n + 1].o[3 * eq_num + 2] += omega2[ 3 * eq_num + 2 ];
solInfoMap[n + 1].o[3 * eq_num + 3] = omega2[ 3 * eq_num + 3 ];
}
}
else if( baseV == 5 )
{
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].o[4 * eq_num + 0] += (*NtoOrt)( i ) * solInfoMap[n + 1].z1[i];
solInfoMap[n + 1].o[4 * eq_num + 1] += (*NtoOrt)( i ) * solInfoMap[n + 1].z2[i];
solInfoMap[n + 1].o[4 * eq_num + 2] += (*NtoOrt)( i ) * solInfoMap[n + 1].z3[i];
solInfoMap[n + 1].o[4 * eq_num + 3] += (*NtoOrt)( i ) * solInfoMap[n + 1].z4[i];
}
for( int i = 0; i < eq_num; ++i )
{
solInfoMap[n + 1].z5[i] = (*NtoOrt)( i ) - solInfoMap[n + 1].o[4 * eq_num + 0] * solInfoMap[n + 1].z1[i]
- solInfoMap[n + 1].o[4 * eq_num + 1] * solInfoMap[n + 1].z2[i]
- solInfoMap[n + 1].o[4 * eq_num + 2] * solInfoMap[n + 1].z3[i]
- solInfoMap[n + 1].o[4 * eq_num + 3] * solInfoMap[n + 1].z4[i];
(*NtoOrt)( i ) = solInfoMap[n + 1].z5[i];
}
}
}
void OrthoBuilderGSh::buildSolution( vector<VarVect>* _mesh )
{
vector<PL_NUM> M;
vector<PL_NUM> f11;
vector<PL_NUM> L;
vector<PL_NUM> R;
vector<PL_NUM> x1;
int msize = eq_num / 2; //caution here!
M.resize( msize * msize, 0.0 );
f11.resize( msize, 0.0 );
L.resize( msize * msize, 0.0 );
R.resize( msize * msize, 0.0 );
x1.resize( msize, 0.0 );
//simply supported plate NO CURRENT PASSING THROUGH THE BOUNDARY
M[0 * msize + 0] = solInfoMap[Km - 1].z1[0];
M[1 * msize + 0] = solInfoMap[Km - 1].z1[1];
M[2 * msize + 0] = solInfoMap[Km - 1].z1[5];
M[3 * msize + 0] = solInfoMap[Km - 1].z1[6];
M[0 * msize + 1] = solInfoMap[Km - 1].z2[0];
M[1 * msize + 1] = solInfoMap[Km - 1].z2[1];
M[2 * msize + 1] = solInfoMap[Km - 1].z2[5];
M[3 * msize + 1] = solInfoMap[Km - 1].z2[6];
M[0 * msize + 2] = solInfoMap[Km - 1].z3[0];
M[1 * msize + 2] = solInfoMap[Km - 1].z3[1];
M[2 * msize + 2] = solInfoMap[Km - 1].z3[5];
M[3 * msize + 2] = solInfoMap[Km - 1].z3[6];
M[0 * msize + 3] = solInfoMap[Km - 1].z4[0];
M[1 * msize + 3] = solInfoMap[Km - 1].z4[1];
M[2 * msize + 3] = solInfoMap[Km - 1].z4[5];
M[3 * msize + 3] = solInfoMap[Km - 1].z4[6];
f11[0] = -solInfoMap[Km - 1].z5[0];
f11[1] = -solInfoMap[Km - 1].z5[1];
f11[2] = -solInfoMap[Km - 1].z5[5];
f11[3] = -solInfoMap[Km - 1].z5[6];
int posI = 0;
int posJ = 0;
for( int i = 0; i < msize; ++i )
{
int found = 0;
//for(int j = 0; j < msize; ++j )
//{
int j =0;
if( fabs( M[i * msize + j].real() ) >= 0.0000000001 )
{
found = 1;
posI = i;
posJ = j;
break;
}
//}
if( found == 1 )
{
break;
}
}
PL_NUM m0, m1, m2, m3;
m0 = M[posI * msize + 0];
m1 = M[posI * msize + 1];
m2 = M[posI * msize + 2];
m3 = M[posI * msize + 3];
M[posI * msize + 0] = M[0 * msize + 0];
M[posI * msize + 1] = M[0 * msize + 1];
M[posI * msize + 2] = M[0 * msize + 2];
M[posI * msize + 3] = M[0 * msize + 3];
M[0 * msize + 0] = m0;
M[0 * msize + 1] = m1;
M[0 * msize + 2] = m2;
M[0 * msize + 3] = m3;
//m0 = M[0 * msize + posJ];
//m1 = M[0 * msize + posJ];
//m2 = M[0 * msize + posJ];
//m3 = M[0 * msize + posJ];
//M[0 * msize + posJ] = M[0 * msize + 0];
//M[1 * msize + posJ] = M[1 * msize + 0];
//M[2 * msize + posJ] = M[2 * msize + 0];
//M[3 * msize + posJ] = M[3 * msize + 0];
//M[0 * msize + 0] = m0;
//M[1 * msize + 0] = m1;
//M[2 * msize + 0] = m2;
//M[3 * msize + 0] = m3;
m0 = f11[posI];
f11[posI] = f11[0];
f11[0] = m0;
for( int i = 0; i < msize; ++i )
{
L[i * msize + 0] = M[i * msize + 0];
for( int j = i + 1; j < msize; ++j ) //TODO I think this is redundant
{
L[i * msize + j] = 0.0;
R[j * msize + i] = 0.0;
}
}
for( int i = 1; i < msize; ++i )
{
R[0 * msize + i] = M[0 * msize + i] / L[0 * msize + 0];
}
for( int i = 0; i < msize; ++i )
{
R[i * msize + i] = 1.0;
}
for( int i = 1; i < msize; ++i )
{
for( int k = i; k < msize; ++k )
{
L[k * msize + i] = M[k * msize + i];
for( int l = 0; l < i; ++l )
{
L[k * msize + i] -= L[k * msize + l] * R[l * msize + i];
}
}
for( int j = i + 1; j < msize; ++j )
{
R[i * msize + j] = M[i * msize + j];
for( int l = 0; l < i; ++l )
{
R[i * msize + j] -= L[i * msize + l] * R[l * msize + j];
}
R[i * msize + j] /= L[i * msize + i];
}
}
f11[0] = f11[0] / L[0 * msize + 0];
for( int i = 1; i < msize; ++i )
{
for( int j = 0; j < i; ++j )
{
f11[i] -= L[i * msize + j] * f11[j];
}
f11[i] /= L[i * msize + i];
}
x1[msize - 1] = f11[msize - 1];
for( int i = msize - 2; i >= 0; --i )
{
x1[i] = f11[i];
for( int j = i + 1; j < msize; ++j )
{
x1[i] -= R[i * msize + j] * x1[j];
}
}
for( int i = 0; i < msize; ++i )
{
solInfoMap[Km - 1].C[i] = x1[i];
}
//m0 = solInfoMap[Km - 1].C[0]; //we changed the order in M matrix, so we must change it in C too
//solInfoMap[Km - 1].C[0] = solInfoMap[Km - 1].C[posJ];
//solInfoMap[Km - 1].C[posJ] = m0;
for( int j = 0; j < eq_num; ++j )
{
(*_mesh)[Km - 1].Nk1[j] = solInfoMap[Km - 1].C[0] * solInfoMap[Km - 1].z1[j]
+ solInfoMap[Km - 1].C[1] * solInfoMap[Km - 1].z2[j]
+ solInfoMap[Km - 1].C[2] * solInfoMap[Km - 1].z3[j]
+ solInfoMap[Km - 1].C[3] * solInfoMap[Km - 1].z4[j]
+ solInfoMap[Km - 1].z5[j];
}
for( int x = Km - 2; x >= 0; --x ) //calculate the coeeficients at all the other points and restore the solution there
{
solInfoMap[x].C[3] = ( solInfoMap[x + 1].C[3]
- solInfoMap[x + 1].o[4 * eq_num + 3] )
/ solInfoMap[x + 1].o[3 * eq_num + 3];
solInfoMap[x].C[2] = ( solInfoMap[x + 1].C[2]
- solInfoMap[x + 1].o[4 * eq_num + 2]
- solInfoMap[x + 1].o[3 * eq_num + 2] * solInfoMap[x].C[3] )
/ solInfoMap[x + 1].o[2 * eq_num + 2];
solInfoMap[x].C[1] = ( solInfoMap[x + 1].C[1]
- solInfoMap[x + 1].o[4 * eq_num + 1]
- solInfoMap[x + 1].o[3 * eq_num + 1] * solInfoMap[x].C[3]
- solInfoMap[x + 1].o[2 * eq_num + 1] * solInfoMap[x].C[2] )
/ solInfoMap[x + 1].o[1 * eq_num + 1];
solInfoMap[x].C[0] = ( solInfoMap[x + 1].C[0]
- solInfoMap[x + 1].o[4 * eq_num + 0]
- solInfoMap[x + 1].o[3 * eq_num + 0] * solInfoMap[x].C[3]
- solInfoMap[x + 1].o[2 * eq_num + 0] * solInfoMap[x].C[2]
- solInfoMap[x + 1].o[1 * eq_num + 0] * solInfoMap[x].C[1] )
/ solInfoMap[x + 1].o[0 * eq_num + 0];
for( int j = 0; j < eq_num; ++j )
{
(*_mesh)[x].Nk1[j] = solInfoMap[x].C[0] * solInfoMap[x].z1[j]
+ solInfoMap[x].C[1] * solInfoMap[x].z2[j]
+ solInfoMap[x].C[2] * solInfoMap[x].z3[j]
+ solInfoMap[x].C[3] * solInfoMap[x].z4[j]
+ solInfoMap[x].z5[j];
}
}
}
|
#ifndef MASTERS_PROJECT_EUROBINOMIALMETHODVERSION2_H
#define MASTERS_PROJECT_EUROBINOMIALMETHODVERSION2_H
#include "EuroBinomialMethod.hpp"
template<typename X>
class EuroBinomialMethod2 : public EuroBinomialMethod<X> {
public:
EuroBinomialMethod2(Case<X> *_aCase);
protected:
void build_asset_price_tree() override;
};
#include "EuroBinomialMethod2.tpp"
#endif //MASTERS_PROJECT_EUROBINOMIALMETHODVERSION2_H
|
#include <Arduino.h>
using namespace std;
#ifndef __OneLiner_H__
#define __OneLiner_H__
struct OneLinerMessage{
float data;
int msgType;
char* topic;
char* msg;
};
class OneLiner
{
/*
OneLiner is a simple class for arduino
that makes writing messages to rofous_ros
clean and easy. These messages are handled
by the arduino_reader package.
*/
private:
unsigned long start;
public:
OneLiner(); // Default init
float stamp(); // Return curent timestamp
void publish(OneLinerMessage); // publish a OneLinerMessage
OneLinerMessage init(char*, int); // Create a message instance
};
# endif
|
/*
朴素的实现方法,时间复杂度为O(n^4)——需要找O(n)次增广路,每次增广最多需要修改O(n)次顶标,
每次修改顶标时由于要枚举边来求min值,复杂度为O(n^2)。实际上KM算法的复杂度是可以做到O(n^3)的。
我们给每个Y顶点一个“松弛量”函数slack,每次开始找增广路时初始化为无穷大。
在寻找增广路的过程中,检查边(i,j)时,如果它不在相等子图中,
则让slack[j]变成原值与lx[i]+ly[j]-g[i][j]的较小值。
这样,在修改顶标时,取所有不在交错树中的Y顶点的slack值中的最小值作为d值即可。
但还要注意一点:由于修改顶标后,所有在交错树中的lx[i]都减d,因此要把所有的slack值都减去d。
*/
#include<iostream>
#define fo(i,u,d) for (long i=(u); i<=(d); ++i)
using namespace std;
const long maxn=201;
const long inf=1000000000;
long w[maxn];
long lx[maxn],ly[maxn];
bool bx[maxn],by[maxn];
long n,g[maxn][maxn];
long slack[maxn];
void init()
{
fo(i,1,n)
fo(j,1,n) scanf("%d",&g[i][j]);
}
bool find(long x)
{
bx[x]=1;
fo(i,1,n) {
if (!by[i] && lx[x]+ly[i]==g[x][i]) {
by[i]=1;
if (!w[i] || find(w[i])) {
w[i]=x;
return 1;
}
continue;
}
if (lx[x]+ly[i]>g[x][i]) slack[i]=slack[i]<lx[x]+ly[i]-g[x][i]?slack[i]:lx[x]+ly[i]-g[x][i];
}
return 0;
}
void solve()
{
fo(i,1,n) {
lx[i]=ly[i]=0;
fo(j,1,n)
if (g[i][j]>lx[i]) lx[i]=g[i][j];
}
memset(w,0,sizeof(w));
for (long l=1,min; l<=n; ++l) {
fo(i,1,n) slack[i]=inf;
for (;;) {
memset(bx,0,sizeof(bx));
memset(by,0,sizeof(by));
if (find(l)) break;
min=inf;
fo(i,1,n)
if (!by[i]) min=min<slack[i]?min:slack[i];
/*fo(i,1,n) if (bx[i])
fo(j,1,n) if (!by[j])
min=lx[i]+ly[j]-g[i][j]<min?lx[i]+ly[j]-g[i][j]:min;*/
fo(i,1,n) {
if (bx[i]) lx[i]-=min;
if (by[i]) ly[i]+=min;
slack[i]-=min;
}
}
}
long ans=0;
fo(i,1,n) ans+=g[w[i]][i];
printf("%d\n",ans);
}
int main()
{
while (scanf("%d",&n),n!=0) {
init();
solve();
}
return 0;
}
|
#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
using namespace std;
void print_list(const list<int> &l1, const list<int> &l2)
{
cout << "list 1 : " ;
copy(l1.begin(), l1.end(), ostream_iterator<int>(cout, " "));
cout << endl << "list 2 : ";
copy(l2.begin(), l2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
int main(int argc, char *argv[])
{
list<int> list1,list2;
for (int i = 0; i < 6; ++ i) {
list1.push_back(i);
list2.push_front(i);
}
print_list(list1, list2);
list2.splice(find(list2.begin(), list2.end(), 3), list1);
print_list(list1, list2);
/* move first element to the end */
list2.splice(list2.end(),
list2,
list2.begin());
print_list(list1, list2);
list2.sort();
list1 = list2;
list2.unique();
print_list(list1, list2);
list1.merge(list2);
print_list(list1, list2);
return 0;
}
|
/*
* File: main.cpp
* Author: Elijah De Vera
* Created on January 14, 2021, 12:29 PM
* Purpose: Calculating sums of pos and neg integers
*/
//System Libraries
#include <iostream> //Input/Output Library
#include <iomanip>
using namespace std;
//User Libraries
//Global Constants, no Global Variables are allowed
//Math/Physics/Conversions/Higher Dimensions - i.e. PI, e, etc...
//Function Prototypes
//Execution Begins Here!
int main(int argc, char** argv) {
//Set the random number seed
//Declare Variables
float number,
negSum,
posSum,
sum;
//Initialize or input i.e. set variable values
cout << "Input 10 numbers, any order, positive or negative" << endl;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
cin >> number;
posSum += ( number > 0 ) ? number : 0.0;
negSum += ( number < 0 ) ? number : 0.0;
//Map inputs ->
sum = negSum + posSum; // calc total sum
//Display the outputs
cout << "Negative sum = " << setw(3) << negSum << endl;
cout << "Positive sum = " << setw(3) << posSum << endl;
cout << "Total sum = " << setw(3) << sum;
//Exit stage right or left!
return 0;
}
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files(the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
====================================================================*/
#pragma once
#include <atomic>
namespace HoloIntervention
{
namespace Rendering
{
class Model;
}
namespace UI
{
class Icon
{
public:
Icon();
~Icon();
void SetId(uint64 id);
uint64 GetId() const;
std::shared_ptr<Rendering::Model> GetModel() const;
void SetModel(std::shared_ptr<Rendering::Model> entry);
void SetUserRotation(float pitch, float yaw, float roll);
void SetUserRotation(Windows::Foundation::Numerics::quaternion rotation);
void SetUserRotation(Windows::Foundation::Numerics::float4x4 rotation);
Windows::Foundation::Numerics::float4x4 GetUserRotation() const;
std::array<float, 6> GetRotatedBounds() const;
bool GetFirstFrame() const;
void SetFirstFrame(bool firstFrame);
void SetUserValue(uint64 userValue);
uint64 GetUserValueNumber() const;
void SetUserValue(const std::wstring& userValue);
std::wstring GetUserValueString() const;
protected:
uint64 m_id;
std::atomic_bool m_firstFrame = true;
std::shared_ptr<Rendering::Model> m_model;
// Allow a custom rotation for optical icon viewing angles
Windows::Foundation::Numerics::float4x4 m_userRotation = Windows::Foundation::Numerics::float4x4::identity();
// Cache model bounds to reduce recomputation
std::array<float, 6> m_rotatedBounds;
uint64 m_userValueNumber = 0;
std::wstring m_userValueString = L"";
};
}
}
|
// Module2.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
using namespace std;
int main()
{
// Get the variables for this module
// Joe paid his stockbroker a commission that amounted to 2 percent of the amount he paid for the stock.
const float BROKER = .02,
// When Joe purchased the stock, he paid $45.50 per share.
PAID_SHARE = 45.50,
// He sold the stock for $56.90 per share.
SOLD_SHARE = 56.90;
/// The number of shares that Joe purchased was 1,000.
const int SHARES = 1000;
// Math variables to do some mix/match
float joes_purchase,
total_com_bought,
total_com_sold,
amount_stock_sold_for,
amount_of_profit;
// Math Time
// The amount of money Joe paid for the stock.
joes_purchase = SHARES * PAID_SHARE;
// The amount of commission Joe paid his broker when he bought the stock.
total_com_bought = joes_purchase * BROKER;
// The amount that Joe sold the stock for.
amount_stock_sold_for = SHARES * SOLD_SHARE;
// The amount of commission Joe paid his broker when he sold the stock.
total_com_sold = amount_stock_sold_for * BROKER;
// (If the amount of profit that your program displays is a negative number, then Joe lost money on the transaction.
amount_of_profit = (amount_stock_sold_for - (total_com_bought + total_com_sold));
// Time to Display
cout << "Amount paid for the stock: " << joes_purchase << "\n" << endl;
cout << "Amount of commission Joe paid to broker to buy the stock: " << total_com_bought << "\n" << endl;
cout << "Amount Joe sold the stock for: " << amount_stock_sold_for << "\n" << endl;
cout << "Amount of commission Joe paid his broker when he sold the stock: " << total_com_sold << "\n" << endl;
cout << "Amount of profit that Joe made after selling his stock and paying the two commissions to his broker: " << amount_of_profit << "\n" << endl;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.