text
stringlengths 8
6.88M
|
|---|
/*
*
* Copyright (c) 2002, 2003 Kresimir Fresl, Toon Knapen and Karl Meerbergen
*
* 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)
*
* KF acknowledges the support of the Faculty of Civil Engineering,
* University of Zagreb, Croatia.
*
*/
#ifndef BOOST_NUMERIC_BINDINGS_TRAITS_VECTOR_TRAITS_HPP
#define BOOST_NUMERIC_BINDINGS_TRAITS_VECTOR_TRAITS_HPP
#include <boost/numeric/bindings/traits/config.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/numeric/bindings/traits/is_numeric.hpp>
#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS
#include <boost/numeric/bindings/traits/detail/generate_const.hpp>
#include <boost/type_traits/remove_const.hpp>
#ifndef BOOST_NUMERIC_BINDINGS_NO_SANITY_CHECK
# include <boost/type_traits/is_same.hpp>
# include <boost/static_assert.hpp>
#endif
namespace boost { namespace numeric { namespace bindings { namespace traits {
/// default_vector_traits is just a base-class that can be
/// used as the default vector_traits and the different
/// specialisation to automatically define most of the
/// functions.
template <typename V, typename T = typename V::value_type >
struct default_vector_traits {
typedef T value_type;
typedef typename detail::generate_const<V,value_type>::type* pointer; // if V is const, pointer will be a const value_type*
static pointer storage (V& v) { return &v[0]; }
static std::ptrdiff_t size (V& v) { return static_cast<std::ptrdiff_t>(v.size()); }
static std::ptrdiff_t stride (V&) { return 1; }
};
// vector_detail_traits is used to implement specializations of vector_traits.
// VIdentifier is the vector_type without const, while VType can have a const.
// VIdentifier is used to write template specializations for VType and const VType.
// e.g. vector_detail_traits< std::vector<int>, std::vector<int> const >
// e.g. vector_detail_traits< std::vector<int>, std::vector<int> >
// Note that boost::remove_const<VType>::type == VIdentifier.
template <typename VIdentifier, typename VType>
struct vector_detail_traits {
typedef VIdentifier identifier_type;
typedef VType vector_type;
};
// vector_traits<> generic version: no specialization(s)
template< typename V, typename Enable = void>
struct vector_traits {};
// vector_traits<>, derives from vector_detail_traits<> if
// vector_detail_traits<>::value_type is a numeric type
template <typename V>
struct vector_traits< V, typename boost::enable_if< is_numeric<
typename vector_detail_traits< typename boost::remove_const<V>::type, V >::value_type
> >::type >:
vector_detail_traits< typename boost::remove_const<V>::type, V > {};
///////////////////////////
//
// free accessor functions:
//
///////////////////////////
template <typename V>
inline
typename vector_traits<V>::pointer vector_storage (V& v) {
return vector_traits<V>::storage (v);
}
template <typename V>
inline
std::ptrdiff_t vector_size (V& v) {
return vector_traits<V>::size (v);
}
template <typename V>
inline
std::ptrdiff_t vector_stride (V& v) {
return vector_traits<V>::stride (v);
}
}}}}
#else // BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS
#include <boost/numeric/bindings/traits/vector_raw.hpp>
#endif // BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS
#endif // BOOST_NUMERIC_BINDINGS_TRAITS_VECTOR_TRAITS_HPP
|
#include <iostream>
#include "matrix.h"
using namespace std;
template <class T>
Matrix<T>::Matrix(){
this->matrix = NULL;
rows=0;
cols = 0;
}
template <class T>
Matrix<T>::Matrix(int rows, int cols){
// rol cols constructor called
matrix = new T* [rows];
for(int i=0; i< rows; i++) matrix[i] = new T[cols];
this->rows = rows;
this->cols = cols;
}
template <class T>
Matrix<T>::Matrix(const Matrix &obj){
this->rows = obj.rows;
this->cols = obj.cols;
this->matrix = new T* [this->rows];
for(int i=0; i< this->rows; i++){
this->matrix[i] = new T [this->cols];
}
for(int i=0; i< this->rows; i++){
for(int j=0; j< this->cols; j++){
T element = obj.getElement(i,j);
this->insertElement(element,i,j);
}
}
}
template <class T>
int Matrix<T>::getNoOfRows() const {return this->rows;}
template <class T>
int Matrix<T>::getNoOfCols() const {return this->cols;}
template <class T>
T Matrix<T>::getElement(int row, int col) const{
return matrix[row][col];
}
template <class T>
void Matrix<T>::insertElement(T const &element, int rowNo, int colNo){
if(rows >= rowNo && cols >= colNo){
matrix[rowNo][colNo] = element;
}
else{
cout << "index out of range \n";
}
}
template <class T>
void Matrix<T>::print(){
for(int i=0; i< rows; i++){
for(int j=0; j < cols; j++){
cout << this->matrix[i][j] << " ";
}
cout << "\n";
}
}
template <class T>
void Matrix<T>::transpose(){
T **temp_matrix = new T*[cols];
for(int i=0; i < cols; i++){
temp_matrix[i] = new T[rows];
}
// now fill the values
for(int i=0; i< cols; i++){
for(int j=0; j < rows; j++){
temp_matrix[i][j] = matrix[j][i];
}
}
//------------- delete old matrix
for(int i=0; i< rows; i++){
delete[]matrix[i];
}
//------------ now point matrix to temp_matrix
matrix = temp_matrix;
int temp_rows = this->rows;
this->rows = cols;
this->cols =temp_rows;
}
template <class T>
Matrix& Matrix<T>::operator+ (const Matrix & obj){
if(this->rows == obj.getNoOfRows() && this->cols == obj.getNoOfCols()){
Matrix *m = new Matrix(this->rows, this->cols);
for(int i=0; i< this->rows; i++){
for(int j=0; j< this->cols; j++){
T element = this->getElement(i,j)+obj.getElement(i,j);
m->insertElement(element,i,j);
}
}
return *m;
}
else{
cout << "addition is not possible as there are different dimensions \n";
}
}
template <class T>
void Matrix<T>::operator = (const Matrix &obj){
if(this != &obj){
this->rows = obj.rows;
this->cols = obj.cols;
this->matrix = new T*[this->rows];
for(int i=0; i < this->rows; i++){
this->matrix[i] = new T [this->cols];
}
// now assign correspinding values
for(int i=0; i< this->rows; i++){
for(int j=0; j< this->cols; j++){
T element = obj.getElement(i,j);
//this->matrix[i][j] = obj.matrix[i][j];
this->insertElement(element,i,j);
}
}
}
}
//------------
template <class T>
Matrix<T>::~Matrix(){
if(this->rows !=0){
for(int i=0; i< this->rows; i++) delete []matrix[i];
delete matrix;
matrix = NULL;
}
}
|
#pragma once
#include "SFML/Graphics.hpp"
namespace RTB
{
class TileMap : public sf::Drawable, public sf::Transformable
{
};
}
|
#include "valid_test_sub.h"
#include "my_utils.h"
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
double apk(unordered_set<unsigned long> &actual, vector<unsigned long> &predicted, const int k){
int num_pred = predicted.size();
num_pred = num_pred < k ? num_pred : k;
int num_hit = 0;
double score = 0;
for (int i = 0; i < num_pred; i++){
if (actual.count(predicted[i])){
num_hit++;
score += double(num_hit) / (i+1);
}
}
if (num_hit != 0)
score /= actual.size();
return score;
}
void time_split_generate_validate(unsigned int split, ifstream &f_train, ofstream &f_valid_train, ofstream &f_valid_test){
string line;
getline(f_train, line);
f_valid_train << line << endl;
f_valid_test << line << endl;
while (getline(f_train, line)){
vector<string> tokens;
split_line(line, ',', tokens);
unsigned int cur_time;
cur_time = stoi(tokens[4]);
if (cur_time <= split){
f_valid_train << line << endl;
}else{
f_valid_test << line << endl;
}
}
f_train.clear();
f_train.seekg(0, ios_base::beg);
}
void generate_valid_score(ofstream &f_sub, int max_sub, vector<unordered_map<unsigned long, double> > &score){
size_t num_lines = score.size();
f_sub << "row_id,place_id" << endl;
for (int i_line = 0; i_line < num_lines; i_line++){
unordered_map<unsigned long, double> &line_score = score[i_line];
priority_queue<pair<double, unsigned long> > line_pq;
for (auto it = line_score.begin(); it != line_score.end(); it++){
line_pq.push( pair<double, unsigned long>( (*it).second, (*it).first) );
}
f_sub << i_line << ',';
int i = 0;
while (i < max_sub && !line_pq.empty()){
f_sub << ',';
f_sub << line_pq.top().second;
f_sub << ',';
f_sub << line_pq.top().first;
line_pq.pop();
i++;
}
f_sub << endl;
}
}
void generate_sub(ofstream &f_sub, int max_sub, vector<unordered_map<unsigned long, double> > &score){
size_t num_lines = score.size();
f_sub << "row_id,place_id" << endl;
for (int i_line = 0; i_line < num_lines; i_line++){
unordered_map<unsigned long, double> &line_score = score[i_line];
priority_queue<pair<double, unsigned long> > line_pq;
for (auto it = line_score.begin(); it != line_score.end(); it++){
line_pq.push( pair<double, unsigned long>( (*it).second, (*it).first) );
}
f_sub << i_line << ',';
int i = 0;
while (i < max_sub && !line_pq.empty()){
f_sub << ' ';
f_sub << line_pq.top().second;
line_pq.pop();
i++;
}
f_sub << endl;
}
}
double validate_apk(ifstream &f_valid_test, int max_sub, vector<unordered_map<unsigned long, double>> &score){
size_t num_lines = score.size();
string line;
// maybe write a header to the f_valid
getline(f_valid_test, line);
double mapk_score = 0;
for (int i_line = 0; i_line < num_lines; i_line++){
if ( !getline(f_valid_test, line) ){
cout << "f_valid not matching with score!" << endl;
return 0;
}
vector<string> tokens;
split_line(line, ',', tokens);
unsigned long place_id;
unsigned int row_id;
place_id = stoul(tokens[5]);
row_id = stoi(tokens[0]);
unordered_set<unsigned long> line_act({place_id});
unordered_map<unsigned long, double> &line_score = score[i_line];
priority_queue<pair<double, unsigned long> > line_pq;
for (auto it = line_score.begin(); it != line_score.end(); it++){
line_pq.push( pair<double, unsigned long>( (*it).second, (*it).first) );
}
vector<unsigned long> line_pred;
int i = 0;
while (i < max_sub && !line_pq.empty()){
line_pred.push_back(line_pq.top().second);
line_pq.pop();
i++;
}
double cur_score = apk(line_act, line_pred, max_sub);
// if (cur_score < 0.3)
// cout << line << endl;
mapk_score += cur_score;
}
mapk_score /= num_lines;
f_valid_test.clear();
f_valid_test.seekg(0, ios_base::beg);
return mapk_score;
}
void reorder_score(ifstream &f_input, ofstream &f_output){
string header, line;
getline(f_input, header);
unordered_map<unsigned int, string> line_map;
vector<unsigned int> row_ids;
while ( getline(f_input, line) ){
vector<string> tokens;
split_line(line, ',', tokens);
unsigned int row_id;
row_id = stoi(tokens[0]);
row_ids.push_back(row_id);
line_map[row_id] = line;
}
f_input.clear();
f_input.seekg(0, ios_base::beg);
sort(row_ids.begin(), row_ids.end());
unsigned int num_lines = line_map.size();
cout << "reorder_score: " << num_lines << endl;
f_output << header << endl;
for (int i = 0; i < num_lines; i++){
unsigned int row_id = row_ids[i];
f_output << line_map[row_id] << endl;
}
}
void generate_row_id_map(ifstream &f_valid_test, unordered_map<unsigned int, unsigned int> &row_id_map){
string line;
getline(f_valid_test, line);
unsigned int line_counter = 0;
while (getline(f_valid_test, line)){
vector<string> tokens;
split_line(line, ',', tokens);
unsigned int row_id;
row_id = stoi(tokens[0]);
row_id_map[row_id] = line_counter;
line_counter++;
}
f_valid_test.clear();
f_valid_test.seekg(0, ios_base::beg);
}
// here we assume that the file is unordered
void file_update_score(ifstream &f_input, double weight,
vector<unordered_map<unsigned long, double> > &score, unordered_map<unsigned int, unsigned int> &row_id_map){
size_t num_lines = score.size();
string line;
// maybe write a header to the f_valid
getline(f_input, line);
for (int i_line = 0; i_line < num_lines; i_line++){
if ( !getline(f_input, line) ){
cout << "file not matching with score!" << endl;
// return 0;
}
vector<string> tokens;
split_line(line, ',', tokens);
int num_tokens, num_pairs;
num_tokens = tokens.size();
num_pairs = (tokens.size()-1)/2;
unsigned int row_id, line_id;
row_id = stoi(tokens[0]);
line_id = row_id_map[row_id];
unordered_map<unsigned long, double> &line_score = score[line_id];
for (int i = 0; i < num_pairs; i++){
unsigned long place_id;
double score;
place_id = stoul(tokens[i * 2 + 1]);
score = stod(tokens[i * 2 + 2]);
if (line_score.count(place_id)){
line_score[place_id] += weight * score;
}else{
line_score[place_id] = weight * score;
}
}
}
f_input.clear();
f_input.seekg(0, ios_base::beg);
}
// file_update_score only keep first several
void file_update_score_limited(ifstream &f_input, double weight, unsigned int limit,
vector<unordered_map<unsigned long, double> > &score, unordered_map<unsigned int, unsigned int> &row_id_map){
size_t num_lines = score.size();
string line;
// maybe write a header to the f_valid
getline(f_input, line);
for (int i_line = 0; i_line < num_lines; i_line++){
if ( !getline(f_input, line) ){
cout << "file not matching with score!" << endl;
// return 0;
}
vector<string> tokens;
split_line(line, ',', tokens);
int num_tokens, num_pairs;
num_tokens = tokens.size();
num_pairs = (tokens.size()-1)/2;
unsigned int row_id, line_id;
row_id = stoi(tokens[0]);
line_id = row_id_map[row_id];
unordered_map<unsigned long, double> &line_score = score[line_id];
for (int i = 0; i < num_pairs; i++){
unsigned long place_id;
double score;
place_id = stoul(tokens[i * 2 + 1]);
score = stod(tokens[i * 2 + 2]);
if (line_score.count(place_id)){
line_score[place_id] += weight * score;
}else{
line_score[place_id] = weight * score;
}
}
if (limit > 0 && limit < line_score.size()){
vector<pair<double, unsigned long> > cur_line_scores;
for (auto it = line_score.begin(); it != line_score.end(); it++){
cur_line_scores.push_back( pair<double, unsigned long>((*it).second, (*it).first) );
}
for (int i = limit; i < cur_line_scores.size(); i++){
line_score.erase(cur_line_scores[i].second);
}
}
}
f_input.clear();
f_input.seekg(0, ios_base::beg);
}
// generate score and submission
void file_generate_sub(ofstream &f_sub, vector<ifstream*> &f_scores, vector<double> &weights,
int max_sub, size_t num_lines){
for (int i = 0; i < weights.size(); i++){
cout << weights[i] << "\t";
}
cout << endl;
int num_files = f_scores.size();
string line;
for (int i = 0; i < num_files; i++){
getline(*(f_scores[i]), line);
}
f_sub << "row_id,place_id" << endl;
for (int i_line = 0; i_line < num_lines; i_line++){
// generate the candidate place_ids from the f_scores
unsigned int row_id = -1;
unordered_map<unsigned long, double> line_score;
for (int i_file = 0; i_file < num_files; i_file++){
if ( !getline(*(f_scores[i_file]), line) ){
cout << "file not matching with score!" << endl;
// return 0;
}
vector<string> score_tokens;
split_line(line, ',', score_tokens);
unsigned int score_row_id;
int num_tokens, num_pairs;
num_tokens = score_tokens.size();
num_pairs = (score_tokens.size()-1)/2;
score_row_id = stoi(score_tokens[0]);
if (row_id == -1){
row_id = score_row_id;
}
if (score_row_id != row_id){
cout << "score row id not matching:" << row_id << ":" << score_row_id << endl;
}
double weight = weights[i_file];
for (int i = 0; i < num_pairs; i++){
unsigned long place_id;
double score;
place_id = stoul(score_tokens[i * 2 + 1]);
score = stod(score_tokens[i * 2 + 2]);
if (line_score.count(place_id)){
line_score[place_id] += weight * score;
}else{
line_score[place_id] = weight * score;
}
}
}
priority_queue<pair<double, unsigned long> > line_pq;
for (auto it = line_score.begin(); it != line_score.end(); it++){
line_pq.push( pair<double, unsigned long>( (*it).second, (*it).first) );
}
f_sub << row_id << ',';
int i = 0;
while (i < max_sub && !line_pq.empty()){
f_sub << ' ';
f_sub << line_pq.top().second;
line_pq.pop();
i++;
}
f_sub << endl;
}
for (int i = 0; i < num_files; i++){
(*(f_scores[i])).clear();
(*(f_scores[i])).seekg(0, ios_base::beg);
}
}
// generate score and submission
void file_cache_generate_sub(ofstream &f_sub, vector<ifstream*> &f_scores, vector<double> &weights,
int max_sub, size_t num_lines, size_t cache_size){
for (int i = 0; i < weights.size(); i++){
cout << weights[i] << "\t";
}
cout << endl;
int num_files = f_scores.size();
string line;
for (int i = 0; i < num_files; i++){
getline(*(f_scores[i]), line);
}
f_sub << "row_id,place_id" << endl;
int i_line = 0;
while (i_line < num_lines){
int next_line = i_line + cache_size < num_lines ? i_line + cache_size : num_lines;
int cur_size = next_line - i_line;
vector<unordered_map<unsigned long, double> > cache_line_score(cur_size);
vector<unsigned int> cache_row_id(cur_size, -1);
// generate the candidate place_ids from the f_scores
for (int i_file = 0; i_file < num_files; i_file++){
double weight = weights[i_file];
for (int j_line = 0; j_line < cur_size; j_line++){
if ( !getline(*(f_scores[i_file]), line) ){
cout << "file not matching with score!" << endl;
// return 0;
}
unordered_map<unsigned long, double> &line_score = cache_line_score[j_line];
unsigned int &row_id = cache_row_id[j_line];
vector<string> score_tokens;
split_line(line, ',', score_tokens);
unsigned int score_row_id;
int num_tokens, num_pairs;
num_tokens = score_tokens.size();
num_pairs = (score_tokens.size()-1)/2;
score_row_id = stoi(score_tokens[0]);
if (row_id == -1){
row_id = score_row_id;
}
if (score_row_id != row_id){
cout << "score row id not matching:" << row_id << ":" << score_row_id << endl;
}
for (int i = 0; i < num_pairs; i++){
unsigned long place_id;
double score;
place_id = stoul(score_tokens[i * 2 + 1]);
score = stod(score_tokens[i * 2 + 2]);
if (line_score.count(place_id)){
line_score[place_id] += weight * score;
}else{
line_score[place_id] = weight * score;
}
}
}
}
for (int j_line = 0; j_line < cur_size; j_line++){
unordered_map<unsigned long, double> &line_score = cache_line_score[j_line];
unsigned int &row_id = cache_row_id[j_line];
priority_queue<pair<double, unsigned long> > line_pq;
for (auto it = line_score.begin(); it != line_score.end(); it++){
line_pq.push( pair<double, unsigned long>( (*it).second, (*it).first) );
}
f_sub << row_id << ',';
int i = 0;
while (i < max_sub && !line_pq.empty()){
f_sub << ' ';
f_sub << line_pq.top().second;
line_pq.pop();
i++;
}
f_sub << endl;
}
i_line = next_line;
cout << next_line << " lines written" << endl;
}
for (int i = 0; i < num_files; i++){
(*(f_scores[i])).clear();
(*(f_scores[i])).seekg(0, ios_base::beg);
}
}
// generate score and compute apk line by line
double file_generate_validate_apk(ifstream &f_valid_test, vector<ifstream*> &f_scores, vector<double> &weights,
int max_sub, size_t num_lines){
int num_files = f_scores.size();
string line;
getline(f_valid_test, line);
for (int i = 0; i < num_files; i++){
getline(*(f_scores[i]), line);
}
double mapk_score = 0;
for (int i_line = 0; i_line < num_lines; i_line++){
// get the true place_id from f_valid_test
if ( !getline(f_valid_test, line) ){
cout << "f_valid not matching with score!" << endl;
return 0;
}
vector<string> test_tokens;
split_line(line, ',', test_tokens);
unsigned long test_place_id;
unsigned int test_row_id;
test_place_id = stoul(test_tokens[5]);
test_row_id = stoi(test_tokens[0]);
unordered_set<unsigned long> line_act({test_place_id});
// generate the candidate place_ids from the f_scores
unordered_map<unsigned long, double> line_score;
for (int i_file = 0; i_file < num_files; i_file++){
if ( !getline(*(f_scores[i_file]), line) ){
cout << "file not matching with score!" << endl;
// return 0;
}
vector<string> score_tokens;
split_line(line, ',', score_tokens);
unsigned int score_row_id;
int num_tokens, num_pairs;
num_tokens = score_tokens.size();
num_pairs = (score_tokens.size()-1)/2;
score_row_id = stoi(score_tokens[0]);
if (score_row_id != test_row_id){
cout << "test and score row id not matching:" << test_row_id << ":" << score_row_id << endl;
}
double weight = weights[i_file];
for (int i = 0; i < num_pairs; i++){
unsigned long place_id;
double score;
place_id = stoul(score_tokens[i * 2 + 1]);
score = stod(score_tokens[i * 2 + 2]);
if (line_score.count(place_id)){
line_score[place_id] += weight * score;
}else{
line_score[place_id] = weight * score;
}
}
}
priority_queue<pair<double, unsigned long> > line_pq;
for (auto it = line_score.begin(); it != line_score.end(); it++){
line_pq.push( pair<double, unsigned long>( (*it).second, (*it).first) );
}
vector<unsigned long> line_pred;
int i = 0;
while (i < max_sub && !line_pq.empty()){
line_pred.push_back(line_pq.top().second);
line_pq.pop();
i++;
}
double cur_score = apk(line_act, line_pred, max_sub);
// if (cur_score < 0.3)
// cout << line << endl;
mapk_score += cur_score;
}
mapk_score /= num_lines;
f_valid_test.clear();
f_valid_test.seekg(0, ios_base::beg);
for (int i = 0; i < num_files; i++){
(*(f_scores[i])).clear();
(*(f_scores[i])).seekg(0, ios_base::beg);
}
return mapk_score;
}
// generate score and compute apk line by line into a cache
double file_cache_generate_validate_apk(ifstream &f_valid_test, vector<ifstream*> &f_scores, vector<double> &weights,
int max_sub, size_t num_lines, size_t cache_size){
int num_files = f_scores.size();
string line;
getline(f_valid_test, line);
for (int i = 0; i < num_files; i++){
getline(*(f_scores[i]), line);
}
double mapk_score = 0;
int i_line = 0;
while (i_line < num_lines){
int next_line = i_line + cache_size < num_lines ? i_line + cache_size : num_lines;
int cur_size = next_line - i_line;
vector<unordered_set<unsigned long> > cache_line_act(cur_size);
vector<unordered_map<unsigned long, double> > cache_line_score(cur_size);
vector<unsigned int> cache_row_id(cur_size);
for (int j_line = 0; j_line < cur_size; j_line++){
// get the true place_id from f_valid_test
if ( !getline(f_valid_test, line) ){
cout << "f_valid not matching with score!" << endl;
return 0;
}
vector<string> test_tokens;
split_line(line, ',', test_tokens);
unsigned long test_place_id;
unsigned int test_row_id;
test_place_id = stoul(test_tokens[5]);
test_row_id = stoi(test_tokens[0]);
cache_line_act[j_line] = unordered_set<unsigned long>({test_place_id});
cache_row_id[j_line] = test_row_id;
}
// generate the candidate place_ids from the f_scores
for (int i_file = 0; i_file < num_files; i_file++){
for (int j_line = 0; j_line < cur_size; j_line++){
if ( !getline(*(f_scores[i_file]), line) ){
cout << "file not matching with score!" << endl;
// return 0;
}
vector<string> score_tokens;
split_line(line, ',', score_tokens);
unsigned int score_row_id;
int num_tokens, num_pairs;
num_tokens = score_tokens.size();
num_pairs = (score_tokens.size()-1)/2;
score_row_id = stoi(score_tokens[0]);
unsigned int test_row_id = cache_row_id[j_line];
if (score_row_id != test_row_id){
cout << "test and score row id not matching:" << test_row_id << ":" << score_row_id << endl;
}
unordered_map<unsigned long, double> &line_score = cache_line_score[j_line];
double weight = weights[i_file];
for (int i = 0; i < num_pairs; i++){
unsigned long place_id;
double score;
place_id = stoul(score_tokens[i * 2 + 1]);
score = stod(score_tokens[i * 2 + 2]);
if (line_score.count(place_id)){
line_score[place_id] += weight * score;
}else{
line_score[place_id] = weight * score;
}
}
}
}
for (int j_line = 0; j_line < cur_size; j_line++){
unordered_map<unsigned long, double> &line_score = cache_line_score[j_line];
unordered_set<unsigned long> &line_act = cache_line_act[j_line];
priority_queue<pair<double, unsigned long> > line_pq;
for (auto it = line_score.begin(); it != line_score.end(); it++){
line_pq.push( pair<double, unsigned long>( (*it).second, (*it).first) );
}
vector<unsigned long> line_pred;
int i = 0;
while (i < max_sub && !line_pq.empty()){
line_pred.push_back(line_pq.top().second);
line_pq.pop();
i++;
}
double cur_score = apk(line_act, line_pred, max_sub);
// if (cur_score < 0.3)
// cout << line << endl;
mapk_score += cur_score;
}
i_line = next_line;
// print partial result
cout << next_line << " lines validated: " << (mapk_score/next_line) << endl;
}
mapk_score /= num_lines;
f_valid_test.clear();
f_valid_test.seekg(0, ios_base::beg);
for (int i = 0; i < num_files; i++){
(*(f_scores[i])).clear();
(*(f_scores[i])).seekg(0, ios_base::beg);
}
return mapk_score;
}
// generate score and compute apk line by line into a cache with log add last one contains all the target
double file_cache_generate_validate_apk_log(ifstream &f_valid_test, vector<ifstream*> &f_scores, vector<double> &weights,
int max_sub, size_t num_lines, size_t cache_size){
int num_files = f_scores.size();
int num_add_files = f_scores.size() - 1;
double add_weights_sum = 0.0;
for (int i = 0; i < num_add_files; i++){
add_weights_sum += weights[i];
}
string line;
getline(f_valid_test, line);
for (int i = 0; i < num_files; i++){
getline(*(f_scores[i]), line);
}
double mapk_score = 0;
int i_line = 0;
while (i_line < num_lines){
int next_line = i_line + cache_size < num_lines ? i_line + cache_size : num_lines;
int cur_size = next_line - i_line;
vector<unordered_set<unsigned long> > cache_line_act(cur_size);
vector<unordered_map<unsigned long, double> > cache_line_score(cur_size);
vector<unordered_map<unsigned long, double> > cache_line_score_final(cur_size);
vector<unsigned int> cache_row_id(cur_size);
for (int j_line = 0; j_line < cur_size; j_line++){
// get the true place_id from f_valid_test
if ( !getline(f_valid_test, line) ){
cout << "f_valid not matching with score!" << endl;
return 0;
}
vector<string> test_tokens;
split_line(line, ',', test_tokens);
unsigned long test_place_id;
unsigned int test_row_id;
test_place_id = stoul(test_tokens[5]);
test_row_id = stoi(test_tokens[0]);
cache_line_act[j_line] = unordered_set<unsigned long>({test_place_id});
cache_row_id[j_line] = test_row_id;
}
// generate the candidate place_ids from the f_scores
for (int i_file = 0; i_file < num_add_files; i_file++){
for (int j_line = 0; j_line < cur_size; j_line++){
if ( !getline(*(f_scores[i_file]), line) ){
cout << "file not matching with score!" << endl;
// return 0;
}
vector<string> score_tokens;
split_line(line, ',', score_tokens);
unsigned int score_row_id;
int num_tokens, num_pairs;
num_tokens = score_tokens.size();
num_pairs = (score_tokens.size()-1)/2;
score_row_id = stoi(score_tokens[0]);
unsigned int test_row_id = cache_row_id[j_line];
if (score_row_id != test_row_id){
cout << "test and score row id not matching:" << test_row_id << ":" << score_row_id << endl;
}
unordered_map<unsigned long, double> &line_score = cache_line_score[j_line];
double weight = weights[i_file];
for (int i = 0; i < num_pairs; i++){
unsigned long place_id;
double score;
place_id = stoul(score_tokens[i * 2 + 1]);
score = stod(score_tokens[i * 2 + 2]);
if (line_score.count(place_id)){
line_score[place_id] += weight * score;
}else{
line_score[place_id] = weight * score;
}
}
}
}
// last item using multiply
int last_i_file = num_add_files;
for (int j_line = 0; j_line < cur_size; j_line++){
if ( !getline(*(f_scores[last_i_file]), line) ){
cout << "file not matching with score!" << endl;
// return 0;
}
vector<string> score_tokens;
split_line(line, ',', score_tokens);
unsigned int score_row_id;
int num_tokens, num_pairs;
num_tokens = score_tokens.size();
num_pairs = (score_tokens.size()-1)/2;
score_row_id = stoi(score_tokens[0]);
unsigned int test_row_id = cache_row_id[j_line];
if (score_row_id != test_row_id){
cout << "test and score row id not matching:" << test_row_id << ":" << score_row_id << endl;
}
unordered_map<unsigned long, double> &line_score = cache_line_score[j_line];
unordered_map<unsigned long, double> &line_score_final = cache_line_score_final[j_line];
double weight = weights[last_i_file];
for (int i = 0; i < num_pairs; i++){
unsigned long place_id;
double score;
place_id = stoul(score_tokens[i * 2 + 1]);
score = stod(score_tokens[i * 2 + 2]);
if (line_score.count(place_id)){
line_score_final[place_id] = weight * log(score) + log(line_score[place_id] / add_weights_sum);
}else{
line_score_final[place_id] = weight * log(score) + log(0.001);
}
}
}
for (int j_line = 0; j_line < cur_size; j_line++){
unordered_map<unsigned long, double> &line_score_final = cache_line_score_final[j_line];
unordered_set<unsigned long> &line_act = cache_line_act[j_line];
priority_queue<pair<double, unsigned long> > line_pq;
for (auto it = line_score_final.begin(); it != line_score_final.end(); it++){
line_pq.push( pair<double, unsigned long>( (*it).second, (*it).first) );
}
vector<unsigned long> line_pred;
int i = 0;
while (i < max_sub && !line_pq.empty()){
line_pred.push_back(line_pq.top().second);
line_pq.pop();
i++;
}
double cur_score = apk(line_act, line_pred, max_sub);
// if (cur_score < 0.3)
// cout << line << endl;
mapk_score += cur_score;
}
i_line = next_line;
// print partial result
cout << next_line << " lines validated: " << (mapk_score/next_line) << endl;
}
mapk_score /= num_lines;
f_valid_test.clear();
f_valid_test.seekg(0, ios_base::beg);
for (int i = 0; i < num_files; i++){
(*(f_scores[i])).clear();
(*(f_scores[i])).seekg(0, ios_base::beg);
}
return mapk_score;
}
|
#include <iostream>
#include <deque>
using namespace std;
deque <int> Cycle;
void findHamiltonianCycle (bool ** A, int B) {
for (int k = 0; k < B * (B - 1); k++) {
if (A[Cycle.at (0)][Cycle.at (1)] == 0) {
int i = 2;
while (A[Cycle.at (0)][Cycle.at (i)] == 0 || A[Cycle.at (1)][Cycle.at (i + 1)] == 0) i++;
int next = Cycle.at (i);
Cycle.erase (Cycle.cbegin () + i);
Cycle.insert (Cycle.cbegin () + i, Cycle.at (1));
Cycle.erase (++Cycle.cbegin ());
Cycle.insert (++Cycle.cbegin (), next);
}
Cycle.push_back (Cycle.front ());
Cycle.pop_front ();
}
for (int j = 0; j < B; i++) cout << Cycle.at (j) + 1 << " ";
}
int main () {
int G;
bool **matrix;
cin >> G;
matrix = new bool *[G];
for (int i = 0; i < G; i++) {
matrix[i] = new bool[G];
}
for (int i = 0; i < G; i++) {
for (int j = 0; j < G; j++) {
cin >> matrix[i][j];
}
}
for (int i = 0; i < G; i++) {
Cycle.push_back (i);
}
findHamiltonianCycle(matrix, G);
return 0;
}
|
#include <gtest/gtest.h>
#include <whiskey/Unicode/FileByteOutStream.hpp>
using namespace whiskey;
TEST(Unicode_Unit_FileByteOutStream, Unopened) {
const char *path = "thisIsAFileNameThatProbablyDoesntExist.txt";
FileByteOutStream bs(path);
ASSERT_FALSE(bs.isOpen());
ASSERT_EQ(bs.getEncoding(), Encoding::Auto);
bs.setEncoding(Encoding::UTF8);
ASSERT_EQ(bs.getEncoding(), Encoding::UTF8);
ASSERT_FALSE(bs.isOpen());
ASSERT_DEATH({ bs.close(); }, "");
ASSERT_DEATH({ bs.writeChar(0); }, "");
}
TEST(Unicode_Unit_FileByteOutStream, Auto) {
const char *path = "thisIsAFileNameThatProbablyDoesntExist.txt";
FileByteOutStream bs(path);
ASSERT_TRUE(bs.open());
bs.writeChar('h');
bs.writeChar('e');
bs.writeChar('l');
bs.writeChar('l');
bs.writeChar('o');
bs.close();
FILE *f = fopen(path, "r");
ASSERT_NE(f, nullptr);
Char8 buf[1024];
ASSERT_EQ(fread(buf, 1, 1024, f), 5);
fclose(f);
ASSERT_EQ(buf[0], 'h');
ASSERT_EQ(buf[1], 'e');
ASSERT_EQ(buf[2], 'l');
ASSERT_EQ(buf[3], 'l');
ASSERT_EQ(buf[4], 'o');
}
TEST(Unicode_Unit_FileByteOutStream, UTF8) {
const char *path = "thisIsAFileNameThatProbablyDoesntExist.txt";
FileByteOutStream bs(path, Encoding::UTF8);
ASSERT_TRUE(bs.open());
bs.writeChar('h');
bs.writeChar('e');
bs.writeChar('l');
bs.writeChar('l');
bs.writeChar('o');
bs.close();
FILE *f = fopen(path, "r");
ASSERT_NE(f, nullptr);
Char8 buf[1024];
ASSERT_EQ(fread(buf, 1, 1024, f), 8);
fclose(f);
ASSERT_EQ(buf[0], '\xef');
ASSERT_EQ(buf[1], '\xbb');
ASSERT_EQ(buf[2], '\xbf');
ASSERT_EQ(buf[3], 'h');
ASSERT_EQ(buf[4], 'e');
ASSERT_EQ(buf[5], 'l');
ASSERT_EQ(buf[6], 'l');
ASSERT_EQ(buf[7], 'o');
}
TEST(Unicode_Unit_FileByteOutStream, UTF16LE) {
const char *path = "thisIsAFileNameThatProbablyDoesntExist.txt";
FileByteOutStream bs(path, Encoding::UTF16LE);
ASSERT_TRUE(bs.open());
bs.writeChar('h');
bs.writeChar('e');
bs.writeChar('l');
bs.writeChar('l');
bs.writeChar('o');
bs.close();
FILE *f = fopen(path, "r");
ASSERT_NE(f, nullptr);
Char8 buf[1024];
ASSERT_EQ(fread(buf, 1, 1024, f), 7);
fclose(f);
ASSERT_EQ(buf[0], '\xfe');
ASSERT_EQ(buf[1], '\xff');
ASSERT_EQ(buf[2], 'h');
ASSERT_EQ(buf[3], 'e');
ASSERT_EQ(buf[4], 'l');
ASSERT_EQ(buf[5], 'l');
ASSERT_EQ(buf[6], 'o');
}
TEST(Unicode_Unit_FileByteOutStream, UTF16BE) {
const char *path = "thisIsAFileNameThatProbablyDoesntExist.txt";
FileByteOutStream bs(path, Encoding::UTF16BE);
ASSERT_TRUE(bs.open());
bs.writeChar('h');
bs.writeChar('e');
bs.writeChar('l');
bs.writeChar('l');
bs.writeChar('o');
bs.close();
FILE *f = fopen(path, "r");
ASSERT_NE(f, nullptr);
Char8 buf[1024];
ASSERT_EQ(fread(buf, 1, 1024, f), 7);
fclose(f);
ASSERT_EQ(buf[0], '\xff');
ASSERT_EQ(buf[1], '\xfe');
ASSERT_EQ(buf[2], 'h');
ASSERT_EQ(buf[3], 'e');
ASSERT_EQ(buf[4], 'l');
ASSERT_EQ(buf[5], 'l');
ASSERT_EQ(buf[6], 'o');
}
TEST(Unicode_Unit_FileByteOutStream, UTF32LE) {
const char *path = "thisIsAFileNameThatProbablyDoesntExist.txt";
FileByteOutStream bs(path, Encoding::UTF32LE);
ASSERT_TRUE(bs.open());
bs.writeChar('h');
bs.writeChar('e');
bs.writeChar('l');
bs.writeChar('l');
bs.writeChar('o');
bs.close();
FILE *f = fopen(path, "r");
ASSERT_NE(f, nullptr);
Char8 buf[1024];
ASSERT_EQ(fread(buf, 1, 1024, f), 9);
fclose(f);
ASSERT_EQ(buf[0], '\xff');
ASSERT_EQ(buf[1], '\xfe');
ASSERT_EQ(buf[2], '\x00');
ASSERT_EQ(buf[3], '\x00');
ASSERT_EQ(buf[4], 'h');
ASSERT_EQ(buf[5], 'e');
ASSERT_EQ(buf[6], 'l');
ASSERT_EQ(buf[7], 'l');
ASSERT_EQ(buf[8], 'o');
}
TEST(Unicode_Unit_FileByteOutStream, UTF32BE) {
const char *path = "thisIsAFileNameThatProbablyDoesntExist.txt";
FileByteOutStream bs(path, Encoding::UTF32BE);
ASSERT_TRUE(bs.open());
bs.writeChar('h');
bs.writeChar('e');
bs.writeChar('l');
bs.writeChar('l');
bs.writeChar('o');
bs.close();
FILE *f = fopen(path, "r");
ASSERT_NE(f, nullptr);
Char8 buf[1024];
ASSERT_EQ(fread(buf, 1, 1024, f), 9);
fclose(f);
ASSERT_EQ(buf[0], '\x00');
ASSERT_EQ(buf[1], '\x00');
ASSERT_EQ(buf[2], '\xfe');
ASSERT_EQ(buf[3], '\xff');
ASSERT_EQ(buf[4], 'h');
ASSERT_EQ(buf[5], 'e');
ASSERT_EQ(buf[6], 'l');
ASSERT_EQ(buf[7], 'l');
ASSERT_EQ(buf[8], 'o');
}
|
#include "COREVector.h"
using namespace CORE;
COREVector::COREVector() {
m_theta = 0;
m_r = 0;
}
COREVector::COREVector(const COREVector &other) {
m_r = other.m_r;
m_theta = other.m_theta;
}
COREVector::COREVector(double r, double theta) {
m_r = r;
m_theta = theta;
}
COREVector COREVector::FromRadians(double radians, double mag) {
return COREVector(mag, radians);
}
COREVector COREVector::FromDegrees(double degrees, double mag) {
return FromRadians(ToRadians(degrees), mag);
}
COREVector COREVector::FromCompassDegrees(double compassDegrees, double mag) {
double degrees = 90 - compassDegrees;
degrees = degrees < 0 ? 360 + degrees : degrees;
return FromRadians(ToRadians(degrees), mag);
}
COREVector COREVector::FromXY(double x, double y) {
return COREVector(hypot(x, y), atan2(y, x));
}
void COREVector::Normalize() {
if(m_r < 0) {
Opposite();
}
m_r = 1;
}
double COREVector::NormalizeMagnitude() {
m_r = 1;
return 0;
//TODO: figure out what this is supposed to do and fix this
}
double COREVector::GetRadians() {
return m_theta;
}
double COREVector::GetDegrees() {
return CORE::ToDegrees(GetRadians());
}
double COREVector::GetCompassDegrees() {
double degrees = 450 - GetDegrees();
return (degrees >= 360 ? degrees - 360 : degrees);
}
COREVector COREVector::RotateBy(COREVector other) {
return COREVector(m_r, m_theta + other.m_theta);
}
COREVector COREVector::RotationInverse() {
return COREVector(m_r, fmod(m_theta + PI, 2 * PI));
}
COREVector COREVector::Opposite() {
return COREVector(-m_r, fmod(m_theta + PI, 2 * PI));
}
COREVector COREVector::InterpolateRotation(COREVector other, double x) {
if (x <= 0) {
return *this;
} else if (x >= 1) {
return other;
}
double diff = RotationInverse().RotateBy(other).GetRadians();
return RotateBy(FromRadians(diff * x));
}
double COREVector::GetX() {
return cos(m_theta) * m_r;
}
double COREVector::GetY() {
return sin(m_theta) * m_r;
}
void COREVector::Invert() {
m_r *= -1;
m_theta = fmod(m_theta + PI, 2 * PI);
}
double COREVector::GetMagnitude() {
return m_r;
}
void COREVector::SetXY(double x, double y) {
m_r = hypot(x, y);
m_theta = atan2(y, x);
}
COREVector COREVector::TranslateBy(COREVector other) {
return COREVector(m_r + other.m_r, m_theta + other.m_theta);
}
COREVector COREVector::MagnitudeInverse() {
return COREVector(-m_r, m_theta);
}
COREVector COREVector::InterpolateMagnitude(COREVector other, double x) {
if (x <= 0) {
return *this;
} else if (x >= 1) {
return other;
}
return Extrapolate(other, x);
}
COREVector COREVector::Extrapolate(COREVector other, double x) {
return FromXY(x * (other.GetX() - GetX()) + GetX(), x * (other.GetY() - GetY()) + GetY());
}
COREVector COREVector::FlipX() {
//return COREVector(-m_x, m_y);
return COREVector(0, 0);
}
COREVector COREVector::FlipY() {
//return COREVector(m_x, -m_y);
return COREVector(0, 0);
}
COREVector COREVector::AddVector(COREVector firstVector) {
return FromXY(GetX() + firstVector.GetX(), GetY() + firstVector.GetY());
}
COREVector COREVector::SubtractVector(COREVector firstVector) {
return FromXY(GetX() - firstVector.GetX(), GetY() - firstVector.GetY());
}
double COREVector::GetDotProduct(COREVector firstVector) {
return GetX() * firstVector.GetX() + GetY() + firstVector.GetY();
}
double COREVector::GetCrossProduct(COREVector firstVector) {
return GetX() * firstVector.GetY() - GetY() * firstVector.GetX();
}
double COREVector::ShortestRotationTo(COREVector target) {
double counterClockwiseMove = GetCompassDegrees() - target.GetCompassDegrees();
double clockwiseMove = target.GetCompassDegrees() - GetCompassDegrees();
clockwiseMove += (clockwiseMove < 0 ? 360 : 0);
counterClockwiseMove += (counterClockwiseMove < 0 ? 360 : 0);
return (abs(clockwiseMove) < abs(counterClockwiseMove) ? clockwiseMove : -counterClockwiseMove);
}
void COREVector::SetMagnitude(double magnitude) {
m_r = magnitude;
}
double COREVector::GetCos() {
return cos(m_theta);
}
double COREVector::GetSin() {
return sin(m_theta);
}
|
#pragma once
#include <memory>
#include "../rtti.hpp"
#include "DataObject.hpp"
namespace fantom
{
/**
* Vector of arbitrary data objects that can be added as a DataOutput.
*
* This class is a \c DataObject itself, but also stores a bundle of \c DataObject s
* that are of the same kind in most cases, but need not be.
*/
class DataObjectBundle : public DataObject
{
typedef RTTI_Info< DataObjectBundle, DataObject > TypeInfo;
TYPE_INFORMATION( "Data Object Bundle" )
public:
// ------------------ construction ------------------------------------------------------------
/**
* Default constructor to create an empty bundle.
*/
DataObjectBundle() = default;
/**
* Constructor to reserve a certain capacity to speed up insertion.
*/
DataObjectBundle( size_t capacity );
/**
* Construct a DataObjectBundle and fill it with the data of the given vector.
*/
DataObjectBundle( std::vector< std::shared_ptr< const DataObject > > dataObjects );
/**
* Construct a DataObjectBundle and fill it with the given data.
*/
template < class InputIterator >
DataObjectBundle( InputIterator first, InputIterator last );
// ------------------ manage content ------------------------------------------------------------
/// Add another \c DataObject to the bundle.
/**
* When creating specialized DataObjectBundles, this method can be overridden
* and be used for additional typechecks etc.
*/
virtual void addContent( std::shared_ptr< const DataObject > dataObject, const std::string& name = "" );
/// Sets the name of the DataObject at index \c position.
void setName( size_t position, const std::string& name );
/// Erase all \c DataObjects from the bundle.
void clearContent();
/**
* Reserves a certain amount of capacity to speed up insertion.
* \param capacity Capacity of new container
*/
void reserve( size_t capacity );
// ------------------ content metadata ------------------------------------------------------------
static const RTTI::TypeId&
getCommonType( const std::vector< std::shared_ptr< const DataObject > >& dataObjects );
/// \return the type of most specialized common type of the \c DataObjects in the \c DataObjectBundle
const RTTI::TypeId& getContentTypeId() const;
/**
* @copydoc DataObject::getInfoStrings()
*/
virtual std::vector< std::pair< std::string, std::string > > getInfoStrings() const override;
// ------------------ access content ------------------------------------------------------------
/// \return the number of \c DataObjects in the bundle.
size_t getSize() const;
/// \return whether the bundle is empty
bool isEmpty() const;
/// \return the \c DataObject at index \c position in the bundle.
const std::shared_ptr< const DataObject >& getContent( size_t position ) const;
/// \return the DataObject with the name \c name or nullptr if no such DataObject exists.
std::shared_ptr< const DataObject > getContent( const std::string& name ) const;
/// \return the name of the DataObject at index \c position in the bundle
const std::string& getName( size_t position ) const;
/// \return the index of the DataObject with the name \c name. Returns size_t(-1) if no such DataObject exists.
size_t getIndexOf( const std::string& name ) const;
// ------------------ iteration ------------------------------------------------------------
/// iterator to begin of contained data objects
std::vector< std::shared_ptr< const DataObject > >::const_iterator begin() const;
/// iterator to end of contained data objects
std::vector< std::shared_ptr< const DataObject > >::const_iterator end() const;
//==================================================== Deprecated =====
/**
* Creates a DataObjectBundle holding a griben type.
*
* \deprecated { Since typechecking has been moved to
* Output system, this is not needed anymore.
* Use std::make_shared< DataObjectBundle >() instead }
*/
template < class T >
FANTOM_DEPRECATED static std::shared_ptr< DataObjectBundle > create()
{
return std::shared_ptr< DataObjectBundle >( new DataObjectBundle() );
}
/**
* Creates a DataObjectBundle holding a griben type.
*
* \deprecated { Since typechecking has been moved to
* Output system, this is not needed anymore.
* Use std::make_shared< DataObjectBundle >() instead }
*/
FANTOM_DEPRECATED static std::shared_ptr< DataObjectBundle > create( const RTTI::TypeId& /*type*/ )
{
return std::shared_ptr< DataObjectBundle >( new DataObjectBundle() );
}
private:
std::vector< std::shared_ptr< const DataObject > > mDataObjects;
std::vector< std::string > mNames;
};
//================================================ Inline definitions =====
inline void DataObjectBundle::clearContent()
{
mDataObjects.clear();
mNames.clear();
}
inline void DataObjectBundle::reserve( size_t capacity )
{
mDataObjects.reserve( capacity );
mNames.reserve( capacity );
}
inline size_t DataObjectBundle::getSize() const
{
return mDataObjects.size();
}
inline bool DataObjectBundle::isEmpty() const
{
return mDataObjects.empty();
}
inline std::vector< std::shared_ptr< const DataObject > >::const_iterator DataObjectBundle::begin() const
{
return mDataObjects.begin();
}
inline std::vector< std::shared_ptr< const DataObject > >::const_iterator DataObjectBundle::end() const
{
return mDataObjects.end();
}
//============================================== Template definitions =====
template < class InputIterator >
DataObjectBundle::DataObjectBundle( InputIterator first, InputIterator last )
: mDataObjects( first, last )
{
mNames.resize( mDataObjects.size() );
}
}
|
#include "PuzzleGenerator.h"
#include <iostream>
using namespace std;
//Constructor
PuzzleGenerator::PuzzleGenerator(int _nRows, int _nColumns, int _minVal, int _maxVal)
:nRows(_nRows), nColumns(_nColumns), minVal(_minVal), maxVal(_maxVal)
{
maxtime = 57.0; //set the max time value
}
/*Sample code, not used*/
/*Puzzle PuzzleGenerator::GeneratePuzzle()
{
timer.StartTimer();
maxtime = 59.9; // To make sure we don't exceed a minute
return RandomWalk(5); // Do a random walk for 5 seconds and return the solution.
// We could also do as many random walks as we can within the given time limit.
while (timer.GetElapsedTime() + 5 < maxtime)
{
Puzzle p = RandomWalk(5);
// Check if p is better than the best puzzle we have found so far.
}
}*/
Puzzle PuzzleGenerator::GeneratePuzzle()
{
timer.StartTimer();
// Declare variables for Simulated Annealing Algorithm
double initialTemp = 100;
double finalTemp = 0.001;
double changePerStep = 0.9999;
//Try to start at a puzzle that has a solution
Puzzle initialPuzzle = Puzzle(nRows, nColumns, minVal, maxVal);
while(!initialPuzzle.HasSolution() && timer.GetElapsedTime() < maxtime){
initialPuzzle = Puzzle(nRows, nColumns, minVal, maxVal);
}
//perform the simulated annealing algorithm
Puzzle bestPuzzle = simulatedAnnealing(initialPuzzle, initialTemp, changePerStep, finalTemp);
while (timer.GetElapsedTime() < maxtime){
initialPuzzle = Puzzle(nRows, nColumns, minVal, maxVal);
//Try to perform the algorithm on a puzzle with solution
while(!initialPuzzle.HasSolution() && timer.GetElapsedTime() < maxtime){
initialPuzzle = Puzzle(nRows, nColumns, minVal, maxVal);
}
Puzzle p = simulatedAnnealing(initialPuzzle, initialTemp, changePerStep, finalTemp);
if (p.GetValue() > bestPuzzle.GetValue()){
bestPuzzle = p;
}
}
return bestPuzzle;
}
//uses the exponential simulated Annealing
Puzzle PuzzleGenerator::simulatedAnnealing(Puzzle p, double initialTemp, double changePerStep, double finalTemp)
{
//cerr << "get in SA time: " << timer.GetElapsedTime() << endl;
Puzzle curr = p;
int count = 0; // iteration counter (for debugging)
double currTemp = initialTemp;
while (timer.GetElapsedTime() < maxtime && currTemp > finalTemp)
{
// get random successor
Puzzle next = curr.GetRandomSuccessor();
if(next.GetValue() <= curr.GetValue()){//if the next value is not better than the current value
double expo_thres = exp((next.GetValue() - curr.GetValue())/currTemp);
double doubleRand = (rand() % 1000) / 1000.0; // generate random value between (0,1)
if (doubleRand < expo_thres){//jump out of the local optimum by accepting a worse solution
curr = next;
}
}else{//if next value is better than the current colution
curr = next;
}
// at each iteration the temperature is cooled
currTemp = changePerStep * currTemp;//using the exponential simulated annealing
count++;
}
//cerr << "get out SA time: " << timer.GetElapsedTime() << endl;
return curr;
}
/*Sample code, not used*/
/*Puzzle PuzzleGenerator::RandomWalk(double timelimit)
{
// A very simple function that start at a random configuration and keeps randomly modifying it
// until it hits the time limit. Returns the best solution found so far.
Puzzle p(nRows, nColumns, minVal, maxVal); // Generate a random puzzle with the specified values.
// Keep track of the best puzzle found so far (and its value).
Puzzle bestPuzzle = p;
int bestValue = p.GetValue();
// Keep track of the time so we don't exceed it.
Timer t;
t.StartTimer();
// Loop until we hit the time limit.
while (t.GetElapsedTime() < timelimit-0.1) // To make sure that we don't exceed the time limit, we stop just before we hit the time limit.
{
// Generate a successor of p by randomly changing the value of a random cell
// (since we are doing a random walk, we just replace p with its successor).
p = p.GetRandomSuccessor();
// Update the current best solution.
if (p.GetValue() > bestValue) // Calling GetValue() for the first time is costly
// since the puzzle has to be evaluated first.
{
bestValue = p.GetValue(); // Calling it a second time simply returns the value that was computed before.
bestPuzzle = p;
}
}
return bestPuzzle;
// The following code is not executed in this function. It exists just as an example for getting all the successors of a puzzle.
vector<Puzzle> successors;
bestPuzzle.GetAllSuccessors(successors);
}*/
|
#ifndef THREADBEHAVIOR_H
#define THREADBEHAVIOR_H
#include <QThread>
class ThreadBehavior : public QThread
{
public:
ThreadBehavior();
virtual void run();
};
#endif // THREADBEHAVIOR_H
|
/**
REFERENCES:
BasicBot - The basic working bot.
Part of the Asimi project - http://sudarmuthu.com/arduino/asimi
Copyright 2011 Sudar Muthu (email : sudar@sudarmuthu.com)
**/
int E1 = 5; // Enable Pin for motor 1
int E2 = 4 // Enable Pin for motor 2
int I1 = 3 // Control pin 1 for motor 1
int I2 = 2 // Control pin 2 for motor 1
int I3 = 1 // Control pin 1 for motor 2
int I4 = 0 // Control pin 2 for motor 2
void setup() {
pinMode(E1, OUTPUT);
pinMode(E2, OUTPUT);
pinMode(I1, OUTPUT);
pinMode(I2, OUTPUT);
pinMode(I3, OUTPUT);
pinMode(I4, OUTPUT);
digitalWrite(E1, HIGH);
digitalWrite(E2, HIGH);
digitalWrite(I1, HIGH);
digitalWrite(I2, LOW);
digitalWrite(I3, HIGH);
digitalWrite(I4, LOW);
}
void loop() {
// off ten seconds
digitalWrite(E1, LOW);
digitalWrite(E2, LOW);
delay(10000);
// drive forward
digitalWrite(E1, HIGH);
digitalWrite(E2, HIGH);
digitalWrite(I1, HIGH);
digitalWrite(I2, LOW);
digitalWrite(I3, HIGH);
digitalWrite(I4, LOW);
delay(10000);
// off ten seconds
// time for bridge to be lowered
digitalWrite(E1, LOW);
digitalWrite(E2, LOW);
delay(10000);
// drive forward
digitalWrite(E1, HIGH);
digitalWrite(E2, HIGH);
digitalWrite(I1, HIGH);
digitalWrite(I2, LOW);
digitalWrite(I3, HIGH);
digitalWrite(I4, LOW);
delay(10000);
// off ten seconds
// time for bridge to be raised
digitalWrite(E1, LOW);
digitalWrite(E2, LOW);
delay(10000);
// drive forward
digitalWrite(E1, HIGH);
digitalWrite(E2, HIGH);
digitalWrite(I1, HIGH);
digitalWrite(I2, LOW);
digitalWrite(I3, HIGH);
digitalWrite(I4, LOW);
delay(10000);
// turn 180
digitalWrite(E1, HIGH);
digitalWrite(E2, HIGH);
digitalWrite(I1, LOW);
digitalWrite(I2, HIGH);
digitalWrite(I3, HIGH);
digitalWrite(I4, LOW);
delay(10000);
// drive backward
digitalWrite(E1, HIGH);
digitalWrite(E2, HIGH);
digitalWrite(I1, LOW);
digitalWrite(I2, HIGH);
digitalWrite(I3, LOW);
digitalWrite(I4, HIGH);
delay(10000);
// off ten seconds
// time for bridge to be lowered
digitalWrite(E1, LOW);
digitalWrite(E2, LOW);
delay(10000);
// drive backward
digitalWrite(E1, HIGH);
digitalWrite(E2, HIGH);
digitalWrite(I1, LOW);
digitalWrite(I2, HIGH);
digitalWrite(I3, LOW);
digitalWrite(I4, HIGH);
delay(10000);
// off ten seconds
// time for bridge to be raised
digitalWrite(E1, LOW);
digitalWrite(E2, LOW);
delay(10000);
}
|
#include <iostream>
#include "dsl/interpreter.h"
#include "device_manager.h"
using namespace std;
using namespace dm;
int main(int argc, const char *argv[]) {
if (argc != 2) {
cout << "ERROR: supply only one DSL sourcecode file" << endl;
return -1;
}
cout << "starting Device Manager" << endl;
string fileName(argv[1]);
device_manager dm(fileName);
while (cin) {
string line;
getline(cin, line);
int splitPos = line.find_first_of(' ');
string cmd = line.substr(0, splitPos);
line = line.substr(splitPos + 1, line.length());
if (cmd == "addDev") {
dm.addDev(dm.getInput(line));
} else if (cmd == "addCon") {
int splitPos = line.find_first_of(' ');
string context = line.substr(0, splitPos);
int devClusterID = stoi(line.substr(splitPos + 1, line.length()));
dm.addCon(context, devClusterID);
} else if (cmd == "rmCon") {
int splitPos = line.find_first_of(' ');
string context = line.substr(0, splitPos);
dm.rmCon(context);
} else if (cmd == "rmDev") {
dsl::Input input = dm.getInput(line);
dm.rmDev(input);
} else if (cmd == "list") {
cout << "Context clustering is:" << endl;
dm.print_context_clusterings();
cout << "Device clustering is:" << endl;
dm.print_device_clusterings();
} else if (cmd == "end") {
return 0;
} else {
cout << "Unknown command" << endl;
continue;
}
}
return 0;
}
|
// Copyright (c) 2014-2019 winking324
//
#include "controller/agora_rtc_engine.h"
#include <QMessageBox>
#include "commons/definitions.h"
#include "model/video_renderer.h"
namespace avc {
class AgoraRtcEngineEvent : public agora::rtc::IRtcEngineEventHandler {
public:
AgoraRtcEngineEvent(AgoraRtcEngine *rtc_engine) {
rtc_engine_ = rtc_engine;
}
private:
virtual void onVideoStopped() override {
emit rtc_engine_->VideoStoppedEvent();
}
virtual void onJoinChannelSuccess(const char* channel, uid_t uid,
int elapsed) override {
emit rtc_engine_->JoinChannelSuccessEvent(channel, uid, elapsed);
}
virtual void onUserJoined(uid_t uid, int elapsed) override {
emit rtc_engine_->UserJoinedEvent(uid, elapsed);
}
virtual void onUserOffline(
uid_t uid, agora::rtc::USER_OFFLINE_REASON_TYPE reason) override {
emit rtc_engine_->UserOfflineEvent(uid, reason);
}
virtual void onFirstLocalVideoFrame(int width, int height,
int elapsed) override {
emit rtc_engine_->FirstLocalVideoFrameEvent(width, height, elapsed);
}
virtual void onFirstRemoteVideoFrame(uid_t uid, int width, int height,
int elapsed) override {
emit rtc_engine_->FirstRemoteVideoFrameEvent(uid, width, height, elapsed);
}
virtual void onFirstRemoteVideoDecoded(uid_t uid, int width, int height,
int elapsed) override {
emit rtc_engine_->FirstRemoteVideoDecodedEvent(uid, width, height, elapsed);
}
private:
AgoraRtcEngine *rtc_engine_;
};
void AgoraRtcEngine::RtcEngineDeleter::operator()(
agora::rtc::IRtcEngine *engine) const {
if (engine != nullptr) {
engine->release();
}
}
AgoraRtcEngine::AgoraRtcEngine(QObject *parent)
: QObject(parent) {
rtc_engine_.reset(createAgoraRtcEngine());
event_handler_.reset(new AgoraRtcEngineEvent(this));
agora::rtc::RtcEngineContext context;
context.eventHandler = event_handler_.get();
if (strlen(kAppId) == 0) {
QMessageBox::critical(nullptr, tr("Agora QT Demo"),
tr("You must specify APP ID before using the demo"));
}
context.appId = kAppId;
rtc_engine_->initialize(context);
agora::util::AutoPtr<agora::media::IMediaEngine> media_engine;
media_engine.queryInterface(rtc_engine_.get(), agora::AGORA_IID_MEDIA_ENGINE);
if (media_engine) {
media_engine->registerVideoRenderFactory(this);
}
rtc_engine_->enableVideo();
}
void AgoraRtcEngine::JoinChannel(const QString &token,
const QString &channel_name, uint32_t uid) {
rtc_engine_->startPreview();
auto ret = rtc_engine_->joinChannel(token.toUtf8().data(),
channel_name.toUtf8().data(),
nullptr, uid);
emit JoiningChannelEvent(ret);
}
agora::media::IExternalVideoRender *
AgoraRtcEngine::createRenderInstance(
const agora::media::ExternalVideoRenerContext &context) {
if (context.view == nullptr) {
return nullptr;
}
return new VideoRenderer(context);
}
} // namespace avc
|
#ifndef __CLUCK2SESAME_PLATFORM_POWERMANAGEMENT_INC
#define __CLUCK2SESAME_PLATFORM_POWERMANAGEMENT_INC
radix decimal
extern initialisePowerManagement
extern pollPowerManagement
extern preventSleep
extern ensureFastClock
extern allowSlowClock
#endif
|
/**
MIT License
Copyright (c) 2019 mpomaranski at gmail
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "box.hpp"
#include "hdd_box_serialization_strategy.hpp"
#include <catch/catch.hpp>
#include <thread>
static std::string createM2MMessage() {
return "00000000100000000000000003F361CCB02C928BB461DD4EF";
}
static cleric::data::Box createBoxFromScratch() {
auto retention = std::chrono::hours(24);
std::unique_ptr<cleric::data::IBoxSerializationStrategy> serializer{
new cleric::data::HddBoxSerializationStrategy(1, ".")};
cleric::data::Box result{1, "dummy", retention, 1000, std::move(serializer)};
return result;
}
TEST_CASE("Box can be serialized and deserialized",
"[hdd box serialization strategy]") {
auto m2m = createM2MMessage();
auto b1 = createBoxFromScratch();
auto t = std::thread([&]() {
for (int i = 0; i < 500; i++) {
b1.process(m2m);
}
});
t.join();
b1.persist();
std::unique_ptr<cleric::data::IBoxSerializationStrategy> serializer{
new cleric::data::HddBoxSerializationStrategy(1, ".")};
cleric::data::Box b2{std::move(serializer)};
CHECK(b1 == b2);
auto t2 = std::thread([&]() {
for (int i = 0; i < 500; i++) {
b1.process(m2m);
}
});
t2.join();
b1.persist();
std::unique_ptr<cleric::data::IBoxSerializationStrategy> serializer3{
new cleric::data::HddBoxSerializationStrategy(1, ".")};
cleric::data::Box b3{std::move(serializer3)};
CHECK(b1 == b3);
CHECK(!(b2 == b3));
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** 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
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#include "../progsvm/progsvm.h"
#include "../quake_hexen/local.h"
#include "local.h"
#include "../../common/common_defs.h"
#include "../../common/strings.h"
#include "../../common/Common.h"
Cvar* sv_ce_scale;
Cvar* sv_ce_max_size;
// this will create several effects and store the ids in the array
static float MultiEffectIds[ 10 ];
static int MultiEffectIdCount;
static void SVH2_ClearEffects() {
Com_Memset( sv.h2_Effects,0,sizeof ( sv.h2_Effects ) );
}
static void SVH2_GetSendEffectTestParams( int index, bool& DoTest, float& TestDistance, vec3_t TestO ) {
VectorCopy( oldvec3_origin, TestO );
TestDistance = 0;
switch ( sv.h2_Effects[ index ].type ) {
case H2CE_RAIN:
case H2CE_SNOW:
DoTest = false;
break;
case H2CE_FOUNTAIN:
DoTest = false;
break;
case H2CE_QUAKE:
VectorCopy( sv.h2_Effects[ index ].Quake.origin, TestO );
TestDistance = 700;
break;
case H2CE_WHITE_SMOKE:
case H2CE_GREEN_SMOKE:
case H2CE_GREY_SMOKE:
case H2CE_RED_SMOKE:
case H2CE_SLOW_WHITE_SMOKE:
case H2CE_TELESMK1:
case H2CE_TELESMK2:
case H2CE_GHOST:
case H2CE_REDCLOUD:
case H2CE_FLAMESTREAM:
case H2CE_ACID_MUZZFL:
case H2CE_FLAMEWALL:
case H2CE_FLAMEWALL2:
case H2CE_ONFIRE:
VectorCopy( sv.h2_Effects[ index ].Smoke.origin, TestO );
TestDistance = 250;
break;
case H2CE_SM_WHITE_FLASH:
case H2CE_YELLOWRED_FLASH:
case H2CE_BLUESPARK:
case H2CE_YELLOWSPARK:
case H2CE_SM_CIRCLE_EXP:
case H2CE_BG_CIRCLE_EXP:
case H2CE_SM_EXPLOSION:
case H2CE_LG_EXPLOSION:
case H2CE_FLOOR_EXPLOSION:
case H2CE_BLUE_EXPLOSION:
case H2CE_REDSPARK:
case H2CE_GREENSPARK:
case H2CE_ICEHIT:
case H2CE_MEDUSA_HIT:
case H2CE_MEZZO_REFLECT:
case H2CE_FLOOR_EXPLOSION2:
case H2CE_XBOW_EXPLOSION:
case H2CE_NEW_EXPLOSION:
case H2CE_MAGIC_MISSILE_EXPLOSION:
case H2CE_BONE_EXPLOSION:
case H2CE_BLDRN_EXPL:
case H2CE_ACID_HIT:
case H2CE_LBALL_EXPL:
case H2CE_FIREWALL_SMALL:
case H2CE_FIREWALL_MEDIUM:
case H2CE_FIREWALL_LARGE:
case H2CE_ACID_SPLAT:
case H2CE_ACID_EXPL:
case H2CE_FBOOM:
case H2CE_BRN_BOUNCE:
case H2CE_LSHOCK:
case H2CE_BOMB:
case H2CE_FLOOR_EXPLOSION3:
VectorCopy( sv.h2_Effects[ index ].Smoke.origin, TestO );
TestDistance = 250;
break;
case H2CE_WHITE_FLASH:
case H2CE_BLUE_FLASH:
case H2CE_SM_BLUE_FLASH:
case H2CE_RED_FLASH:
VectorCopy( sv.h2_Effects[ index ].Smoke.origin, TestO );
TestDistance = 250;
break;
case H2CE_RIDER_DEATH:
DoTest = false;
break;
case H2CE_GRAVITYWELL:
DoTest = false;
break;
case H2CE_TELEPORTERPUFFS:
VectorCopy( sv.h2_Effects[ index ].Teleporter.origin, TestO );
TestDistance = 350;
break;
case H2CE_TELEPORTERBODY:
VectorCopy( sv.h2_Effects[ index ].Teleporter.origin, TestO );
TestDistance = 350;
break;
case H2CE_BONESHARD:
case H2CE_BONESHRAPNEL:
VectorCopy( sv.h2_Effects[ index ].Missile.origin, TestO );
TestDistance = 600;
break;
case H2CE_CHUNK:
VectorCopy( sv.h2_Effects[ index ].Chunk.origin, TestO );
TestDistance = 600;
break;
default:
PR_RunError( "SV_SendEffect: bad type" );
break;
}
}
static void SVHW_GetSendEffectTestParams( int index, bool& DoTest, vec3_t TestO ) {
VectorCopy( oldvec3_origin, TestO );
switch ( sv.h2_Effects[ index ].type ) {
case HWCE_HWSHEEPINATOR:
case HWCE_HWXBOWSHOOT:
VectorCopy( sv.h2_Effects[ index ].Xbow.origin[ 5 ], TestO );
break;
case HWCE_SCARABCHAIN:
VectorCopy( sv.h2_Effects[ index ].Chain.origin, TestO );
break;
case HWCE_TRIPMINE:
VectorCopy( sv.h2_Effects[ index ].Chain.origin, TestO );
break;
//ACHTUNG!!!!!!! setting DoTest to false here does not insure that effect will be sent to everyone!
case HWCE_TRIPMINESTILL:
DoTest = false;
break;
case HWCE_RAIN:
DoTest = false;
break;
case HWCE_FOUNTAIN:
DoTest = false;
break;
case HWCE_QUAKE:
VectorCopy( sv.h2_Effects[ index ].Quake.origin, TestO );
break;
case HWCE_WHITE_SMOKE:
case HWCE_GREEN_SMOKE:
case HWCE_GREY_SMOKE:
case HWCE_RED_SMOKE:
case HWCE_SLOW_WHITE_SMOKE:
case HWCE_TELESMK1:
case HWCE_TELESMK2:
case HWCE_GHOST:
case HWCE_REDCLOUD:
case HWCE_FLAMESTREAM:
case HWCE_ACID_MUZZFL:
case HWCE_FLAMEWALL:
case HWCE_FLAMEWALL2:
case HWCE_ONFIRE:
case HWCE_RIPPLE:
VectorCopy( sv.h2_Effects[ index ].Smoke.origin, TestO );
break;
case HWCE_SM_WHITE_FLASH:
case HWCE_YELLOWRED_FLASH:
case HWCE_BLUESPARK:
case HWCE_YELLOWSPARK:
case HWCE_SM_CIRCLE_EXP:
case HWCE_BG_CIRCLE_EXP:
case HWCE_SM_EXPLOSION:
case HWCE_SM_EXPLOSION2:
case HWCE_BG_EXPLOSION:
case HWCE_FLOOR_EXPLOSION:
case HWCE_BLUE_EXPLOSION:
case HWCE_REDSPARK:
case HWCE_GREENSPARK:
case HWCE_ICEHIT:
case HWCE_MEDUSA_HIT:
case HWCE_MEZZO_REFLECT:
case HWCE_FLOOR_EXPLOSION2:
case HWCE_XBOW_EXPLOSION:
case HWCE_NEW_EXPLOSION:
case HWCE_MAGIC_MISSILE_EXPLOSION:
case HWCE_BONE_EXPLOSION:
case HWCE_BLDRN_EXPL:
case HWCE_ACID_HIT:
case HWCE_LBALL_EXPL:
case HWCE_FIREWALL_SMALL:
case HWCE_FIREWALL_MEDIUM:
case HWCE_FIREWALL_LARGE:
case HWCE_ACID_SPLAT:
case HWCE_ACID_EXPL:
case HWCE_FBOOM:
case HWCE_BRN_BOUNCE:
case HWCE_LSHOCK:
case HWCE_BOMB:
case HWCE_FLOOR_EXPLOSION3:
VectorCopy( sv.h2_Effects[ index ].Smoke.origin, TestO );
break;
case HWCE_WHITE_FLASH:
case HWCE_BLUE_FLASH:
case HWCE_SM_BLUE_FLASH:
case HWCE_HWSPLITFLASH:
case HWCE_RED_FLASH:
VectorCopy( sv.h2_Effects[ index ].Smoke.origin, TestO );
break;
case HWCE_RIDER_DEATH:
DoTest = false;
break;
case HWCE_TELEPORTERPUFFS:
VectorCopy( sv.h2_Effects[ index ].Teleporter.origin, TestO );
break;
case HWCE_TELEPORTERBODY:
VectorCopy( sv.h2_Effects[ index ].Teleporter.origin, TestO );
break;
case HWCE_DEATHBUBBLES:
if ( sv.h2_Effects[ index ].Bubble.owner < 0 || sv.h2_Effects[ index ].Bubble.owner >= sv.qh_num_edicts ) {
return;
}
VectorCopy( PROG_TO_EDICT( sv.h2_Effects[ index ].Bubble.owner )->GetOrigin(), TestO );
break;
case HWCE_HWDRILLA:
case HWCE_BONESHARD:
case HWCE_BONESHRAPNEL:
case HWCE_HWBONEBALL:
case HWCE_HWRAVENSTAFF:
case HWCE_HWRAVENPOWER:
VectorCopy( sv.h2_Effects[ index ].Missile.origin, TestO );
break;
case HWCE_HWMISSILESTAR:
case HWCE_HWEIDOLONSTAR:
VectorCopy( sv.h2_Effects[ index ].Missile.origin, TestO );
break;
default:
PR_RunError( "SV_SendEffect: bad type" );
break;
}
}
static void SVH2_WriteEffectRain( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Rain.min_org[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.min_org[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.min_org[ 2 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.max_org[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.max_org[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.max_org[ 2 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.e_size[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.e_size[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.e_size[ 2 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.dir[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.dir[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Rain.dir[ 2 ] );
message.WriteShort( sv.h2_Effects[ index ].Rain.color );
message.WriteShort( sv.h2_Effects[ index ].Rain.count );
message.WriteFloat( sv.h2_Effects[ index ].Rain.wait );
}
static void SVH2_WriteEffectSnow( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Snow.min_org[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Snow.min_org[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Snow.min_org[ 2 ] );
message.WriteCoord( sv.h2_Effects[ index ].Snow.max_org[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Snow.max_org[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Snow.max_org[ 2 ] );
message.WriteByte( sv.h2_Effects[ index ].Snow.flags );
message.WriteCoord( sv.h2_Effects[ index ].Snow.dir[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Snow.dir[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Snow.dir[ 2 ] );
message.WriteByte( sv.h2_Effects[ index ].Snow.count );
}
static void SVH2_WriteEffectFountain( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Fountain.pos[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Fountain.pos[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Fountain.pos[ 2 ] );
message.WriteAngle( sv.h2_Effects[ index ].Fountain.angle[ 0 ] );
message.WriteAngle( sv.h2_Effects[ index ].Fountain.angle[ 1 ] );
message.WriteAngle( sv.h2_Effects[ index ].Fountain.angle[ 2 ] );
message.WriteCoord( sv.h2_Effects[ index ].Fountain.movedir[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Fountain.movedir[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Fountain.movedir[ 2 ] );
message.WriteShort( sv.h2_Effects[ index ].Fountain.color );
message.WriteByte( sv.h2_Effects[ index ].Fountain.cnt );
}
static void SVH2_WriteEffectQuake( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Quake.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Quake.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Quake.origin[ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Quake.radius );
}
static void SVH2_WriteEffectSmoke( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Smoke.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Smoke.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Smoke.origin[ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Smoke.velocity[ 0 ] );
message.WriteFloat( sv.h2_Effects[ index ].Smoke.velocity[ 1 ] );
message.WriteFloat( sv.h2_Effects[ index ].Smoke.velocity[ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Smoke.framelength );
if ( !( GGameType & GAME_HexenWorld ) ) {
message.WriteFloat( sv.h2_Effects[ index ].Smoke.frame );
}
}
static void SVH2_WriteEffectFlash( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Smoke.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Smoke.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Smoke.origin[ 2 ] );
}
static void SVH2_WriteEffectRiderDeath( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].RD.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].RD.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].RD.origin[ 2 ] );
}
static void SVH2_WriteEffectTeleporterPuffs( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Teleporter.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Teleporter.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Teleporter.origin[ 2 ] );
}
static void SVH2_WriteEffectTeleporterBody( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Teleporter.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Teleporter.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Teleporter.origin[ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Teleporter.velocity[ 0 ][ 0 ] );
message.WriteFloat( sv.h2_Effects[ index ].Teleporter.velocity[ 0 ][ 1 ] );
message.WriteFloat( sv.h2_Effects[ index ].Teleporter.velocity[ 0 ][ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Teleporter.skinnum );
}
static void SVH2_WriteEffectBoneShrapnel( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Missile.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Missile.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Missile.origin[ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.velocity[ 0 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.velocity[ 1 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.velocity[ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.angle[ 0 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.angle[ 1 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.angle[ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.avelocity[ 0 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.avelocity[ 1 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.avelocity[ 2 ] );
}
static void SVH2_WriteEffectGravityWell( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].GravityWell.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].GravityWell.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].GravityWell.origin[ 2 ] );
message.WriteShort( sv.h2_Effects[ index ].GravityWell.color );
message.WriteFloat( sv.h2_Effects[ index ].GravityWell.lifetime );
}
static void SVH2_WriteEffectChunk( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Chunk.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Chunk.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Chunk.origin[ 2 ] );
message.WriteByte( sv.h2_Effects[ index ].Chunk.type );
message.WriteCoord( sv.h2_Effects[ index ].Chunk.srcVel[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Chunk.srcVel[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Chunk.srcVel[ 2 ] );
message.WriteByte( sv.h2_Effects[ index ].Chunk.numChunks );
}
static void SVHW_WriteEffectRavenStaff( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Missile.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Missile.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Missile.origin[ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.velocity[ 0 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.velocity[ 1 ] );
message.WriteFloat( sv.h2_Effects[ index ].Missile.velocity[ 2 ] );
}
static void SVHW_WriteEffectDrilla( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Missile.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Missile.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Missile.origin[ 2 ] );
message.WriteAngle( sv.h2_Effects[ index ].Missile.angle[ 0 ] );
message.WriteAngle( sv.h2_Effects[ index ].Missile.angle[ 1 ] );
message.WriteShort( sv.h2_Effects[ index ].Missile.speed );
}
static void SVHW_WriteEffectDeathBubbles( int index, QMsg& message ) {
message.WriteShort( sv.h2_Effects[ index ].Bubble.owner );
message.WriteByte( sv.h2_Effects[ index ].Bubble.offset[ 0 ] );
message.WriteByte( sv.h2_Effects[ index ].Bubble.offset[ 1 ] );
message.WriteByte( sv.h2_Effects[ index ].Bubble.offset[ 2 ] );
message.WriteByte( sv.h2_Effects[ index ].Bubble.count );
}
static void SVHW_WriteEffectScarabChain( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Chain.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Chain.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Chain.origin[ 2 ] );
message.WriteShort( sv.h2_Effects[ index ].Chain.owner + sv.h2_Effects[ index ].Chain.material );
message.WriteByte( sv.h2_Effects[ index ].Chain.tag );
}
static void SVHW_WriteEffectTripMine( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Chain.origin[ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Chain.origin[ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Chain.origin[ 2 ] );
message.WriteFloat( sv.h2_Effects[ index ].Chain.velocity[ 0 ] );
message.WriteFloat( sv.h2_Effects[ index ].Chain.velocity[ 1 ] );
message.WriteFloat( sv.h2_Effects[ index ].Chain.velocity[ 2 ] );
}
static void SVHW_WriteEffectSheepinator( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ 5 ][ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ 5 ][ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ 5 ][ 2 ] );
message.WriteAngle( sv.h2_Effects[ index ].Xbow.angle[ 0 ] );
message.WriteAngle( sv.h2_Effects[ index ].Xbow.angle[ 1 ] );
//now send the guys that have turned
message.WriteByte( sv.h2_Effects[ index ].Xbow.turnedbolts );
message.WriteByte( sv.h2_Effects[ index ].Xbow.activebolts );
for ( int i = 0; i < 5; i++ ) {
if ( ( 1 << i ) & sv.h2_Effects[ index ].Xbow.turnedbolts ) {
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ i ][ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ i ][ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ i ][ 2 ] );
message.WriteAngle( sv.h2_Effects[ index ].Xbow.vel[ i ][ 0 ] );
message.WriteAngle( sv.h2_Effects[ index ].Xbow.vel[ i ][ 1 ] );
}
}
}
static void SVHW_WriteEffectXBowShoot( int index, QMsg& message ) {
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ 5 ][ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ 5 ][ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ 5 ][ 2 ] );
message.WriteAngle( sv.h2_Effects[ index ].Xbow.angle[ 0 ] );
message.WriteAngle( sv.h2_Effects[ index ].Xbow.angle[ 1 ] );
message.WriteByte( sv.h2_Effects[ index ].Xbow.bolts );
message.WriteByte( sv.h2_Effects[ index ].Xbow.randseed );
//now send the guys that have turned
message.WriteByte( sv.h2_Effects[ index ].Xbow.turnedbolts );
message.WriteByte( sv.h2_Effects[ index ].Xbow.activebolts );
for ( int i = 0; i < 5; i++ ) {
if ( ( 1 << i ) & sv.h2_Effects[ index ].Xbow.turnedbolts ) {
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ i ][ 0 ] );
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ i ][ 1 ] );
message.WriteCoord( sv.h2_Effects[ index ].Xbow.origin[ i ][ 2 ] );
message.WriteAngle( sv.h2_Effects[ index ].Xbow.vel[ i ][ 0 ] );
message.WriteAngle( sv.h2_Effects[ index ].Xbow.vel[ i ][ 1 ] );
}
}
}
static void SVH2_WriteEffect( int index, QMsg& message ) {
message.WriteByte( h2svc_start_effect );
message.WriteByte( index );
message.WriteByte( sv.h2_Effects[ index ].type );
switch ( sv.h2_Effects[ index ].type ) {
case H2CE_RAIN:
SVH2_WriteEffectRain( index, message );
break;
case H2CE_SNOW:
SVH2_WriteEffectSnow( index, message );
break;
case H2CE_FOUNTAIN:
SVH2_WriteEffectFountain( index, message );
break;
case H2CE_QUAKE:
SVH2_WriteEffectQuake( index, message );
break;
case H2CE_WHITE_SMOKE:
case H2CE_GREEN_SMOKE:
case H2CE_GREY_SMOKE:
case H2CE_RED_SMOKE:
case H2CE_SLOW_WHITE_SMOKE:
case H2CE_TELESMK1:
case H2CE_TELESMK2:
case H2CE_GHOST:
case H2CE_REDCLOUD:
case H2CE_FLAMESTREAM:
case H2CE_ACID_MUZZFL:
case H2CE_FLAMEWALL:
case H2CE_FLAMEWALL2:
case H2CE_ONFIRE:
SVH2_WriteEffectSmoke( index, message );
break;
case H2CE_SM_WHITE_FLASH:
case H2CE_YELLOWRED_FLASH:
case H2CE_BLUESPARK:
case H2CE_YELLOWSPARK:
case H2CE_SM_CIRCLE_EXP:
case H2CE_BG_CIRCLE_EXP:
case H2CE_SM_EXPLOSION:
case H2CE_LG_EXPLOSION:
case H2CE_FLOOR_EXPLOSION:
case H2CE_FLOOR_EXPLOSION3:
case H2CE_BLUE_EXPLOSION:
case H2CE_REDSPARK:
case H2CE_GREENSPARK:
case H2CE_ICEHIT:
case H2CE_MEDUSA_HIT:
case H2CE_MEZZO_REFLECT:
case H2CE_FLOOR_EXPLOSION2:
case H2CE_XBOW_EXPLOSION:
case H2CE_NEW_EXPLOSION:
case H2CE_MAGIC_MISSILE_EXPLOSION:
case H2CE_BONE_EXPLOSION:
case H2CE_BLDRN_EXPL:
case H2CE_ACID_HIT:
case H2CE_ACID_SPLAT:
case H2CE_ACID_EXPL:
case H2CE_LBALL_EXPL:
case H2CE_FIREWALL_SMALL:
case H2CE_FIREWALL_MEDIUM:
case H2CE_FIREWALL_LARGE:
case H2CE_FBOOM:
case H2CE_BOMB:
case H2CE_BRN_BOUNCE:
case H2CE_LSHOCK:
case H2CE_WHITE_FLASH:
case H2CE_BLUE_FLASH:
case H2CE_SM_BLUE_FLASH:
case H2CE_RED_FLASH:
SVH2_WriteEffectFlash( index, message );
break;
case H2CE_RIDER_DEATH:
SVH2_WriteEffectRiderDeath( index, message );
break;
case H2CE_TELEPORTERPUFFS:
SVH2_WriteEffectTeleporterPuffs( index, message );
break;
case H2CE_TELEPORTERBODY:
SVH2_WriteEffectTeleporterBody( index, message );
break;
case H2CE_BONESHARD:
case H2CE_BONESHRAPNEL:
SVH2_WriteEffectBoneShrapnel( index, message );
break;
case H2CE_GRAVITYWELL:
SVH2_WriteEffectGravityWell( index, message );
break;
case H2CE_CHUNK:
SVH2_WriteEffectChunk( index, message );
break;
default:
PR_RunError( "SV_SendEffect: bad type" );
break;
}
}
static void SVHW_WriteEffect( int index, QMsg& message ) {
message.WriteByte( hwsvc_start_effect );
message.WriteByte( index );
message.WriteByte( sv.h2_Effects[ index ].type );
switch ( sv.h2_Effects[ index ].type ) {
case HWCE_RAIN:
SVH2_WriteEffectRain( index, message );
break;
case HWCE_FOUNTAIN:
SVH2_WriteEffectFountain( index, message );
break;
case HWCE_QUAKE:
SVH2_WriteEffectQuake( index, message );
break;
case HWCE_WHITE_SMOKE:
case HWCE_GREEN_SMOKE:
case HWCE_GREY_SMOKE:
case HWCE_RED_SMOKE:
case HWCE_SLOW_WHITE_SMOKE:
case HWCE_TELESMK1:
case HWCE_TELESMK2:
case HWCE_GHOST:
case HWCE_REDCLOUD:
case HWCE_FLAMESTREAM:
case HWCE_ACID_MUZZFL:
case HWCE_FLAMEWALL:
case HWCE_FLAMEWALL2:
case HWCE_ONFIRE:
case HWCE_RIPPLE:
SVH2_WriteEffectSmoke( index, message );
break;
case HWCE_SM_WHITE_FLASH:
case HWCE_YELLOWRED_FLASH:
case HWCE_BLUESPARK:
case HWCE_YELLOWSPARK:
case HWCE_SM_CIRCLE_EXP:
case HWCE_BG_CIRCLE_EXP:
case HWCE_SM_EXPLOSION:
case HWCE_SM_EXPLOSION2:
case HWCE_BG_EXPLOSION:
case HWCE_FLOOR_EXPLOSION:
case HWCE_BLUE_EXPLOSION:
case HWCE_REDSPARK:
case HWCE_GREENSPARK:
case HWCE_ICEHIT:
case HWCE_MEDUSA_HIT:
case HWCE_MEZZO_REFLECT:
case HWCE_FLOOR_EXPLOSION2:
case HWCE_XBOW_EXPLOSION:
case HWCE_NEW_EXPLOSION:
case HWCE_MAGIC_MISSILE_EXPLOSION:
case HWCE_BONE_EXPLOSION:
case HWCE_BLDRN_EXPL:
case HWCE_ACID_HIT:
case HWCE_ACID_SPLAT:
case HWCE_ACID_EXPL:
case HWCE_LBALL_EXPL:
case HWCE_FIREWALL_SMALL:
case HWCE_FIREWALL_MEDIUM:
case HWCE_FIREWALL_LARGE:
case HWCE_FBOOM:
case HWCE_BOMB:
case HWCE_BRN_BOUNCE:
case HWCE_LSHOCK:
case HWCE_WHITE_FLASH:
case HWCE_BLUE_FLASH:
case HWCE_SM_BLUE_FLASH:
case HWCE_HWSPLITFLASH:
case HWCE_RED_FLASH:
SVH2_WriteEffectFlash( index, message );
break;
case HWCE_RIDER_DEATH:
SVH2_WriteEffectRiderDeath( index, message );
break;
case HWCE_TELEPORTERPUFFS:
SVH2_WriteEffectTeleporterPuffs( index, message );
break;
case HWCE_TELEPORTERBODY:
SVH2_WriteEffectTeleporterBody( index, message );
break;
case HWCE_BONESHRAPNEL:
case HWCE_HWBONEBALL:
SVH2_WriteEffectBoneShrapnel( index, message );
break;
case HWCE_BONESHARD:
case HWCE_HWRAVENSTAFF:
case HWCE_HWMISSILESTAR:
case HWCE_HWEIDOLONSTAR:
case HWCE_HWRAVENPOWER:
SVHW_WriteEffectRavenStaff( index, message );
break;
case HWCE_HWDRILLA:
SVHW_WriteEffectDrilla( index, message );
break;
case HWCE_DEATHBUBBLES:
SVHW_WriteEffectDeathBubbles( index, message );
break;
case HWCE_SCARABCHAIN:
SVHW_WriteEffectScarabChain( index, message );
break;
case HWCE_TRIPMINESTILL:
case HWCE_TRIPMINE:
SVHW_WriteEffectTripMine( index, message );
break;
case HWCE_HWSHEEPINATOR:
SVHW_WriteEffectSheepinator( index, message );
break;
case HWCE_HWXBOWSHOOT:
SVHW_WriteEffectXBowShoot( index, message );
break;
default:
PR_RunError( "SV_SendEffect: bad type" );
break;
}
}
static void SVH2_SendEffect( QMsg* sb, int index ) {
bool DoTest;
if ( sb == &sv.qh_reliable_datagram && sv_ce_scale->value > 0 ) {
DoTest = true;
} else {
DoTest = false;
}
vec3_t TestO;
float TestDistance;
SVH2_GetSendEffectTestParams( index, DoTest, TestDistance, TestO );
int count;
if ( !DoTest ) {
count = 1;
} else {
count = svs.qh_maxclients;
TestDistance = ( float )TestDistance * sv_ce_scale->value;
TestDistance *= TestDistance;
}
for ( int i = 0; i < count; i++ ) {
if ( DoTest ) {
if ( svs.clients[ i ].state >= CS_CONNECTED ) {
sb = &svs.clients[ i ].datagram;
vec3_t Diff;
VectorSubtract( svs.clients[ i ].qh_edict->GetOrigin(), TestO, Diff );
float Size = ( Diff[ 0 ] * Diff[ 0 ] ) + ( Diff[ 1 ] * Diff[ 1 ] ) + ( Diff[ 2 ] * Diff[ 2 ] );
if ( Size > TestDistance ) {
continue;
}
if ( sv_ce_max_size->value > 0 && sb->cursize > sv_ce_max_size->value ) {
continue;
}
} else {
continue;
}
}
SVH2_WriteEffect( index, *sb );
}
}
void SVHW_SendEffect( QMsg* sb, int index ) {
bool DoTest;
if ( ( GGameType & GAME_HexenWorld || sb == &sv.qh_reliable_datagram ) && sv_ce_scale->value > 0 ) {
DoTest = true;
} else {
DoTest = false;
}
vec3_t TestO;
SVHW_GetSendEffectTestParams( index, DoTest, TestO );
SVHW_WriteEffect( index, sv.multicast );
if ( sb ) {
sb->WriteData( sv.multicast._data, sv.multicast.cursize );
sv.multicast.Clear();
} else {
if ( DoTest ) {
SVQH_Multicast( TestO, MULTICAST_PVS_R );
} else {
SVQH_Multicast( TestO, MULTICAST_ALL_R );
}
sv.h2_Effects[ index ].client_list = clients_multicast;
}
}
void SVH2_UpdateEffects( QMsg* sb ) {
for ( int index = 0; index < MAX_EFFECTS_H2; index++ ) {
if ( sv.h2_Effects[ index ].type ) {
SVH2_SendEffect( sb,index );
}
}
}
static void SVH2_ParseEffectRain( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Rain.min_org );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Rain.max_org );
VectorCopy( G_VECTOR( OFS_PARM3 ), sv.h2_Effects[ index ].Rain.e_size );
VectorCopy( G_VECTOR( OFS_PARM4 ), sv.h2_Effects[ index ].Rain.dir );
sv.h2_Effects[ index ].Rain.color = G_FLOAT( OFS_PARM5 );
sv.h2_Effects[ index ].Rain.count = G_FLOAT( OFS_PARM6 );
sv.h2_Effects[ index ].Rain.wait = G_FLOAT( OFS_PARM7 );
sv.h2_Effects[ index ].Rain.next_time = 0;
}
static void SVH2_ParseEffectSnow( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Snow.min_org );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Snow.max_org );
sv.h2_Effects[ index ].Snow.flags = G_FLOAT( OFS_PARM3 );
VectorCopy( G_VECTOR( OFS_PARM4 ), sv.h2_Effects[ index ].Snow.dir );
sv.h2_Effects[ index ].Snow.count = G_FLOAT( OFS_PARM5 );
sv.h2_Effects[ index ].Snow.next_time = 0;
}
static void SVH2_ParseEffectFountain( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Fountain.pos );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Fountain.angle );
VectorCopy( G_VECTOR( OFS_PARM3 ), sv.h2_Effects[ index ].Fountain.movedir );
sv.h2_Effects[ index ].Fountain.color = G_FLOAT( OFS_PARM4 );
sv.h2_Effects[ index ].Fountain.cnt = G_FLOAT( OFS_PARM5 );
}
static void SVH2_ParseEffectQuake( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Quake.origin );
sv.h2_Effects[ index ].Quake.radius = G_FLOAT( OFS_PARM2 );
}
static void SVH2_ParseEffectSmoke( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Smoke.origin );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Smoke.velocity );
sv.h2_Effects[ index ].Smoke.framelength = G_FLOAT( OFS_PARM3 );
if ( !( GGameType & GAME_HexenWorld ) ) {
sv.h2_Effects[ index ].Smoke.frame = 0;
}
sv.h2_Effects[ index ].expire_time = sv.qh_time + 1000;
}
static void SVH2_ParseEffectFlameWall( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Smoke.origin );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Smoke.velocity );
sv.h2_Effects[ index ].Smoke.framelength = 0.05;
sv.h2_Effects[ index ].Smoke.frame = G_FLOAT( OFS_PARM3 );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 1000;
}
static void SVH2_ParseEffectSmokeFlash( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Smoke.origin );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 1000;
}
static void SVH2_ParseEffectFlash( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Flash.origin );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 1000;
}
static void SVH2_ParseEffectRiderDeath( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].RD.origin );
}
static void SVH2_ParseEffectTeleporterPuffs( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Teleporter.origin );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 1000;
}
static void SVH2_ParseEffectTeleporterBody( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Teleporter.origin );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Teleporter.velocity[ 0 ] );
sv.h2_Effects[ index ].Teleporter.skinnum = G_FLOAT( OFS_PARM3 );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 1000;
}
static void SVH2_ParseEffectBoneShrapnel( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Missile.origin );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Missile.velocity );
VectorCopy( G_VECTOR( OFS_PARM3 ), sv.h2_Effects[ index ].Missile.angle );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Missile.avelocity );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 10000;
}
static void SVH2_ParseEffectGravityWell( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].GravityWell.origin );
sv.h2_Effects[ index ].GravityWell.color = G_FLOAT( OFS_PARM2 );
sv.h2_Effects[ index ].GravityWell.lifetime = G_FLOAT( OFS_PARM3 );
}
static void SVH2_ParseEffectChunk( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Chunk.origin );
sv.h2_Effects[ index ].Chunk.type = G_FLOAT( OFS_PARM2 );
VectorCopy( G_VECTOR( OFS_PARM3 ), sv.h2_Effects[ index ].Chunk.srcVel );
sv.h2_Effects[ index ].Chunk.numChunks = G_FLOAT( OFS_PARM4 );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 3000;
}
static void SVHW_ParseEffectRavenStaff( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Missile.origin );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Missile.velocity );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 10000;
}
static void SVHW_ParseEffectDeathBubbles( int index ) {
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Bubble.offset );
sv.h2_Effects[ index ].Bubble.owner = G_EDICTNUM( OFS_PARM1 );
sv.h2_Effects[ index ].Bubble.count = G_FLOAT( OFS_PARM3 );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 30000;
}
static void SVHW_ParseEffectDrilla( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Missile.origin );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Missile.angle );
sv.h2_Effects[ index ].Missile.speed = G_FLOAT( OFS_PARM3 );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 10000;
}
static void SVHW_ParseEffectTripMineStill( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Chain.origin );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Chain.velocity );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 70000;
}
static void SVHW_ParseEffectTripMine( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Chain.origin );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Chain.velocity );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 10000;
}
static void SVHW_ParseEffectScarabChain( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Chain.origin );
sv.h2_Effects[ index ].Chain.owner = G_EDICTNUM( OFS_PARM2 );
sv.h2_Effects[ index ].Chain.material = G_INT( OFS_PARM3 );
sv.h2_Effects[ index ].Chain.tag = G_INT( OFS_PARM4 );
sv.h2_Effects[ index ].Chain.state = 0;
sv.h2_Effects[ index ].expire_time = sv.qh_time + 15000;
}
static void SVHW_ParseEffectSheepinator( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 0 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 1 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 2 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 3 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 4 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 5 ] );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Xbow.angle );
sv.h2_Effects[ index ].Xbow.bolts = 5;
sv.h2_Effects[ index ].Xbow.activebolts = 31;
sv.h2_Effects[ index ].Xbow.randseed = 0;
sv.h2_Effects[ index ].Xbow.turnedbolts = 0;
sv.h2_Effects[ index ].expire_time = sv.qh_time + 7000;
}
static void SVHW_ParseEffectXBowShoot( int index ) {
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 0 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 1 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 2 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 3 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 4 ] );
VectorCopy( G_VECTOR( OFS_PARM1 ), sv.h2_Effects[ index ].Xbow.origin[ 5 ] );
VectorCopy( G_VECTOR( OFS_PARM2 ), sv.h2_Effects[ index ].Xbow.angle );
sv.h2_Effects[ index ].Xbow.bolts = G_FLOAT( OFS_PARM3 );
sv.h2_Effects[ index ].Xbow.randseed = G_FLOAT( OFS_PARM4 );
sv.h2_Effects[ index ].Xbow.turnedbolts = 0;
if ( sv.h2_Effects[ index ].Xbow.bolts == 3 ) {
sv.h2_Effects[ index ].Xbow.activebolts = 7;
} else {
sv.h2_Effects[ index ].Xbow.activebolts = 31;
}
sv.h2_Effects[ index ].expire_time = sv.qh_time + 15000;
}
static void SVH2_ParseEffectDetails( int index ) {
switch ( sv.h2_Effects[ index ].type ) {
case H2CE_RAIN:
SVH2_ParseEffectRain( index );
break;
case H2CE_SNOW:
SVH2_ParseEffectSnow( index );
break;
case H2CE_FOUNTAIN:
SVH2_ParseEffectFountain( index );
break;
case H2CE_QUAKE:
SVH2_ParseEffectQuake( index );
break;
case H2CE_WHITE_SMOKE:
case H2CE_GREEN_SMOKE:
case H2CE_GREY_SMOKE:
case H2CE_RED_SMOKE:
case H2CE_SLOW_WHITE_SMOKE:
case H2CE_TELESMK1:
case H2CE_TELESMK2:
case H2CE_GHOST:
case H2CE_REDCLOUD:
SVH2_ParseEffectSmoke( index );
break;
case H2CE_ACID_MUZZFL:
case H2CE_FLAMESTREAM:
case H2CE_FLAMEWALL:
case H2CE_FLAMEWALL2:
case H2CE_ONFIRE:
SVH2_ParseEffectFlameWall( index );
break;
case H2CE_SM_WHITE_FLASH:
case H2CE_YELLOWRED_FLASH:
case H2CE_BLUESPARK:
case H2CE_YELLOWSPARK:
case H2CE_SM_CIRCLE_EXP:
case H2CE_BG_CIRCLE_EXP:
case H2CE_SM_EXPLOSION:
case H2CE_LG_EXPLOSION:
case H2CE_FLOOR_EXPLOSION:
case H2CE_FLOOR_EXPLOSION3:
case H2CE_BLUE_EXPLOSION:
case H2CE_REDSPARK:
case H2CE_GREENSPARK:
case H2CE_ICEHIT:
case H2CE_MEDUSA_HIT:
case H2CE_MEZZO_REFLECT:
case H2CE_FLOOR_EXPLOSION2:
case H2CE_XBOW_EXPLOSION:
case H2CE_NEW_EXPLOSION:
case H2CE_MAGIC_MISSILE_EXPLOSION:
case H2CE_BONE_EXPLOSION:
case H2CE_BLDRN_EXPL:
case H2CE_ACID_HIT:
case H2CE_ACID_SPLAT:
case H2CE_ACID_EXPL:
case H2CE_LBALL_EXPL:
case H2CE_FIREWALL_SMALL:
case H2CE_FIREWALL_MEDIUM:
case H2CE_FIREWALL_LARGE:
case H2CE_FBOOM:
case H2CE_BOMB:
case H2CE_BRN_BOUNCE:
case H2CE_LSHOCK:
SVH2_ParseEffectSmokeFlash( index );
break;
case H2CE_WHITE_FLASH:
case H2CE_BLUE_FLASH:
case H2CE_SM_BLUE_FLASH:
case H2CE_RED_FLASH:
SVH2_ParseEffectFlash( index );
break;
case H2CE_RIDER_DEATH:
SVH2_ParseEffectRiderDeath( index );
break;
case H2CE_TELEPORTERPUFFS:
SVH2_ParseEffectTeleporterPuffs( index );
break;
case H2CE_TELEPORTERBODY:
SVH2_ParseEffectTeleporterBody( index );
break;
case H2CE_BONESHARD:
case H2CE_BONESHRAPNEL:
SVH2_ParseEffectBoneShrapnel( index );
break;
case H2CE_GRAVITYWELL:
SVH2_ParseEffectGravityWell( index );
break;
case H2CE_CHUNK:
SVH2_ParseEffectChunk( index );
break;
default:
PR_RunError( "SVH2_SendEffect: bad type" );
}
}
static void SVHW_ParseEffectDetails( int index ) {
switch ( sv.h2_Effects[ index ].type ) {
case HWCE_RAIN:
SVH2_ParseEffectRain( index );
break;
case HWCE_FOUNTAIN:
SVH2_ParseEffectFountain( index );
break;
case HWCE_QUAKE:
SVH2_ParseEffectQuake( index );
break;
case HWCE_WHITE_SMOKE:
case HWCE_GREEN_SMOKE:
case HWCE_GREY_SMOKE:
case HWCE_RED_SMOKE:
case HWCE_SLOW_WHITE_SMOKE:
case HWCE_TELESMK1:
case HWCE_TELESMK2:
case HWCE_GHOST:
case HWCE_REDCLOUD:
case HWCE_RIPPLE:
SVH2_ParseEffectSmoke( index );
break;
case HWCE_ACID_MUZZFL:
case HWCE_FLAMESTREAM:
case HWCE_FLAMEWALL:
case HWCE_FLAMEWALL2:
case HWCE_ONFIRE:
SVH2_ParseEffectFlameWall( index );
break;
case HWCE_SM_WHITE_FLASH:
case HWCE_YELLOWRED_FLASH:
case HWCE_BLUESPARK:
case HWCE_YELLOWSPARK:
case HWCE_SM_CIRCLE_EXP:
case HWCE_BG_CIRCLE_EXP:
case HWCE_SM_EXPLOSION:
case HWCE_SM_EXPLOSION2:
case HWCE_BG_EXPLOSION:
case HWCE_FLOOR_EXPLOSION:
case HWCE_BLUE_EXPLOSION:
case HWCE_REDSPARK:
case HWCE_GREENSPARK:
case HWCE_ICEHIT:
case HWCE_MEDUSA_HIT:
case HWCE_MEZZO_REFLECT:
case HWCE_FLOOR_EXPLOSION2:
case HWCE_XBOW_EXPLOSION:
case HWCE_NEW_EXPLOSION:
case HWCE_MAGIC_MISSILE_EXPLOSION:
case HWCE_BONE_EXPLOSION:
case HWCE_BLDRN_EXPL:
case HWCE_ACID_HIT:
case HWCE_ACID_SPLAT:
case HWCE_ACID_EXPL:
case HWCE_LBALL_EXPL:
case HWCE_FIREWALL_SMALL:
case HWCE_FIREWALL_MEDIUM:
case HWCE_FIREWALL_LARGE:
case HWCE_FBOOM:
case HWCE_BOMB:
case HWCE_BRN_BOUNCE:
case HWCE_LSHOCK:
SVH2_ParseEffectSmokeFlash( index );
break;
case HWCE_WHITE_FLASH:
case HWCE_BLUE_FLASH:
case HWCE_SM_BLUE_FLASH:
case HWCE_HWSPLITFLASH:
case HWCE_RED_FLASH:
SVH2_ParseEffectFlash( index );
break;
case HWCE_RIDER_DEATH:
SVH2_ParseEffectRiderDeath( index );
break;
case HWCE_TELEPORTERPUFFS:
SVH2_ParseEffectTeleporterPuffs( index );
break;
case HWCE_TELEPORTERBODY:
SVH2_ParseEffectTeleporterBody( index );
break;
case HWCE_BONESHRAPNEL:
case HWCE_HWBONEBALL:
SVH2_ParseEffectBoneShrapnel( index );
break;
case HWCE_BONESHARD:
case HWCE_HWRAVENSTAFF:
case HWCE_HWMISSILESTAR:
case HWCE_HWEIDOLONSTAR:
case HWCE_HWRAVENPOWER:
SVHW_ParseEffectRavenStaff( index );
break;
case HWCE_DEATHBUBBLES:
SVHW_ParseEffectDeathBubbles( index );
break;
case HWCE_HWDRILLA:
SVHW_ParseEffectDrilla( index );
break;
case HWCE_TRIPMINESTILL:
SVHW_ParseEffectTripMineStill( index );
break;
case HWCE_TRIPMINE:
SVHW_ParseEffectTripMine( index );
break;
case HWCE_SCARABCHAIN:
SVHW_ParseEffectScarabChain( index );
break;
case HWCE_HWSHEEPINATOR:
SVHW_ParseEffectSheepinator( index );
break;
case HWCE_HWXBOWSHOOT:
SVHW_ParseEffectXBowShoot( index );
break;
default:
PR_RunError( "SV_SendEffect: bad type" );
}
}
void SVH2_ParseEffect( QMsg* sb ) {
byte effect = G_FLOAT( OFS_PARM0 );
int index;
for ( index = 0; index < MAX_EFFECTS_H2; index++ ) {
if ( !sv.h2_Effects[ index ].type ||
( sv.h2_Effects[ index ].expire_time && sv.h2_Effects[ index ].expire_time <= sv.qh_time ) ) {
break;
}
}
if ( index >= MAX_EFFECTS_H2 ) {
PR_RunError( "MAX_EFFECTS_H2 reached" );
return;
}
Com_Memset( &sv.h2_Effects[ index ], 0, sizeof ( struct h2EffectT ) );
sv.h2_Effects[ index ].type = effect;
G_FLOAT( OFS_RETURN ) = index;
if ( GGameType & GAME_HexenWorld ) {
SVHW_ParseEffectDetails( index );
SVHW_SendEffect( sb,index );
} else {
SVH2_ParseEffectDetails( index );
SVH2_SendEffect( sb,index );
}
}
static void SVHW_ParseMultiEffectRavenPower( QMsg* sb, byte effect ) {
// need to set aside 3 effect ids
sb->WriteByte( hwsvc_multieffect );
sb->WriteByte( effect );
vec3_t orig;
VectorCopy( G_VECTOR( OFS_PARM1 ), orig );
sb->WriteCoord( orig[ 0 ] );
sb->WriteCoord( orig[ 1 ] );
sb->WriteCoord( orig[ 2 ] );
vec3_t vel;
VectorCopy( G_VECTOR( OFS_PARM2 ), vel );
sb->WriteCoord( vel[ 0 ] );
sb->WriteCoord( vel[ 1 ] );
sb->WriteCoord( vel[ 2 ] );
for ( int count = 0; count < 3; count++ ) {
int index;
for ( index = 0; index < MAX_EFFECTS_H2; index++ ) {
if ( !sv.h2_Effects[ index ].type ||
( sv.h2_Effects[ index ].expire_time && sv.h2_Effects[ index ].expire_time <= sv.qh_time ) ) {
break;
}
}
if ( index >= MAX_EFFECTS_H2 ) {
PR_RunError( "MAX_EFFECTS_H2 reached" );
return;
}
sb->WriteByte( index );
sv.h2_Effects[ index ].type = HWCE_HWRAVENPOWER;
VectorCopy( orig, sv.h2_Effects[ index ].Missile.origin );
VectorCopy( vel, sv.h2_Effects[ index ].Missile.velocity );
sv.h2_Effects[ index ].expire_time = sv.qh_time + 10000;
MultiEffectIds[ count ] = index;
}
}
void SVHW_ParseMultiEffect( QMsg* sb ) {
MultiEffectIdCount = 0;
byte effect = G_FLOAT( OFS_PARM0 );
switch ( effect ) {
case HWCE_HWRAVENPOWER:
SVHW_ParseMultiEffectRavenPower( sb, effect );
break;
default:
PR_RunError( "SVHW_ParseMultiEffect: bad type" );
}
}
float SVHW_GetMultiEffectId() {
MultiEffectIdCount++;
return MultiEffectIds[ MultiEffectIdCount - 1 ];
}
void SVH2_SaveEffects( fileHandle_t FH ) {
int count = 0;
for ( int index = 0; index < MAX_EFFECTS_H2; index++ ) {
if ( sv.h2_Effects[ index ].type ) {
count++;
}
}
FS_Printf( FH,"Effects: %d\n", count );
for ( int index = 0; index < MAX_EFFECTS_H2; index++ ) {
if ( sv.h2_Effects[ index ].type ) {
FS_Printf( FH,"Effect: %d %d %f: ", index, sv.h2_Effects[ index ].type, sv.h2_Effects[ index ].expire_time * 0.001f );
switch ( sv.h2_Effects[ index ].type ) {
case H2CE_RAIN:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.min_org[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.min_org[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.min_org[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.max_org[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.max_org[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.max_org[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.e_size[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.e_size[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.e_size[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.dir[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.dir[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Rain.dir[ 2 ] );
FS_Printf( FH, "%d ", sv.h2_Effects[ index ].Rain.color );
FS_Printf( FH, "%d ", sv.h2_Effects[ index ].Rain.count );
FS_Printf( FH, "%f\n", sv.h2_Effects[ index ].Rain.wait );
break;
case H2CE_SNOW:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Snow.min_org[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Snow.min_org[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Snow.min_org[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Snow.max_org[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Snow.max_org[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Snow.max_org[ 2 ] );
FS_Printf( FH, "%d ", sv.h2_Effects[ index ].Snow.flags );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Snow.dir[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Snow.dir[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Snow.dir[ 2 ] );
FS_Printf( FH, "%d ", sv.h2_Effects[ index ].Snow.count );
break;
case H2CE_FOUNTAIN:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Fountain.pos[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Fountain.pos[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Fountain.pos[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Fountain.angle[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Fountain.angle[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Fountain.angle[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Fountain.movedir[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Fountain.movedir[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Fountain.movedir[ 2 ] );
FS_Printf( FH, "%d ", sv.h2_Effects[ index ].Fountain.color );
FS_Printf( FH, "%d\n", sv.h2_Effects[ index ].Fountain.cnt );
break;
case H2CE_QUAKE:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Quake.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Quake.origin[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Quake.origin[ 2 ] );
FS_Printf( FH, "%f\n", sv.h2_Effects[ index ].Quake.radius );
break;
case H2CE_WHITE_SMOKE:
case H2CE_GREEN_SMOKE:
case H2CE_GREY_SMOKE:
case H2CE_RED_SMOKE:
case H2CE_SLOW_WHITE_SMOKE:
case H2CE_TELESMK1:
case H2CE_TELESMK2:
case H2CE_GHOST:
case H2CE_REDCLOUD:
case H2CE_ACID_MUZZFL:
case H2CE_FLAMESTREAM:
case H2CE_FLAMEWALL:
case H2CE_FLAMEWALL2:
case H2CE_ONFIRE:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Smoke.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Smoke.origin[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Smoke.origin[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Smoke.velocity[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Smoke.velocity[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Smoke.velocity[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Smoke.framelength );
FS_Printf( FH, "%f\n", sv.h2_Effects[ index ].Smoke.frame );
break;
case H2CE_SM_WHITE_FLASH:
case H2CE_YELLOWRED_FLASH:
case H2CE_BLUESPARK:
case H2CE_YELLOWSPARK:
case H2CE_SM_CIRCLE_EXP:
case H2CE_BG_CIRCLE_EXP:
case H2CE_SM_EXPLOSION:
case H2CE_LG_EXPLOSION:
case H2CE_FLOOR_EXPLOSION:
case H2CE_FLOOR_EXPLOSION3:
case H2CE_BLUE_EXPLOSION:
case H2CE_REDSPARK:
case H2CE_GREENSPARK:
case H2CE_ICEHIT:
case H2CE_MEDUSA_HIT:
case H2CE_MEZZO_REFLECT:
case H2CE_FLOOR_EXPLOSION2:
case H2CE_XBOW_EXPLOSION:
case H2CE_NEW_EXPLOSION:
case H2CE_MAGIC_MISSILE_EXPLOSION:
case H2CE_BONE_EXPLOSION:
case H2CE_BLDRN_EXPL:
case H2CE_BRN_BOUNCE:
case H2CE_LSHOCK:
case H2CE_ACID_HIT:
case H2CE_ACID_SPLAT:
case H2CE_ACID_EXPL:
case H2CE_LBALL_EXPL:
case H2CE_FIREWALL_SMALL:
case H2CE_FIREWALL_MEDIUM:
case H2CE_FIREWALL_LARGE:
case H2CE_FBOOM:
case H2CE_BOMB:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Smoke.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Smoke.origin[ 1 ] );
FS_Printf( FH, "%f\n", sv.h2_Effects[ index ].Smoke.origin[ 2 ] );
break;
case H2CE_WHITE_FLASH:
case H2CE_BLUE_FLASH:
case H2CE_SM_BLUE_FLASH:
case H2CE_RED_FLASH:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Flash.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Flash.origin[ 1 ] );
FS_Printf( FH, "%f\n", sv.h2_Effects[ index ].Flash.origin[ 2 ] );
break;
case H2CE_RIDER_DEATH:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].RD.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].RD.origin[ 1 ] );
FS_Printf( FH, "%f\n", sv.h2_Effects[ index ].RD.origin[ 2 ] );
break;
case H2CE_GRAVITYWELL:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].GravityWell.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].GravityWell.origin[ 1 ] );
FS_Printf( FH, "%f", sv.h2_Effects[ index ].GravityWell.origin[ 2 ] );
FS_Printf( FH, "%d", sv.h2_Effects[ index ].GravityWell.color );
FS_Printf( FH, "%f\n", sv.h2_Effects[ index ].GravityWell.lifetime );
break;
case H2CE_TELEPORTERPUFFS:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Teleporter.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Teleporter.origin[ 1 ] );
FS_Printf( FH, "%f\n", sv.h2_Effects[ index ].Teleporter.origin[ 2 ] );
break;
case H2CE_TELEPORTERBODY:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Teleporter.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Teleporter.origin[ 1 ] );
FS_Printf( FH, "%f\n", sv.h2_Effects[ index ].Teleporter.origin[ 2 ] );
break;
case H2CE_BONESHARD:
case H2CE_BONESHRAPNEL:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.origin[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.origin[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.velocity[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.velocity[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.velocity[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.angle[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.angle[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.angle[ 2 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.avelocity[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.avelocity[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Missile.avelocity[ 2 ] );
break;
case H2CE_CHUNK:
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Chunk.origin[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Chunk.origin[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Chunk.origin[ 2 ] );
FS_Printf( FH, "%d ", sv.h2_Effects[ index ].Chunk.type );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Chunk.srcVel[ 0 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Chunk.srcVel[ 1 ] );
FS_Printf( FH, "%f ", sv.h2_Effects[ index ].Chunk.srcVel[ 2 ] );
FS_Printf( FH, "%d ", sv.h2_Effects[ index ].Chunk.numChunks );
break;
default:
PR_RunError( "SV_SaveEffect: bad type" );
break;
}
}
}
}
static int GetInt( const char*& Data ) {
// Skip whitespace.
while ( *Data && *Data <= ' ' ) {
Data++;
}
char Tmp[ 32 ];
int Len = 0;
while ( ( *Data >= '0' && *Data <= '9' ) || *Data == '-' ) {
if ( Len >= ( int )sizeof ( Tmp ) - 1 ) {
Tmp[ 31 ] = 0;
common->FatalError( "Number too long %s", Tmp );
}
Tmp[ Len ] = *Data++;
Len++;
}
Tmp[ Len ] = 0;
return String::Atoi( Tmp );
}
static float GetFloat( const char*& Data ) {
// Skip whitespace.
while ( *Data && *Data <= ' ' ) {
Data++;
}
char Tmp[ 32 ];
int Len = 0;
while ( ( *Data >= '0' && *Data <= '9' ) || *Data == '-' || *Data == '.' ) {
if ( Len >= ( int )sizeof ( Tmp ) - 1 ) {
Tmp[ 31 ] = 0;
common->FatalError( "Number too long %s", Tmp );
}
Tmp[ Len ] = *Data++;
Len++;
}
Tmp[ Len ] = 0;
return String::Atof( Tmp );
}
const char* SVH2_LoadEffects( const char* Data ) {
// Since the map is freshly loaded, clear out any effects as a result of
// the loading
SVH2_ClearEffects();
if ( String::NCmp( Data, "Effects: ", 9 ) ) {
common->Error( "Effects expected" );
}
Data += 9;
int Total = GetInt( Data );
for ( int count = 0; count < Total; count++ ) {
// Skip whitespace.
while ( *Data && *Data <= ' ' )
Data++;
if ( String::NCmp( Data, "Effect: ", 8 ) ) {
common->FatalError( "Effect expected" );
}
Data += 8;
int index = GetInt( Data );
sv.h2_Effects[ index ].type = GetInt( Data );
sv.h2_Effects[ index ].expire_time = GetFloat( Data ) * 1000;
if ( *Data != ':' ) {
common->FatalError( "Colon expected" );
}
Data++;
switch ( sv.h2_Effects[ index ].type ) {
case H2CE_RAIN:
sv.h2_Effects[ index ].Rain.min_org[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.min_org[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.min_org[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.max_org[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.max_org[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.max_org[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.e_size[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.e_size[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.e_size[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.dir[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.dir[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.dir[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Rain.color = GetInt( Data );
sv.h2_Effects[ index ].Rain.count = GetInt( Data );
sv.h2_Effects[ index ].Rain.wait = GetFloat( Data );
break;
case H2CE_SNOW:
sv.h2_Effects[ index ].Snow.min_org[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Snow.min_org[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Snow.min_org[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Snow.max_org[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Snow.max_org[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Snow.max_org[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Snow.flags = GetInt( Data );
sv.h2_Effects[ index ].Snow.dir[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Snow.dir[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Snow.dir[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Snow.count = GetInt( Data );
break;
case H2CE_FOUNTAIN:
sv.h2_Effects[ index ].Fountain.pos[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Fountain.pos[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Fountain.pos[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Fountain.angle[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Fountain.angle[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Fountain.angle[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Fountain.movedir[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Fountain.movedir[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Fountain.movedir[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Fountain.color = GetInt( Data );
sv.h2_Effects[ index ].Fountain.cnt = GetInt( Data );
break;
case H2CE_QUAKE:
sv.h2_Effects[ index ].Quake.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Quake.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Quake.origin[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Quake.radius = GetFloat( Data );
break;
case H2CE_WHITE_SMOKE:
case H2CE_GREEN_SMOKE:
case H2CE_GREY_SMOKE:
case H2CE_RED_SMOKE:
case H2CE_SLOW_WHITE_SMOKE:
case H2CE_TELESMK1:
case H2CE_TELESMK2:
case H2CE_GHOST:
case H2CE_REDCLOUD:
case H2CE_ACID_MUZZFL:
case H2CE_FLAMESTREAM:
case H2CE_FLAMEWALL:
case H2CE_FLAMEWALL2:
case H2CE_ONFIRE:
sv.h2_Effects[ index ].Smoke.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Smoke.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Smoke.origin[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Smoke.velocity[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Smoke.velocity[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Smoke.velocity[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Smoke.framelength = GetFloat( Data );
sv.h2_Effects[ index ].Smoke.frame = GetFloat( Data );
break;
case H2CE_SM_WHITE_FLASH:
case H2CE_YELLOWRED_FLASH:
case H2CE_BLUESPARK:
case H2CE_YELLOWSPARK:
case H2CE_SM_CIRCLE_EXP:
case H2CE_BG_CIRCLE_EXP:
case H2CE_SM_EXPLOSION:
case H2CE_LG_EXPLOSION:
case H2CE_FLOOR_EXPLOSION:
case H2CE_FLOOR_EXPLOSION3:
case H2CE_BLUE_EXPLOSION:
case H2CE_REDSPARK:
case H2CE_GREENSPARK:
case H2CE_ICEHIT:
case H2CE_MEDUSA_HIT:
case H2CE_MEZZO_REFLECT:
case H2CE_FLOOR_EXPLOSION2:
case H2CE_XBOW_EXPLOSION:
case H2CE_NEW_EXPLOSION:
case H2CE_MAGIC_MISSILE_EXPLOSION:
case H2CE_BONE_EXPLOSION:
case H2CE_BLDRN_EXPL:
case H2CE_BRN_BOUNCE:
case H2CE_LSHOCK:
case H2CE_ACID_HIT:
case H2CE_ACID_SPLAT:
case H2CE_ACID_EXPL:
case H2CE_LBALL_EXPL:
case H2CE_FBOOM:
case H2CE_FIREWALL_SMALL:
case H2CE_FIREWALL_MEDIUM:
case H2CE_FIREWALL_LARGE:
case H2CE_BOMB:
sv.h2_Effects[ index ].Smoke.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Smoke.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Smoke.origin[ 2 ] = GetFloat( Data );
break;
case H2CE_WHITE_FLASH:
case H2CE_BLUE_FLASH:
case H2CE_SM_BLUE_FLASH:
case H2CE_RED_FLASH:
sv.h2_Effects[ index ].Flash.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Flash.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Flash.origin[ 2 ] = GetFloat( Data );
break;
case H2CE_RIDER_DEATH:
sv.h2_Effects[ index ].RD.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].RD.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].RD.origin[ 2 ] = GetFloat( Data );
break;
case H2CE_GRAVITYWELL:
sv.h2_Effects[ index ].GravityWell.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].GravityWell.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].GravityWell.origin[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].GravityWell.color = GetInt( Data );
sv.h2_Effects[ index ].GravityWell.lifetime = GetFloat( Data );
break;
case H2CE_TELEPORTERPUFFS:
sv.h2_Effects[ index ].Teleporter.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Teleporter.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Teleporter.origin[ 2 ] = GetFloat( Data );
break;
case H2CE_TELEPORTERBODY:
sv.h2_Effects[ index ].Teleporter.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Teleporter.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Teleporter.origin[ 2 ] = GetFloat( Data );
break;
case H2CE_BONESHARD:
case H2CE_BONESHRAPNEL:
sv.h2_Effects[ index ].Missile.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.origin[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.velocity[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.velocity[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.velocity[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.angle[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.angle[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.angle[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.avelocity[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.avelocity[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Missile.avelocity[ 2 ] = GetFloat( Data );
break;
case H2CE_CHUNK:
sv.h2_Effects[ index ].Chunk.origin[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Chunk.origin[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Chunk.origin[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Chunk.type = GetInt( Data );
sv.h2_Effects[ index ].Chunk.srcVel[ 0 ] = GetFloat( Data );
sv.h2_Effects[ index ].Chunk.srcVel[ 1 ] = GetFloat( Data );
sv.h2_Effects[ index ].Chunk.srcVel[ 2 ] = GetFloat( Data );
sv.h2_Effects[ index ].Chunk.numChunks = GetInt( Data );
break;
default:
PR_RunError( "SV_SaveEffect: bad type" );
break;
}
}
return Data;
}
|
#include "stdafx.h"
#include "UXMLParser.h"
#include "BRenderer.h"
#include "BRenderingBatch.h"
#include "CWindowsViewport.h"
#include "CWindowsApplication.h"
#include "CDirectXDriver.h"
#include "CWaveIODriver.h"
#include "BViewport.h"
#include "RSKNImporter.h"
#include "UWorld.h"
BXMLParser::BXMLParser() {
}
BXMLParser::~BXMLParser() {
}
void BXMLParser::StartElement(void *UserData, const char *Name, const char **Atts) {
BXMLParser* Parser = (BXMLParser*) UserData;
TXMLElement Element;
Element.ElementName = Name;
unsigned int Idx = 0;
const char *Att = *Atts;
while (Atts[Idx]) {
TXMLAttribute Attribute;
Attribute.AttributeName = Atts[Idx];
Idx++;
if (Atts[Idx]) {
Attribute.AttributeValue = Atts[Idx];
Idx++;
}
Element.Attributes.AddItem(Attribute);
}
Element.Parent = Parser->ParentElement;
Parser->ParentElement->ChildElements.AddItem(Element);
Parser->ParentElement = &Parser->ParentElement->ChildElements.EndItem();
}
void BXMLParser::EndElement(void *UserData, const char *Name) {
BXMLParser* Parser = (BXMLParser*) UserData;
Parser->ParentElement = Parser->ParentElement->Parent;
}
bool BXMLParser::ReadXMLFile(char* FileName) {
FILE* FilePointer = NULL;
fopen_s(&FilePointer, FileName, "r");
if (FilePointer) {
Parser = XML_ParserCreate(NULL);
ParentElement = &Root;
char buf[BUFSIZ];
int Done;
XML_SetUserData(Parser, this);
XML_SetElementHandler(Parser, BXMLParser::StartElement,
BXMLParser::EndElement);
do {
int len = (int) fread(buf, 1, sizeof(buf), FilePointer);
Done = len < sizeof(buf);
if (!XML_Parse(Parser, buf, len, Done)) {
printf("%s at line %d\n",
XML_ErrorString(XML_GetErrorCode(Parser)),
XML_GetCurrentLineNumber(Parser));
return false;
}
} while (!Done);
fclose(FilePointer);
XML_ParserFree(Parser);
return true;
}
return false;
}
bool BXMLParser::GetValue(char* Path, TString& Ret) {
return Root.GetValue(Path, Ret);
}
/////////////////////////////////// Application Config Parser ///////////////////////////////////
CXMLApplicationParser::CXMLApplicationParser() {
}
CXMLApplicationParser::~CXMLApplicationParser() {
}
void CXMLApplicationParser::Parse() {
TXMLElement Application;
if (Root.GetChildElement("Application", Application)) {
AApplication *app = 0;
TWindowInfo Info;
if (Application.HasAttribute("Platform", "Windows_x86")) {
TString Value;
if (Application.GetValue("Resolution.Width", Value)) {
Info.m_wWidth = Value.ToInt();
}
if (Application.GetValue("Resolution.Height", Value)) {
Info.m_wHeight = Value.ToInt();
}
if (Application.GetValue("Class", Value)) {
app = ConstructClass<AApplication>(Value);
}
}
TXMLElement Renderer;
if (Application.GetChildElement("Renderer", Renderer)) {
TRendererInfo RInfo;
TXMLElement Driver;
if (Renderer.GetChildElement("Driver", Driver)) {
if (Driver.HasAttribute("Platform", "DirectX")) {
GDriver = new CDirectXDriver();
GSoundDriver = new CWaveIODriver();
}
}
}
app->CreateApplicationWindow(Info);
TXMLElement World;
if (Application.GetChildElement("World", World)) {
TString Value;
if (World.GetValue("Class", Value)) {
UWorld* pWorld = ConstructClass<UWorld>(Value);
if (World.GetValue("Template", Value)) {
UWorldTemplate* WT = ConstructClass<UWorldTemplate>(Value);
WT->Create(pWorld);
}
pWorld->m_pRenderer = app->m_pRenderer;
pWorld->BatchManager->m_Viewports = &pWorld->Viewports;
app->m_pRenderer->BatchManager.AddItem(pWorld->BatchManager);
app->Worlds.AddItem(pWorld);
pWorld->SaveObject(TString("..\\..\\Resources\\FirstWorld.exmap"));
} else {
return;
}
}
app->Do();
app->DestroyApp();
delete app;
}
}
|
//mainึ
#include "DevAreaFlamework_ver.2.h"
int main(int argc, char *argv[]){
DevAreaFlamework daf;
daf.LoadParamater(argv[1]);
//daf.LoadParamater("step1.ini");
daf.Run();
return 0;
}
|
#include "ThreadPool.h"
ThreadPool::ThreadPool(int min, int max) : finished_(false), min_(min), max_(max)
{
for (int i = 0; i < min_; i++) {
AddThread();
}
manageThread_ = std::thread([this]() {
while (!finished_) {
if ((taskQue_.GetSize() > 2 * threads_.size()) && (threads_.size() < max_)) {
AddThread();
}
else {
int cnt = 0;
for (auto& t : threads_) {
if (t.second->GetState() == WorkThread::STATE_WAIT) {
++cnt;
}
}
if ((cnt > 2 * taskQue_.GetSize()) && (threads_.size() > min_)) {
DelThread();
}
}
std::this_thread::sleep_for(std::chrono::microseconds(100));
}
});
}
ThreadPool::~ThreadPool()
{
if (manageThread_.joinable()) {
manageThread_.join();
}
}
void ThreadPool::AddTask(TaskPtr task)
{
printf("-- add task: [%s]\n", task->GetName().c_str());
taskQue_.AddTask(task);
}
void ThreadPool::Finish()
{
finished_ = true;
for (auto& t : threads_) {
t.second->Finish();
}
}
void ThreadPool::AddThread()
{
printf("-- add thread\n");
auto tdPtr = std::make_shared<WorkThread>(taskQue_);
threads_[tdPtr->GetId()] = tdPtr;
}
void ThreadPool::DelThread()
{
printf("-- del thread\n");
std::thread::id tid;
for (auto& t : threads_) {
if (t.second->GetState() == WorkThread::STATE_WAIT) {
t.second->Finish();
tid = t.first;
break;
}
}
threads_.erase(tid);
}
|
#include "scene.hpp"
Scene::Scene() :
cloud(MAP_WIDTH,CLOUD_COUNT)
{
//Background Initialize
textureBackground.setRepeated(true);
textureBackground.loadFromFile("images/background.png");
spriteBackground.setTexture(textureBackground);
//spriteBackground.setOrigin(textureBackground.getSize().x/2.0f,textureBackground.getSize().y/2.0f);
spriteBackground.setOrigin(0,0);
spriteBackground.setPosition(-(MAP_WIDTH/2.0f),0.f);
spriteBackground.setTextureRect(sf::IntRect(sf::Vector2i(0,0),sf::Vector2i(MAP_WIDTH,MAP_HEIGHT)));
textureBarricade.loadFromFile("images/brick.png");
textureBarricade.setRepeated(true);
barricadeLeft.setPosition(0.0f, 600.0f);
//barricadeLeft.setColor(sf::Color::Red);
barricadeLeft.setTexture(textureBarricade);
//barricadeLeft.setScale(0.2f, 0.2f);
barricadeLeft.scale(0.2f, 0.2f);
barricadeLeft.setTextureRect(sf::IntRect(sf::Vector2i(0,0), sf::Vector2i(90,1000)));
barricadeLeft.canMove = false;
barricadeLeft.weight = 1000.0f;
barricadeLeft.penetration = 0.0f;
barricadeRight.setPosition(1280.0f, 600.0f);
//barricadeRight.setColor(sf::Color::Red);
barricadeRight.setTexture(textureBarricade);
barricadeRight.setScale(0.2f, 0.2f);
barricadeRight.setTextureRect(sf::IntRect(sf::Vector2i(0,0), sf::Vector2i(90,1000)));
barricadeRight.canMove = false;
barricadeRight.weight = 1000.0f;
barricadeRight.penetration = 0.0f;
//Player Initialize
playerTexture.loadFromFile("images/tux_from_linux.png");
player = new Player(&playerTexture,sf::Vector2u(3,9),PLAYER_ANIMATION_TIME,PLAYER_SPEED);
//Fill Obj Vector
objList.push_back(player->getSprite());
objList.push_back(&barricadeLeft);
objList.push_back(&barricadeRight);
}
void Scene::draw(sf::RenderWindow* window){
window->draw(spriteBackground);
cloud.draw(window);
player->draw(window);
window->draw(barricadeLeft);
window->draw(barricadeRight);
}
void Scene::update(float deltaTime){
cloud.update(deltaTime);
player->update(deltaTime);
collider.checkCollision(&objList);
}
sf::Vector2f Scene::getPlayerPosition(){
return player->getPosition();
}
int Scene::getPlayerScore(){
return player->score;
}
|
using namespace std;
extern datatable bufferuser;
extern int u;
int load(){
mkdir("D:\\My\\icode\\database\\database\\user");
if(bufferuser.load("user","user") == 0){
datatable user("user");
user.addrow("id","char","10");
user.addrow("password","char","10");
user.addrow("create","char","10");
user.addrow("drop","char","10");
user.addrow("select","char","10");
user.addrow("delete","char","10");
user.addrow("insert","char","10");
user.addrow("update","char","10");
user.addrow("help","char","10");
user.addrow("use","char","10");
user.addrow("delete","char","10");
user.addrow("add","char","10");
string tmp[12] = {"root","root","1","1","1","1","1","1","1","1","1","1"};
user.addline(tmp,12);
user.save("user");
}
while(1){
string name,p;
cout << "Log in" <<endl;
cout << "username:";
cin >> name;
if(*(bufferuser.selectline("id","=",name)) == 1){
int k = *(bufferuser.selectline("id","=",name) + 1);
cout << "password:" ;
cin >> p;
if(bufferuser.compare("password",k,p) == 1){
u = k;
cout << "hello " << name << "!"<<endl;
return 1;
}
else{
cout << "password error!" << endl;
}
}
else{
cout <<"user doesn't exist!" <<endl;
}
}
}
|
/*
* Copyright (c) 2012 Joey Yore
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include "../events/timeout.h"
using namespace std;
bool go = true;
void funcA() {
cout << "funcA" << endl;
}
void funcB() {
cout << "funcB" << endl;
register_timeout(funcB,0.1);
}
void funcC() {
cout << "funcC" << endl;
go = false;
}
int main() {
register_timeout(funcA,0.5);
register_timeout(funcB,0.1);
register_timeout(funcC,1.0);
while(go) {;}
return 0;
}
|
#include <iostream>
using namespace std;
int task1();
int task2();
int task3();
int main()
{
setlocale(LC_ALL, "Russian");
task1();
return 0;
}
// Дано трехзначное число. Вывести вначале его последнюю цифру (единицы), а затем — его среднюю цифру (десятки).
int task1()
{
int number = 0;
cin >> number;
cout << "последняя цифра числа: " << number % 10 << "\nсредняя цифра числа: " << number / 10 % 10;
return 0;
}
// Даны две переменные целого типа: A и B. Если их значения не равны, то присвоить каждой переменной большее из этих значений, а если равны, то присвоить переменным нулевые значения.
// Вывести новые значения переменных A и B.
int task2()
{
int A = 0;
int B = 0;
cin >> A >> B;
if (A == B)
{
A = 0;
B = 0;
}
if (A > B)
{
B = A;
}
else if (A < B)
{
A = B;
}
cout << "A = " << A << "; B = " << B << endl;
return 0;
}
// Даны два целых числа А и В(А < B). Найти сумму всех целых чисел от А до В включительно.
int task3()
{
int A = 0;
int B = 0;
cin >> A >> B;
int sum = 0;
for (int i = A; A <= B; ++i)
{
sum = sum + i;
}
return 0;
}
|
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef set<int> si;
typedef map<string, int> msi;
typedef long long ll;
typedef vector<bool> vb;
typedef vector<vb> vvb;
const ll INF = 1e18L + 1;
void dfs(vector<string> &newMap, vvb &visited, int x, int y)
{
if (visited[x][y])
return;
if (newMap[x][y] == 'o')
visited[x][y] = true;
else
return;
if (x)
dfs(newMap, visited, x - 1, y);
if (y)
dfs(newMap, visited, x, y - 1);
if (x + 1 < 10)
dfs(newMap, visited, x + 1, y);
if (y + 1 < 10)
dfs(newMap, visited, x, y + 1);
}
int main()
{
vector<string> MAP(10);
rep(i, 10) cin >> MAP[i];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
vector<string> newMap = MAP;
vvb visited(10, vector<bool>(10, false));
newMap[i][j] = 'o';
dfs(newMap, visited, i, j);
bool ok = true;
for (int x = 0; x < 10; x++)
for (int y = 0; y < 10; y++)
if (newMap[x][y] == 'o' && !visited[x][y])
{
ok = false;
}
if (ok)
{
puts("YES");
return 0;
}
}
}
puts("NO");
return 0;
}
|
// p293
// case1.
// case2.
// case3.
// case4. 뛰어넘기만
// n+mCn 에서.. 앞에 -일 경우 n+m-1Cn-1 / o일경우 n+m-1Cn..
// 재귀호출할 때마다 1씩 줄어드므로 O(n+m)
#include <iostream>
#include <string>
using namespace std;
const int M = 1000000000+100;
int bino[201][201];
int n, m;
int skip;
// nCm
void calcBino(){
memset(bino, 0, sizeof(bino));
for(int i=0; i<=200; i++){
bino[i][0] = bino[i][i] = 1;
// iCj = i-1Cj-1 + j-1Cj
for(int j=1; j<i; j++) bino[i][j] = min(M, bino[i-1][j-1] + bino[i-1][j]);
}
}
string kth(int n, int m, int skip){
if(n==0) return string(m, 'o');
if(skip<bino[n+m-1][n-1]) return "-"+kth(n-1, m, skip);
else return "o" + kth(n, m-1, skip-bino[n+m-1][n-1]);
}
int main(){
calcBino();
cin>>n>>m;
cin>>skip;
string tmp = "";
generate(n, m, tmp);
}
|
/*
Given a NxN matrix with 0s and 1s. now whenever you encounter a 0 make the
corresponding row and column elements 0.
Flip 1 to 0 and 0 remains as they are.
*/
#include<iostream>
using namespace std;
void removezero(int arr[][5],int n)
{
int rowzero=0;
int columnzero=0;
for(int i=0;i<n;i++)
if(arr[0][i]==0)
rowzero=1;
for(int i=0;i<n;i++)
if(arr[i][0]==0)
columnzero=1;
for(int i=1;i<n;i++)
for(int j=1;j<n;j++)
{
if(arr[i][j]==0)
{
arr[0][j]=0;
arr[i][0]=0;
}
}
// cout<<rowzero<<" "<< columnzero<<endl;
for(int i=0;i<n;i++)
{
if(arr[0][i]==0)
{
for(int j=1;j<n;j++)
{
arr[j][i]=0;
}
}
}
//cout<<rowzero<<endl;
if(rowzero)
for(int i=0;i<n;i++)
arr[0][i]=0;
for(int i=0;i<n;i++)
{
if(arr[i][0]==0)
{
for(int j=1;j<n;j++)
{
arr[i][j]=0;
}
}
}
if(columnzero)
for(int i=0;i<n;i++)
arr[i][0]=0;
}
int main()
{
int arr[][5]={
1,1,1,1,1,
1,1,1,0,0,
1,1,1,1,1,
1,1,0,1,1,
1,1,1,1,1
};
removezero(arr,5);
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
cout<<arr[i][j]<<" ";
cout<<endl;
}
system("pause");
return 0;
}
|
// @copyright 2017 - 2018 Shaun Ostoic
// Distributed under the MIT License.
// (See accompanying file LICENSE.md or copy at https://opensource.org/licenses/MIT)
#pragma once
#include <distant/types.hpp>
#include <distant/utility/meta/array.hpp>
#include <boost/assert.hpp>
namespace distant
{
template <class Scalar, class>
constexpr byte get_byte_n(const index_t index, const Scalar scalar) noexcept
{
BOOST_ASSERT_MSG(index < sizeof(Scalar), "[distant::get_byte] Byte index out of range");
return (scalar >> (8 * index)) & 0xff;
}
template <std::size_t N>
constexpr byte get_byte(const word bytes) noexcept
{
static_assert(N < sizeof(word), "[distant::get_byte<word>] Byte index out of range");
return get_byte_n(N, bytes);
}
template <std::size_t N>
constexpr byte get_byte(const dword bytes) noexcept
{
static_assert(N < sizeof(dword), "[distant::get_byte<dword>] Byte index out of range");
return get_byte_n(N, bytes);
}
template <std::size_t N>
constexpr byte get_byte(const qword bytes) noexcept
{
static_assert(N < sizeof(qword), "[distant::get_byte<qword>] Byte index out of range");
return get_byte_n(N, bytes);
}
namespace detail
{
template <class Return, std::size_t S>
constexpr auto make_impl(const std::array<byte, S>& array) noexcept
{
namespace meta = utility::meta;
Return result = 0;
index_t i = 0;
meta::tuple_for_each(array, [&result, &i](const byte b)
{
result |= (b << 8 * i++);
});
//for (std::size_t i = 1; i < S; ++i)
return result;
}
template <typename T>
struct reverse_bytes_generator
{
const T& data;
constexpr explicit reverse_bytes_generator(const T& d) : data(d) {}
constexpr auto operator()(const index_t index) const noexcept
{
return get_byte(sizeof(T) - 1 - index, data);
}
};
}
template <class Scalar>
constexpr Scalar reverse_bytes(const Scalar scalar) noexcept
{
namespace meta = utility::meta;
const auto generator = detail::reverse_bytes_generator<Scalar>(scalar);
return detail::make_impl<Scalar>(meta::generate_array<sizeof(Scalar)>(generator));
}
namespace detail
{
template <class T>
struct byte_array_from_impl
{
constexpr auto operator()(const T& data) const noexcept
{
using under_t = std::conditional_t<std::is_enum<T>::value,
std::underlying_type_t<T>,
T
>;
return utility::meta::generate_array<sizeof(data)>([&data](const index_t i)
{
return get_byte_n(i, static_cast<under_t>(data));
});
}
};
template <std::size_t N>
struct byte_array_from_impl<char[N]>
{
constexpr auto operator()(const char data[N]) const noexcept
{
return utility::meta::generate_array<N>([&data](const index_t i)
{
return data[i];
});
}
};
}
template <class T>
constexpr auto byte_array_from(const T& data) noexcept
{
return detail::byte_array_from_impl<T>{}(data);
}
template <class... Bytes, typename>
constexpr word make_word(Bytes&&... bytes) noexcept
{
static_assert(
std::is_convertible<std::common_type_t<Bytes...>, byte>::value,
"[distant::make_word] Type of bytes must be convertible to distant::byte"
);
using result_t = word;
return detail::make_impl<word>(
utility::meta::make_array(static_cast<byte>(std::forward<Bytes>(bytes))...)
);
}
template <class... Bytes, typename>
constexpr dword make_dword(Bytes&&... bytes) noexcept
{
static_assert(
std::is_convertible<std::common_type_t<Bytes...>, byte>::value,
"[distant::make_dword] Type of bytes must be convertible to distant::byte"
);
using result_t = dword;
return detail::make_impl<result_t>(
utility::meta::make_array(static_cast<byte>(std::forward<Bytes>(bytes))...)
);
}
template <class... Bytes, class>
constexpr qword make_qword(Bytes&&... bytes) noexcept
{
static_assert(
std::is_convertible<std::common_type_t<Bytes...>, byte>::value,
"[distant::make_qword] Type of bytes must be convertible to distant::byte"
);
using result_t = qword;
return detail::make_impl<result_t>(
utility::meta::make_array(static_cast<byte>(std::forward<Bytes>(bytes))...)
);
}
template <class Integer, class... Bytes>
constexpr Integer make_integer(Bytes&&... bytes) noexcept
{
static_assert(
std::is_convertible<std::common_type_t<Bytes...>, Integer>::value,
"[distant::make_qword] Type of bytes must be convertible to distant::byte"
);
using result_t = Integer;
return detail::make_impl<result_t>(
utility::meta::make_array(static_cast<byte>(std::forward<Bytes>(bytes))...)
);
}
}
|
/***************************************************************************
Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD
FileName: RTPSessionInterface.h
Description: Provides an API interface for objects to access the attributes
related to a RTPSession, also implements the RTP Session Dictionary.
Comment: copy from Darwin Streaming Server 5.5.5
Author: taoyunxing@dadimedia.com
Version: v1.0.0.1
CreateDate: 2010-08-16
LastUpdate: 2010-08-16
****************************************************************************/
#ifndef _RTPSESSIONINTERFACE_H_
#define _RTPSESSIONINTERFACE_H_
#include "QTSSDictionary.h"
#include "QTSServerInterface.h"
#include "TimeoutTask.h"
#include "Task.h"
#include "RTCPSRPacket.h"
#include "RTSPSessionInterface.h"
#include "RTPBandwidthTracker.h"
#include "RTPOverbufferWindow.h"
#include "OSMutex.h"
#include "atomic.h"
class RTSPRequestInterface;
class RTPSessionInterface : public QTSSDictionary, public Task
{
public:
// Initializes dictionary resources
static void Initialize();
// CONSTRUCTOR / DESTRUCTOR
RTPSessionInterface();
virtual ~RTPSessionInterface()
{
if (GetQualityLevel() != 0)
QTSServerInterface::GetServer()->IncrementNumThinned(-1);
if (fRTSPSession != NULL)
fRTSPSession->DecrementObjectHolderCount();
delete [] fSRBuffer.Ptr;
delete [] fAuthNonce.Ptr;
delete [] fAuthOpaque.Ptr;
}
virtual void SetValueComplete(UInt32 inAttrIndex, QTSSDictionaryMap* inMap,
UInt32 inValueIndex, void* inNewValue, UInt32 inNewValueLen);
//Timeouts. This allows clients to refresh the timeout on this session
void RefreshTimeout() { fTimeoutTask.RefreshTimeout(); }
void RefreshRTSPTimeout() { if (fRTSPSession != NULL) fRTSPSession->RefreshTimeout(); }
void RefreshTimeouts() { RefreshTimeout(); RefreshRTSPTimeout();}
// ACCESSORS
Bool16 IsFirstPlay() { return fIsFirstPlay; }
SInt64 GetFirstPlayTime() { return fFirstPlayTime; }
//Time (msec) most recent play was issued
SInt64 GetPlayTime() { return fPlayTime; }
SInt64 GetNTPPlayTime() { return fNTPPlayTime; }
/* used in RTPStatsUpdaterTask::GetNewestSession() */
SInt64 GetSessionCreateTime() { return fSessionCreateTime; }
//Time (msec) most recent play, adjusted for start time of the movie
//ex: PlayTime() == 20,000. Client said start 10 sec into the movie,
//so AdjustedPlayTime() == 10,000
QTSS_PlayFlags GetPlayFlags() { return fPlayFlags; } /* need by RTPSession::run() */
OSMutex* GetSessionMutex() { return &fSessionMutex; }
UInt32 GetPacketsSent() { return fPacketsSent; }
UInt32 GetBytesSent() { return fBytesSent; }
/* 得到Hash Table表元(也就是RTPSession) */
OSRef* GetRef() { return &fRTPMapElem; }
/* 得到RTSP SessionInterface */
RTSPSessionInterface* GetRTSPSession() { return fRTSPSession; }
UInt32 GetMovieAvgBitrate(){ return fMovieAverageBitRate; }/* needed by RTPSession::Play() */
QTSS_CliSesTeardownReason GetTeardownReason() { return fTeardownReason; }
QTSS_RTPSessionState GetSessionState() { return fState; }
void SetUniqueID(UInt32 theID) {fUniqueID = theID;}
UInt32 GetUniqueID() { return fUniqueID; }
RTPBandwidthTracker* GetBandwidthTracker() { return &fTracker; } /* needed by RTPSession::run() */
RTPOverbufferWindow* GetOverbufferWindow() { return &fOverbufferWindow; }
UInt32 GetFramesSkipped() { return fFramesSkipped; }
// MEMORY FOR RTCP PACKETS
// Class for easily building a standard RTCP SR
RTCPSRPacket* GetSRPacket() { return &fRTCPSRPacket; }//注意它的设置在RTPStream::SendRTCPSR()中
// Memory if you want to build your own
char* GetSRBuffer(UInt32 inSRLen);
// STATISTICS UPDATING
//The session tracks the total number of bytes sent during the session.
//Streams can update that value by calling this function
/* 更新该RTPSession发送的字节总数 */
void UpdateBytesSent(UInt32 bytesSent) { fBytesSent += bytesSent; }
//The session tracks the total number of packets sent during the session.
//Streams can update that value by calling this function
/* 更新该RTPSession发送的RTP Packet总数 */
void UpdatePacketsSent(UInt32 packetsSent) { fPacketsSent += packetsSent; }
void UpdateCurrentBitRate(const SInt64& curTime)
{ if (curTime > (fLastBitRateUpdateTime + 10000)) this->UpdateBitRateInternal(curTime); }
/* 根据入参设置all track是否interleaved? */
void SetAllTracksInterleaved(Bool16 newValue) { fAllTracksInterleaved = newValue; }
// RTSP RESPONSE
// This function appends a session header to the SETUP response, and
// checks to see if it is a 304 Not Modified. If it is, it sends the entire
// response and returns an error
QTSS_Error DoSessionSetupResponse(RTSPRequestInterface* inRequest);
// RTSP SESSION
// This object has a current RTSP session. This may change over the
// life of the RTSPSession, so update it. It keeps an RTSP session in
// case interleaved data or commands need to be sent back to the client.
/* 更新RTSPSession */
void UpdateRTSPSession(RTSPSessionInterface* inNewRTSPSession);
// let's RTSP Session pass along it's query string
/* 设置查询字符串 */
void SetQueryString( StrPtrLen* queryString );
// SETTERS and ACCESSORS for auth information
// Authentication information that needs to be kept around
// for the duration of the session
QTSS_AuthScheme GetAuthScheme() { return fAuthScheme; }
StrPtrLen* GetAuthNonce() { return &fAuthNonce; }
UInt32 GetAuthQop() { return fAuthQop; }
UInt32 GetAuthNonceCount() { return fAuthNonceCount; }
StrPtrLen* GetAuthOpaque() { return &fAuthOpaque; }
void SetAuthScheme(QTSS_AuthScheme scheme) { fAuthScheme = scheme; }
// Use this if the auth scheme or the qop has to be changed from the defaults
// of scheme = Digest, and qop = auth
void SetChallengeParams(QTSS_AuthScheme scheme, UInt32 qop, Bool16 newNonce, Bool16 createOpaque);
// Use this otherwise...if newNonce == true, it will create a new nonce
// and reset nonce count. If newNonce == false but nonce was never created earlier
// a nonce will be created. If newNonce == false, and there is an existing nonce,
// the nounce count will be incremented.
void UpdateDigestAuthChallengeParams(Bool16 newNonce, Bool16 createOpaque, UInt32 qop);
Float32* GetPacketLossPercent() { UInt32 outLen;return (Float32*) this->PacketLossPercent(this, &outLen);}
SInt32 GetQualityLevel() { return fSessionQualityLevel; }
SInt32* GetQualityLevelPtr() { return &fSessionQualityLevel; }
void SetQualityLevel(SInt32 level) { if (fSessionQualityLevel == 0 && level != 0)
QTSServerInterface::GetServer()->IncrementNumThinned(1);
else if (fSessionQualityLevel != 0 && level == 0)
QTSServerInterface::GetServer()->IncrementNumThinned(-1);
fSessionQualityLevel = level;
}
//the server's thinning algorithm(quality level),参见RTPStream::UpdateQualityLevel()
SInt64 fLastQualityCheckTime; //上次quality level检查时间
SInt64 fLastQualityCheckMediaTime; //上次发送的RTP设定的发送绝对时间戳
Bool16 fStartedThinning; //是否开始瘦化?
// Used by RTPStream to increment the RTCP packet and byte counts.
/* 用于RTCP包 */
void IncrTotalRTCPPacketsRecv() { fTotalRTCPPacketsRecv++; }
UInt32 GetTotalRTCPPacketsRecv() { return fTotalRTCPPacketsRecv; }
void IncrTotalRTCPBytesRecv(UInt16 cnt) { fTotalRTCPBytesRecv += cnt; }
UInt32 GetTotalRTCPBytesRecv() { return fTotalRTCPBytesRecv; }
protected:
// These variables are setup by the derived RTPSession object when Play and Pause get called
//Some stream related information that is shared amongst all streams,参见RTPSession::Play()
Bool16 fIsFirstPlay; /* 是第一次播放吗? */
SInt64 fFirstPlayTime;//in milliseconds,第一次播放的时间
SInt64 fPlayTime;//RTP包的当前播放时间戳,参见RTPStream::UpdateQualityLevel()
SInt64 fAdjustedPlayTime;/* 获取当前播放时间戳和RTSP Request Header Range中的fStartTime的差值,这个量非常重要 */
SInt64 fNTPPlayTime;/* 为方便SR包,将fPlayTime存成NTP格式的值 */
Bool16 fAllTracksInterleaved;/* all stream 通过RTSP channel交替发送吗? */
/* very important! this is actual absolute timestamp of send the next RTP packets */
SInt64 fNextSendPacketsTime;/* need by RTPSession::run()/RTPSession::Play() */
/* RTPSession的quality level */
SInt32 fSessionQualityLevel;
//keeps track of whether we are playing or not
/* Play or Pause,need by RTPSession::run() */
QTSS_RTPSessionState fState;
// have the server generate RTCP Sender Reports or have the server append the server info APP packet to your RTCP Sender Reports
/* see QTSS.h */
QTSS_PlayFlags fPlayFlags;
//Session mutex. This mutex should be grabbed before invoking the module
//responsible for managing this session. This allows the module to be
//non-preemptive-safe with respect to a session
OSMutex fSessionMutex; /* 会话互斥锁,used in RTPSession::run() */
//Stores the RTPsession ID
/* RTPSession存为RTPSessionMap的HashTable表元 */
OSRef fRTPMapElem;
/* RTSPSession的ID值,是个唯一的随机数,比如"58147963412401" */
char fRTSPSessionIDBuf[QTSS_MAX_SESSION_ID_LENGTH + 4];
/* 以当前比特率送出的字节数 */
UInt32 fLastBitRateBytes;
/* 当前比特率的更新时间 */
SInt64 fLastBitRateUpdateTime;
/* movie的当前比特率,它是如何计算的? 参见RTPSessionInterface::UpdateBitRateInternal() */
UInt32 fMovieCurrentBitRate;
// In order to facilitate sending data over the RTSP channel from
// an RTP session, we store a pointer to the RTSP session used in
// the last RTSP request.
/* needed by RTPSession::Play(),与RTSP会话相关的纽带 */
/* 为了便于用RTSP channel发送Interleaved数据,在上一个RTSPRequest中存放一个RTSPSession的指针,这个量非常重要! */
RTSPSessionInterface* fRTSPSession;
private:
// Utility function for calculating current bit rate
void UpdateBitRateInternal(const SInt64& curTime);
/* 下面这三个函数用于setup ClientSessionDictionary Attr */
static void* CurrentBitRate(QTSSDictionary* inSession, UInt32* outLen);
static void* PacketLossPercent(QTSSDictionary* inSession, UInt32* outLen);
static void* TimeConnected(QTSSDictionary* inSession, UInt32* outLen);
// Create nonce
/* 生成摘要认证随机序列,Nonce指随机序列 */
void CreateDigestAuthenticationNonce();
// One of the RTP session attributes is an iterated list of all streams.
// As an optimization, we preallocate a "large" buffer of stream pointers,
// even though we don't know how many streams we need at first.
/* 这些常数下面要用到 */
enum
{
kStreamBufSize = 4,
kUserAgentBufSize = 256,
kPresentationURLSize = 256,
kFullRequestURLBufferSize = 256,
kRequestHostNameBufferSize = 80,
kIPAddrStrBufSize = 20,
kLocalDNSBufSize = 80,
kAuthNonceBufSize = 32,
kAuthOpaqueBufSize = 32,
};
void* fStreamBuffer[kStreamBufSize];
// theses are dictionary items picked up by the RTSPSession
// but we need to store copies of them for logging purposes.
/* 从RTSPSession获取的相关字典属性,为了日志记录,需要它们,参见RTSPSession::SetupClientSessionAttrs() */
char fUserAgentBuffer[kUserAgentBufSize]; //eg VLC media player (LIVE555 Streaming Media v2007.02.20)
char fPresentationURL[kPresentationURLSize]; // eg /foo/bar.mov,/sample_300kbit.mp4
char fFullRequestURL[kFullRequestURLBufferSize]; // eg rtsp://172.16.34.22/sample_300kbit.mp4
char fRequestHostName[kRequestHostNameBufferSize]; // eg 172.16.34.22
char fRTSPSessRemoteAddrStr[kIPAddrStrBufSize];
char fRTSPSessLocalDNS[kLocalDNSBufSize];
char fRTSPSessLocalAddrStr[kIPAddrStrBufSize];
char fUserNameBuf[RTSPSessionInterface::kMaxUserNameLen];
char fUserPasswordBuf[RTSPSessionInterface::kMaxUserPasswordLen];
char fUserRealmBuf[RTSPSessionInterface::kMaxUserRealmLen];
UInt32 fLastRTSPReqRealStatusCode;
//for timing out this session
TimeoutTask fTimeoutTask; /* 使会话超时的TimeoutTask类 */
UInt32 fTimeout;/* 超时时间,默认1s */
UInt32 fUniqueID;/* RTPSession ID */
// Time when this session got created
/* 生成RTPSession的时间 */
SInt64 fSessionCreateTime;
//Packet priority levels. Each stream has a current level, and
//the module that owns this session sets what the number of levels is.
/* 当前RTPSession的Packet优先级,相关Module可以设置 */
UInt32 fNumQualityLevels;
//Statistics
UInt32 fBytesSent;/* 发送的字节数 */
UInt32 fPacketsSent; /* 发送的包数 */
Float32 fPacketLossPercent; /* 丢包百分比 */
SInt64 fTimeConnected; /* 连接时长 */
UInt32 fTotalRTCPPacketsRecv; /* 接收到的RTCP包总数 */
UInt32 fTotalRTCPBytesRecv; /* 接收到的RTCP包字节总数 */
// Movie size & movie duration. It may not be so good to associate these
// statistics with the movie, for a session MAY have multiple movies...
// however, the 1 movie assumption is in too many subsystems at this point
/* 电影的持续时间 */
Float64 fMovieDuration;
/* 当前movie的字节数 */
UInt64 fMovieSizeInBytes;
/* movie的平均比特率 */
UInt32 fMovieAverageBitRate;
/* RTPSession TEARDOWN的原因 */
QTSS_CliSesTeardownReason fTeardownReason;
// So the streams can send sender reports(SR)
RTCPSRPacket fRTCPSRPacket;
StrPtrLen fSRBuffer;
/* needed by RTPSession::run() */
/* 追踪当前带宽的类 */
RTPBandwidthTracker fTracker;
/* overbuffering Windows超前发送机制 */
RTPOverbufferWindow fOverbufferWindow;
// Built in dictionary attributes
/* 静态的内建字典属性 */
static QTSSAttrInfoDict::AttrInfo sAttributes[];
static unsigned int sRTPSessionIDCounter; /* RTPSessionID计数器 */
// Authentication information that needs to be kept around
// for the duration of the session
QTSS_AuthScheme fAuthScheme; /* 使用的认证格式 */
StrPtrLen fAuthNonce; /* 认证序列 */
UInt32 fAuthQop;
UInt32 fAuthNonceCount;
StrPtrLen fAuthOpaque;
UInt32 fQualityUpdate;// fQualityUpdate is a counter, the starting value is the unique ID, so every session starts at a different position
UInt32 fFramesSkipped;
/* 是否启用overbuffering Window,参见RTPOverbufferWindow.h中同名字段 */
Bool16 fOverBufferEnabled;
};
#endif //_RTPSESSIONINTERFACE_H_
|
#include "interface_selectors.h"
#include "asylo/platform/primitives/extent.h"
#include "asylo/platform/primitives/primitive_status.h"
#include "asylo/platform/primitives/trusted_primitives.h"
#include "asylo/util/status_macro.h"
extern void show_score(screen_t* screen);
extern void setup_level(screen_t* screen, snake_t* snake, int level);
extern void move(snake_t* snake, char[] keys, char key);
extern int collide_object(snake_t* snake, screen_t* screen, char object);
extern int collision(snake_t* snake, screen_t* screen);
extern int eat_gold(snake_t* snake, screen_t* screen);
int printf(char* ) {
int returnVal;
asylo::primitives::printf(&*, &returnVal);
return returnVal;
}
int printf(char* __format) {
int returnVal;
asylo::primitives::printf(&*__format, &returnVal);
return returnVal;
}
int puts(char* __s) {
int returnVal;
asylo::primitives::puts(&*__s, &returnVal);
return returnVal;
}
int rand() {
int returnVal;
asylo::primitives::rand(&returnVal);
return returnVal;
}
void srand(unsigned int __seed) {
asylo::primitives::srand(__seed);
return returnVal;
}
long time(long* __timer) {
long returnVal;
asylo::primitives::time(&*__timer, &returnVal);
return returnVal;
}
void draw_line(int col, int row) {
asylo::primitives::draw_line(col, row);
return returnVal;
}
namespace asylo {
namespace primitives {
extern "C" PrimitiveStatus asylo_enclave_init() {
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::RegisterEntryHandler(keat_goldEnclaveSelector, EntryHandler{secure_eat_gold}));
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::RegisterEntryHandler(kcollisionEnclaveSelector, EntryHandler{secure_collision}));
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::RegisterEntryHandler(kcollide_objectEnclaveSelector, EntryHandler{secure_collide_object}));
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::RegisterEntryHandler(kshow_scoreEnclaveSelector, EntryHandler{secure_show_score}));
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::RegisterEntryHandler(kmoveEnclaveSelector, EntryHandler{secure_move}));
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::RegisterEntryHandler(ksetup_levelEnclaveSelector, EntryHandler{secure_setup_level}));
return PrimitiveStatus::OkStatus();
}
extern "C" PrimitiveStatus asylo_enclave_fini() {
return PrimitiveStatus::OkStatus();
}
namespace {
PrimitiveStatus Abort(void* context, TrustedParameterStack* params) {
TrustedPrimitives::BestEffortAbort("Aborting enclave");
return PrimitiveStatus::OkStatus();
}
PrimitiveStatus secure_show_score(void* context, TrustedParameterStack* params) {
screen_t screen_param = params->Pop<screen_t>();
show_score(&screen_param);
*params->PushAlloc<screen_t>() = screen_param;
PrimitiveStatus::OkStatus();
}
PrimitiveStatus secure_setup_level(void* context, TrustedParameterStack* params) {
int level_param = params->Pop<int>();
snake_t snake_param = params->Pop<snake_t>();
screen_t screen_param = params->Pop<screen_t>();
setup_level(&screen_param, &snake_param, level_param);
*params->PushAlloc<screen_t>() = screen_param;
*params->PushAlloc<snake_t>() = snake_param;
*params->PushAlloc<int>() = level_param;
PrimitiveStatus::OkStatus();
}
PrimitiveStatus secure_move(void* context, TrustedParameterStack* params) {
char key_param = params->Pop<char>();
char* keys_param = reinterpret_cast<char*>(params->Pop()->data());
snake_t snake_param = params->Pop<snake_t>();
move(&snake_param, keys_param, key_param);
*params->PushAlloc<snake_t>() = snake_param;
auto keys_param_ext = params->PushAlloc(sizeof(char) *strlen(keys_param));
memcpy(keys_param_ext.As<char>(), keys_param, strlen(keys_param));
*params->PushAlloc<char>() = key_param;
PrimitiveStatus::OkStatus();
}
PrimitiveStatus secure_collide_object(void* context, TrustedParameterStack* params) {
char object_param = params->Pop<char>();
screen_t screen_param = params->Pop<screen_t>();
snake_t snake_param = params->Pop<snake_t>();
int returnVal = collide_object(&snake_param, &screen_param, object_param);
*params->PushAlloc<int>() = returnVal;
*params->PushAlloc<snake_t>() = snake_param;
*params->PushAlloc<screen_t>() = screen_param;
*params->PushAlloc<char>() = object_param;
PrimitiveStatus::OkStatus();
}
PrimitiveStatus secure_collision(void* context, TrustedParameterStack* params) {
screen_t screen_param = params->Pop<screen_t>();
snake_t snake_param = params->Pop<snake_t>();
int returnVal = collision(&snake_param, &screen_param);
*params->PushAlloc<int>() = returnVal;
*params->PushAlloc<snake_t>() = snake_param;
*params->PushAlloc<screen_t>() = screen_param;
PrimitiveStatus::OkStatus();
}
PrimitiveStatus secure_eat_gold(void* context, TrustedParameterStack* params) {
screen_t screen_param = params->Pop<screen_t>();
snake_t snake_param = params->Pop<snake_t>();
int returnVal = eat_gold(&snake_param, &screen_param);
*params->PushAlloc<int>() = returnVal;
*params->PushAlloc<snake_t>() = snake_param;
*params->PushAlloc<screen_t>() = screen_param;
PrimitiveStatus::OkStatus();
}
PrimitiveStatus printf(char* , int* returnVal) {
TrustedParameterStack params;
*params.PushAlloc<char>() = *;
*params.PushAlloc<int>() = *returnVal;
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::UntrustedCall(kprintfOCallHandler, ¶ms));
= params.Pop<char>();
returnVal = params.Pop<int>();
return PrimitiveStatus::OkStatus();
}
PrimitiveStatus printf(char* __format, int* returnVal) {
TrustedParameterStack params;
*params.PushAlloc<char>() = *__format;
*params.PushAlloc<int>() = *returnVal;
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::UntrustedCall(kprintfOCallHandler, ¶ms));
__format = params.Pop<char>();
returnVal = params.Pop<int>();
return PrimitiveStatus::OkStatus();
}
PrimitiveStatus puts(char* __s, int* returnVal) {
TrustedParameterStack params;
*params.PushAlloc<char>() = *__s;
*params.PushAlloc<int>() = *returnVal;
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::UntrustedCall(kputsOCallHandler, ¶ms));
__s = params.Pop<char>();
returnVal = params.Pop<int>();
return PrimitiveStatus::OkStatus();
}
PrimitiveStatus rand(int* returnVal) {
TrustedParameterStack params;
*params.PushAlloc<int>() = *returnVal;
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::UntrustedCall(krandOCallHandler, ¶ms));
returnVal = params.Pop<int>();
return PrimitiveStatus::OkStatus();
}
PrimitiveStatus srand(unsigned int __seed) {
TrustedParameterStack params;
*params.PushAlloc<unsigned int>() = __seed;
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::UntrustedCall(ksrandOCallHandler, ¶ms));
__seed = params.Pop<unsigned int>();
return PrimitiveStatus::OkStatus();
}
PrimitiveStatus time(long* __timer, long* returnVal) {
TrustedParameterStack params;
*params.PushAlloc<long>() = *__timer;
*params.PushAlloc<long>() = *returnVal;
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::UntrustedCall(ktimeOCallHandler, ¶ms));
__timer = params.Pop<long>();
returnVal = params.Pop<long>();
return PrimitiveStatus::OkStatus();
}
PrimitiveStatus draw_line(int col, int row) {
TrustedParameterStack params;
*params.PushAlloc<int>() = col;
*params.PushAlloc<int>() = row;
ASYLO_RETURN_IF_ERROR(TrustedPrimitives::UntrustedCall(kdraw_lineOCallHandler, ¶ms));
col = params.Pop<int>();
row = params.Pop<int>();
return PrimitiveStatus::OkStatus();
}
} // namespace
} // namespace primitives
} // namespace asylo
|
class Solution {
public:
multiset<int, less<int> > big;
multiset<int, greater<int> > small;
double add(int val)
{
if (small.empty())
{
small.insert(val);
return val;
}
else if (small.size() == big.size())
{
if (val > *(big.begin()))
{
small.insert(*(big.begin()));
big.erase(big.begin());
big.insert(val);
}
else
{
small.insert(val);
}
return *(small.begin());
}
else
{
if (val < *(small.begin()))
{
big.insert(*(small.begin()));
small.erase(small.begin());
small.insert(val);
}
else
{
big.insert(val);
}
return 0.5*(*(small.begin()))+0.5*(*(big.begin()));
}
}
void rm(int val)
{
if (small.size() == big.size())
{
if (val >= *(big.begin()))
{
big.erase(big.find(val));
}
else
{
small.erase(small.find(val));
small.insert(*(big.begin()));
big.erase(big.begin());
}
}
else
{
if (val <= *(small.begin()))
{
small.erase(small.find(val));
}
else
{
big.erase(big.find(val));
big.insert(*(small.begin()));
small.erase(small.begin());
}
}
}
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
int size = nums.size();
vector<double> result(size-k+1, 0);
big.clear();
small.clear();
int i;
for (i = 0; i < k-1; i++)
{
add(nums[i]);
}
for (i = k-1; i < size-1; i++)
{
result[i-k+1] = add(nums[i]);
rm(nums[i-k+1]);
}
result[i-k+1] = add(nums[i]);
return result;
}
};
|
/*
* GameObject.cpp
*
* Created on: 28 ÿíâ. 2015 ã.
* Author: azakharov
*/
#include "headers/GameObject.h"
GameObject::GameObject(float x, float y, float width, float height)
{
this->x = x;
this->y = y;
this->width = width;
this->height = height;
}
GameObject::GameObject(float width, float height)
{
this->x = 0;
this->y = 0;
this->width = width;
this->height = height;
}
GameObject::~GameObject()
{
//EMPTY
}
float GameObject::get_x()
{
return x;
}
float GameObject::get_y()
{
return y;
}
float GameObject::get_width()
{
return width;
}
float GameObject::get_height()
{
return height;
}
void GameObject::set_x(float x)
{
this->x = x;
}
void GameObject::set_y(float y)
{
this->y = y;
}
void GameObject::set_width(float width)
{
this->width = width;
}
void GameObject::set_height(float height)
{
this->height = height;
}
|
#include "stdafx.h"
#include "Resource.h"
Resource::Resource()
{
}
Resource::~Resource()
{
}
|
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_SHIFTREGISTER_INITIALISESHIFTREGISTERMOCK_INC
#define __CLUCK2SESAME_TESTS_PLATFORM_SHIFTREGISTER_INITIALISESHIFTREGISTERMOCK_INC
extern initialiseInitialiseShiftRegisterMock
extern calledInitialiseShiftRegister
#endif
|
#include <atomic>
#include <iostream>
#include <thread>
using namespace std;
//原子数据类型
atomic<long> total = {0}; //需要头文件 #include <atomic>
//点击函数
void func()
{
for (int i = 0; i < 1000000; ++i)
{
total += 1;
}
}
int main()
{
clock_t start = clock(); // 计时开始
//线程
thread t1(func);
thread t2(func);
t1.join();
t2.join();
clock_t end = clock(); // 计时结束
cout << "total = " << total << endl;
cout << "time = " << end - start << " ms\n";
return 0;
}
|
//#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <stack>
#include <cctype>
//#include <iomanip>
//#define LOCAL
#define Inf 0x3f3f3f3f
#define NeInf 0xc0c0c0c0
#define REP(i,n) for(int i=0;i<n;++i)
using namespace std;
stack<char> S;
int main(){
#ifdef LOCAL
freopen("./file/in.txt","r",stdin);
freopen("./file/out.txt","w",stdout);
#endif // LOCAL
//ios::sync_with_stdio(0);
//cin.tie(0);
//cout << fixed << setprecision(3);
int t;
string s;
cin >> t;
cin.get();cin.get();
bool b = 0;
while(t--){
if(b) cout << "\n";
else b = 1;
while(getline(cin, s) && s.size()){
//cout << s[0];
if(isdigit(s[0])) cout << s[0];
else{
const char& c = s[0];
switch(c){
case '(':
S.push(c);
break;
case ')':
while(S.top() != '('){
cout << S.top();
S.pop();
}
if(S.top() == '(') S.pop();
break;
case '*':
case '/':
while(!S.empty() && (S.top() == '*' || S.top() == '/')){
cout << S.top();
S.pop();
}
S.push(c);
break;
default:
while(!S.empty() && S.top() != '('){
cout << S.top();
S.pop();
}
S.push(c);
}
}
}
//cout << "\n";
if(!s.size()){
while(!S.empty()){
|
#include "ReverseLinkedListII.hpp"
ListNode *ReverseLinkedListII::reverseBetween(ListNode *head, int m, int n) {
ListNode *rprev = nullptr;
ListNode *rhead = head;
for (int i = 1; i < m; i++) {
rprev = rhead;
rhead = rhead->next;
}
ListNode *p1 = rhead, *p2 = rhead->next;
for (int j = m; j <= n - 1; j++) {
ListNode *tmp = p2->next;
p2->next = p1;
p1 = p2;
p2 = tmp;
}
rhead->next = p2;
if (rprev != nullptr)
rprev->next = p1;
else
head = p1;
return head;
}
|
#include <iostream>
using namespace std;
void merge(int array[], int izq, int mid, int derecha)
{
auto const subarrayuno = mid - izq + 1;
auto const subarraidos = derecha - mid;
auto *izqArray = new int[subarrayuno],
*derechaArray = new int[subarraidos];
for (auto i = 0; i < subarrayuno; i++)
izqArray[i] = array[izq + i];
for (auto j = 0; j < subarraidos; j++)
derechaArray[j] = array[mid + 1 + j];
auto indicedesubarrayuno = 0,
indicedesubarraidos = 0;
int indicedeMergedArray = izq;
while (indicedesubarrayuno < subarrayuno && indicedesubarraidos < subarraidos)
{
if (izqArray[indicedesubarrayuno] <= derechaArray[indicedesubarraidos])
{
array[indicedeMergedArray] = izqArray[indicedesubarrayuno];
indicedesubarrayuno++;
}
else
{
array[indicedeMergedArray] = derechaArray[indicedesubarraidos];
indicedesubarraidos++;
}
indicedeMergedArray++;
}
while (indicedesubarrayuno < subarrayuno)
{
array[indicedeMergedArray] = izqArray[indicedesubarrayuno];
indicedesubarrayuno++;
indicedeMergedArray++;
}
while (indicedesubarraidos < subarraidos)
{
array[indicedeMergedArray] = derechaArray[indicedesubarraidos];
indicedesubarraidos++;
indicedeMergedArray++;
}
}
void mergeSort(int array[], int inicio, int fin)
{
// Caso base
if (inicio >= fin)
return;
int mid = inicio + (fin - inicio) / 2;
mergeSort(array, inicio, mid);
mergeSort(array, mid + 1, fin);
merge(array, inicio, mid, fin);
}
|
#ifndef BUNNY_WRL
#define BUNNY_WRL \
"/Users/nikhil/IfsViewer-data/bunny-opts.wrl"
#endif // BUNNY_WRL
#include <iostream>
#include "WrlMainWindow.hpp"
#include "WrlGLWidget.hpp"
#include "WrlAboutDialog.hpp"
#include <QApplication>
#include <QMenuBar>
#include <QGroupBox>
#include <QStatusBar>
#include <QFileDialog>
#include <QRect>
#include <QMargins>
#include "io/LoaderWrl.hpp"
#include "io/SaverWrl.hpp"
int WrlMainWindow::_timerInterval = 20;
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::showStatusBarMessage(const QString & message) {
_statusBar->showMessage(message);
}
//////////////////////////////////////////////////////////////////////
WrlMainWindow::WrlMainWindow():
_bdryTop(5),
_bdryBottom(5),
_bdryLeft(5),
_bdryCenter(5),
_bdryRight(5),
_toolsWidth(300) {
setWindowIcon(QIcon("qt.icns"));
setWindowTitle("WrlViewer3-2015 | ENGN2912B");
LoaderWrl* wrlLoader = new LoaderWrl();
_loader.registerLoader(wrlLoader);
SaverWrl* wrlSaver = new SaverWrl();
_saver.registerSaver(wrlSaver);
// QColor clearColor = qRgb(175, 200, 150);
QColor clearColor = qRgb(200, 200, 200);
QColor materialColor = qRgb(225, 150, 75);
_glWidget = new WrlGLWidget(this, clearColor, materialColor);
_toolsWidget = new WrlToolsWidget(this);
_centralWidget = new QWidget(this);
setCentralWidget(_centralWidget);
_glWidget->setParent(_centralWidget);
_toolsWidget->setParent(_centralWidget);
_toolsWidget->setMinimumWidth(300);
_glWidget->show();
// _toolsWidget->hide();
_toolsWidget->show();
_statusBar = new QStatusBar(this);
QFont font;
font.setPointSize(9);
_statusBar->setFont(font);
setStatusBar(_statusBar);
// _statusBar->hide();
//////////////////////////////////////////////////
QMenu *fileMenu = menuBar()->addMenu("&File");
QAction *exit = new QAction("E&xit" , fileMenu);
fileMenu->addAction(exit);
connect(exit, SIGNAL(triggered(bool)),
this, SLOT(onMenuFileExit()));
QAction *load = new QAction("Load" , fileMenu);
fileMenu->addAction(load);
connect(load, SIGNAL(triggered(bool)),
this, SLOT(onMenuFileLoad()));
QAction *save = new QAction("Save" , fileMenu);
fileMenu->addAction(save);
connect(save, SIGNAL(triggered(bool)),
this, SLOT(onMenuFileSave()));
QAction *qtLogo = new QAction("Qt Logo" , fileMenu);
fileMenu->addAction(qtLogo);
connect(qtLogo, SIGNAL(triggered(bool)),
_glWidget, SLOT(setQtLogo()));
QAction *bunny = new QAction("Bunny" , fileMenu);
fileMenu->addAction(bunny);
connect(bunny, SIGNAL(triggered(bool)),
this, SLOT(onMenuFileLoadBunny()));
//////////////////////////////////////////////////
QMenu *toolsMenu = menuBar()->addMenu("&Tools");
QAction *showTools = new QAction("Show" , toolsMenu);
toolsMenu->addAction(showTools);
connect(showTools, SIGNAL(triggered(bool)),
this, SLOT(onMenuToolsShow()));
QAction *hideTools = new QAction("Hide" , toolsMenu);
toolsMenu->addAction(hideTools);
connect(hideTools, SIGNAL(triggered(bool)),
this, SLOT(onMenuToolsHide()));
//////////////////////////////////////////////////
QMenu *helpMenu = menuBar()->addMenu("&Help");
QAction *about = new QAction("About QtOpenGL",helpMenu);
helpMenu->addAction(about);
connect(about, SIGNAL(triggered(bool)),
this, SLOT(onMenuHelpAbout()));
// for animation
_timer = new QTimer(this);
_timer->setInterval(_timerInterval);
connect(_timer, SIGNAL(timeout()), _glWidget, SLOT(update()));
showStatusBarMessage("");
_glWidget->setFocus();
}
//////////////////////////////////////////////////////////////////////
SceneGraph* WrlMainWindow::loadSceneGraph(const char* fname) {
static char str[1024];
sprintf(str,"Trying to load \"%s\" ...",fname);
showStatusBarMessage(QString(str));
SceneGraph* pWrl = new SceneGraph();
if(_loader.load(fname,*pWrl)) { // if success
sprintf(str,"Loaded \"%s\"",fname);
pWrl->updateBBox();
_glWidget->setSceneGraph(pWrl,true);
_toolsWidget->updateState();
} else {
sprintf(str,"Unable to load \"%s\"",fname);
delete pWrl;
pWrl = (SceneGraph*)0;
}
showStatusBarMessage(QString(str));
return pWrl;
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::onMenuFileLoad() {
std::string filename;
// stop animation
_timer->stop();
QFileDialog fileDialog(this);
fileDialog.setFileMode(QFileDialog::ExistingFile); // allowed to select only one
fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
fileDialog.setNameFilter(tr("VRML Files (*.wrl)"));
QStringList fileNames;
if(fileDialog.exec()) {
fileNames = fileDialog.selectedFiles();
if(fileNames.size()>0)
filename = fileNames.at(0).toStdString();
}
if (filename.empty()) {
showStatusBarMessage("load filename is empty");
} else {
loadSceneGraph(filename.c_str());
}
// restart animation
_timer->start(_timerInterval);
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::onMenuFileLoadBunny() {
std::string filename(BUNNY_WRL);
// stop animation
_timer->stop();
if (filename.empty()) {
showStatusBarMessage("load filename is empty");
} else {
loadSceneGraph(filename.c_str());
}
// restart animation
_timer->start(_timerInterval);
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::onMenuFileSave() {
std::string filename;
// stop animation
_timer->stop();
QFileDialog fileDialog(this);
fileDialog.setFileMode(QFileDialog::AnyFile); // allowed to select only one
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
fileDialog.setNameFilter(tr("VRML Files (*.wrl)"));
QStringList fileNames;
if(fileDialog.exec()) {
fileNames = fileDialog.selectedFiles();
if(fileNames.size()>0)
filename = fileNames.at(0).toStdString();
}
// restart animation
_timer->start(_timerInterval);
if (filename.empty()) {
showStatusBarMessage("save filename is empty");
} else {
static char str[1024];
sprintf(str,"Saving \"%s\" ...",filename.c_str());
showStatusBarMessage(QString(str));
SceneGraph* pWrl = _glWidget->getSceneGraph();
if(_saver.save(filename.c_str(),*pWrl)) {
sprintf(str,"Saved \"%s\"", filename.c_str());
} else {
sprintf(str,"Unable to save \"%s\"",filename.c_str());
}
showStatusBarMessage(QString(str));
}
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::onMenuFileExit() {
close();
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::onMenuToolsShow() {
int c3dWidth = getGLWidgetWidth();
int c3dHeight = getGLWidgetHeight();
_toolsWidget->show();
setGLWidgetSize(c3dWidth,c3dHeight);
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::onMenuToolsHide() {
int c3dWidth = getGLWidgetWidth();
int c3dHeight = getGLWidgetHeight();
_toolsWidget->hide();
setGLWidgetSize(c3dWidth,c3dHeight);
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::onMenuHelpAbout() {
WrlAboutDialog dialog(this);
dialog.exec();
}
//////////////////////////////////////////////////////////////////////
int WrlMainWindow::getGLWidgetWidth() {
return _glWidget->size().width();
}
//////////////////////////////////////////////////////////////////////
int WrlMainWindow::getGLWidgetHeight() {
return _glWidget->size().height();
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::_resize(int width, int height) {
std::cout << "WrlMainWindow::_resize(int width, int height) {\n";
QMenuBar *menuBar = this->menuBar();
QStatusBar *statusBar = this->statusBar();
int mbH = (menuBar )?menuBar->height() :0;
int sbH = (statusBar)?statusBar->height():0;
std::cout << " menuBar.height = "<< mbH <<"\n";
std::cout << " statusBar.height = "<< sbH<<"\n";
int x0 = _bdryLeft;
int w0 = width-_bdryLeft-_bdryRight;
int w1 = _toolsWidth;
int y = _bdryTop;
int h = height-_bdryTop-_bdryBottom-sbH-mbH;
if(_toolsWidget->isVisible()) {
w0 -= (w1+_bdryCenter);
int x1 = x0+w0+_bdryCenter;
_toolsWidget->setGeometry(x1,y,w1,h);
}
_glWidget->setGeometry(x0,y,w0,h);
_toolsWidget->updateState();
std::cout << "}\n";
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::resizeEvent(QResizeEvent* event) {
QSize size = event->size();
_resize(size.width(),size.height());
}
//////////////////////////////////////////////////////////////////////
void WrlMainWindow::setGLWidgetSize(int c3dWidth, int c3dHeight) {
int width = _bdryLeft + c3dWidth + _bdryRight;
if(_toolsWidget->isVisible()) width += _bdryCenter + _toolsWidth;
QMenuBar *menuBar = this->menuBar();
QStatusBar *statusBar = this->statusBar();
int mbH = (menuBar )?menuBar->height() :0;
int sbH = (statusBar)?statusBar->height():0;
int height = _bdryTop + c3dHeight + _bdryBottom + sbH+mbH;
this->resize(width,height);
// _resize(width,height);
}
WrlViewerData& WrlMainWindow::getData() const {
return _glWidget->getData();
}
SceneGraph* WrlMainWindow::getSceneGraph() {
return _glWidget->getSceneGraph();
}
void WrlMainWindow::setSceneGraph(SceneGraph* pWrl, bool resetHomeView) {
_glWidget->setSceneGraph(pWrl,resetHomeView);
}
void WrlMainWindow::updateState() {
_toolsWidget->updateState();
}
void WrlMainWindow::refresh() {
_glWidget->update();
}
|
#include "Com.h"
namespace Native {
using namespace Com;
FILE* GetStdOut() {return stdout;}
FILE* GetStdIn() {return stdin;}
FILE* GetStdErr() {return stderr;}
int SignificantBits(dword x) {
// basically log2(x) + 1 except that for 0 this is 0, number of significant bits of x
#ifdef COMPILER_MSC
DWORD index;
return _BitScanReverse(&index, x) ? index + 1 : 0;
#else
return x ? 32 - __builtin_clz(x) : 0;
#endif
}
int SignificantBits64(uint64 x) {
static_assert(sizeof(uint64) == 8, "Expecting 8-byte uint64");
// basically log2(x) + 1 except that for 0 this is 0, number of significant bits of x
#ifdef COMPILER_MSC
#ifdef CPU_64
DWORD index;
return _BitScanReverse64(&index, x) ? index + 1 : 0;
#else
if (x & 0xffffffff00000000)
return SignificantBits(HIDWORD(x)) + 32;
else
return SignificantBits((DWORD)x);
#endif
#else
return x ? 64 - __builtin_clzl(x) : 0;
#endif
}
static int s_month[] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
static int s_month_off[] = {
0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334
};
bool IsLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}
int GetDaysOfMonth(int m, int y) {
ASSERT(m >= 1 && m <= 12);
return s_month[m - 1] + (m == 2) * IsLeapYear(y);
}
int64 DateSeconds(uint64 year, uint64 month, uint64 day) {
int64 y400 = (year / 400 ) - 2;
int64 ym = year - y400 * 400;
return y400 * (400 * 365 + 100 - 3) +
ym * 365 + s_month_off[month - 1] + (day - 1) +
(ym - 1) / 4 - (ym - 1) / 100 + (ym - 1) / 400 + 1 +
(month > 2) * IsLeapYear(ym);
}
int64 TimeSeconds(uint64 year, uint64 month, uint64 day, uint64 hour, uint64 minute, uint64 second) {
int64 date = DateSeconds(year, month, day);
return date * (int64)24 * 3600 + hour * 3600 + minute * 60 + second;
}
int64 CurrentTime() {
time_t rawtime;
time(&rawtime);
struct tm t;
#ifdef flagWIN32
localtime_s(&t, &rawtime);
#else
t = *localtime(&rawtime);
#endif
return TimeSeconds(
t.tm_year + 1900, t.tm_mon, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec);
}
uint64 NanoSeconds() {
auto p2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(p2.time_since_epoch()).count();
}
uint64 MilliSeconds() {
auto p2 = std::chrono::steady_clock::now();
return (int)std::chrono::duration_cast<std::chrono::milliseconds>(p2.time_since_epoch()).count();
}
void GetSysTime(short& year, byte& mon, byte& day, byte& hour, byte& min, byte& sec) {
time_t rawtime;
time(&rawtime);
struct tm tmp;
#ifdef flagWIN32
localtime_s(&tmp, &rawtime);
#else
tmp = *localtime(&rawtime);
#endif
year = 1900 + tmp.tm_year;
mon = 1 + tmp.tm_mon;
day = tmp.tm_mday;
hour = tmp.tm_hour;
min = tmp.tm_min;
sec = tmp.tm_sec;
}
void HighResTimePoint::Reset() {
start = high_resolution_clock::now();
}
int HighResTimePoint::Elapsed() const {
return (int)(ElapsedSeconds() * 1000);
}
double HighResTimePoint::ElapsedSeconds() const {
std::chrono::high_resolution_clock::time_point stop = high_resolution_clock::now();
duration<double> time_span = duration_cast<duration<double> >(stop - start);
return time_span.count();
}
int HighResTimePoint::ResetElapsed() {
return (int)(ResetElapsedSeconds() * 1000);
}
double HighResTimePoint::ResetElapsedSeconds() {
std::chrono::high_resolution_clock::time_point stop = high_resolution_clock::now();
duration<double> time_span = duration_cast<duration<double> >(stop - start);
start = stop;
return time_span.count();
}
HighResTimePoint* HighResTimePoint::Create() {
return new HighResTimePoint();
}
void DblStr(double d, char* buf, int buf_size) {
snprintf(buf, buf_size, "%g", d);
}
void DblStr(double d, short* buf, int buf_size) {
char tmp[50];
snprintf(tmp, 50, "%g", d);
int len = std::min(50, buf_size);
char* it = tmp;
char* end = it + len;
while (it != end)
*buf++ = *it++;
}
typedef std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> UnicodeConverter;
inline UnicodeConverter& GetUnicodeConverter() {thread_local static UnicodeConverter conv; return conv;}
const short* Utf8To16(const char* in) {
thread_local static std::wstring ws = GetUnicodeConverter().from_bytes(std::string(in));
thread_local static std::vector<short> v;
v.resize(ws.size());
int i = 0;
for(wchar_t w : ws)
v[i++] = w;
v[i] = 0;
return v.data();
}
const char* Utf16To8(const short* in) {
thread_local static std::vector<wchar_t> v;
thread_local static std::string s;
int len = Lang::StringLength(in, 10000000);
v.resize(len + 1);
for(wchar_t& w : v)
w = *in++;
v[len] = 0;
std::wstring ws(v.data());
s = GetUnicodeConverter().to_bytes(ws);
return s.c_str();
}
const char* GetHomeDir() {
#ifdef flagPOSIX
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
return homedir;
#else
char homedir[2048];
getenv_s(0, homedir, 2048, "USERPROFILE");
return homedir;
#endif
}
bool DirExists(const char* path) {
DIR* d = opendir(path);
if (d) {
closedir(d);
return true;
}
return false;
}
bool PathExists(const char* path) {
#ifdef flagWIN32
#ifndef flagUWP
return PathFileExistsA(path);
#else
struct stat stat_info = {0};
if (stat(path, &stat_info) != 0)
return false;
return true;
#endif
#else
return access( path, F_OK ) != -1;
#endif
}
void CreateDirectory(const char* path) {
mkdir(path, 0700);
}
void DeleteFile(const char* path) {
unlink(path);
}
void RenameFile(const char* oldpath, const char* newpath) {
rename(oldpath, newpath);
}
const char* GetEnv(const char* id) {
#ifdef flagWIN32
size_t len = 0;
char homedir[2048];
getenv_s(&len, &homedir[0], 2048, id);
return String(homedir, len);
#else
return getenv(id);
#endif
}
bool is_dot_string(const char* s) {
int len = strlen(s);
if (!len) return false;
if (len == 1 && !memcmp(s, ".", 1)) return true;
if (len == 2 && !memcmp(s, "..", 2)) return true;
return false;
}
void GetDirFiles(const char* dir, void(*add_path)(const char*, void*), void* arg) {
#ifdef flagPOSIX
DIR* dirp = opendir(dir);
struct dirent * dp;
while ((dp = readdir(dirp)) != NULL) {
if (!is_dot_string(dp->d_name))
add_path(dp->d_name, arg);
}
closedir(dirp);
#endif
#ifdef flagWIN32
std::string pattern = std::string(dir) + "\\*";
WIN32_FIND_DATA data;
HANDLE hFind;
if ((hFind = FindFirstFile(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE) {
do {
if (!IsDotString(data.cFileName))
add_path(data.cFileName, arg);
}
while (FindNextFile(hFind, &data) != 0);
FindClose(hFind);
}
#endif
}
int PopCount64(uint64 i) {
#ifdef flagMSC
#if CPU_64
return (int)__popcnt64(i);
#elif CPU_32
return __popcnt(i) + __popcnt(i >> 32);
#endif
#else
return (int)__builtin_popcountll(i);
#endif
}
int PopCount32(dword i) {
#ifdef flagMSC
return (int)__popcnt64(i);
#else
return (int)__builtin_popcountl(i);
#endif
}
int HammingDistance32(int count, const dword* a, const dword* b) {
if (count <= 0) return 0;
const dword* end = a + count;
int distance = 0;
while(a != end)
distance += PopCount32(*a++ ^ *b++);
return distance;
}
int HammingDistance64(int count, const uint64* a, const uint64* b) {
if (count <= 0) return 0;
const uint64* end = a + count;
int distance = 0;
while(a != end)
distance += PopCount64(*a++ ^ *b++);
return distance;
}
bool IsFinite(float f) {
return ::isfinite(f);
}
bool IsFinite(double f) {
return ::isfinite(f);
}
int64 GetCpuTicks() {
#ifdef flagWIN32
return __rdtsc();
#else
return clock();
#endif
}
int64 Delay(int64 cpu_ticks) {
int64 end = GetCpuTicks() + cpu_ticks;
int64 iters = 0;
while (GetCpuTicks() < end)
iters++;
return iters;
}
struct Trans8x16 {
union {
uint16 u16[8];
uint8 u8[16];
__m128i m;
uint64 u64[2];
};
void TransFrom16x8();
void Zero();
};
void Trans8x16::TransFrom16x8() {
__m128i x = m;
for (int i = 0; i < 8; ++i) {
u16[7-i] = _mm_movemask_epi8(x);
x = _mm_slli_epi64(x,1);
}
}
void Trans8x16::Zero() {u64[0] = 0; u64[1] = 0;}
}
|
///
/// \file Subject.h
/// \brief
/// \author PISUPATI Phanindra
/// \date 01.04.2014
///
#ifndef SUBJECT_H
#define SUBJECT_H
#include "Settings.h"
#include "StringFunc.h"
#include "TextReader.h"
#include "Sequence.h"
#include "Targets.h"
#include <string>
#include <memory>
///
/// \class Subject
/// \brief Subject Class
///
class Subject
{
public:
///
/// \struct Thresholds for the subject
///
struct Thresholds
{
float speedCutoff; ///< max speed allowed
float rotSpeedCutoff; ///< max rotation speed allowed
float stepSizeThreshold; ///< step size threshold (# frames)
float speedThreshold; ///< speed threshold
float rotSpeedThreshold; ///< rotation speed threshold
Thresholds() :
speedCutoff(50),
rotSpeedCutoff(0.02),
stepSizeThreshold(50),
speedThreshold(436.8 / FRAME_RATE),
rotSpeedThreshold(0.008)
{
}
std::string toString()
{
return StringFunc::numToString(speedCutoff) + " " +
StringFunc::numToString(rotSpeedCutoff) + " " +
StringFunc::numToString(stepSizeThreshold) + " " +
StringFunc::numToString(speedThreshold) + " " +
StringFunc::numToString(rotSpeedThreshold);
}
};
private:
uint _subjectNumber; ///< subject number
std::string _c3dDirectory; ///< c3d directory
std::string _saveDirectory; ///< directory where intermediate files are saved
std::string _txtDirectory; ///< txt directory
Thresholds _thresholds; ///< thresholds
std::shared_ptr<Sequence::CalibrationCorrection> _calibrationCorrection; ///< calibration correction
std::vector<std::unique_ptr<Sequence> > _sequences; ///<
std::shared_ptr<Targets> _targets;
public:
///
/// \brief Constructor
/// \param subjectNumber: subject number
/// \param targets: pointer to targets object, including all info about all targets
///
Subject(uint subjectNumber, std::shared_ptr<Targets> targets);
///
/// \brief set the thresholds for the subject
/// \param thresholds: thresholds to determine the steps
///
void setThresholds(Thresholds thresholds);
///
/// \brief read the calibration files and store the corrections
///
void calibrate();
///
/// \brief saveCalibration: saves the calibration correction of the subject in a file
///
inline void saveCalibration();
void initialiseAllSequences();
///
/// \brief initialiseSequence
/// \param textReader
/// \param sequenceNumber
///
void initialiseSequence(TextReader& textReader, uint sequenceNumber);
void computeTrajectories(uint sequenceNumber);
std::shared_ptr<Trajectory> getTrajectory(uint sequenceNumber, TrajectoryType trajectoryType = TrajectoryType::NORMAL);
private:
};
#endif
|
//
// Copyright Jason Rice 2017
// 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 NBDL_SQL_DB_STATEMENT_INSERT_HPP
#define NBDL_SQL_DB_STATEMENT_INSERT_HPP
#include <mpdef/list.hpp>
#include <nbdl/sql_db/detail/string_sum.hpp>
#include <nbdl/string.hpp>
static_assert(
BOOST_HANA_CONFIG_ENABLE_STRING_UDL
, "nbdl::sql_db requires BOOST_HANA_CONFIG_ENABLE_STRING_UDL to be set... sorry."
);
#include <boost/hana/basic_tuple.hpp>
#include <boost/hana/pair.hpp>
#include <boost/hana/plus.hpp>
#include <boost/hana/string.hpp>
#include <boost/hana/sum.hpp>
#include <boost/hana/unpack.hpp>
#include <boost/mp11/algorithm.hpp>
#include <utility>
namespace nbdl::sql_db::statement
{
namespace hana = boost::hana;
using namespace boost::mp11;
using namespace hana::literals;
namespace insert_detail
{
template <typename Name1, typename ...NameN>
constexpr auto column_name_list(hana::basic_tuple<Name1, NameN...>)
{
return detail::string_sum(
detail::string_sum("\""_s, Name1{})
, detail::string_sum("\",\""_s, NameN{})...
, "\""_s
);
};
template <std::size_t count>
constexpr auto placeholder_list(hana::size_t<count>)
{
return hana::sum<hana::string_tag>(
mp_append<
mpdef::list<hana::string<'?'>>
, mp_repeat_c<mpdef::list<hana::string<',', '?'>>, count - 1>
>{}
);
};
}
constexpr auto insert = [](auto table_name, auto&& columns)
{
// columns is a hana::map with pair<name, column>
auto stmt = detail::string_sum(
"INSERT INTO \""_s, table_name
, "\" ("_s
, insert_detail::column_name_list(hana::keys(columns))
, ") VALUES ("_s
, insert_detail::placeholder_list(hana::size(columns))
, ");"_s
);
return hana::make_pair(
stmt
, hana::values(std::forward<decltype(columns)>(columns))
);
};
}
#endif
|
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<algorithm>
#include<set>
using namespace std;
vector<int> hi[1005];
bool f[1005];
vector<int> edge[1005];
set<int,less<int> > set1;
vector<int> v;
void dfs(int v){
f[v]=0;
int p;
for(int i=0;i<hi[v].size();i++){
p=hi[v][i];
set1.insert(p);
}
for(int i=0;i<edge[v].size();i++){
int w=edge[v][i];
if(f[w]){
dfs(w);
}
}
}
int main(){
int n;
int m;
int a,b;
cin>>n;
for(int i=1;i<=n;i++){
cin>>m;
getchar();
a=0;
for(int j=0;j<m;j++){
cin>>b;
f[b]=1;
hi[b].push_back(i);
if(a!=0){
edge[a].push_back(b);
edge[b].push_back(a);
}
a=b;
}
}
for(int i=1;i<=1000;i++){
if(f[i]){
set1.clear();
dfs(i);
int num=set1.size();
v.push_back(num);
}
}
cout<<v.size()<<endl;
sort(v.begin(),v.end());
for(int i=v.size()-1;i>0;i--){
cout<<v[i]<<" ";
}
cout<<v[0]<<endl;
return 0;
}
|
/* License: Apache 2.0. See LICENSE file in root directory.
Copyright(c) 2017 Intel Corporation. All Rights Reserved. */
#include "python.hpp"
#include "../include/librealsense2-framos/hpp/rs_types.hpp"
void init_types(py::module &m) {
/** rs2_types.hpp **/
// error+subclasses
py::class_<rs2::option_range> option_range(m, "option_range"); // No docstring in C++
option_range.def_readwrite("min", &rs2::option_range::min)
.def_readwrite("max", &rs2::option_range::max)
.def_readwrite("default", &rs2::option_range::def)
.def_readwrite("step", &rs2::option_range::step)
.def("__repr__", [](const rs2::option_range &self) {
std::stringstream ss;
ss << "<" SNAME ".option_range: " << self.min << "-" << self.max
<< "/" << self.step << " [" << self.def << "]>";
return ss.str();
});
py::class_<rs2::region_of_interest> region_of_interest(m, "region_of_interest"); // No docstring in C++
region_of_interest.def(py::init<>())
.def_readwrite("min_x", &rs2::region_of_interest::min_x)
.def_readwrite("min_y", &rs2::region_of_interest::min_y)
.def_readwrite("max_x", &rs2::region_of_interest::max_x)
.def_readwrite("max_y", &rs2::region_of_interest::max_y);
/** end rs_types.hpp **/
}
|
/***************************************************************************
Copyright (c) 2020 Philip Fortier
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 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
***************************************************************************/
#pragma once
struct ToolTipResult
{
ToolTipResult() : vocabWordInfo(0xffffffff), possibleResourceNumber(0xffff) {}
// Is the tooltip empty (e.g. no result)
bool empty() { return strTip.empty(); }
// The tip
std::string strTip;
// Line number, text, and scriptid for "goto" information
int iLineNumber;
ScriptId scriptId;
std::string strBaseText;
std::string helpURL; // For kernels
DWORD vocabWordInfo; // For saids
uint16_t possibleResourceNumber;
std::string OriginalText;
};
|
#include "DUIColor.h"
#include "DUIDebug.h"
DUI_BGN_NAMESPCE
//////////////////////////// CARGB /////////////////////////
CARGB::CARGB()
:m_byteR(0), m_byteG(0), m_byteB(0), m_byteA(0)
{
}
CARGB::CARGB(BYTE r, BYTE g, BYTE b, BYTE a /* = 0 */)
:m_byteR(r), m_byteG(g), m_byteB(b), m_byteA(a)
{
}
BOOL CARGB::IsEmpty() const
{
return (m_byteA == 0
&& m_byteB == 0
&& m_byteG == 0
&& m_byteR == 0);
}
//string format: ARGB
VOID CARGB::SetColor(LPCTSTR lpszColor)
{
LPTSTR lpszEnd = NULL;
DWORD clrTemp = _tcstoul(lpszColor, &lpszEnd, 16);
m_byteB = GetRValue(clrTemp);
m_byteG = GetGValue(clrTemp);
m_byteR = GetBValue(clrTemp);
m_byteA = (clrTemp&0xFF000000)>>24;
}
VOID CARGB::SetColor(COLORREF clr)
{
m_byteB = GetBValue(clr);
m_byteG = GetGValue(clr);
m_byteR = GetRValue(clr);
m_byteA = 255;
}
COLORREF CARGB::GetColor() const
{
return RGB(m_byteR, m_byteG, m_byteB);
}
VOID CARGB::WriteToDIB4(LPBYTE lp) const
{
DUI_ASSERT(lp != NULL);
memcpy(lp, this, 4);
}
VOID CARGB::WriteToDIB3(LPBYTE lp) const
{
DUI_ASSERT(lp != NULL);
memcpy(lp, this, 3);
}
LPBYTE CARGB::ReadFromDIB4(LPBYTE lp)
{
DUI_ASSERT(lp != NULL);
memcpy(this, lp, 4);
return lp+4;
}
LPBYTE CARGB::ReadFromDIB3(LPBYTE lp)
{
DUI_ASSERT(lp != NULL);
memcpy(this, lp, 3);
return lp+3;
}
//////////////////////////// CARGB /////////////////////////
/////////////////////////// CColor ////////////////////////
CHLSColor::operator COLORREF() const
{
return RGB(red, green, blue);
}
void CHLSColor::CorrectHLS()
{
if(lightness < 0) lightness = 0;
if(lightness > 1) lightness = 1;
if(saturation <0 ) saturation = 0;
if(saturation > 1) saturation = 1;
if(hue <0 ) hue = 0;
if(hue >= 359 ) hue = 358.9999;
}
// lightness [0..1]
// saturation [0..1]
// hue [0..359)
void CHLSColor::ToHLS(void)
{
double mn, mx;
int major;
if ( red < green )
{
mn = red; mx = green; major = Green;
}
else
{
mn = green; mx = red; major = Red;
}
if ( blue < mn )
mn = blue;
else if ( blue > mx )
{
mx = blue; major = Blue;
}
if ( mn==mx )
{
lightness = mn/255;
saturation = 0;
hue = 0;
}
else
{
lightness = (mn+mx) / 510;
if ( lightness <= 0.5 )
saturation = (mx-mn) / (mn+mx);
else
saturation = (mx-mn) / (510-mn-mx);
switch ( major )
{
case Red : hue = (green-blue) * 60 / (mx-mn) + 360; break;
case Green: hue = (blue-red) * 60 / (mx-mn) + 120; break;
case Blue : hue = (red-green) * 60 / (mx-mn) + 240;
}
if (hue >= 360)
hue = hue - 360;
}
}
unsigned char Value(double m1, double m2, double h)
{
while (h >= 360) h -= 360;
while (h < 0) h += 360;
if (h < 60)
m1 = m1 + (m2 - m1) * h / 60;
else if (h < 180)
m1 = m2;
else if (h < 240)
m1 = m1 + (m2 - m1) * (240 - h) / 60;
return (unsigned char)(m1 * 255);
}
void CHLSColor::ToRGB(void)
{
CorrectHLS();
if (saturation == 0)
{
red = green = blue = (unsigned char) (lightness*255);
}
else
{
double m1, m2;
if ( lightness <= 0.5 )
m2 = lightness + lightness * saturation;
else
m2 = lightness + saturation - lightness * saturation;
m1 = 2 * lightness - m2;
red = Value(m1, m2, hue + 120);
green = Value(m1, m2, hue);
blue = Value(m1, m2, hue - 120);
}
}
/////////////////////////// CColor ////////////////////////
DUI_END_NAMESPCE
|
/*
* insultgenerator.cpp
* Author: Mike Cruickshank
*/
#include "insultgenerator.h"
FileException::FileException(const string& message) : message(message) {}
string& FileException::what() { return message; }
NumInsultsOutOfBounds::NumInsultsOutOfBounds(const string& message) : message(message) {}
string& NumInsultsOutOfBounds::what() {return message; }
void InsultGenerator::initialize() {
srand(time(NULL));
ifstream file("InsultsSource.txt");
if (file.is_open()){
string currentLine;
while (getline(file, currentLine, '\n') ){
vector <string> currentLineDiv;
stringstream ss(currentLine);
string currentWord;
while(getline(ss, currentWord, '\t')) {
currentLineDiv.push_back(currentWord);
}
columnOne.push_back(currentLineDiv[0]);
columnTwo.push_back(currentLineDiv[1]);
columnThree.push_back(currentLineDiv[2]);
}
file.close();
} else {
throw FileException("File cannot be opened.");
}
} // end initialize method
string InsultGenerator::talkToMe() {
string newInsult;
newInsult = "Thou " + columnOne[rand() % 50] + " " + columnTwo[rand() % 50] + " " + columnThree[rand() % 50] + "!";
return newInsult;
} // end talkToMe method
vector <string> InsultGenerator::generate(const int& numberOfInsults) {
if (numberOfInsults > 10000){
throw NumInsultsOutOfBounds("Number of Insults is Greater Than 10 000");
}
else if (numberOfInsults < 1){
throw NumInsultsOutOfBounds("Number of Insults is Less Than 1");
}
else{
string tempString;
set <string> sortedInsults;
vector <string> listOfInsults;
pair<set<string>::iterator, bool> ret;
for (int i = 0; i < numberOfInsults; ++i) {
tempString = talkToMe();
ret = sortedInsults.insert(tempString);
bool isUnique = ret.second;
while (!isUnique){
ret = sortedInsults.insert(talkToMe());
isUnique = ret.second;
}
}
listOfInsults.assign(sortedInsults.begin(), sortedInsults.end());
return listOfInsults;
}
}
void InsultGenerator::generateAndSave(const string& outputFileName, const int& numberOfInsults){
const vector<string> insults = generate(numberOfInsults);
ofstream file(outputFileName);
if (file.is_open()){
for (int i = 0; i < numberOfInsults; ++ i){
file << insults[i] << endl;;
}
file.close();
}
else {
throw FileException("File cannot be opened.");
}
} // end generateAndSave method
|
# include <cstdio>
# include <set>
# include <vector>
# include <list>
// Não funciona
using namespace std;
int L, K, fileiras, fileirasMax;
set<int> X;
vector<int> Xvec;
inline int somaTabuas(int i, int altura) {
int tamParcial, tamParcialAtual;
list<vector<int>::iterator> selecionados;
bool fechou = false;
while (true) {
tamParcial = Xvec[i];
tamParcialAtual = tamParcial;
for (auto it = Xvec.begin() + i + 1; it < Xvec.end(); ++it) {
tamParcialAtual += *it;
if (tamParcialAtual == altura) {
tamParcial = tamParcialAtual;
selecionados.push_back(it);
fechou = true;
break;
} else if (tamParcialAtual > altura)
tamParcialAtual = tamParcial;
else {
tamParcial = tamParcialAtual;
selecionados.push_back(it);
}
}
if (fechou) {
for (auto &e : selecionados)
Xvec.erase(e);
return selecionados.size();
} else
return 0;
}
}
inline int verifica(int largura, int altura) {
int tabuas = 0, tabuas2;
fileiras = 0;
if ((largura * 100) % L != 0)
return 0;
else
fileirasMax = largura / (L/100.0);
for (int i = 0; i < K; ++i) {
if (fileiras == fileirasMax)
break;
if (Xvec[i] <= altura) {
if (Xvec[i] == altura) {
++tabuas;
++fileiras;
Xvec.erase(Xvec.begin() + i);
} else {
tabuas2 = somaTabuas(i, altura);
if (tabuas2 > 0)
--i;
tabuas += tabuas2;
}
}
}
return tabuas;
}
int main() {
int N, M, Xi, fileirasN, fileirasM, tabuasN, tabuasM, fileirasMaxN, fileirasMaxM;
while (true) {
scanf("%d%d", &N, &M);
if (N == 0 && M == 0)
break;
scanf("%d%d", &L, &K);
X.clear();
for(int i = 0; i < K; ++i) {
scanf("%d", &Xi);
X.insert(Xi);
}
Xvec = vector<int>(X.rbegin(), X.rend());
tabuasN = verifica(N, M);
fileirasN = fileiras;
fileirasMaxN = fileirasMax;
printf("tabuasN: %d\n", tabuasN);
tabuasM = verifica(M, N);
fileirasM = fileiras;
fileirasMaxM = fileirasMax;
printf("tabuasM: %d\n", tabuasM);
if (fileirasN == fileirasMaxN && fileirasM == fileirasMaxM)
(tabuasN < tabuasM) ? printf("%d\n", tabuasN) : printf("%d\n", tabuasM);
else if (fileirasN == fileirasMaxN)
printf("%d\n", tabuasN);
else if (fileirasM == fileirasMaxM)
printf("%d\n", tabuasM);
else
printf("impossivel\n");
}
return 0;
}
|
#pragma once
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <string>
#include <string.h>
#include <list>
#include "rapidxml_utils.hpp"
#include "rapidxml.hpp"
#include "rapidxml_print.hpp"
using namespace std;
using namespace rapidxml;
class Attack{
public:
string print;
vector<string> action;
struct condition {
string object;
string status;
}cond;
bool hasAction = false;
bool hasPrint = false;
bool hasCondition = false;
Attack(){};
Attack(xml_node<> *node)
{
//xml_node<>* temp = node;
cpy_Attack(node);
}
void cpy_Attack(xml_node<> *node)
{
for(xml_node<> *current = node -> first_node(); current != NULL; current = current -> next_sibling())
{
if(string(current -> name()) == (string)"print")
{
hasPrint = true;
print = current -> value();
}
if(string(current -> name()) == (string)"condition")
{
hasCondition = true;
xml_node<>* child = current -> first_node();
while(child != NULL)
{
if(string(child -> name()) == (string)"object")
{
cond.object = child-> value();
}
if(string(child -> name()) == (string)"status")
{
cond.status = child-> value();
}
child = child -> next_sibling();
}
}
if(string(current -> name()) == (string)"action")
{
hasAction = true;
string temp = current -> value();
action.push_back(temp);
}
}
}
};
|
//===--- FormalEvaluation.cpp ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "FormalEvaluation.h"
#include "LValue.h"
#include "SILGenFunction.h"
using namespace swift;
using namespace Lowering;
//===----------------------------------------------------------------------===//
// Formal Access
//===----------------------------------------------------------------------===//
void FormalAccess::_anchor() {}
void FormalAccess::verify(SILGenFunction &SGF) const {
#ifndef NDEBUG
// If this access was already finished, continue. This can happen if an
// owned formal access was forwarded.
if (isFinished()) {
assert(getKind() == FormalAccess::Owned &&
"Only owned formal accesses should be forwarded.");
// We can not check that our cleanup is actually dead since the cleanup
// may have been popped at this point and the stack may have new values.
return;
}
assert(!isFinished() && "Can not finish a formal access cleanup "
"twice");
// Now try to look up the cleanup handle of the formal access.
SGF.Cleanups.checkIterator(getCleanup());
#endif
}
//===----------------------------------------------------------------------===//
// Shared Borrow Formal Evaluation
//===----------------------------------------------------------------------===//
void SharedBorrowFormalAccess::finishImpl(SILGenFunction &SGF) {
SGF.B.createEndBorrow(CleanupLocation::get(loc), borrowedValue,
originalValue);
}
//===----------------------------------------------------------------------===//
// OwnedFormalAccess
//===----------------------------------------------------------------------===//
void OwnedFormalAccess::finishImpl(SILGenFunction &SGF) {
auto cleanupLoc = CleanupLocation::get(loc);
if (value->getType().isAddress())
SGF.B.createDestroyAddr(cleanupLoc, value);
else
SGF.B.emitDestroyValueOperation(cleanupLoc, value);
}
//===----------------------------------------------------------------------===//
// Formal Evaluation Scope
//===----------------------------------------------------------------------===//
FormalEvaluationScope::FormalEvaluationScope(SILGenFunction &SGF)
: SGF(SGF), savedDepth(SGF.FormalEvalContext.stable_begin()),
wasInFormalEvaluationScope(SGF.InFormalEvaluationScope),
wasInInOutConversionScope(SGF.InInOutConversionScope) {
if (wasInInOutConversionScope) {
savedDepth.reset();
return;
}
SGF.InFormalEvaluationScope = true;
}
FormalEvaluationScope::FormalEvaluationScope(FormalEvaluationScope &&o)
: SGF(o.SGF), savedDepth(o.savedDepth),
wasInFormalEvaluationScope(o.wasInFormalEvaluationScope),
wasInInOutConversionScope(o.wasInInOutConversionScope) {
o.savedDepth.reset();
assert(o.isPopped());
}
void FormalEvaluationScope::popImpl() {
// Pop the SGF.InFormalEvaluationScope bit.
SGF.InFormalEvaluationScope = wasInFormalEvaluationScope;
// Check to see if there is anything going on here.
auto &context = SGF.FormalEvalContext;
using iterator = FormalEvaluationContext::iterator;
using stable_iterator = FormalEvaluationContext::stable_iterator;
iterator unwrappedSavedDepth = context.find(savedDepth.getValue());
iterator iter = context.begin();
if (iter == unwrappedSavedDepth)
return;
// Save our start point to make sure that we are not adding any new cleanups
// to the front of the stack.
stable_iterator originalBegin = context.stable_begin();
(void)originalBegin;
// Then working down the stack until we visit unwrappedSavedDepth...
for (; iter != unwrappedSavedDepth; ++iter) {
// Grab the next evaluation...
FormalAccess &access = *iter;
// If this access was already finished, continue. This can happen if an
// owned formal access was forwarded.
if (access.isFinished()) {
assert(access.getKind() == FormalAccess::Owned &&
"Only owned formal accesses should be forwarded.");
// We can not check that our cleanup is actually dead since the cleanup
// may have been popped at this point and the stack may have new values.
continue;
}
assert(!access.isFinished() && "Can not finish a formal access cleanup "
"twice");
// and deactivate the cleanup. This will set the isFinished bit for owned
// FormalAccess.
SGF.Cleanups.setCleanupState(access.getCleanup(), CleanupState::Dead);
// Attempt to diagnose problems where obvious aliasing introduces illegal
// code. We do a simple N^2 comparison here to detect this because it is
// extremely unlikely more than a few writebacks are active at once.
if (access.getKind() == FormalAccess::Exclusive) {
iterator j = iter;
++j;
for (; j != unwrappedSavedDepth; ++j) {
FormalAccess &other = *j;
if (other.getKind() != FormalAccess::Exclusive)
continue;
auto &lhs = static_cast<ExclusiveBorrowFormalAccess &>(access);
auto &rhs = static_cast<ExclusiveBorrowFormalAccess &>(other);
lhs.diagnoseConflict(rhs, SGF);
}
}
// Claim the address of each and then perform the writeback from the
// temporary allocation to the source we copied from.
//
// This evaluates arbitrary code, so it's best to be paranoid
// about iterators on the context.
access.finish(SGF);
}
// Then check that we did not add any additional cleanups to the beginning of
// the stack...
assert(originalBegin == context.stable_begin() &&
"more formal eval cleanups placed onto context during formal eval scope pop?!");
// And then pop off all stack elements until we reach the savedDepth.
context.pop(savedDepth.getValue());
}
void FormalEvaluationScope::verify() const {
// Check to see if there is anything going on here.
auto &context = SGF.FormalEvalContext;
using iterator = FormalEvaluationContext::iterator;
iterator unwrappedSavedDepth = context.find(savedDepth.getValue());
iterator iter = context.begin();
if (iter == unwrappedSavedDepth)
return;
// Then working down the stack until we visit unwrappedSavedDepth...
for (; iter != unwrappedSavedDepth; ++iter) {
// Grab the next evaluation verify that we can successfully access this
// formal access.
(*iter).verify(SGF);
}
}
//===----------------------------------------------------------------------===//
// Formal Evaluation Context
//===----------------------------------------------------------------------===//
void FormalEvaluationContext::dump(SILGenFunction &SGF) {
for (auto II = begin(), IE = end(); II != IE; ++II) {
FormalAccess &access = *II;
SGF.Cleanups.dump(access.getCleanup());
}
}
|
#ifndef GRAPHICS_H
#define GRAPHICS_H
#include <QWidget>
class graphics : public QWidget
{
Q_OBJECT
public:
explicit graphics(QWidget *parent = 0);
void paintEvent(QPaintEvent *);
void thaiCuc(QPainter &painter, QPoint p, int x, int y);
//Chỉ cần truyền vị trí và kích thước cần vẽ là được
void moon(QPainter &painter, QPoint p, int size);
void cloud(QPainter &painter, QPoint p, int size);
void boat(QPainter &painter, QPoint p, int size);
void star(QPainter &painter, QPoint p, int size);
QPoint tinhtien(QPoint p, int tx, int ty);
QPoint quay(QPoint p, QPoint c, int deta);
QPoint trungdiem(QPoint a, QPoint b);
QPoint dichuyen(QPoint p, int kc, int huong);
void timerEvent(QTimerEvent *);
int timerId, position;
int random(int n);
signals:
public slots:
};
#endif // GRAPHICS_H
|
#ifndef WBPERODINBLACKBOARDGET_H
#define WBPERODINBLACKBOARDGET_H
#include "wbpe.h"
class WBPERodinBlackboardGet : public WBPE
{
public:
WBPERodinBlackboardGet();
virtual ~WBPERodinBlackboardGet();
DEFINE_WBPE_FACTORY( RodinBlackboardGet );
virtual void InitializeFromDefinition( const SimpleString& DefinitionName );
virtual void Evaluate( const WBParamEvaluator::SPEContext& Context, WBParamEvaluator::SEvaluatedParam& EvaluatedParam ) const;
private:
HashedString m_BlackboardKey; // Config
};
#endif // WBPERODINBLACKBOARDGET_H
|
/*WishTest.cpp
Wish
copyright Vixac Ltd. All Rights Reserved
*/
#include "Wish.h"
#include <gtest/gtest.h>
namespace VI = vixac;
namespace IN = VI::inout;
TEST(Wish, aTest)
{
// EXPECT_STREQ( "write some tests for Wish", "TODO");
}
|
/**
* ****************************************************************************
* Copyright (c) 2015, Robert Lukierski.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ****************************************************************************
* DC1394 Driver.
* ****************************************************************************
*/
#ifndef FIREWIRE_CAMERA_DRIVER_HPP
#define FIREWIRE_CAMERA_DRIVER_HPP
#include <stdint.h>
#include <stddef.h>
#include <stdexcept>
#include <cstring>
#include <string>
#include <sstream>
#include <memory>
#include <chrono>
#include <functional>
#include <CameraDrivers.hpp>
namespace drivers
{
namespace camera
{
/**
* DC1394 Camera Driver.
*/
class FireWire : public CameraDriverBase
{
public:
enum class EISOSpeed
{
ISO_SPEED_100 = 0,
ISO_SPEED_200,
ISO_SPEED_400,
ISO_SPEED_800,
ISO_SPEED_1600,
ISO_SPEED_3200
};
struct FWAPIPimpl;
class FireWireException : public std::exception
{
public:
FireWireException(uint32_t errcode, const char* file, int line);
virtual ~FireWireException() throw() { }
virtual const char* what() const throw()
{
return errormsg.c_str();
}
private:
std::string errormsg;
};
FireWire();
virtual ~FireWire();
void open(uint32_t id = 0);
void close();
void start();
void stop();
void setModeAndFramerate(EVideoMode vmode, EFrameRate framerate);
void setCustomMode(EPixelFormat pixfmt, unsigned int width, unsigned int height, unsigned int offset_x = 0, unsigned int offset_y = 0, uint16_t format7mode = 0);
virtual bool getFeaturePower(EFeature fidx);
virtual void setFeaturePower(EFeature fidx, bool b);
virtual bool getFeatureAuto(EFeature fidx);
virtual void setFeatureAuto(EFeature fidx, bool b);
virtual uint32_t getFeatureValue(EFeature fidx);
virtual float getFeatureValueAbs(EFeature fidx);
virtual uint32_t getFeatureMin(EFeature fidx);
virtual uint32_t getFeatureMax(EFeature fidx);
virtual void setFeatureValue(EFeature fidx, uint32_t val);
virtual void setFeatureValueAbs(EFeature fidx, float val);
std::size_t getWidth() const { return m_width; }
std::size_t getHeight() const { return m_height; }
EPixelFormat getPixelFormat() const { return m_pixfmt; }
EISOSpeed getISOSpeed() const { return iso_speed; }
void setISOSpeed(EISOSpeed i) { iso_speed = i; }
unsigned int getDMABuffers() const { return dma_buf; }
void setDMABuffers(unsigned int v) { dma_buf = v;}
private:
void image_release(void* img);
virtual bool isOpenedImpl() const;
virtual bool isStartedImpl() const { return is_running; }
virtual bool captureFrameImpl(FrameBuffer* cf1, FrameBuffer* cf2, FrameBuffer* cf3, FrameBuffer* cf4, int64_t timeout = 0);
std::unique_ptr<FWAPIPimpl> m_pimpl;
std::size_t m_width, m_height;
EPixelFormat m_pixfmt;
EISOSpeed iso_speed;
unsigned int dma_buf;
int m_camid;
bool is_running;
};
}
}
#endif // FIREWIRE_CAMERA_DRIVER_HPP
|
#include<bits/stdc++.h>
using namespace std;
#define lli long long int
#define ld long double
#define rep(i,n) for(lli i=0;i<n;i++)
#define ii pair<lli,lli>
#define F first
#define S second
vector<vector<ii> > g;
vector<lli> dist;
lli n, m,st;
void bellman()
{
for(lli i=1;i<=n;i++)
{
for(auto v:g[i])
{
dist[v.F]=min(dist[v.F],dist[i]+v.S);
}
}
}
void solve()
{
cin >> n >> m >> st;
g.resize(n+1);
dist.assign(n+1,1e9);
dist[st]=0;
for(lli i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
lli a,b,k;
cin >> a >> b >> k;
g[a].push_back({b,k});
g[b].push_back({a,k});
}
}
for(lli i=1;i<n;i++)
{
bellman();
}
bool neg_cyc=0;
for(lli k=1;k<n;k++)
{
for(lli i=1;i<=n;i++)
{
for(auto v:g[i])
{
if(dist[v.F]>dist[i]+v.S){
neg_cycle=1;
break;
}
}
}
}
}
// O(V*E)
|
/*
* SPDX-FileCopyrightText: (C) 2017-2022 Matthias Fehring <mf@huessenbergnetz.de>
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "validatorip_p.h"
#include <utility>
#include <QHostAddress>
#include <QRegularExpression>
using namespace Cutelyst;
ValidatorIp::ValidatorIp(const QString &field, Constraints constraints, const Cutelyst::ValidatorMessages &messages, const QString &defValKey)
: ValidatorRule(*new ValidatorIpPrivate(field, constraints, messages, defValKey))
{
}
ValidatorIp::~ValidatorIp()
{
}
ValidatorReturnType ValidatorIp::validate(Cutelyst::Context *c, const ParamsMultiMap ¶ms) const
{
ValidatorReturnType result;
Q_D(const ValidatorIp);
const QString v = value(params);
if (!v.isEmpty()) {
if (ValidatorIp::validate(v, d->constraints)) {
result.value.setValue(v);
} else {
result.errorMessage = validationError(c);
qCDebug(C_VALIDATOR, "ValidatorIp: Validation failed for field %s at %s::%s: not a valid IP address within the constraints.", qPrintable(field()), qPrintable(c->controllerName()), qPrintable(c->actionName()));
}
} else {
defaultValue(c, &result, "ValidatorIp");
}
return result;
}
bool ValidatorIp::validate(const QString &value, Constraints constraints)
{
bool valid = true;
// simple check for an IPv4 address with four parts, because QHostAddress also tolerates addresses like 192.168.2 and fills them with 0 somewhere
if (!value.contains(QLatin1Char(':')) && !value.contains(QRegularExpression(QStringLiteral("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")))) {
valid = false;
} else {
// private IPv4 subnets
static const std::vector<std::pair<QHostAddress, int>> ipv4Private({// Used for local communications within a private network
// https://tools.ietf.org/html/rfc1918
{QHostAddress(QStringLiteral("10.0.0.0")), 8},
// Used for link-local addresses between two hosts on a single link when no IP address
// is otherwise specified, such as would have normally been retrieved from a DHCP server
// https://tools.ietf.org/html/rfc3927
{QHostAddress(QStringLiteral("169.254.0.0")), 16},
// Used for local communications within a private network
// https://tools.ietf.org/html/rfc1918
{QHostAddress(QStringLiteral("172.16.0.0")), 12},
// Used for local communications within a private network
// https://tools.ietf.org/html/rfc1918
{QHostAddress(QStringLiteral("192.168.0.0")), 12}});
// reserved IPv4 subnets
static const std::vector<std::pair<QHostAddress, int>> ipv4Reserved({// Used for broadcast messages to the current ("this")
// https://tools.ietf.org/html/rfc1700
{QHostAddress(QStringLiteral("0.0.0.0")), 8},
// Used for communications between a service provider and its subscribers when using a carrier-grade NAT
// https://tools.ietf.org/html/rfc6598
{QHostAddress(QStringLiteral("100.64.0.0")), 10},
// Used for loopback addresses to the local host
// https://tools.ietf.org/html/rfc990
{QHostAddress(QStringLiteral("127.0.0.1")), 8},
// Used for the IANA IPv4 Special Purpose Address Registry
// https://tools.ietf.org/html/rfc5736
{QHostAddress(QStringLiteral("192.0.0.0")), 24},
// Assigned as "TEST-NET" for use in documentation and examples. It should not be used publicly.
// https://tools.ietf.org/html/rfc5737
{QHostAddress(QStringLiteral("192.0.2.0")), 24},
// Used by 6to4 anycast relays
// https://tools.ietf.org/html/rfc3068
{QHostAddress(QStringLiteral("192.88.99.0")), 24},
// Used for testing of inter-network communications between two separate subnets
// https://tools.ietf.org/html/rfc2544
{QHostAddress(QStringLiteral("198.18.0.0")), 15},
// Assigned as "TEST-NET-2" for use in documentation and examples. It should not be used publicly.
// https://tools.ietf.org/html/rfc5737
{QHostAddress(QStringLiteral("198.51.100.0")), 24},
// Assigned as "TEST-NET-3" for use in documentation and examples. It should not be used publicly.
// https://tools.ietf.org/html/rfc5737
{QHostAddress(QStringLiteral("203.0.113.0")), 24},
// Reserved for future use
// https://tools.ietf.org/html/rfc6890
{QHostAddress(QStringLiteral("240.0.0.0")), 4},
// Reserved for the "limited broadcast" destination address
// https://tools.ietf.org/html/rfc6890
{QHostAddress(QStringLiteral("255.255.255.255")), 32}});
// private IPv6 subnets
static const std::vector<std::pair<QHostAddress, int>> ipv6Private({// unique local address
{QHostAddress(QStringLiteral("fc00::")), 7},
// link-local address
{QHostAddress(QStringLiteral("fe80::")), 10}});
// reserved IPv6 subnets
static const std::vector<std::pair<QHostAddress, int>> ipv6Reserved({// unspecified address
{QHostAddress(QStringLiteral("::")), 128},
// loopback address to the loca host
{QHostAddress(QStringLiteral("::1")), 128},
// IPv4 mapped addresses
{QHostAddress(QStringLiteral("::ffff:0:0")), 96},
// discard prefix
// https://tools.ietf.org/html/rfc6666
{QHostAddress(QStringLiteral("100::")), 64},
// IPv4/IPv6 translation
// https://tools.ietf.org/html/rfc6052
{QHostAddress(QStringLiteral("64:ff9b::")), 96},
// Teredo tunneling
{QHostAddress(QStringLiteral("2001::")), 32},
// deprected (previously ORCHID)
{QHostAddress(QStringLiteral("2001:10::")), 28},
// ORCHIDv2
{QHostAddress(QStringLiteral("2001:20::")), 28},
// addresses used in documentation and example source code
{QHostAddress(QStringLiteral("2001:db8::")), 32},
// 6to4
{QHostAddress(QStringLiteral("2002::")), 16}});
QHostAddress a;
if (a.setAddress(value)) {
if (!constraints.testFlag(NoConstraint)) {
if (a.protocol() == QAbstractSocket::IPv4Protocol) {
if (constraints.testFlag(IPv6Only)) {
valid = false;
}
if (valid && (constraints.testFlag(NoPrivateRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress, int> &subnet : ipv4Private) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoReservedRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress, int> &subnet : ipv4Reserved) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoMultiCast) || constraints.testFlag(PublicOnly))) {
if (a.isInSubnet(QHostAddress(QStringLiteral("224.0.0.0")), 4)) {
valid = false;
}
}
} else {
if (constraints.testFlag(IPv4Only)) {
valid = false;
}
if (valid && (constraints.testFlag(NoPrivateRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress, int> &subnet : ipv6Private) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoReservedRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress, int> &subnet : ipv6Reserved) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoMultiCast) || constraints.testFlag(PublicOnly))) {
if (a.isInSubnet(QHostAddress(QStringLiteral("ff00::")), 8)) {
valid = false;
}
}
}
}
} else {
valid = false;
}
}
return valid;
}
QString ValidatorIp::genericValidationError(Context *c, const QVariant &errorData) const
{
QString error;
Q_UNUSED(errorData)
const QString _label = label(c);
if (_label.isEmpty()) {
error = c->translate("Cutelyst::ValidatorIp", "IP address is invalid or not acceptable.");
} else {
//: %1 will be replaced by the field label
error = c->translate("Cutelyst::ValidatorIp", "The IP address in the “%1” field is invalid or not acceptable.").arg(_label);
}
return error;
}
|
#ifndef __SCRIPT_SCOPE__
#define __SCRIPT_SCOPE__
#include <functional>
#include <unordered_map>
#include "string_t.h"
#include "ActionVal.h"
#include "ScriptRaw.h"
typedef std::function<ActionVal(ActionVal*)> script_action_t;
typedef std::pair<script_action_t, ActionVal*> script_statement_t;
typedef std::list<script_statement_t> script_statement_list_t;
typedef std::function<void(ActionVal*, std::function<void()>)> script_async_action_t;
typedef std::pair<script_async_action_t, ActionVal*> script_async_statement_t;
typedef std::list<script_async_statement_t> script_async_statement_list_t;
class ScriptScope
{
public:
ScriptScope();
std::unordered_map<string_t, script_action_t> actions;
std::unordered_map<string_t, script_async_action_t> async_actions;
std::unordered_map<string_t, std::function<ScriptScope*(ScriptRaw*)>> defs;
std::list<script_statement_t> * statements;
std::list<script_async_statement_t> * async_statements;
string_t scope_target;
};
#endif //__SCRIPT_SCOPE__
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTSOLVINGSTIFFODESYSTEMS_HPP_
#define TESTSOLVINGSTIFFODESYSTEMS_HPP_
#include <cxxtest/TestSuite.h>
#include "CheckpointArchiveTypes.hpp"
#include <iostream>
#include "BackwardEulerIvpOdeSolver.hpp"
#include "RungeKutta4IvpOdeSolver.hpp"
#include "FieldNoyesReactionSystem.hpp"
#include "PetscSetupAndFinalize.hpp"
class TestSolvingStiffOdeSystems : public CxxTest::TestSuite
{
public:
/**
* Solve the Field-Noyes system.
* This is a stiff ODE so Runge-Kutta won't work - program hangs if
* end time > 0.01 and variables go out of bounds.
* Can be solved ok with backward Euler.
*/
void TestFieldNoyesReactionSystem()
{
FieldNoyesReactionSystem ode_system;
RungeKutta4IvpOdeSolver rk4_solver;
OdeSolution ode_solution;
std::vector<double> ode_state_variables = ode_system.GetInitialConditions();
// note small end time
ode_solution = rk4_solver.Solve(&ode_system, ode_state_variables, 0.0, 0.01, 0.001, 0.001);
int last = ode_solution.GetNumberOfTimeSteps();
for (int i=0; i<=last; i++)
{
double x = ode_solution.rGetSolutions()[i][0];
TS_ASSERT_LESS_THAN(x, 9.7e3);
TS_ASSERT_LESS_THAN(0.99, x);
}
BackwardEulerIvpOdeSolver backward_euler_solver(ode_system.GetNumberOfStateVariables());
OdeSolution ode_solution2;
std::vector<double> ode_state_variables2 = ode_system.GetInitialConditions();
ode_solution2 = backward_euler_solver.Solve(&ode_system, ode_state_variables2, 0.0, 0.1, 0.001, 0.001);
last = ode_solution2.GetNumberOfTimeSteps();
for (int i=0; i<=last; i++)
{
double x = ode_solution2.rGetSolutions()[i][0];
TS_ASSERT_LESS_THAN(x, 9.7e3);
TS_ASSERT_LESS_THAN(0.99, x);
}
}
};
#endif /*TESTSOLVINGSTIFFODESYSTEMS_HPP_*/
|
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv/cv.h>
#include <opencv2/optflow.hpp>
#include<iostream>
#include<fstream>
#include<conio.h>
#include<cmath>
#define MHI_DURATION 0.5
using namespace cv;
using namespace cv::motempl;
using namespace std;
char key;
char mode;
short frames=0;
short ycount = 0;
//text file for writing Cmotion
//plik tekstowy do zapisywania wspolczynnika C
ofstream coeff("motion_coeff.txt");
ofstream stdevs("stanard_deviations.txt");
ofstream stdevs2("stdevs.csv");
//MOG2
Ptr<BackgroundSubtractorMOG2> pMOG2 = createBackgroundSubtractorMOG2(500, 64);
double odchylenie(vector<double> v);
bool fallDetect(double cmot,double theta,double ab,double y);
int main()
{
//initial Mat's
//poczatkowe Mat-y
Mat frame;
Mat gray;
Mat mhi;
Mat eroded, dilated;
stdevs2 << "Theta,ab,y\n";
VideoCapture cap("video.mp4");
//VideoCapture cap;
//cap.open(0);
//wektory do odchylen
vector<double> angles;
vector<double> a_to_b;
vector<double> ycoord;
while ((char)key != 'q' && (char)key != 27) {
key = 0;
frames += 1;
stringstream dev_theta, dev_atob,dev_y;
double timestamp = (double)clock() / CLOCKS_PER_SEC;
//securing input
//Zabezpieczenie przed brakiem obrazu zrodlowego
if (!cap.isOpened()) {
cerr << "Zrodlo wideo nie jest zdefiniowane!";
exit(EXIT_FAILURE);
}
//securing next frame
//Zabezpieczenie przed brakiem nastepnej ramki
if (!cap.read(frame)) {
cerr << "Nie mozna odczytac kolejnej klatki!";
exit(EXIT_FAILURE);
}
//main algorithm
//dodatkowe Mat-y i zmienne pomocnicze
Mat eroded, dilated;
Mat mask, bin_mask;
double mot_coeff = 0.0;
double mhi_sum = 0.0;
double fg_sum = 0.0;
//resizing mhi
//dostosowanie formatu i wymiaru mhi
Size size = frame.size();
if (mhi.size() != size) {
mhi = Mat::zeros(size, CV_32F);
}
//morphological cleaning
//"oczyszczenie" obrazu - morfologia
erode(frame, eroded, Mat(), Point(-1, -1), 3);
dilate(eroded, dilated, Mat(6, 6, CV_32F), Point(-1, -1), 3);
//MOG2 applying to imgae
//nalozenie maski do mikstur gaussowskich
pMOG2->apply(dilated, mask);
//threshhold
//binaryzacja i poszukiwanie najwiekszego konturu
threshold(mask, bin_mask, 10, 255, THRESH_BINARY);
blur(bin_mask.clone(), bin_mask, Size(3, 3));
//calculcating MHI
//obliczenie MHI - Motion History
updateMotionHistory(bin_mask, mhi, timestamp, MHI_DURATION);
//calculating Cmotion - finding contours
//policzenie bialych pikseli w obu obrazach - wykrywany kontury
double white_mhi = (mhi.rows * mhi.cols) - countNonZero(mhi);
double white_fg = (bin_mask.rows * bin_mask.cols) - countNonZero(bin_mask);
mot_coeff = 1 - (white_mhi / white_fg);
cout << mot_coeff << endl;
vector<vector<Point>> contours;
double largest_contour = 0;
int largest_id = 0;
findContours(bin_mask, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
for (int i = 0; i < contours.size(); i++) {
double area = contourArea(contours[i], false);
if (area > largest_contour) {
largest_contour = area;
largest_id = i;
}
}
//fitting ellipse to the biggest blob
//nalozenie elipsy na najwiekszy kontur
RotatedRect ell;
if (contours.size() > 0 & contours[largest_id].size() >= 5) {
ell = fitEllipse(contours[largest_id]);
ellipse(frame, ell, Scalar(0, 0, 255), 2, 8);
angles.push_back(ell.angle);
a_to_b.push_back(ell.size.width / ell.size.height);
//dodanie do wektorow wartosci y
if (ycount >= 30) {
ycount = 0;
ycoord.clear();
}
ycoord.push_back(ell.center.y);
ycount += 1;
}
//usuwany jest pierwszy element, jesli jest pusty
//if(isnan(a_to_b[0])) {
// a_to_b.erase(a_to_b.begin());
//}
if (angles.size() > 1 & a_to_b.size() > 1) {
double std_angle = 0.0;
double std_a_to_b = 0.0;
double std_y = 0.0;
std_angle = odchylenie(angles);
std_a_to_b = odchylenie(a_to_b);
std_y = odchylenie(ycoord);
//na razie wpisanie tego do pliku
stdevs << "Std_angle: " << std_angle << ", std_a_to_b: " << std_a_to_b << ", std_y: " << std_y << "\n";
stdevs2 << std_angle << "," << std_a_to_b << "," << std_y << "\n";
dev_theta << "Dev theta: " << std_angle;
dev_atob << "Dev atob: " << std_a_to_b;
dev_y << "Dev y: " << std_y;
if (fallDetect(mot_coeff, std_angle, std_a_to_b, std_y) == true) {
putText(frame, "FALL DETECTED", Point(frame.cols - 100,10), FONT_HERSHEY_DUPLEX, 0.5, Scalar(0, 255, 0), 1, 8);
}
}
//wypisanie na ekran
stringstream ss,y;
ss << "Motion coeff: " << mot_coeff;
putText(frame, ss.str(), Point(10, 10), FONT_HERSHEY_DUPLEX, 0.5, Scalar(0, 0, 255), 1, 8);
putText(frame, dev_theta.str(), Point(10, 30), FONT_HERSHEY_DUPLEX, 0.5, Scalar(0, 0, 255), 1, 8);
putText(frame, dev_atob.str(), Point(10, 50), FONT_HERSHEY_DUPLEX, 0.5, Scalar(0, 0, 255), 1, 8);
putText(frame, dev_y.str(), Point(10, 70), FONT_HERSHEY_DUPLEX, 0.5, Scalar(0, 0, 255), 1, 8);
//writing down the Cmotion to file
coeff << "Motion coefficient at frame " << frames << ": " << mot_coeff << "\n";
//showing results
imshow("Original image", frame);
imshow("MOG2 mask", bin_mask);
imshow("MHI", mhi);
//przerwa na wcisniecie klawisza
key = (char)waitKey(50);
}
cap.release();
cv::destroyAllWindows();
return 0;
}
//odchylenie
double odchylenie(vector<double> v)
{
int sum = 0;
for (int i = 0; i<v.size(); i++)
sum += v[i];
double ave = sum / v.size();
double E = 0;
for (int i = 0; i<v.size(); i++)
E += (v[i] - ave)*(v[i] - ave);
return sqrt(E / v.size());
}
//sprawdzenie warunkow upadku
bool fallDetect(double cmot, double theta, double ab, double y)
{
//wartosci wyznaczone empirycznie - przy lepszym dopasowaniu elips mozna by sie pokusic o unormowanie tych wartosci
if (cmot > 0.12) {
if (theta > 0 & ab > 0) {
if (y > 0) {
return true;
}
}
}
else {
return false;
}
}
|
/*
* Copyright (c) 2014, Julien Bernard
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <mm/thermal_erosion.h>
namespace mm {
heightmap thermal_erosion::operator()(const heightmap& src) const {
double d[3][3];
heightmap map(src);
heightmap material(size_only, src);
for (size_type k = 0; k < m_iterations; ++k) {
// initialize material map
for (size_type x = 1; x < material.width() - 1; ++x) {
for (size_type y = 1; y < material.height() - 1; ++y) {
material(x, y) = 0.0;
}
}
// compute material map
for (size_type x = 1; x < src.width() - 1; ++x) {
for (size_type y = 1; y < src.height() - 1; ++y) {
double d_total = 0.0;
double d_max = 0.0;
for (int i = -1; i <= 1; ++i) {
for (int j = -1; j <= 1; ++j) {
double diff = map(x, y) - map(x+i, y+j);
d[1+i][1+j] = diff;
if (diff > m_talus) {
d_total += diff;
if (diff > d_max) {
d_max = diff;
}
}
}
}
for (int i = -1; i <= 1; ++i) {
for (int j = -1; j <= 1; ++j) {
double diff = d[1+i][1+j];
if (diff > m_talus) {
material(x+i, y+j) += m_fraction * (d_max - m_talus) * (diff / d_total);
}
}
}
}
}
// add material map to the map
for (size_type x = 1; x <= map.width() - 2; ++x) {
for (size_type y = 1; y <= map.height() - 2; ++y) {
map(x, y) += material(x, y);
}
}
}
return map;
}
}
|
// 50. Write a program in C++ to enter length in centimeter and convert it into meter and kilometer.
#include<iostream>
using namespace std;
int main()
{
float km, met,cent;
cout<<"Enter the distance in centimeter:";
cin>>cent;
met = (cent/100);
km = (cent/100000);
cout << " The distance in meter is: "<< met << endl;
cout << " The distance in kilometer is: "<< km << endl;
cout << endl;
return 0;
}
|
#include <iostream>
#include<vector>
using namespace std;
class Union {
public:
Union(size_t size = 10) :SIZE(size) { parent = vector<int>(SIZE); weight = vector<int>(SIZE); for (auto i = 0; i < SIZE; ++i) { parent[i] = i; weight[i] = 0; } }
void union_element(int source, int destination);
bool if_connected(int first,int second);
size_t count() { return SIZE; }
int find();
void traverse() { for (auto i = 0; i < SIZE; ++i) cout << parent[i] << ends; cout << endl; }
private:
size_t SIZE;
vector<int>parent;
vector<int>weight;
};
void Union::union_element(int destination, int source) {
if (!if_connected(destination, source)) {
while (parent[source] != source) { parent[source] = parent[parent[source]]; source = parent[source]; }
while (parent[destination] != destination) { parent[destination]=parent[parent[destination]]; destination = parent[destination]; }
if (weight[source] >= weight[destination])
{
parent[destination] = source;
weight[source]++;
weight[source]+=weight[destination];
}
else
{
parent[source] = destination;
weight[destination]++;
weight[destination]+=weight[source];
}
}
traverse();
}
bool Union::if_connected(int first, int second) {
while (parent[first] != first) { first = parent[first]; }
while (parent[second] != second) { second = parent[second]; }
return first==second?true:false; }
int main()
{
Union a;
a.union_element(3,4);
a.union_element(3, 8);
a.union_element(5, 6);
a.union_element(9, 4);
a.union_element(1, 2);
a.union_element(0, 5);
a.union_element(7, 2);
a.union_element(1, 6);
a.union_element(7, 3);
a.union_element(4, 6);
}
|
//
// Created by Sweet Acid on 02.05.2021.
//
#pragma once
#include <Snow.h>
class ExampleWindow : public Snow::GUIWindow {
private:
int corner = 0;
public:
ExampleWindow() {
name = "Statistics";
window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav;
}
void pre_begin() override {
ImGuiIO& io = ImGui::GetIO();
if (corner != -1)
{
const float PAD = 10.0f;
const ImGuiViewport* viewport = ImGui::GetMainViewport();
ImVec2 work_pos = viewport->WorkPos; // Use work area to avoid menu-bar/task-bar, if any!
ImVec2 work_size = viewport->WorkSize;
ImVec2 window_pos, window_pos_pivot;
window_pos.x = (corner & 1) ? (work_pos.x + work_size.x - PAD) : (work_pos.x + PAD);
window_pos.y = (corner & 2) ? (work_pos.y + work_size.y - PAD) : (work_pos.y + PAD);
window_pos_pivot.x = (corner & 1) ? 1.0f : 0.0f;
window_pos_pivot.y = (corner & 2) ? 1.0f : 0.0f;
ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
ImGui::SetNextWindowViewport(viewport->ID);
window_flags |= ImGuiWindowFlags_NoMove;
}
ImGui::SetNextWindowBgAlpha(0.65f); // Transparent background
}
void update() override {
ImGui::LabelText("FPS", "%f", 1 / Snow::Time::deltaTime);
ImGui::Separator();
ImGuiIO& io = ImGui::GetIO();
if (ImGui::IsMousePosValid())
ImGui::Text("Mouse Position: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y);
else
ImGui::Text("Mouse Position: <invalid>");
if (ImGui::BeginPopupContextWindow())
{
if (ImGui::MenuItem("Custom", NULL, corner == -1)) corner = -1;
if (ImGui::MenuItem("Top-left", NULL, corner == 0)) corner = 0;
if (ImGui::MenuItem("Top-right", NULL, corner == 1)) corner = 1;
if (ImGui::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2;
if (ImGui::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3;
if (collapsed && ImGui::MenuItem("Close")) collapsed = false;
ImGui::EndPopup();
}
}
};
|
/*
===============================================================================
Name : main.c
Author : $(author)
Version :
Copyright : $(copyright)
Description : main definition
===============================================================================
*/
#if defined (__USE_LPCOPEN)
#if defined(NO_BOARD_LIB)
#include "chip.h"
#else
#include "board.h"
#endif
#endif
#include "DigitalIOPin.h"
#include <cr_section_macros.h>
#include <mutex>
#include "syslog.h"
#include <semphr.h>
#include <queue.h>
#include <stdio.h>
#include <stdlib.h>
#include "ITM_write.h"
#include <string.h>
// TODO: insert other include files here
// TODO: insert other definitions and declarations here
#include "FreeRTOS.h"
#include "task.h"
QueueSetHandle_t queueLine;
SemaphoreHandle_t learning;
SemaphoreHandle_t nothing;
int filterTime = 50;
struct swEvent{
uint8_t sendVal;
uint32_t ticks;
};
static void Interrupt_init()
{
// assign interrupts to pins
Chip_INMUX_PinIntSel(0, 0, 17); //sw1
Chip_INMUX_PinIntSel(1, 1, 11); //sw2
Chip_INMUX_PinIntSel(2, 1, 9); //sw3
// enable clock for GPIO interrupt
Chip_PININT_Init(LPC_GPIO_PIN_INT);
// Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_PININT);
// Enable IRQ
NVIC_EnableIRQ(PIN_INT0_IRQn);
NVIC_EnableIRQ(PIN_INT1_IRQn);
NVIC_EnableIRQ(PIN_INT2_IRQn);
// Set Interrupt priorities
NVIC_SetPriority(PIN_INT0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1);
NVIC_SetPriority(PIN_INT1_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1);
NVIC_SetPriority(PIN_INT2_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1);
// interrupt at falling edge, clear initial status
Chip_PININT_SetPinModeEdge(LPC_GPIO_PIN_INT, PININTCH0);
Chip_PININT_EnableIntLow(LPC_GPIO_PIN_INT, PININTCH0);
Chip_PININT_ClearIntStatus(LPC_GPIO_PIN_INT, PININTCH0);
Chip_PININT_SetPinModeEdge(LPC_GPIO_PIN_INT, PININTCH1);
Chip_PININT_EnableIntLow(LPC_GPIO_PIN_INT, PININTCH1);
Chip_PININT_ClearIntStatus(LPC_GPIO_PIN_INT, PININTCH1);
Chip_PININT_SetPinModeEdge(LPC_GPIO_PIN_INT, PININTCH2);
Chip_PININT_EnableIntLow(LPC_GPIO_PIN_INT, PININTCH2);
Chip_PININT_ClearIntStatus(LPC_GPIO_PIN_INT, PININTCH2);
NVIC_ClearPendingIRQ(PIN_INT0_IRQn);
NVIC_ClearPendingIRQ(PIN_INT1_IRQn);
NVIC_ClearPendingIRQ(PIN_INT2_IRQn);
}
static void prvSetupHardware(void)
{
SystemCoreClockUpdate();
Board_Init();
/* Initial LED0 state is off */
Board_LED_Set(0, false);
ITM_init();
Interrupt_init();
// initialize RIT (= enable clocking etc.)
Chip_RIT_Init(LPC_RITIMER);
// set the priority level of the interrupt
// The level must be equal or lower than the maximum priority specified in FreeRTOS config
// Note that in a Cortex-M3 a higher number indicates lower interrupt priority
NVIC_SetPriority( RITIMER_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1 );
}
void queueFunction(int i)
{
swEvent e;
e.sendVal = i;
e.ticks = xTaskGetTickCountFromISR();
portBASE_TYPE xHigherPriorityWoken = pdFALSE;
xQueueSendToBackFromISR(queueLine, &e, &xHigherPriorityWoken);
}
extern "C" {
void PIN_INT0_IRQHandler() {
Chip_PININT_ClearIntStatus(LPC_GPIO_PIN_INT, PININTCH0);
int val = 0;
queueFunction(val);
}
void PIN_INT1_IRQHandler() {
Chip_PININT_ClearIntStatus(LPC_GPIO_PIN_INT, PININTCH1);
int val1 = 1;
queueFunction(val1);
}
void PIN_INT2_IRQHandler() {
Chip_PININT_ClearIntStatus(LPC_GPIO_PIN_INT, PININTCH2);
int val1 = 2;
queueFunction(val1);
}
}
static void vMonitorTask(void *pvParameters) {
DigitalIoPin sw1(17,0, true, true, false);
DigitalIoPin sw2(11,1, true, true, false);
DigitalIoPin sw3(9, 1, true, true, false);
int monitorTime = 0;
int nothingTime = 0;
bool sw1press;
bool sw2press;
bool sw3press;
while(1){
sw1press = sw1.read();
sw2press = sw2.read();
sw3press = sw3.read();
if (sw3press == true ){
monitorTime++;
if(monitorTime == 3000){
xSemaphoreGive(learning);
}
}else{
monitorTime = 0;
}
if (sw1press == false && sw2press == false && sw3press == false ){
nothingTime++;
}else{nothingTime = 0;}
if(nothingTime == 14000){
xSemaphoreGive(nothing);
}
vTaskDelay(1);
}
}
static void vReadTask(void *pvParameters) {
char key[9] = {1,1,1,1,0,1,1,0};
char input_buffer[9] = {255,255,255,255,255,255,255,255};
int input_buffer_pos = 0;
int prev_input_time = 0;
int key_index = 0;
char debug[50];
//int ascii_conv_add = 48;
swEvent e;
const int input_interval_ms = 50;
while(true)
{
xQueueReceive(queueLine,&e,portMAX_DELAY);
if (e.ticks - prev_input_time > input_interval_ms)
{
sprintf(debug, "input: %d buffer: ", e.sendVal);
ITM_write(debug);
input_buffer[input_buffer_pos] = e.sendVal;
bool match = true;
int check_pos = input_buffer_pos + 1;
for (int i = 0; i < 8; i++)
{
if (check_pos > 7) check_pos = 0;
int val0 = (int)input_buffer[check_pos];
int val1 = (int)key[i];
sprintf(debug, "%d-%d ", val0, val1);
//sprintf(debug, "%d, ", val0);
ITM_write(debug);
if (val0 != val1) match = false;
check_pos++;
}
ITM_write("\r\n");
if (match)
{
ITM_write("match!\n");
Board_LED_Set(0, false);
Board_LED_Set(1, true);
vTaskDelay(5000);
Board_LED_Set(1, false);
Board_LED_Set(0, true);
}
//learning mode
if (xSemaphoreTake(learning,1) == pdPASS)
{
ITM_write("Start learning.\n");
Board_LED_Set(0, false);
Board_LED_Set(2, true);
while(key_index < 8)
{
if (e.ticks - prev_input_time > input_interval_ms)
{
xQueueReceive(queueLine,&e,portMAX_DELAY);
key[key_index] = e.sendVal;
sprintf(debug, "%d, ", (int)key[key_index]);
ITM_write(debug);
key_index++;
}
}
ITM_write("\r\n");
key_index = 0;
Board_LED_Set(2, false);
}
if (xSemaphoreTake(nothing,1) == pdPASS)memset(input_buffer, 225, 9);
input_buffer_pos++;
if (input_buffer_pos > 7) input_buffer_pos = 0;
prev_input_time = e.ticks;
}
vTaskDelay(10);
}
}
extern "C" {
void vConfigureTimerForRunTimeStats( void ) {
Chip_SCT_Init(LPC_SCTSMALL1);
LPC_SCTSMALL1->CONFIG = SCT_CONFIG_32BIT_COUNTER;
LPC_SCTSMALL1->CTRL_U = SCT_CTRL_PRE_L(255) | SCT_CTRL_CLRCTR_L; // set prescaler to 256 (255 + 1), and start timer
}
}
int main(void)
{
prvSetupHardware();
queueLine = xQueueCreate(8, sizeof(swEvent));
learning = xSemaphoreCreateBinary();
nothing = xSemaphoreCreateBinary();
xTaskCreate(vMonitorTask, "vTaskMonitor",
configMINIMAL_STACK_SIZE *3 , NULL, (tskIDLE_PRIORITY + 1UL),
(TaskHandle_t *) NULL);
xTaskCreate(vReadTask, "vTaskRead",
configMINIMAL_STACK_SIZE *3 , NULL, (tskIDLE_PRIORITY + 1UL),
(TaskHandle_t *) NULL);
vTaskStartScheduler();
return 1;
}
|
// github.com/andy489
// AutoComplete Trie
#include <iostream>
#include <vector>
#include <map>
using namespace std;
struct Node {
bool end;
map<char, Node*> children;
Node(bool end = false) :end(end) {}
};
struct Trie {
Node* root = new Node();
void insert(const string& word) {
Node* curr = root;
int len(word.length()), i;
for (i = 0; i < len; ++i) {
if (curr->children.count(word[i]) == 0) {
curr->children[word[i]] = new Node();
}
curr = curr->children[word[i]];
}
curr->end = true;
}
void dfs(Node* curr, string& prefix) {
if (curr->end) {
cout << prefix << '\n';
}
for (pair<char, Node*>kvp : curr->children) {
prefix.push_back(kvp.first);
dfs(kvp.second, prefix);
prefix.pop_back();
}
}
void search(string& prefix) {
Node* curr = root;
int len(prefix.length()), i;
for (i = 0;i < len;++i) {
if (curr->children.count(prefix[i]) == 0) {
return;
}
curr = curr->children[prefix[i]];
}
dfs(curr, prefix);
}
};
int main() {
Trie autoComplete;
string prefix;
autoComplete.insert("unicorn celociraptor");
autoComplete.insert("rewrite");
autoComplete.insert("unpack");
autoComplete.insert("reconsider");
autoComplete.insert("upgrade");
autoComplete.insert("undo");
autoComplete.insert("underestimate");
autoComplete.insert("uphill");
autoComplete.insert("redo");
for (size_t i = 0; i < 3; i++) {
cin >> prefix;
autoComplete.search(prefix);
}
return 0;
}
|
#ifndef POOL
#define POOL
#include <iostream>
#include <vector>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include "Event.hpp"
#include "TargetPointChangeEvent.hpp"
#include "MoveLeftEvent.hpp"
#include "MoveRightEvent.hpp"
#include "MoveUpEvent.hpp"
#include "RollLeftEvent.hpp"
#include "RollRightEvent.hpp"
#include "ShotEvent.hpp"
#include "Menu.hpp"
using namespace std;
using namespace sf;
static SocketTCP mSocket;
static vector<GameEvent*>* Messages;
static vector<GameEvent*>* MessagesToSend;
class Pool {
public:
int id;
Pool() {
Messages = new vector<GameEvent*>();
MessagesToSend = new vector<GameEvent*>();
cout<<"\nPOOL created\n";
}
void start() {
cout<<"\n\tSTART\n";
SocketTCP* pSocket;
GameEvent* ev = new GameEvent("INIT");
GameEvent* iv = new GameEvent("INIT");
MessagesToSend->push_back(ev);
Messages->push_back(iv);
Thread* ThreadSendMess = new Thread(&ThreadSendMessFunc);
Thread* ThreadReceiveMess = new Thread(&ThreadReceiveMessFunc, this);
ThreadSendMess -> Launch();
ThreadReceiveMess -> Launch();
cout<<"\n\tstart END\n";
}
//Figyeli a socket-et, ha stringet kap cast-olja a megfelelő típusú üzenetté, és a Messages vektorba teszi.
void static ThreadReceiveMessFunc(void* UserData) {
cout << "\nReceiveThread START\n";
while (true) {
string s = ReceiveMess(mSocket);
cout<<"ezt kaptam: "<<s;
if(s.at(0) == '1'){
TargetPointChangeEvent* ge = new TargetPointChangeEvent(s);
Messages->push_back(ge);
}
if(s.at(0) == '2'){
MoveLeftEvent* mle = new MoveLeftEvent();
Messages->push_back(mle);
}
if(s.at(0) =='3'){
MoveRightEvent* mre = new MoveRightEvent();
Messages->push_back(mre);
}
if(s.at(0) =='4'){
MoveUpEvent* mue = new MoveUpEvent();
Messages->push_back(mue);
}
if(s.at(0) =='5'){
MoveDownEvent* mde = new MoveDownEvent();
Messages->push_back(mde);
}
if(s.at(0) =='7'){
RollLeftEvent* rle = new RollLeftEvent();
Messages->push_back(rle);
}
if(s.at(0) =='8'){
RollRightEvent* rre = new RollRightEvent();
Messages->push_back(rre);
}
if(s.at(0) =='9'){
GranadeThrowedEvent* gte = new GranadeThrowedEvent();
Messages->push_back(gte);
}
if(s.at(0)=='#'){//"#ShotEvent"){
cout<<"Loves van";
ShotEvent* se = new ShotEvent();
Messages->push_back(se);
}
else {
GameEvent* ge = new GameEvent(s);
Messages->push_back(ge);
}
}
}
//visszatér a Messages vektor méretével
int GetMessSize(){
return Messages->size();
}
void static ThreadSendMessFunc(void* UserData) {
cout << "\nSendThread Start\n";
while(true){
if(MessagesToSend->size() > 0){
GameEvent* ev;
if(MessagesToSend->size()>0){
ev = MessagesToSend->at(0);
} else {
ev = new GameEvent("NULL");
}
string s;
s = ev->EventToString();
// cout<<"ezt kuldom: "<<s;
if(s.at(0)!='N'){
SendMess(mSocket, s);
vector<GameEvent*>::iterator i = MessagesToSend->begin();
MessagesToSend->erase(i);
}
}
//Sleep(1.0f);
}
}
//MessagesToSend vektorba beletesz egy eventet
static void AddMess(GameEvent* ev){
MessagesToSend->push_back(ev);
// cout<<ev->EventToString()<<" lett hozzaadva\n\n";
}
//Messages vektorba beletesz egy eventet
static void AddMess2(GameEvent* ev){
Messages->push_back(ev);
}
//Visszatér a Messages vektor első elemével, majd kitörli azt
static GameEvent* GetMess(){
GameEvent* tp;
if(Messages->size()>0){
tp = Messages->at(0);
} else {
tp = new GameEvent("NULL");
}
if(tp->EventToString().at(1) == 'N'){
} else {
vector<GameEvent*>::iterator i = Messages->begin();
Messages->erase(i);
}
return tp;
}
static void SendMess(SocketTCP mSock, string s) {
char ToSend[s.size()];
for (int i =0; i<s.size(); i++) {
ToSend[i] = s[i];
}
if (mSock.Send(ToSend, sizeof(ToSend)) != sf::Socket::Done) {
cout<< "\n\nError in SendMess";
} else {
// cout<< "Message sent";
}
}
static string ReceiveMess(SocketTCP mSock) {
string s="";
char Message[50];
std::size_t Received;
if (mSock.Receive(Message, sizeof(Message), Received) != sf::Socket::Done)
return "-";
for (int i = 0; i<40; i++) {
s+= Message[i];
}
return s;
}
};
#endif
|
#include "statistics.h"
void Statistics::UpdateStatistics(int iteration)
{
{
if (sai.verbose)
{
DumpAllCustomers();
}
firstTimeUntilServ.UpdateMean();
firstTimeServ.UpdateMean();
secondTimeUntilServ.UpdateMean();
secondTimeServ.UpdateMean();
firstPrimary.UpdateMean();
secondHigh.UpdateMean();
secondLow.UpdateMean();
middle.UpdateMean();
if (stationaryMode)
{
ofstream file_(sai.outFiles.stationaryFileMeans, ofstream::out | ofstream::app );
DumpStatsMean(file_); file_<<endl;
// this->firstTimeUntilServ.Print_errs();
// cout<<endl;
}
}
}
void Statistics::DumpAllCustomers()
{
ofstream file1(sai.outFiles.firstCustomersFile, ofstream::out | ofstream::app );
ofstream file2(sai.outFiles.secondCustomersFile, ofstream::out | ofstream::app );
for (auto& a : departFirstQueue)
a.Dump(file1);
for (auto& a : departSecondQueue)
a.Dump(file2);
}
void Statistics::AddFirstCustomer(Customer cust)
{
long untilServ = cust.serviceTime - cust.arrivalTime,
serv = cust.departureTime - cust.serviceTime;
if (untilServ < 0 || serv <= 0)
{
cout <<" "<<cust.arrivalTime<<" "<<cust.serviceTime<<" "<<cust.departureTime<<";";
cout <<untilServ << " "<<serv<<" < 0"<<endl;
exit(1);
}
else
{
firstTimeUntilServ.values.push_back(untilServ);
firstTimeServ.values.push_back(serv);
departFirstQueue.push_back(cust);
}
}
void Statistics::AddSecondCustomer(Customer cust)
{
secondTimeUntilServ.values.push_back(cust.serviceTime - cust.arrivalTime);
secondTimeServ.values.push_back(cust.departureTime - cust.serviceTime);
departSecondQueue.push_back(cust);
}
void Statistics::AddStatistics(Statistics& s)
{
firstTimeUntilServ.AddMeans(s.firstTimeUntilServ);
firstTimeServ.AddMeans(s.firstTimeServ);
secondTimeUntilServ.AddMeans(s.secondTimeUntilServ);
secondTimeServ.AddMeans(s.secondTimeServ);
firstPrimary.AddMeans(s.firstPrimary);
secondHigh.AddMeans(s.secondHigh);
secondLow.AddMeans(s.secondLow);
middle.AddMeans(s.middle);
}
void Statistics::Print(ostream& outStream)
{
outStream << "FirstTimeUntilServ:";
firstTimeUntilServ.Print(outStream);
outStream << "FirstTimeServ:";
firstTimeServ.Print(outStream);
outStream << "SecondTimeUntilServ:";
secondTimeUntilServ.Print(outStream);
outStream << "SecondTimeServ:";
secondTimeServ.Print(outStream);
outStream<<endl;
outStream << "FirstPrimary queue:";
firstPrimary.Print(outStream);
outStream << "SecondHigh queue:";
secondHigh.Print(outStream);
outStream << "SecondLow queue:";
secondLow.Print(outStream);
outStream << "Middle queue:";
middle.Print(outStream);
}
void Statistics::ClearStatistics()
{
// cout<<"Clearing stats"<<endl;
firstTimeUntilServ.Clear();
firstTimeServ.Clear();
secondTimeUntilServ.Clear();
secondTimeServ.Clear();
firstPrimary.Clear();
secondHigh.Clear();
secondLow.Clear();
middle.Clear();
loadStatistics.inputNumLow =
loadStatistics.theoreticalNumLow =
loadStatistics.inputNumHigh =
loadStatistics.theoreticalNumHigh = 0;
// timesLocate[0] = timesLocate[1] = timesLocate[2] = 0;
// timesLocateTimes[0] = timesLocateTimes[1] = timesLocateTimes[2] = 0;
}
void Statistics::DumpStatsMean(ofstream& _stream)
{
firstTimeUntilServ.DumpMeans(_stream);
firstTimeServ.DumpMeans(_stream);
secondTimeUntilServ.DumpMeans(_stream);
secondTimeServ.DumpMeans(_stream);
firstPrimary.DumpMeans(_stream);
secondHigh.DumpMeans(_stream);
secondLow.DumpMeans(_stream);
middle.DumpMeans(_stream);
}
void MyMean::UpdateMean()
{
double old_sum = mean,
old_sum_sq = mean_sq;
double sum = mean * num,
sum_sq = mean_sq * num;
for (auto& a: values)
{
sum += a;
sum_sq += a*a;
if (a < 0)
cout <<a<<endl;
}
num += values.size();
if (num > 0)
{
mean = sum/num;
mean_sq = sum_sq/num;
values.clear();
}
if (old_sum > 0)
diff = std::abs(old_sum - mean)/old_sum;
else
diff = 1.;
double old_std = std::sqrt(double(old_sum_sq - old_sum * old_sum)),
new_std = std::sqrt(double(mean_sq - mean*mean));
if (old_std > 0)
diff_std = std::abs(old_std - new_std)/double(old_std);
else
diff_std = 1.;
//Error est
double tmp_est = est_err * est_num,
tmp_est_sq = est_err_sq * est_num;
tmp_est += mean;
tmp_est_sq += mean*mean;
est_num++;
est_err = tmp_est/est_num;
est_err_sq = tmp_est_sq/est_num;
}
void MyMean::AddMeans(MyMean& m)
{
double old_sum = mean,
old_sum_sq = mean_sq;
this->UpdateMean();
m.UpdateMean();
mean = mean * num + m.mean * m.num;
mean_sq = mean_sq * num + m.mean_sq * m.num;
num += m.num;
if (num > 0)
{
mean /= num;
mean_sq /= num;
}
if (old_sum > 0)
diff = std::abs(old_sum - mean)/old_sum;
else
diff = 1.;
double old_std = std::sqrt(double(old_sum_sq - old_sum * old_sum)),
new_std = std::sqrt(double(mean_sq - mean*mean));
if (old_std > 0)
diff_std = std::abs(old_std - new_std)/double(old_std);
else
diff_std = 1.;
}
|
#include "processor.h"
#include "linux_parser.h"
#include <fstream>
#include <string>
// TODO: Return the aggregate CPU utilization
float Processor::Utilization() {
std::ifstream filestream(LinuxParser::kProcDirectory + LinuxParser::kStatFilename);
if (filestream.is_open()){
std::string line;
std::getline(filestream,line);
std::istringstream sstr(line);
std::string ignore;
float user, nice, system, irq, idle, iowait, softirq, steal;
sstr >> ignore >> user >> nice >> system >> irq >> idle >> iowait >> softirq >> steal;
/*
PrevIdle = previdle + previowait
Idle = idle + iowait
PrevNonIdle = prevuser + prevnice + prevsystem + previrq + prevsoftirq + prevsteal
NonIdle = user + nice + system + irq + softirq + steal
PrevTotal = PrevIdle + PrevNonIdle
Total = Idle + NonIdle
# differentiate: actual value minus the previous one
totald = Total - PrevTotal
idled = Idle - PrevIdle
CPU_Percentage = (totald - idled)/totald
*/
float Idle = idle + iowait;
float NonIdle = user + nice + system +irq + softirq + steal;
float Total = Idle + NonIdle;
float totald = Total - PrevTotal;
float idled = Idle - PrevIdle;
prev_user = user;
prev_nice = nice;
prev_system = system;
prev_irq = idle;
prev_iowait = iowait;
prev_softirq = softirq;
prev_steal = steal;
return (totald - idled)/totald;
}
return 0.;
}
|
#include <iomanip>
#include <string>
#include <sdf_tracker.h>
#include <opencv2/opencv.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
int main(int argc, char* argv[])
{
boost::filesystem::path p(argv[1]);
//Parameters for an SDFtracker object
SDF_Parameters myParameters;
myParameters.interactive_mode = true;
myParameters.resolution = 0.04;
myParameters.Dmax = 0.2;
myParameters.Dmin = -0.1;
// The sizes can be different from each other
// +Y is up +Z is forward.
myParameters.XSize = 350;
myParameters.YSize = 100;
myParameters.ZSize = 500;
myParameters.image_width = 640;
myParameters.image_height = 480;
myParameters.fx = 525.0;
myParameters.fy = 525.0;
myParameters.cx = 320;
myParameters.cy = 240;
//Pose Offset as a transformation matrix
// Eigen::Matrix4d initialTransformation =
// Eigen::MatrixXd::Identity(4,4);
//define translation offsets in x y z if you want to offset the camera relative to the TSDF volume
// initialTransformation(0,3) = 0.0; //x
// initialTransformation(1,3) = 0.0; //y
// initialTransformation(2,3) = static_cast<double>( - 0.5 * myParameters.ZSize * myParameters.resolution) -0.44; //z
// myParameters.pose_offset = initialTransformation;
SDFTracker myTracker(myParameters);
cv::Mat depth(480,640,CV_32FC1);
Vector6d poseVector;
Eigen::Matrix4d currentTransformation;
std::stringstream ss;
std::string image_list_path = p.string() + "/assoc.txt";
if(!boost::filesystem::is_regular_file(image_list_path)) // is p a regular file?
{
std::cout << image_list_path << " is not a regular file!" << '\n';
exit(1);
}
std::string image_list_line;
std::string depth_img_filename;
double timestamp_depth_image;
std::ifstream image_list_file(image_list_path.c_str());
try
{
if (boost::filesystem::exists(p)) // does p actually exist?
{
if (boost::filesystem::is_regular_file(p)) // is p a regular file?
{
std::cout << p << " is a file, not a directory!" << '\n';
exit(1);
}
else if (boost::filesystem::is_directory(p)) // is p a directory?
{
if(!boost::filesystem::exists(p.string() + "/trajectory"))
boost::filesystem::create_directory(p.string() + "/trajectory");
std::ofstream output(p.string() + "/trajectory/trajectory.txt");
while(std::getline(image_list_file,image_list_line))
{
std::istringstream iss( image_list_line );
std::string result;
std::getline(iss, result,' ');
if(result.empty()) continue;
ss << result;
ss >> timestamp_depth_image;
ss >> depth_img_filename;
ss.clear();
depth_img_filename = p.string() + "/depth/" + std::to_string(timestamp_depth_image) +".png";
std::cout << "processing: " << depth_img_filename << '\n';
depth = cv::imread(depth_img_filename.c_str(), CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR );
if( !depth.data )// Check for invalid input
{
std::cerr << "Could not open or find the depth image" << std::endl ;
break;
}
depth.convertTo(depth, CV_32FC1);
depth/=5000.f;
cv::imshow("debug",depth/10.0f);
cv::waitKey(3);
myTracker.UpdateDepth(depth);
poseVector = myTracker.EstimatePoseFromDepth();
currentTransformation = myTracker.Twist(poseVector).exp()*myTracker.GetCurrentTransformation();
myTracker.SetCurrentTransformation(currentTransformation);
myTracker.FuseDepth();
myTracker.Render();
Eigen::Matrix3d Rot3d;
Rot3d << currentTransformation(0,0), currentTransformation(0,1), currentTransformation(0,2),
currentTransformation(1,0), currentTransformation(1,1), currentTransformation(1,2),
currentTransformation(2,0), currentTransformation(2,1), currentTransformation(2,2);
Eigen::AngleAxisd aa; aa = Rot3d;
Eigen::Quaterniond Q;
Q = aa;
if(std::isnan(Q.x())) continue;
const Eigen::Vector4d translation(
currentTransformation(0,3),
currentTransformation(1,3),
currentTransformation(2,3),
1.f);
output << std::setprecision(6) << std::fixed << timestamp_depth_image << " "
<< translation(0) <<" "<< translation(1) <<" "<< translation(2) <<" "
<< Q.x() <<" "<< Q.y() <<" "<< Q.z() <<" "<< Q.w()
<< std::endl;
timestamp_depth_image += 1.0/30.0; // in absence of real time stamps just increment assuming 30Hz
}
}
else
std::cout << p << " exists, but is neither a regular file nor a directory\n";
}
else
std::cout << p << " does not exist\n";
}
catch (const boost::filesystem::filesystem_error& ex)
{
std::cout << ex.what() << '\n';
}
return 0;
}
|
#include "graphics\Singularity.Graphics.h"
using namespace Singularity;
using namespace Singularity::Threading;
using namespace Singularity::Components;
using namespace Singularity::Graphics::Devices;
namespace Singularity
{
namespace Graphics
{
IMPLEMENT_OBJECT_TYPE(Singularity.Graphics, RenderSubTask, Singularity::Threading::Task);
#pragma region Constructors and Finalizers
/*RenderSubTask::RenderSubTask()
: Task("Render Sub-Task"), m_pCamera(NULL), m_pDrawingContext(NULL), m_pBufferedDrawingContext(NULL), m_pIterator(NULL) { }*/
RenderSubTask::RenderSubTask()
: Task("Render Sub-Task"), m_pCamera(NULL), m_pDrawingContext(NULL), m_pDeferredDrawingContext(NULL), m_pIterator(NULL) { }
#pragma endregion
#pragma region Methods
void RenderSubTask::Update(DrawingContext* context, Camera* camera)
{
this->m_pDrawingContext = context;
this->m_pCamera = camera;
}
#pragma endregion
#pragma region Overriden Methods
void RenderSubTask::OnExecute()
{
RenderTask* parent;
Renderer* renderer;
DynamicSet<Light*>::iterator it;
if(this->m_pDrawingContext == NULL || this->m_pCamera == NULL)
return;
parent = (RenderTask*)this->Get_ParentTask();
try
{
//lock(parent->m_kLock)
//{
this->m_pCamera->OnPreCull(this->m_pDrawingContext);
this->m_pCamera->OnPreRender(this->m_pDrawingContext);
if(this->m_pIterator == NULL)
this->m_pIterator = new OctreeIterator<Renderer*>(parent->m_pRenderers);
this->m_pIterator->Reset();
for(it = parent->m_pLights.begin(); it != parent->m_pLights.end(); ++it)
{
if((*it)->Get_Enabled())
this->m_pDrawingContext->AddLight(*it);
}
//Vector3 cameraLoc;
//Vector3 renderLoc;
//
//cameraLoc = m_pCamera->Get_Description().Position;
// Now we can draw them knowing they're all synced.
this->m_pIterator->Reset();
while(this->m_pIterator->Next(renderer))
{
//renderLoc = renderer->Get_GameObject()->Get_Transform()->Get_Position();
//if(Vector3(cameraLoc - renderLoc).length() > 500)
//{
// printf("%d %d %d\n", cameraLoc.x, cameraLoc.y, cameraLoc.z);
// continue;
//}
if(renderer->Get_Enabled() && renderer->Get_IsVisible())
renderer->InternalOnRender(this->m_pDrawingContext, this->m_pCamera);
}
//}
this->m_pCamera->OnRenderImage(this->m_pDrawingContext);
this->m_pCamera->OnPostRender(this->m_pDrawingContext);
}
catch(SingularityException& e)
{
this->m_pDrawingContext->Clear(this->m_pCamera->Get_BackgroundColor());
fprintf(stderr, "An exception has occurred in the RenderSubTask: %s\n", boost::diagnostic_information(e).c_str());
}
}
#pragma endregion
}
}
|
#include "Common.h"
#include "Devices.h"
|
// https://s-kita.hatenablog.com/entry/20130502/1367458848
#include <windows.h>
#include <strsafe.h>
#include <process.h>
#include <stdio.h>
#include <errhandlingapi.h>
#include <iostream>
SERVICE_STATUS ss;
SERVICE_STATUS_HANDLE hss;
BOOL installservice() {
SC_HANDLE hSCM = NULL;
SC_HANDLE hService = NULL;
TCHAR binarypath[MAX_PATH];
SERVICE_DESCRIPTION sd;
BOOL ret = FALSE;
hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if(hSCM==NULL)
goto EXIT;
GetModuleFileName(NULL, binarypath, sizeof(binarypath)/sizeof(binarypath[0]));
hService = CreateService(hSCM,
"ApiPracticeService",
"PracServiceDisplayName",
SERVICE_CHANGE_CONFIG,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_IGNORE,
binarypath,
NULL,
NULL,
NULL,
NULL,
NULL
);
if(hService==NULL)
goto EXIT;
sd.lpDescription = "Sample service application for practice";
ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sd);
ret = TRUE;
EXIT:
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return ret;
}
DWORD WINAPI HandlerEx(DWORD dwControl, DWORD dwEventType, PVOID pvEventData, PVOID pvContext) {
switch(dwControl) {
case SERVICE_CONTROL_STOP:
ss.dwCurrentState = SERVICE_STOPPED;
break;
case SERVICE_CONTROL_SHUTDOWN:
ss.dwCurrentState = SERVICE_STOPPED;
break;
case SERVICE_CONTROL_PAUSE:
ss.dwCurrentState = SERVICE_PAUSED;
break;
case SERVICE_CONTROL_CONTINUE:
ss.dwCurrentState = SERVICE_RUNNING;
break;
default:
break;
}
MessageBox(NULL, "inside HandlerEx", "info", MB_OK);
SetServiceStatus(hss, &ss);
return ERROR_CALL_NOT_IMPLEMENTED;
}
unsigned int WINAPI ServiceThread(LPVOID arg) {
char filename[MAX_PATH];
SYSTEMTIME localtime;
MessageBox(NULL, "inside ServiceThread", "info", MB_OK);
while(1) {
FILE *f = fopen("aabbcc.txt", "a");
if(f!=NULL) {
GetLocalTime(&localtime);
fprintf(f, "%02d:%02d:%02d\n", localtime.wHour, localtime.wMinute, localtime.wSecond);
fclose(f);
}
Sleep(1000);
}
return 0;
}
void WINAPI ServiceEntry(DWORD dwArgs, LPTSTR *pszArgv) {
unsigned int threadid;
HANDLE hThread;
hThread = (HANDLE)_beginthreadex(NULL, 0, ServiceThread, NULL, 0, &threadid);
hss = RegisterServiceCtrlHandlerEx("ApiPracticeService", HandlerEx, NULL);
memset(&ss, 0, sizeof(ss));
ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
ss.dwCurrentState = SERVICE_RUNNING;
ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
ss.dwWin32ExitCode = NO_ERROR;
ss.dwServiceSpecificExitCode = 0;
ss.dwCheckPoint = 0;
ss.dwWaitHint = 2000;
SetServiceStatus(hss, &ss);
MessageBox(NULL, "Service Entry done", "info", MB_OK);
}
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
) {
/*
*if(installservice())
* MessageBox(NULL, "service installation complete!", "success", MB_OK);
*else
* MessageBox(NULL, "service installation failed", "error", MB_OK); // 管理者権限じゃないとFailedになる
*/
SERVICE_TABLE_ENTRY ServiceTableEntry[] = { {"ApiPracticeService",ServiceEntry}, {NULL,NULL} };
if(StartServiceCtrlDispatcher(ServiceTableEntry)==0)
std::cout << "error code: " << GetLastError() << std::endl;
return 0;
}
|
#ifndef POSITIONCOMPONENT_H
#define POSITIONCOMPONENT_H
#include "../Component.h"
class PositionComponent : public Component
{
public:
PositionComponent() { x = 0; y=0;}
PositionComponent(float xx, float yy) { x = xx; y = yy;}
float x;
float y;
};
#endif // POSITIONCOMPONENT_H
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dbmanager.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow), m_testSession{0,0}
{
ui->setupUi(this);
path = "../../database/vocabulary.db";
db = new DbManager(path);
if (db->isOpen()){
QString categories = ("Category");
}
else{
std::string temp = exec("pwd");
qDebug() << "Couldn't open db, current directory: " << QString::fromStdString(temp) ;
}
this->categoryModel = new QSqlQueryModel();
categoryModel->setQuery("SELECT Category FROM Category;");
// m_cat = 3;
// ui->comboBox->setCurrentIndex(m_cat);
ui->comboBox->setModel(categoryModel);
ui->tableView->hide();
}
MainWindow::~MainWindow()
{
db->close();
delete ui;
}
void MainWindow::on_generateTest_button_clicked()
{
processRandomField();
}
void MainWindow::on_validate_pushbutton_clicked()
{
//Compare the typed texted with the database value
if(compareAnswer(ui->answer_lineEdit->text()))
{
qDebug() << "Bravo !";
m_testSession.validAnswer++;
scoreUpdate();
on_generateTest_button_clicked();
}
else
{
qDebug() << "Wrong answer !, answer is " << ui->answer_lineEdit->text() << "instead of :" << m_translationUnit.englishWord;
}
}
void MainWindow::processRandomField()
{
m_testSession.test++;
scoreUpdate();
QString q("SELECT * FROM Vocabulary Where Category = ");
q.append(QString::number(m_cat));
q.append(" ORDER BY RANDOM() LIMIT 1;");
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery(q);
m_translationUnit.id = model->record(0).value("Id").toInt();
m_translationUnit.polishWord = model->record(0).value("Polish").toString();
m_translationUnit.englishWord = model->record(0).value("English").toString();
m_translationUnit.category = model->record(0).value("Category").toInt();
qDebug() << m_translationUnit.id << " " << m_translationUnit.polishWord << " " << m_translationUnit.englishWord << " " << m_translationUnit.category << " end";
if(m_polishToEnglish)
ui->test_label->setText(m_translationUnit.polishWord);
else
ui->test_label->setText(m_translationUnit.englishWord);
}
void MainWindow::on_comboBox_currentIndexChanged(int index)
{
m_cat = index+1;
QString q("SELECT Polish,English FROM Vocabulary Where Category = ");
q.append(QString::number(m_cat));
qDebug() << q;
this->vocabularyModel = new QSqlQueryModel();
vocabularyModel->setQuery(q);
ui->tableView->setModel(vocabularyModel);
updateMaxCount(vocabularyModel->rowCount());
}
void MainWindow::updateMaxCount(int count){
maxCount = count;
if (maxCount == 0){
ui->validate_pushbutton->setEnabled(false);
ui->validate_pushbutton->repaint();
}
else{
ui->validate_pushbutton->setEnabled(true);
ui->validate_pushbutton->repaint();
}
}
bool MainWindow::compareAnswer(QString suppliedAnswer){
if (m_polishToEnglish)
return !m_translationUnit.englishWord.compare(suppliedAnswer, Qt::CaseInsensitive);
else
return !m_translationUnit.polishWord.compare(suppliedAnswer, Qt::CaseInsensitive);
}
void MainWindow::on_invertLanguage_clicked()
{
m_polishToEnglish = !m_polishToEnglish;
ui->generateTest_button->click();
}
void MainWindow::scoreUpdate(){
QString score("Score: ");
score.append(QString::number(m_testSession.validAnswer));
score.append("/");
score.append(QString::number(m_testSession.test));
ui->score_label->setText(score);
}
|
#include<stdio.h>
#include<vector>
using namespace std;
struct Edge {
int to;
int cost;
int len;
};
int dist[1001];
int cost[1001];
bool marked[1001];
vector<Edge> edge[1000];
void func() {
int n, m;
while (scanf("%d %d",&n,&m)) {
if (n == 0 && m == 0) {
break;
}
for (int i = 1;i <= n;i++) {
dist[i] = -1;
marked[i] = false;
edge[i].clear();
}
for (int i = 0;i < m;i++) {
int a, b, d, p;
scanf("%d %d %d %d", &a, &b, &d, &p);
Edge tmp;
tmp.cost = p;
tmp.len = d;
tmp.to = a;
edge[b].push_back(tmp);
tmp.to = b;
edge[a].push_back(tmp);
}
int s, t;
scanf("%d %d", &s, &t);
int v = s;
marked[v] = true;
dist[v] = 0;
cost[v] = 0;
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < edge[v].size();j++) {
int to = edge[v][j].to;
int newLen = dist[v] + edge[v][j].len;
int newCost = cost[v] + edge[v][j].cost;
if (marked[to]) continue;
if (dist[to] == -1 || newLen <dist[to] || (dist[to] == newLen && newCost < cost[to])) {
dist[to] = newLen;
cost[to] = newCost;
}
}
int minLen=100000000;
int minCost= 100000000;
for (int j = 1;j <= n;j++) {
if (marked[j] || dist[j] == -1) continue;
if (dist[j] < minLen || (dist[j] == minLen && cost[j] < minCost)) {
minLen = dist[j];
minCost = cost[j];
v = j;
}
}
marked[v] = true;
if (v == t) {
break;
}
}
printf("%d %d\n", dist[t], cost[t]);
}
}
int main() {
func();
return 0;
}
|
#ifndef GAMESFML_H
#define GAMESFML_H
#include "game.h"
#include <SFML/Graphics.hpp>
class GameSFML : public Game
{
public:
GameSFML(int nrow, int ncol);
virtual ~GameSFML();
bool initGraphics();
void releaseGraphics();
UserInput getUserInput();
bool isWindowOpen() const { return window.isOpen(); }
void renderGameGraphics(int wonOrLost);
protected:
sf::RenderWindow window;
sf::Font font;
sf::Texture mineTexture;
sf::Sprite mineSprite;
sf::Text numbers[9];
sf::Text wonOrLostMessage[3];
private:
};
#endif // GAMESFML_H
|
#include <bits/stdc++.h>
using namespace std;
struct node
{
node* next;
int data;
};
void print_list(node** head,int n)
{
node *temp=*head;
while(temp!=NULL && n!=0)
{
cout<<temp->data<<" ";
temp=temp->next;
n--;
}
cout<<"\n";
}
void reverse_head_tail(node** head,node** tail,int n)
{
if(n==1)
return;
node* previous=*head;
while(previous->next!=*tail)
{
previous=previous->next;
}
previous->next=*head;
(*tail)->next=(*head)->next;
node* temp=*head;
*head=*tail;
*tail=temp;
}
int main()
{
int n;
cin>>n;
node* head=NULL;
node* tail=NULL;
for(int i=0;i<n;i++)
{
int j;
cin>>j;
node* temp=new node();
temp->data=j;
temp->next=NULL;
if(i==0)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
}
tail->next=head;
reverse_head_tail(&head,&tail,n);
print_list(&head,n);
return 0;
}
|
#pragma once
#include "cmonster.h"
class cBacteria :
public cMonster
{
public:
virtual void Init();
virtual void Update();
virtual void Render();
public:
cBacteria(void);
~cBacteria(void);
};
|
#include <iostream>
#define _USE_MATH_DEFINES
#include <cmath>
int main()
{
double x = .0;
std::cout<<"# Plotting sin fuction in [0,2pi] with delta=0.01pi.";
std::cout<<std::scientific;
while (x < 2* M_PI)
{
std::cout<<x<<" "<<std::sin(x)<<'\n';
x += .01* M_PI;
};
return 0;
}
|
/**
* \file myIncludes.h
*
* \ingroup MySoftwarePackage
*
* \brief Class def header for a class myIncludes
*
* @author erezcohen
*/
/** \addtogroup MySoftwarePackage
@{*/
#ifndef MYINCLUDES_H
#define MYINCLUDES_H
#include <iostream>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <math.h>
#include <vector>
#include <numeric>
#include <string>
#include <functional>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
#include <functional>
#include "TRotation.h"
#include <TTimeStamp.h>
#include <TStopwatch.h>
#include <TString.h>
#include <TSystem.h>
#include <TLine.h>
#include <TArrow.h>
#include <TFile.h>
#include <TTree.h>
#include <TROOT.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TF2.h>
#include <TF12.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TProfile.h>
#include <TPad.h>
#include <TStyle.h>
#include <TMultiGraph.h>
#include <TGraphErrors.h>
#include <TLegend.h>
#include <TPaveStats.h>
#include <TChain.h>
#include <TBranch.h>
#include <TLeaf.h>
#include <TMath.h>
#include <TCut.h>
#include <TLorentzVector.h>
#include <TVector2.h>
#include <TVector3.h>
#include <TPie.h>
#include <TLatex.h>
#include <TEllipse.h>
#include <TPolyLine3D.h>
#include <TRandom2.h>
#include <THStack.h>
#include <TSpectrum.h>
#include <TSpectrum2.h>
#include <TUnfoldSys.h>
#include <TCutG.h>
#include <TGeoSphere.h>
#include <TBox.h>
#include "TGaxis.h"
#include <TRandom3.h>
#include <typeinfo> // operator typeid
#ifndef __CINT__
#include "RooGlobalFunc.h"
#endif
#include "RooRealVar.h"
#include "RooDataSet.h"
#include "RooDataHist.h"
#include "RooGaussian.h"
#include "RooConstVar.h"
#include "RooFormulaVar.h"
#include "RooGenericPdf.h"
#include "RooMsgService.h"
#include "RooPolynomial.h"
#include "RooChi2Var.h"
#include "RooMinuit.h"
#include "TCanvas.h"
#include "TAxis.h"
#include "TMatrix.h"
#include "RooPlot.h"
using namespace std;
// important prints....
#define EndEventBlock() cout << "\033[32m"<< "....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......" << "\033[0m"<< endl;
#define PrintLine() std::cout << "-------------------------------" << std::endl;
#define PrintXLine() std::cout << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" << std::endl;
#define SHOW(a) cout << setprecision(2) << fixed << #a << ": " << (a) << endl
#define SHOW2(a,b) cout <<"\033[34m"<<#a<<": "<<(a)<<"," << #b <<": "<<(b)<< "\033[0m"<< endl;
#define SHOW3(a,b,c) cout <<"\033[36m"<<#a<<": "<<(a)<<"," << #b <<": "<<(b)<<","<<#c<<": "<<(c)<< "\033[0m"<< endl;
#define SHOW4(a,b,c,d) cout <<"\033[31m"<<#a<<": "<<(a)<<"," << #b <<": "<<(b)<<","<<#c<<": "<<(c)<<","<<#d<<": "<<(d)<< "\033[0m"<< endl;
#define PrintPhys(a,units) std::cout << setprecision(2) << fixed << #a << ": " << (a) << " " << (units) << std::endl
#define SHOWTLorentzVector(v) std::cout << #v << ": " << "\t(" << setprecision(2) << fixed << v.Px() << "," << v.Py() << "," << v.Pz() << "," << v.E() << ")" << ", P = " << v.P() << ", M = " << v.M() << std::endl
#define SHOWstdTVector3(v) { if (v.size()<1) {cout << #v << " is empty" << endl;} else {std::cout << #v << "( " << v.size() << " entries ):\t"; for (std::vector<TVector3>::iterator it=v.begin(); it!=v.end(); ++it) std::cout << setprecision(2) << fixed << "\n\t(" << it -> X() << "," << it -> Y() << "," << it -> Z() << ")\t"; std::cout << '\n';}}
#define SHOWvectorTLorentzVector(v) { if (v.size()<1) {cout << #v << " is empty" << endl;} else {std::cout << #v << "( " << v.size() << " entries ):\t"; for (std::vector<TLorentzVector>::iterator it=v.begin(); it!=v.end(); ++it) std::cout << setprecision(2) << fixed << "\n\t(" << it -> Px() << "," << it -> Py() << "," << it -> Pz() << "," << it -> E() << ")" << ", P = " << it -> P() << ", M = " << it -> M(); std::cout << '\n';}}
#define SHOWstdVector(v){ if (v.size()<1) {cout << #v << " is empty" << endl;} else {cout << #v << "( " << v.size() << " entries):\t"; for (auto it:v) cout << it << ",\t"; cout << endl;}}
#define SHOWTVector3(v){ cout << #v << ": (" << v.X() << "," << v.Y() << "," << v.Z() << "), |" << #v << "| = " << v.Mag() << endl;}
/**
\class myIncludes
User defined class myIncludes ... these comments are used to generate
doxygen documentation!
*/
class myIncludes{
public:
/// Default constructor
myIncludes(){}
/// Default destructor
~myIncludes(){}
void SetDebug (int _debug_) {debug = _debug_;};
void Debug (Int_t verobosity_level, std::string text){
if ( debug > verobosity_level ) cout << text << endl;
}
Int_t debug;
};
#endif
/** @} */ // end of doxygen group
|
#ifndef GRAPHICSDLL_LIGHTHANDLER_H
#define GRAPHICSDLL_LIGHTHANDLER_H
#include <DirectXMath.h>
#ifdef GRAPHICSDLL_EXPORTS
#define GRAPHICSDLL_API __declspec(dllexport)
#else
#define GRAPHICSDLL_API __declspec(dllimport)
#endif
#include <d3d11_1.h>
#include <vector>
#include "LightStructs.h"
#include "ConstantBufferHandler.h"
#include "../SSP_Editor/LevelHeaders.h"
#ifdef _DEBUG
#include <iostream>
#endif
/*
Author:Martin Clementson
This class handles the interaction of lights and the shaders
This assumes that the individual light data is stored elsewhere.
It holds pointers to arrays of each individual light type.
If an update to the gpu is desired. Call UpdateStructuredBuffer()
Edit: 21/2 2017
The project decided that we should use cubemapping for shadows to point lights.
This changed the const buffer, the depth stencils and textures
When it comes to holding the data, this class holds the data in the game, however in the editor the light data is still held elsewhere
Edit: 27/2 2017
The class has been reworked to be optimized. The other types of lights has been removed to save ram and vram, Some remnants might be found in the future
*/
#define LIGHT_CHECK_PAUSE_TIME (1.0f / 10.0f)
#define USE_CONST_BUFFER_FOR_LIGHTS //TEMP to test performance
#define MAX_LIGHT_AMOUNT 60
//#define CHECK_IF_EXITED_LIGHT_RADIUS
namespace LIGHTING
{
class LightHandler
{
private:
enum LIGHT_BUFFER_SLOTS // Determines the slots that the buffers are set in the shader
{
POINTLIGHT_BUFFER = 6 , // IMPORTANT: In the shader, these buffers needs to be registered as a t buffer
DIRECTIONALLIGHT_BUFFER = 7 , // not register(sX); BUT, register(tX);
AREALIGHT_BUFFER = 8,
SPOTLIGHT_BUFFER = 9
};
unsigned int NUM_LIGHTS = 0;
const unsigned int BUFFER_SHADER_SLOT = 6;
public:
struct LightArray {
Point* dataPtr = nullptr;
ID3D11ShaderResourceView* shadowMaps; //One should be generated for each light on load
unsigned int numItems = 0;
unsigned int numShadowLights = 0;
int shadowLightIndex[MAX_SHADOW_LIGHTS]; // An array of int that represents the indices of the lights that casts shadows
int currentDynamicShadowIndex = 0;
~LightArray() { //Destructor, s
ReleaseShadowMaps(); //Release the TextureBuffers
}
void ReleaseShadowMaps() {
if (shadowMaps != nullptr){
shadowMaps->Release();
shadowMaps = nullptr;
numShadowLights = 0;
}
}
};
private:
LightHandler();
~LightHandler();
ConstantBufferHandler::ConstantBuffer::shadow::cbData m_shadowCb;
ConstantBufferHandler::ConstantBuffer::light::pData m_constBufferData;
LightArray m_lightData;
ID3D11Device* m_gDevice;
ID3D11DeviceContext* m_gDeviceContext;
ID3D11Buffer* m_lightBuffer = nullptr; //Light constBuffer
ID3D11ShaderResourceView* m_structuredBuffer = nullptr; //Data is handled in shader resource views
//Timer variables
//Time since we last updated the light for shadow mapping
float m_activeLightCheckTimer;
//The light index for shadow mapping
int m_activeLightIndex;
private:
GRAPHICSDLL_API bool CreateStructuredBuffer (int amount);
GRAPHICSDLL_API bool ReleaseStructuredBuffer();
GRAPHICSDLL_API size_t GetStructByteSize (LIGHT_TYPE type);
public: //inits etc
GRAPHICSDLL_API void Initialize(ID3D11Device*, ID3D11DeviceContext*);
GRAPHICSDLL_API static LightHandler* GetInstance();
GRAPHICSDLL_API int Update(float dT, DirectX::XMFLOAT3 pointOfInterest);
public: //dataFlow
GRAPHICSDLL_API LightArray* Get_Light_List() { return &m_lightData; };
GRAPHICSDLL_API bool UpdateStructuredBuffer ();
GRAPHICSDLL_API bool SetStaticShadowsToGPU();
GRAPHICSDLL_API bool SetBufferAsActive();
GRAPHICSDLL_API bool SetLightData(Point* lightArray, unsigned int numLights);
GRAPHICSDLL_API void SetAmbientLight(float r, float g, float b, float intensity);
GRAPHICSDLL_API bool LoadLevelLight(LevelData::Level* level);
GRAPHICSDLL_API bool SetShadowCastingLight(Point* light);
GRAPHICSDLL_API bool SetShadowCastingLight(int index);
GRAPHICSDLL_API bool UpdateActiveLightsToGPU(std::vector<int>* indices);
GRAPHICSDLL_API bool UpdateActiveLightsToGPUeditor(std::vector<int>* indices);
GRAPHICSDLL_API bool SetShadowLightIndexList(std::vector<int>* indices);
//Returns either an index to the internal lightdata or -1 for no lights found
GRAPHICSDLL_API int GetClosestLightIndex( DirectX::XMFLOAT3 pos);
//Stores either an index to the internal lightdata or -1 for no lights found
GRAPHICSDLL_API void GetClosestLightIndex( DirectX::XMFLOAT3 pos, int & storeIn);
};
}
#endif
|
#ifndef SPAN_SRC_SPAN_EXCEPTIONS_EXCEPTION_HH_
#define SPAN_SRC_SPAN_EXCEPTIONS_EXCEPTION_HH_
#include <errno.h>
#include "span/Common.hh"
#if UNIX_FLAVOUR == UNIX_FLAVOUR_BSD
#define error_t errno_t
#endif
error_t lastError();
void lastError(error_t error);
#endif // SPAN_SRC_SPAN_EXCEPTIONS_EXCEPTION_HH_
|
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <iomanip>
#include <functional>
#include <utility>
#include <cmath>
#include <condition_variable>
#include <mutex>
#include <chrono>
#include <iterator>
#include <thread>
#include <algorithm>
#include <cassert>
#include <map>
#include <climits>
#include "game.h"
#include "gameStruct.h"
#include "../../data/troop/troop.h"
#include "../../io/io.h"
// flow: print the page for current mode for every frame
// wait for user actions (switch country, send troops, retreat troops)
// naturally occuring: when country capitulates
// naturally occuring: when all user's troops died
// battle: calc all stats for both side -> user troops give damage -> user troops take damage -> clean up troops with no health
// when adding in troops, they will join the battle on the next day
// printing technique: repaint every character, no screen clearing
// default page render: 4 renders, each corresponding to the 4 columns (map, actions, rewards, enemy troops)
// troop withdraw page: sorted in ascending order of health, then alphanumerical order of battling region
// note the actual damage calculation and battle progression happens in the timer thread in game.cpp and in the BattleUnit class in gameStruct.cpp
// this cpp file is merely a representation and interface of the battle
void Game::sensou(int &gamePhase, int prevPhase)
{
int currentCountry = 0;
for (int i = 0; i < this->enemies->totalEnemies.size(); i++)
if (!this->enemies->totalEnemies[i]->capitulated && this->enemies->totalEnemies[i]->capturedLand > 0)
{
currentCountry = i;
break;
}
// 0: map mode, 0: block action (0b), 1: add troop, 1: add troop detail (2b), 3: retreat all troops, 2: view battle
int mode = 0;
int subMode = 0;
int blockSize[2] = {4, 6};
// io
int prePhase0[2] = {0, 0};
int scroll0[2] = {0, 0};
int phase0[2] = {0, 0};
int subPhase0[2] = {0, 0};
int subPhase0Mode = 0;
int scroll1[2] = {0, 0};
int phase1[2] = {0, 0};
int subPhase1[2] = {0, 0};
int subPhase1Mode = 0;
int scroll2[2] = {0, 0};
int subPhase2Mode = 0;
std::string subPhase1Type;
TroopUnit *subPhase1TroopDetail;
bool enter = false;
std::vector<std::function<void()>> printMode;
std::function<void()> sendAll;
std::function<void()> retreatAll;
std::function<void(std::string)> troopIreru;
std::function<void(ArmyUnit *)> armyIreru;
std::function<void(std::string)> troopNuku;
std::function<void(ArmyUnit *)> armyNuku;
std::vector<TroopUnit *> selectedTroop;
std::vector<ArmyUnit *> selectedArmy;
std::function<void()> deselectAll;
std::function<void()> loopPrint;
std::function<void()> stopPrint;
std::future<void> printFuture;
std::condition_variable printCond;
std::mutex printa;
std::mutex printb;
std::mutex user;
bool terminatePrint = false;
int battleCycle = 0;
const int iconInterval = 300;
int iconLocation = 0;
std::unordered_map<std::string, int> typeToHealth = {
{"infantry", Infantry::baseHp},
{"calvary", Calvary::baseHp},
{"suicideBomber", 0},
{"artillery", Artillery::baseHp},
{"logistic", Logistic::baseHp},
{"armoredCar", ArmoredCar::baseHp},
{"tank1", Tank1::baseHp},
{"tank2", Tank2::baseHp},
{"tankOshimai", TankOshimai::baseHp},
{"cas", Cas::baseHp},
{"fighter", Fighter::baseHp},
{"bomber", Bomber::baseHp},
{"kamikaze", 0}};
std::vector<std::string> indexToTroop = {"infantry", "calvary", "suicideBomber", "artillery", "logistic", "armoredCar", "tank1", "tank2", "tankOshimai", "cas", "fighter", "bomber", "kamikaze"};
std::unordered_map<std::string, std::string> typeToDisplay = {
{"infantry", "Infantry"},
{"calvary", "Calvary"},
{"suicideBomber", "Suicide Bomber"},
{"artillery", "Artillery"},
{"logistic", "Logistic"},
{"armoredCar", "Armored Car"},
{"tank1", "Tank 1"},
{"tank2", "Tank 2"},
{"tankOshimai", "Tank Oshimai"},
{"cas", "Cas"},
{"fighter", "Fighter"},
{"bomber", "Bomber"},
{"kamikaze", "Kamikaze"}};
std::map<std::string, bool> selectedArmyMap;
std::unordered_map<std::string, int> selectedTroopMap = {
{"infantry", 0},
{"calvary", 0},
{"suicideBomber", 0},
{"artillery", 0},
{"logistic", 0},
{"armoredCar", 0},
{"tank1", 0},
{"tank2", 0},
{"tankOshimai", 0},
{"cas", 0},
{"fighter", 0},
{"bomber", 0},
{"kamikaze", 0}};
retreatAll = [&]() {
Block *ptr = this->enemies->totalEnemies[currentCountry]->map[phase0[0]][phase0[1]];
ptr->retreatAll(this->battle);
};
deselectAll = [&]() {
for (auto i : selectedTroopMap)
for (int j = 0; j < i.second; j++)
troopNuku(i.first);
for (int i = selectedArmy.size() - 1; i >= 0; i--)
armyNuku(selectedArmy[i]);
};
sendAll = [&]() {
user.lock();
Enemy *ptr = this->enemies->totalEnemies[currentCountry];
for (auto i : selectedTroop)
if (!ptr->map[phase0[0]][phase0[1]]->captured)
ptr->map[phase0[0]][phase0[1]]->reinforce(
user, [&]() { this->endGame(); }, this->gameOver, this->enemies->totalEnemies.size(), i, this->resource, this->building, this->battle, [&](std::string type, int time, std::function<void(data::Resource &)> &callBack, std::string desc, double land, int amount) { this->buildBase(type, time, callBack, desc, land, amount); });
for (auto i : selectedArmy)
if (!ptr->map[phase0[0]][phase0[1]]->captured)
ptr->map[phase0[0]][phase0[1]]->reinforce(
user, [&]() { this->endGame(); }, this->gameOver, this->enemies->totalEnemies.size(), i, this->resource, this->building, this->battle, [&](std::string type, int time, std::function<void(data::Resource &)> &callBack, std::string desc, double land, int amount) { this->buildBase(type, time, callBack, desc, land, amount); });
deselectAll();
mode = 0;
if (this->gameOver)
{
user.unlock();
return;
}
std::cout << "\033[2J\033[1;1H" << std::endl;
// avoid resource deadlock error
std::thread temp([&]() {
stopPrint();
loopPrint();
});
temp.detach();
};
troopIreru = [&](std::string type) {
std::vector<int> indices;
for (int i = 0; i < this->troop->allTroop.size(); i++)
{
if (this->troop->allTroop[i]->type == type && this->troop->allTroop[i]->state["free"] && !this->troop->allTroop[i]->selected)
{
indices.push_back(i);
}
}
assert(indices.size() != 0);
std::sort(indices.begin(), indices.end(), [this](int a, int b) -> bool {
return this->troop->allTroop[a]->getHealth() > this->troop->allTroop[b]->getHealth();
});
this->troop->allTroop[indices[0]]->selected = true;
selectedTroop.push_back(this->troop->allTroop[indices[0]]);
selectedTroopMap[type]++;
};
armyIreru = [&](ArmyUnit *guntai) {
assert(guntai != NULL);
selectedArmy.push_back(guntai);
selectedArmyMap[guntai->name] = true;
};
troopNuku = [&](std::string type) {
std::vector<int> indices;
for (int i = 0; i < selectedTroop.size(); i++)
{
if (selectedTroop[i]->type == type)
{
indices.push_back(i);
}
}
if (indices.size() == 0)
return;
std::sort(indices.begin(), indices.end(), [&selectedTroop](int a, int b) -> bool {
return selectedTroop[a]->getHealth() < selectedTroop[b]->getHealth();
});
selectedTroop[indices[0]]->selected = false;
selectedTroopMap[selectedTroop[indices[0]]->type]--;
selectedTroop.erase(selectedTroop.begin() + indices[0]);
};
armyNuku = [&](ArmyUnit *guntai) {
assert(guntai != NULL);
int index = -1;
for (int i = 0; i < selectedArmy.size(); i++)
if (selectedArmy[i] == guntai)
{
index = i;
break;
}
assert(index != -1);
selectedArmy.erase(selectedArmy.begin() + index);
selectedArmyMap.erase(guntai->name);
};
printMode.push_back([&]() {
if (enter)
{
enter = false;
if (subMode == 1)
{
if (subPhase0[0] == 0)
mode = 1;
else if (subPhase0[0] == 2)
mode = 2;
else
retreatAll();
subMode = 0;
user.lock();
std::cout << "\033[2J\033[1;1H" << std::endl;
// avoid resource deadlock error
std::thread temp([&]() {
stopPrint();
loopPrint();
});
temp.detach();
return;
}
else
{
Enemy *ptr = this->enemies->totalEnemies[currentCountry];
if ((!this->battle->inBattle || this->battle->countryBattling == ptr->name) && !ptr->map[phase0[0]][phase0[1]]->captured && ptr->map[phase0[0]][phase0[1]]->isAttackable && !ptr->capitulated)
subMode = 1;
}
}
this->lg3.lock();
int screen[2] = {25, 48};
std::vector<std::string> render;
Enemy *ptr = this->enemies->totalEnemies[currentCountry];
battleCycle += 1000 / this->fps;
if (battleCycle >= iconInterval)
{
battleCycle = 0;
iconLocation = !iconLocation;
}
phase0[0] = (phase0[0] + ptr->map.size()) % ptr->map.size();
std::unordered_map<int, int> hasBlock;
int start = -1;
int end = -1;
int scrollable[2] = {std::max(0, (int)(ptr->map.size() * 3 + 1 - screen[0])), std::max(0, (int)(ptr->map[0].size() * 6 - screen[1]))};
scroll0[0] = std::min(std::max(scroll0[0], 0), scrollable[0]);
scroll0[1] = std::min(std::max(scroll0[1], 0), scrollable[1]);
if (subPhase0Mode == 1)
{
if (scroll0[0] > phase0[0] * 3)
phase0[0] = scroll0[0] / 3 + 1;
if (scroll0[0] + screen[0] <= phase0[0] * 3 + 1)
phase0[0] = (scroll0[0] + screen[0]) / 3 - 1;
if (scroll0[1] > phase0[1] * 6)
phase0[1] = scroll0[1] / 6 + 1;
if (scroll0[1] + screen[1] <= phase0[1] * 6 + 1)
phase0[1] = (scroll0[1] + screen[1]) / 6 - 1;
phase0[0] = (phase0[0] + ptr->map.size()) % ptr->map.size();
}
else if (subPhase0Mode == 0)
{
if (scroll0[0] > phase0[0] * 3)
scroll0[0] = phase0[0] * 3;
if (scroll0[0] + screen[0] <= phase0[0] * 3 + 1)
scroll0[0] = phase0[0] * 3 - screen[0] + 3;
scroll0[0] = std::min(std::max(scroll0[0], 0), scrollable[0]);
scroll0[1] = std::min(std::max(scroll0[1], 0), scrollable[1]);
}
for (int i = 0; i < ptr->map[phase0[0]].size(); i++)
{
if (ptr->map[phase0[0]][i] != NULL)
{
hasBlock[i] = 1;
if (start == -1)
start = i;
end = i;
}
}
if (phase0[0] == prePhase0[0])
{
int diff = 0;
if (phase0[1] > prePhase0[1])
{
while (hasBlock.count(phase0[1] + diff) == 0 && phase0[1] + diff < ptr->map[phase0[0]].size())
diff++;
if (phase0[1] + diff == ptr->map[phase0[0]].size())
phase0[1] = start;
else
phase0[1] += diff;
}
else if (phase0[1] < prePhase0[1])
{
while (hasBlock.count(phase0[1] - diff) == 0 && phase0[1] - diff >= 0)
diff++;
if (phase0[1] - diff == -1)
phase0[1] = end;
else
phase0[1] -= diff;
}
else
{
if (hasBlock.count(phase0[1]) == 0)
{
int diff = 1;
bool found = false;
while (!found)
{
if (hasBlock.count(phase0[1] + diff) != 0)
{
phase0[1] = phase0[1] + diff;
found = true;
}
else if (hasBlock.count(phase0[1] - diff) != 0)
{
phase0[1] = phase0[1] - diff;
found = true;
}
diff++;
}
}
}
}
else
{
// find closest block
if (hasBlock.count(phase0[1]) == 0)
{
int diff = 1;
bool found = false;
while (!found)
{
if (hasBlock.count(phase0[1] + diff) != 0)
{
phase0[1] = phase0[1] + diff;
found = true;
}
else if (hasBlock.count(phase0[1] - diff) != 0)
{
phase0[1] = phase0[1] - diff;
found = true;
}
diff++;
}
}
}
if (subPhase0Mode == 0)
{
if (scroll0[1] > phase0[1] * 6)
scroll0[1] = phase0[1] * 6;
if (scroll0[1] + screen[1] <= phase0[1] * 6 + 1)
scroll0[1] = phase0[1] * 6 - screen[1] + 6;
scroll0[0] = std::min(std::max(scroll0[0], 0), scrollable[0]);
scroll0[1] = std::min(std::max(scroll0[1], 0), scrollable[1]);
}
subPhase0Mode = -1;
prePhase0[0] = phase0[0];
prePhase0[1] = phase0[1];
for (int i = 0; i < ptr->map.size(); i++)
{
std::string row1 = "";
std::string row2 = "";
std::string row3 = "";
for (int j = 0; j < ptr->map[i].size(); j++)
{
if (ptr->map[i][j] == NULL)
{
if (i != 0 && ptr->map[i - 1][j] != NULL)
row1 += std::string(blockSize[1], '-');
else
row1 += std::string(blockSize[1], ' ');
row2 += std::string(blockSize[1], ' ');
row3 += std::string(blockSize[1], ' ');
}
else
{
if (i == 0 || ptr->map[i - 1][j] == NULL)
row1 += std::string(blockSize[1], '-');
else
row1 += std::string(blockSize[1], ' ');
if (j == 0 || ptr->map[i][j - 1] == NULL)
{
row2 += '|';
row3 += '|';
}
else
{
row2 += ' ';
row3 += ' ';
}
if (i == phase0[0] && j == phase0[1] && subMode == 0)
row2 += ">";
else
row2 += " ";
if (ptr->map[i][j]->name.length() < 3)
row2 += ' ';
row2 += ptr->map[i][j]->name;
if (j == ptr->map[i].size() - 1 || ptr->map[i][j + 1] == NULL)
row2 += '|';
else
row2 += ' ';
if (i == phase0[0] && j == phase0[1] && subMode == 0)
row3 += "> ";
else
row3 += " ";
std::string iconType = " ";
if (ptr->map[i][j]->battling)
{
iconType = ".";
bool heavilyInjured = false;
for (auto i : ptr->map[i][j]->battle.back()->mikata->totalArmy)
if (i->casualtyPercentage >= 0.7)
{
heavilyInjured = true;
break;
}
if (heavilyInjured)
iconType = "!";
}
if (ptr->map[i][j]->captured)
{
row3 += "xx";
}
else
{
if (!iconLocation)
row3 += iconType + " ";
else
row3 += ' ' + iconType;
}
if (j == ptr->map[i].size() - 1 || ptr->map[i][j + 1] == NULL)
row3 += '|';
else
row3 += ' ';
}
}
assert(row1.length() == blockSize[1] * ptr->map[i].size());
assert(row2.length() == blockSize[1] * ptr->map[i].size());
assert(row3.length() == blockSize[1] * ptr->map[i].size());
render.push_back(row1);
render.push_back(row2);
render.push_back(row3);
}
// a layer unnderneath to compensate for the bottom border of the last row
std::string row1 = "";
for (int j = 0; j < ptr->map.back().size(); j++)
{
if (ptr->map.back()[j] != NULL)
row1 += std::string(blockSize[1], '-');
else
row1 += std::string(blockSize[1], ' ');
}
assert(row1.length() == blockSize[1] * ptr->map.back().size());
render.push_back(row1);
for (int i = 0; i < render.size(); i++)
if (render[i].size() < screen[1])
render[i] += std::string(screen[1] - render[i].length(), ' ');
for (int i = render.size(); i < screen[0]; i++)
render.push_back(std::string(screen[1], ' '));
int maxLength2 = 20;
std::vector<std::string> render2;
if ((!this->battle->inBattle || this->battle->countryBattling == ptr->name) && !ptr->map[phase0[0]][phase0[1]]->captured && ptr->map[phase0[0]][phase0[1]]->isAttackable && !ptr->capitulated)
render2.push_back(" Send Troop (z) ");
if (ptr->map[phase0[0]][phase0[1]]->battling)
{
render2.push_back(" Retreat Troop (r)");
render2.push_back(" View Battle (v) ");
}
if (render2.size() > 0)
{
subPhase0[0] = (subPhase0[0] + render2.size()) % render2.size();
subPhase0[1] = 0;
if (subMode == 1)
render2[subPhase0[0]].replace(1, 1, ">");
}
std::vector<std::string> render3;
render3.push_back("Rewards");
render3.push_back("Farm: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->acquirable["farm"]));
render3.push_back("Civilian Factory: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->acquirable["civilianFactory"]));
render3.push_back("Military Factory: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->acquirable["militaryFactory"]));
render3.push_back("Training Camp: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->acquirable["trainingCamp"]));
render3.push_back("Airport: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->acquirable["airport"]));
render3.push_back("Land: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->acquirable["land"]));
render3.push_back("");
render3.push_back("");
render3.push_back("Terrain");
render3.push_back(ptr->map[phase0[0]][phase0[1]]->terrain);
int maxLength3 = 0;
for (auto i : render3)
if (i.length() > maxLength3)
maxLength3 = i.length();
for (int i = 0; i < render3.size(); i++)
render3[i] += std::string(maxLength3 - render3[i].length(), ' ');
std::vector<std::string> render4;
int soft = 0, hard = 0, air = 0;
for (auto &i : ptr->map[phase0[0]][phase0[1]]->totalFoeTroop)
{
soft += i->getSoftAttack();
hard += i->getHardAttack();
air += i->getAirAttack();
}
for (auto &i : ptr->map[phase0[0]][phase0[1]]->totalFoeArmy)
for (auto &j : i->formation)
for (auto &k : j)
if (k != NULL)
{
soft += k->getSoftAttack();
hard += k->getHardAttack();
air += k->getAirAttack();
}
render4.push_back("Enemies troops");
render4.push_back("Infantry: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["infantry"]));
render4.push_back("Calvary: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["calvary"]));
render4.push_back("Artillery: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["artillery"]));
render4.push_back("Logistic: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["logistic"]));
render4.push_back("Armored Car: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["armoredCar"]));
render4.push_back("Tank 1: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["tank1"]));
render4.push_back("Tank 2: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["tank2"]));
render4.push_back("Tank Oshimai: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["tankOshimai"]));
render4.push_back("Cas: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["cas"]));
render4.push_back("Fighter: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["fighter"]));
render4.push_back("Bomber: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["bomber"]));
render4.push_back("Armies: " + std::to_string(ptr->map[phase0[0]][phase0[1]]->foeCount["army"]));
render4.push_back("");
render4.push_back("");
render4.push_back("Total base attack:");
render4.push_back("Soft: " + std::to_string(soft));
render4.push_back("Hard: " + std::to_string(hard));
render4.push_back("Air: " + std::to_string(air));
int maxLength4 = 0;
for (auto i : render4)
if (i.length() > maxLength4)
maxLength4 = i.length();
for (int i = 0; i < render4.size(); i++)
render4[i] += std::string(maxLength4 - render4[i].length(), ' ');
std::cout << "\033[1;1H";
std::cout << color("Battle", "magenta") << std::endl
<< std::endl;
this->lg.lock();
std::stringstream speed;
speed << std::fixed << std::setprecision(1) << this->setting["speed"] / 1000.0;
std::cout << color("Day: ", "green") << this->day << "/" << this->timeLimit << " (" << speed.str() << "s) " << (this->paused ? color("PAUSED", "red") : "") << std::endl
<< std::endl;
this->lg.unlock();
std::cout << "Country: " << this->enemies->totalEnemies[currentCountry]->name
<< " (" << (this->enemies->totalEnemies[currentCountry]->capitulated ? " defeated" : "not defeated") << ")"
<< " (" << currentCountry + 1 << "/" << this->enemies->totalEnemies.size() << ")"
<< " Battling Regions: " << this->enemies->totalEnemies[currentCountry]->battlingRegions
<< " Captured: " << this->enemies->totalEnemies[currentCountry]->capturedLand << "/" << this->enemies->totalEnemies[currentCountry]->totalLand
<< std::endl;
std::cout << "Change speed: q Pause: p Next country: e (total: " << this->enemies->totalEnemies.size() << ") Move map: wasd Back: spacebar " << std::endl
<< std::endl
<< std::endl;
for (int i = 0; i < 19; i++)
{
std::cout << render[i + scroll0[0]].substr(scroll0[1], screen[1]) << " "
<< (render2.size() > i ? render2[i] : std::string(maxLength2, ' ')) << " "
<< (render3.size() > i ? render3[i] : std::string(maxLength3, ' ')) << " "
<< (render4.size() > i ? render4[i] : std::string(maxLength4, ' ')) << std::endl;
}
for (int i = 19; i < screen[0]; i++)
std::cout << render[i + scroll0[0]].substr(scroll0[1], screen[1]) << std::endl;
this->lg3.unlock();
});
printMode.push_back([&]() {
std::unordered_map<std::string, int> fullHealth = {
{"infantry", 0},
{"calvary", 0},
{"artillery", 0},
{"logistic", 0},
{"armoredCar", 0},
{"tank1", 0},
{"tank2", 0},
{"tankOshimai", 0},
{"cas", 0},
{"fighter", 0},
{"bomber", 0}};
if (enter)
{
enter = false;
if (subMode == 1)
{
if (subPhase1TroopDetail != NULL)
{
if (subPhase1TroopDetail->selected)
{
subPhase1TroopDetail->selected = false;
int index = -1;
for (int i = 0; i < selectedTroop.size(); i++)
if (selectedTroop[i] == subPhase1TroopDetail)
{
index = i;
break;
}
assert(index != -1);
selectedTroop.erase(selectedTroop.begin() + index);
selectedTroopMap[subPhase1Type]--;
}
else
{
subPhase1TroopDetail->selected = true;
selectedTroop.push_back(subPhase1TroopDetail);
selectedTroopMap[subPhase1Type]++;
}
}
}
else
{
if (phase1[0] >= 0 && phase1[0] <= 12)
{
if (phase1[1] == 0 && this->troop->helper[indexToTroop[phase1[0]]](0) > 0 && selectedTroopMap[indexToTroop[phase1[0]]] < this->troop->helper[indexToTroop[phase1[0]]](0))
troopIreru(indexToTroop[phase1[0]]);
else if (phase1[1] == 1)
troopNuku(indexToTroop[phase1[0]]);
else if (phase1[1] == 2)
{
for (int i = selectedTroopMap[indexToTroop[phase1[0]]]; i < this->troop->helper[indexToTroop[phase1[0]]](0); i++)
troopIreru(indexToTroop[phase1[0]]);
}
else if (phase1[1] == 3)
{
subMode = 1;
subPhase1Type = indexToTroop[phase1[0]];
}
else if (phase1[1] == 4)
{
auto current = std::next(this->army->total.begin(), phase1[0]);
bool found = false;
for (auto i : selectedArmy)
{
if (i == current->second)
{
armyNuku(current->second);
found = true;
break;
}
}
if (!found)
armyIreru(current->second);
}
}
else if (phase1[0] == 13)
{
if (phase1[1] == 0)
{
sendAll();
return;
}
else
deselectAll();
}
else
{
user.lock();
std::cout << "\033[2J\033[1;1H" << std::endl;
deselectAll();
mode = 0;
// avoid resource deadlock error
std::thread temp([&]() {
stopPrint();
loopPrint();
});
temp.detach();
return;
}
}
}
this->lg3.lock();
std::cout << "\033[2J\033[1;1H";
if (subMode == 0)
{
std::vector<std::vector<std::string>> prefix = {
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " ", " ", " "},
{" ", " "},
{" "}};
std::vector<std::map<std::string, ArmyUnit *>::iterator> ptr = {this->army->total.begin()};
for (int i = 0; i < this->army->total.size(); i++)
{
if (!ptr.back()->second->inBattle)
prefix[i].push_back(" ");
ptr.push_back(std::next(ptr.back(), 1));
}
phase1[0] = (phase1[0] + prefix.size()) % prefix.size();
phase1[1] = (phase1[1] + prefix[phase1[0]].size()) % prefix[phase1[0]].size();
prefix[phase1[0]][phase1[1]].replace(1, 1, color(">", "cyan"));
for (int i = 0; i < this->troop->allTroop.size(); i++)
{
if (this->troop->allTroop[i]->type != "suicideBomber" && this->troop->allTroop[i]->type != "kamikaze" && this->troop->allTroop[i]->getHealth() == typeToHealth[this->troop->allTroop[i]->type])
fullHealth[this->troop->allTroop[i]->type]++;
}
std::cout << color("Send Troops", "magenta") << std::endl
<< std::endl;
std::cout << std::setw(75 + 11) << color("Troop", "green") + " (full health, free, selected)" << color("Army", "green") << std::endl;
std::cout << std::setw(30) << "Infantry: " + std::to_string(fullHealth["infantry"]) + "/" + std::to_string(this->troop->helper["infantry"](0)) + "/" + std::to_string(selectedTroopMap["infantry"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 0 ? 11 : 0)) << prefix[0][0] + underline("+1", "green") + " (1)" + prefix[0][1] + underline("-1", "green") + prefix[0][2] + underline("All", "green") + prefix[0][3] + underline("Details", "green")
<< (this->army->total.size() > 0 ? (ptr[0]->first + " (" + std::to_string(ptr[0]->second->troopCount) + "/16)" + (ptr[0]->second->inBattle ? "" : prefix[0][4] + (selectedArmyMap.count(ptr[0]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Calvary: " + std::to_string(fullHealth["calvary"]) + "/" + std::to_string(this->troop->helper["calvary"](0)) + "/" + std::to_string(selectedTroopMap["calvary"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 1 ? 11 : 0)) << prefix[1][0] + underline("+1", "green") + " (2)" + prefix[1][1] + underline("-1", "green") + prefix[1][2] + underline("All", "green") + prefix[1][3] + underline("Details", "green")
<< (this->army->total.size() > 1 ? (ptr[1]->first + " (" + std::to_string(ptr[1]->second->troopCount) + "/16)" + (ptr[1]->second->inBattle ? "" : prefix[1][4] + (selectedArmyMap.count(ptr[1]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Suicide Bomber: " + std::string("-/") + std::to_string(this->troop->helper["suicideBomber"](0)) + "/" + std::to_string(selectedTroopMap["suicideBomber"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 2 ? 11 : 0)) << prefix[2][0] + underline("+1", "green") + " (3)" + prefix[2][1] + underline("-1", "green") + prefix[2][2] + underline("All", "green") + prefix[2][3] + underline("Details", "green")
<< (this->army->total.size() > 2 ? (ptr[2]->first + " (" + std::to_string(ptr[2]->second->troopCount) + "/16)" + (ptr[2]->second->inBattle ? "" : prefix[2][4] + (selectedArmyMap.count(ptr[2]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Artillery: " + std::to_string(fullHealth["artillery"]) + "/" + std::to_string(this->troop->helper["artillery"](0)) + "/" + std::to_string(selectedTroopMap["artillery"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 3 ? 11 : 0)) << prefix[3][0] + underline("+1", "green") + " (4)" + prefix[3][1] + underline("-1", "green") + prefix[3][2] + underline("All", "green") + prefix[3][3] + underline("Details", "green")
<< (this->army->total.size() > 3 ? (ptr[3]->first + " (" + std::to_string(ptr[3]->second->troopCount) + "/16)" + (ptr[3]->second->inBattle ? "" : prefix[3][4] + (selectedArmyMap.count(ptr[3]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Logistic: " + std::to_string(fullHealth["logistic"]) + "/" + std::to_string(this->troop->helper["logistic"](0)) + "/" + std::to_string(selectedTroopMap["logistic"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 4 ? 11 : 0)) << prefix[4][0] + underline("+1", "green") + " (5)" + prefix[4][1] + underline("-1", "green") + prefix[4][2] + underline("All", "green") + prefix[4][3] + underline("Details", "green")
<< (this->army->total.size() > 4 ? (ptr[4]->first + " (" + std::to_string(ptr[4]->second->troopCount) + "/16)" + (ptr[4]->second->inBattle ? "" : prefix[4][4] + (selectedArmyMap.count(ptr[4]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Armored Car: " + std::to_string(fullHealth["armoredCar"]) + "/" + std::to_string(this->troop->helper["armoredCar"](0)) + "/" + std::to_string(selectedTroopMap["armoredCar"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 5 ? 11 : 0)) << prefix[5][0] + underline("+1", "green") + " (6)" + prefix[5][1] + underline("-1", "green") + prefix[5][2] + underline("All", "green") + prefix[5][3] + underline("Details", "green")
<< (this->army->total.size() > 5 ? (ptr[5]->first + " (" + std::to_string(ptr[5]->second->troopCount) + "/16)" + (ptr[5]->second->inBattle ? "" : prefix[5][4] + (selectedArmyMap.count(ptr[5]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Tank 1: " + std::to_string(fullHealth["tank1"]) + "/" + std::to_string(this->troop->helper["tank1"](0)) + "/" + std::to_string(selectedTroopMap["tank1"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 6 ? 11 : 0)) << prefix[6][0] + underline("+1", "green") + " (7)" + prefix[6][1] + underline("-1", "green") + prefix[6][2] + underline("All", "green") + prefix[6][3] + underline("Details", "green")
<< (this->army->total.size() > 6 ? (ptr[6]->first + " (" + std::to_string(ptr[6]->second->troopCount) + "/16)" + (ptr[6]->second->inBattle ? "" : prefix[6][4] + (selectedArmyMap.count(ptr[6]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Tank 2: " + std::to_string(fullHealth["tank2"]) + "/" + std::to_string(this->troop->helper["tank2"](0)) + "/" + std::to_string(selectedTroopMap["tank2"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 7 ? 11 : 0)) << prefix[7][0] + underline("+1", "green") + " (8)" + prefix[7][1] + underline("-1", "green") + prefix[7][2] + underline("All", "green") + prefix[7][3] + underline("Details", "green")
<< (this->army->total.size() > 7 ? (ptr[7]->first + " (" + std::to_string(ptr[7]->second->troopCount) + "/16)" + (ptr[7]->second->inBattle ? "" : prefix[7][4] + (selectedArmyMap.count(ptr[7]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Tank Oshimai: " + std::to_string(fullHealth["tankOshimai"]) + "/" + std::to_string(this->troop->helper["tankOshimai"](0)) + "/" + std::to_string(selectedTroopMap["tankOshimai"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 8 ? 11 : 0)) << prefix[8][0] + underline("+1", "green") + " (9)" + prefix[8][1] + underline("-1", "green") + prefix[8][2] + underline("All", "green") + prefix[8][3] + underline("Details", "green")
<< (this->army->total.size() > 8 ? (ptr[8]->first + " (" + std::to_string(ptr[8]->second->troopCount) + "/16)" + (ptr[8]->second->inBattle ? "" : prefix[8][4] + (selectedArmyMap.count(ptr[8]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Cas: " + std::to_string(fullHealth["cas"]) + "/" + std::to_string(this->troop->helper["cas"](0)) + "/" + std::to_string(selectedTroopMap["cas"])
<< std::setw(75 + 11 * 4 - 30 + (phase1[1] < 4 && phase1[0] == 9 ? 11 : 0)) << prefix[9][0] + underline("+1", "green") + " (-)" + prefix[9][1] + underline("-1", "green") + prefix[9][2] + underline("All", "green") + prefix[9][3] + underline("Details", "green")
<< (this->army->total.size() > 9 ? (ptr[9]->first + " (" + std::to_string(ptr[9]->second->troopCount) + "/16)" + (ptr[9]->second->inBattle ? "" : prefix[9][4] + (selectedArmyMap.count(ptr[9]->first) == 0 ? underline("select", "green") : underline("deselect", "green")))) : "") << std::endl
<< std::setw(30) << "Fighter: " + std::to_string(fullHealth["fighter"]) + "/" + std::to_string(this->troop->helper["fighter"](0)) + "/" + std::to_string(selectedTroopMap["fighter"])
<< std::setw(75 + 11 * 4 - 30) << prefix[10][0] + underline("+1", "green") + " (-)" + prefix[10][1] + underline("-1", "green") + prefix[10][2] + underline("All", "green") + prefix[10][3] + underline("Details", "green") << std::endl
<< std::setw(30) << "Bomber: " + std::to_string(fullHealth["bomber"]) + "/" + std::to_string(this->troop->helper["bomber"](0)) + "/" + std::to_string(selectedTroopMap["bomber"])
<< std::setw(75 + 11 * 4 - 30) << prefix[11][0] + underline("+1", "green") + " (-)" + prefix[11][1] + underline("-1", "green") + prefix[11][2] + underline("All", "green") + prefix[11][3] + underline("Details", "green") << std::endl
<< std::setw(30) << "Kamikaze: " + std::string("-/") + std::to_string(this->troop->helper["kamikaze"](0)) + "/" + std::to_string(selectedTroopMap["kamikaze"])
<< std::setw(75 + 11 * 4 - 30) << prefix[12][0] + underline("+1", "green") + " (-)" + prefix[12][1] + underline("-1", "green") + prefix[12][2] + underline("All", "green") + prefix[12][3] + underline("Details", "green") << std::endl
<< std::endl;
std::cout << std::setw(30 + 11) << color("Troops selected: ", "green") + std::to_string(selectedTroop.size()) << color(" Armies selected: ", "green") << selectedArmy.size() << std::endl
<< std::endl;
std::cout << prefix[13][0] << underline("Confirm", "green") << " (z)" << prefix[13][1] << underline("Deselect all", "green") << " (x)" << std::endl
<< prefix[14][0] << underline("Back", "green") << " (spacebar)" << std::endl;
}
else if (subMode == 1)
{
std::vector<TroopUnit *> sort;
for (auto i : this->troop->allTroop)
if (i->type == subPhase1Type)
sort.push_back(i);
std::sort(sort.begin(), sort.end(), [](TroopUnit *a, TroopUnit *b) -> bool {
return a->getHealth() < b->getHealth();
});
if (sort.size() > 0)
{
subPhase1[0] = (subPhase1[0] + (int)std::ceil(sort.size() / 4.0)) % (int)std::ceil(sort.size() / 4.0);
subPhase1[1] = (subPhase1[1] + std::min((int)(sort.size() - subPhase1[0] * 4), 4)) % std::min((int)(sort.size() - subPhase1[0] * 4), 4);
}
else
{
subPhase1[0] = 0;
subPhase1[1] = 0;
}
int screenY = 20;
std::vector<std::string> render;
for (int i = 0; i < sort.size(); i++)
{
if (i % 4 == 0)
render.push_back("");
render.back() += std::string((i / 4 == subPhase1[0] && i % 4 == subPhase1[1] ? " > " : " ")) + (sort[i]->selected ? " ++" : " ") + typeToDisplay[subPhase1Type] + " (" + std::to_string((int)sort[i]->getHealth()) + "/" + std::to_string(typeToHealth[subPhase1Type]) + ") ";
}
int maxX = 0;
for (int i = 0; i < render.size(); i++)
if (render[i].length() > maxX)
maxX = render[i].length();
for (int i = 0; i < render.size(); i++)
if (render[i].length() < maxX)
render[i] += std::string(maxX - render[i].length(), ' ');
int scrollableY = std::max(0, (int)(render.size() - screenY));
scroll1[1] = 0;
scroll1[0] = std::min(std::max(0, scroll1[0]), scrollableY);
if (subPhase1Mode == 0)
{
if (subPhase1[0] < scroll1[0])
scroll1[0] = subPhase1[0];
else if (subPhase1[0] >= scroll1[0] + screenY)
scroll1[0] = subPhase1[0] - screenY + 1;
scroll1[0] = std::min(std::max(0, scroll1[0]), scrollableY);
}
else if (subPhase1Mode == 1)
{
if (subPhase1[0] < scroll1[0])
subPhase1[0] = scroll1[0];
else if (subPhase1[0] >= scroll1[0] + screenY)
subPhase1[0] = scroll1[0] + screenY - 1;
}
if (sort.size() > 0)
subPhase1TroopDetail = sort[subPhase1[0] * 4 + subPhase1[1]];
std::cout << color("Details of " + typeToDisplay[subPhase1Type], "green") << std::endl
<< "(enter to select/deselect) (spacebar to return)" << std::endl
<< std::endl;
if (scroll1[0] != 0)
std::cout << std::string(maxX / 2 - 8, ' ') + "||Scroll up (w)||" + std::string(maxX / 2 - 8, ' ') << std::endl;
else
std::cout << std::endl;
for (int i = scroll1[0]; i < std::min(scroll1[0] + screenY, (int)render.size()); i++)
std::cout << render[i] << std::endl;
if (scroll1[0] != scrollableY)
std::cout << std::string(maxX / 2 - 8, ' ') + "||Scroll down (s)||" + std::string(maxX / 2 - 8, ' ') << std::endl;
else
std::cout << std::endl;
}
this->lg3.unlock();
});
printMode.push_back([&]() {
Block *ptr = this->enemies->totalEnemies[currentCountry]->map[phase0[0]][phase0[1]];
if (!ptr->battling)
{
user.lock();
std::cout << "\033[2J\033[1;1H" << std::endl;
mode = 0;
subPhase2Mode = 0;
// avoid resource deadlock error
std::thread temp([&]() {
stopPrint();
loopPrint();
});
temp.detach();
return;
}
if (subPhase2Mode == 0)
{
int fillX = 150;
int screenY = 27;
std::vector<std::string> render;
BattleUnit *ptr2 = ptr->battle.back();
ptr2->lg.lock();
render.push_back(std::string(fillX / 2 - 2, ' ') + "Stats");
render.back() += std::string((int)(fillX - render.back().length()), ' ');
int deathFd = (int)std::round(1.0 * ptr2->totalFriendlyDeathCount / ptr2->totalFriendly * 20);
int deathFoe = (int)std::round(1.0 * ptr2->totalFoeDeathCount / ptr->totalFoe * 20);
render.push_back("Casualty Rate: " + std::string(20 - deathFd, '+') + std::string(deathFd, '-'));
std::string temp = std::string(deathFoe, '-') + std::string(20 - deathFoe, '+') + " :Casualty Rate";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Soft Attack: " + std::to_string((int)ptr2->totalSoftAttack));
temp = std::to_string((int)ptr2->totalFoeSoftAttack) + " :Soft Attack";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Hard Attack: " + std::to_string((int)ptr2->totalHardAttack));
temp = std::to_string((int)ptr2->totalFoeHardAttack) + " :Hard Attack";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Air Attack: " + std::to_string((int)ptr2->totalAirAttack));
temp = std::to_string((int)ptr2->totalFoeAirAttack) + " :Air Attack";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back(std::string(fillX / 2 - 2, ' ') + "Troops");
render.back() += std::string((int)(fillX - render.back().length()), ' ');
render.push_back("Infantry: " + std::to_string(ptr2->friendCount["infantry"]));
temp = std::to_string(ptr->foeCount["infantry"]) + " :Infantry";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Calvary: " + std::to_string(ptr2->friendCount["Calvary"]));
temp = std::to_string(ptr->foeCount["Calvary"]) + " :Calvary";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Suicide Bomber: " + std::to_string(ptr2->friendCount["suicideBomber"]));
temp = "0 :Suicide Bomber";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Artillery: " + std::to_string(ptr2->friendCount["artillery"]));
temp = std::to_string(ptr->foeCount["artillery"]) + " :Artillery";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Logistic: " + std::to_string(ptr2->friendCount["logistic"]));
temp = std::to_string(ptr->foeCount["logistic"]) + " :Logistic";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Armored Car: " + std::to_string(ptr2->friendCount["armoredCar"]));
temp = std::to_string(ptr->foeCount["armoredCar"]) + " :Armored Car";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Tank 1: " + std::to_string(ptr2->friendCount["tank1"]));
temp = std::to_string(ptr->foeCount["tank1"]) + " :Tank 1";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Tank 2: " + std::to_string(ptr2->friendCount["tank2"]));
temp = std::to_string(ptr->foeCount["tank2"]) + " :Tank 2";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Tank Oshimai: " + std::to_string(ptr2->friendCount["tankOshimai"]));
temp = std::to_string(ptr->foeCount["tankOshimai"]) + " :Tank Oshimai";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Cas: " + std::to_string(ptr2->friendCount["cas"]));
temp = std::to_string(ptr->foeCount["cas"]) + " :Cas";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Fighter: " + std::to_string(ptr2->friendCount["fighter"]));
temp = std::to_string(ptr->foeCount["fighter"]) + " :Fighter";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Bomber: " + std::to_string(ptr2->friendCount["bomber"]));
temp = std::to_string(ptr->foeCount["bomber"]) + " :Bomber";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
render.push_back("Kamikaze: " + std::to_string(ptr2->friendCount["kamikaze"]));
temp = "0 :Kamikaze";
render.back() += std::string((int)(fillX - render.back().length() - temp.length()), ' ') + temp;
for (int i = 0; i < render.size(); i++)
assert(render[i].length() == fillX);
render.push_back(std::string(fillX / 2 - 2, ' ') + "Armies");
render.back() += std::string((int)(fillX - render.back().length()), ' ');
int troopLength = 16;
int start = render.size();
for (auto i : ptr2->mikata->totalArmy)
{
render.push_back("D" + std::string(troopLength - 1, ' ') + "C" + std::string(troopLength - 1, ' ') + "B" + std::string(troopLength - 1, ' ') + "A" + std::string(troopLength - 1, ' '));
render.back() += std::string((int)(fillX / 2 - render.back().length()), ' ');
for (int j = 0; j < 4; j++)
{
render.push_back("");
for (int k = 3; k >= 0; k--)
{
if (i->formation[k][j] != NULL)
temp = typeToDisplay[i->formation[k][j]->type];
else
temp = "None";
render.back() += temp + std::string(troopLength - temp.length(), ' ');
}
render.back() += std::string((int)(fillX / 2 - render.back().length()), ' ');
render.push_back("");
for (int k = 3; k >= 0; k--)
{
if (i->formation[k][j] != NULL)
temp = "(" + std::to_string((int)i->formation[k][j]->getHealth()) + "/" + std::to_string(i->formation[k][j]->getBaseHealth()) + ")";
else
temp = "";
render.back() += temp + std::string(troopLength - temp.length(), ' ');
}
render.back() += std::string((int)(fillX / 2 - render.back().length()), ' ');
}
render.push_back(std::string(fillX / 2, ' '));
}
int tempCount = 0;
std::string temp2 = "";
for (auto i : ptr2->foe->totalArmy)
{
temp = std::string(troopLength - 1, ' ') + "A" + std::string(troopLength - 1, ' ') + "B" + std::string(troopLength - 1, ' ') + "C" + std::string(troopLength - 1, ' ') + "D";
if (render.size() <= start + tempCount * 10)
{
for (int i = 0; i < 10; i++)
render.push_back(std::string(fillX / 2, ' '));
}
render[start + tempCount * 10] += std::string((int)(fillX / 2 - temp.length()), ' ') + temp;
for (int j = 0; j < 4; j++)
{
for (int k = 0; k < 4; k++)
{
if (i->formation[k][j] != NULL)
temp = typeToDisplay[i->formation[k][j]->type];
else
temp = "None";
temp2 += std::string(troopLength - temp.length(), ' ') + temp;
}
render[start + tempCount * 10 + j * 2 + 1] += std::string((int)(fillX / 2 - temp2.length()), ' ') + temp2;
temp2 = std::string(troopLength * 4, ' ');
render[start + tempCount * 10 + j * 2 + 2] += std::string((int)(fillX / 2 - temp2.length()), ' ') + temp2;
temp2 = "";
}
render[start + tempCount * 10 + 9] += std::string(fillX / 2, ' ');
tempCount++;
}
for (int i = 0; i < render.size(); i++)
if (render[i].length() < fillX)
render[i] += std::string(fillX - render[i].length(), ' ');
int scrollableY = std::max(0, (int)(render.size() - screenY));
scroll2[1] = 0;
scroll2[0] = std::min(std::max(0, scroll2[0]), scrollableY);
std::cout << "\033[1;1H";
std::cout << color("View Battle", "magenta") << std::endl
<< "Change Speed: q Pause: p Retreat all: r Battle log: l Back: spacebar"
<< std::endl
<< std::endl;
this->lg.lock();
std::stringstream speed;
speed << std::fixed << std::setprecision(1) << this->setting["speed"] / 1000.0;
std::cout << color("Day: ", "green") << this->day << "/" << this->timeLimit << " (" << speed.str() << "s) " << (this->paused ? color("PAUSED", "red") : "") << std::endl
<< std::endl;
this->lg.unlock();
if (scroll2[0] != 0)
std::cout << std::string(fillX / 2 - 7, ' ') + "||Scroll up (w)||" + std::string(fillX / 2 - 8, ' ') << std::endl;
else
std::cout << std::string(fillX, ' ') << std::endl;
for (int i = scroll2[0]; i < std::min((int)render.size(), scroll2[0] + screenY); i++)
std::cout << render[i] << std::endl;
if (scroll2[0] != scrollableY)
std::cout << std::string(fillX / 2 - 8, ' ') + "||Scroll down (s)||" + std::string(fillX / 2 - 9, ' ') << std::endl;
else
std::cout << std::string(fillX, ' ') << std::endl;
ptr2->lg.unlock();
}
else
{
std::cout << "\033[2J\033[1;1H";
std::cout << color("View Battle", "magenta") << std::endl
<< "Change Speed: q Pause: p Back: spacebar"
<< std::endl
<< std::endl;
this->lg.lock();
std::stringstream speed;
speed << std::fixed << std::setprecision(1) << this->setting["speed"] / 1000.0;
std::cout << color("Day: ", "green") << this->day << "/" << this->timeLimit << " (" << speed.str() << "s) " << (this->paused ? color("PAUSED", "red") : "") << std::endl
<< std::endl;
this->lg.unlock();
BattleUnit *ptr = this->enemies->totalEnemies[currentCountry]->map[phase0[0]][phase0[1]]->battle.back();
for (int i = std::max(0, (int)ptr->log.size() - 26); i < ptr->log.size(); i++)
std::cout << ptr->log[i] << std::endl;
}
});
loopPrint = [&]() {
printFuture = std::async(std::launch::async, [&]() {
terminatePrint = false;
user.unlock();
while (!terminatePrint && !this->gameOver)
{
printMode[mode]();
std::unique_lock<std::mutex> lock(printa);
printCond.wait_for(lock, std::chrono::milliseconds(1000 / this->fps));
}
});
};
stopPrint = [&]() {
if (printFuture.valid())
{
terminatePrint = true;
printCond.notify_all();
printFuture.get();
}
};
std::cout << "\033[2J\033[1;1H";
user.lock();
loopPrint();
char input;
// std::future<void> temp = std::async(std::launch::async, [&]() {while(1){clean_stdin();std::this_thread::sleep_for(std::chrono::milliseconds(500));} });
while (1)
{
if (this->gameOver)
{
this->stopTimer();
this->endGame();
while (input != ' ')
input = getch();
break;
}
input = getch();
if (this->gameOver)
{
this->stopTimer();
this->endGame();
while (input != ' ')
input = getch();
break;
}
user.lock();
stopPrint();
user.unlock();
if (input == '\033')
{
getch();
switch (getch())
{
case 'A':
if (mode == 0)
{
subPhase0Mode = 0;
if (subMode == 0)
phase0[0]--;
else
subPhase0[0]--;
}
else if (mode == 1)
{
subPhase1Mode = 0;
if (subMode == 0)
phase1[0]--;
else
subPhase1[0]--;
}
break;
case 'B':
if (mode == 0)
{
subPhase0Mode = 0;
if (subMode == 0)
phase0[0]++;
else
subPhase0[0]++;
}
else if (mode == 1)
{
subPhase1Mode = 0;
if (subMode == 0)
phase1[0]++;
else
subPhase1[0]++;
}
break;
case 'C':
if (mode == 0)
{
subPhase0Mode = 0;
if (subMode == 0)
phase0[1]++;
else
subPhase0[1]++;
}
else if (mode == 1)
{
subPhase1Mode = 0;
if (subMode == 0)
phase1[1]++;
else
subPhase1[1]++;
}
break;
case 'D':
if (mode == 0)
{
subPhase0Mode = 0;
if (subMode == 0)
phase0[1]--;
else
subPhase0[1]--;
}
else if (mode == 1)
{
subPhase1Mode = 0;
if (subMode == 0)
phase1[1]--;
else
subPhase1[1]--;
}
break;
case '1':
getch();
getch();
getch();
}
}
else if (input == '\n')
{
enter = true;
}
else if (input == 'w')
{
if (mode == 0)
{
subPhase0Mode = 1;
scroll0[0]--;
}
else if (mode == 1)
{
subPhase1Mode = 1;
scroll1[0]--;
}
else if (mode == 2)
scroll2[0]--;
}
else if (input == 'a')
{
if (mode == 0)
{
subPhase0Mode = 1;
scroll0[1]--;
}
else if (mode == 1)
{
subPhase1Mode = 1;
scroll1[1]--;
}
else if (mode == 2)
scroll2[1]--;
}
else if (input == 's')
{
if (mode == 0)
{
scroll0[0]++;
subPhase0Mode = 1;
}
else if (mode == 1)
{
subPhase1Mode = 1;
scroll1[0]++;
}
else if (mode == 2)
scroll2[0]++;
}
else if (input == 'd')
{
if (mode == 0)
{
subPhase0Mode = 1;
scroll0[1]++;
}
else if (mode == 1)
{
subPhase1Mode = 1;
scroll1[1]++;
}
else if (mode == 2)
scroll2[1]++;
}
else if (input == 'q')
{
this->stopTimer();
timeChosen = (timeChosen + 1) % this->timeRange.size();
this->setting["speed"] = this->timeRange[this->timeChosen];
this->timer(this->setting["speed"]);
}
else if (input == 'z')
{
if (mode == 0)
{
Enemy *ptr = this->enemies->totalEnemies[currentCountry];
if ((!this->battle->inBattle || this->battle->countryBattling == ptr->name) && !ptr->map[phase0[0]][phase0[1]]->captured && ptr->map[phase0[0]][phase0[1]]->isAttackable && !ptr->capitulated)
{
mode = 1;
subMode = 0;
}
}
else if (mode == 1 && subMode == 0)
{
sendAll();
continue;
}
}
else if (input == 'r')
{
if (mode == 0)
retreatAll();
else if (mode == 1 && subMode == 0)
{
deselectAll();
}
else if (mode == 2)
retreatAll();
}
else if (input == 'v')
{
if (mode == 0)
{
if (this->enemies->totalEnemies[currentCountry]->map[phase0[0]][phase0[1]]->battling)
{
mode = 2;
subMode = 0;
}
}
}
else if (input == 'e')
{
if (mode == 0)
{
currentCountry = (currentCountry + 1) % this->enemies->totalEnemies.size();
phase0[0] = 0;
phase0[0] = 0;
subMode = 0;
}
}
else if (input == 'p')
{
this->paused = !this->paused;
}
else if (input == 'l')
{
if (mode == 2)
{
if (subPhase2Mode == 0)
subPhase2Mode = 1;
}
}
else if (input == ' ')
{
if (mode == 0)
{
if (subMode == 0)
{
gamePhase = prevPhase;
this->gamePhaseSelect[0] = 0;
this->gamePhaseSelect[1] = 0;
(this->*this->print[this->gamePhase])(this->gamePhaseSelect[0], this->gamePhaseSelect[1]);
break;
}
else
subMode = 0;
}
else if (mode == 1)
{
if (subMode == 0)
{
deselectAll();
mode = 0;
}
else
subMode = 0;
}
else if (mode == 2)
{
if (subPhase2Mode == 0)
mode = 0;
else
subPhase2Mode = 0;
}
}
else if (input == '1')
{
if (mode == 1)
troopIreru(indexToTroop[0]);
}
else if (input == '2')
{
if (mode == 1)
troopIreru(indexToTroop[1]);
}
else if (input == '3')
{
if (mode == 1)
troopIreru(indexToTroop[2]);
}
else if (input == '4')
{
if (mode == 1)
troopIreru(indexToTroop[3]);
}
else if (input == '5')
{
if (mode == 1)
troopIreru(indexToTroop[4]);
}
else if (input == '6')
{
if (mode == 1)
troopIreru(indexToTroop[5]);
}
else if (input == '7')
{
if (mode == 1)
troopIreru(indexToTroop[6]);
}
else if (input == '8')
{
if (mode == 1)
troopIreru(indexToTroop[7]);
}
else if (input == '9')
{
if (mode == 1)
troopIreru(indexToTroop[8]);
}
user.lock();
std::cout << "\033[2J\033[1;1H";
loopPrint();
}
}
|
#include "ImageDrawer.hh"
void ImageDrawer::Compute()
{
sf::Texture texture = LimitTextureSize(in_texture->GetData());
sf::Vector2u texture_size = texture.getSize();
sf::Sprite sprite;
sprite.setTexture(texture);
sf::RenderWindow window(
sf::VideoMode(texture_size.x, texture_size.y),
"Image Display" );
window.setPosition({0, 0});
while(window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color::Black);
window.draw(sprite);
window.display();
}
}
ImageDrawer::ImageDrawer(std::string _name)
: Block(_name)
{
in_texture = new Input<sf::Texture>(this);
}
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
srand(time(NULL));
ofVec2f sunPos = ofVec2f(ofGetWidth() / 2.0f, ofGetHeight() / 2.0f);
// ,distance, radiusAtraction, velocity, mass,size
SolarSystem.push_back(Planet(sunPos, 0, 350, 0, 1989, 80, ofColor(255, 157, 0)));
SolarSystem.push_back(Planet(SolarSystem[Sun].GetPosition(), 350, 85, 360 / 15.0f, 200, 20, ofColor(0, 135, 255)));
SolarSystem.push_back(Planet(SolarSystem[Earth].GetPosition(), 85, 30, 360.0f / 3.5f, 50, 8, ofColor(149, 152, 153)));
contTime = 0;
}
//--------------------------------------------------------------
void ofApp::update(){
float deltaTime = ofGetLastFrameTime();
SolarSystem[Sun]. Update(SolarSystem[Sun].GetPosition(), deltaTime);
SolarSystem[Earth]. Update(SolarSystem[Sun].GetPosition(), deltaTime);
SolarSystem[Moon]. Update(SolarSystem[Earth].GetPosition(), deltaTime);
contTime += deltaTime;
if (contTime >= TIME_SPAWN_METEOR) {
contTime -= TIME_SPAWN_METEOR;
Meteors.push_back(Meteor());
}
// Percorre os meteros atualizando os que estao na tela e exclui os que nao estao
for (int i = 0; i < Meteors.size(); i++) {
if (Meteors[i].OnScreen() && !Meteors[i].Collided()) {
Meteors[i].Update(SolarSystem, deltaTime);
}
else {
Meteors.erase(Meteors.begin() + i);
}
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofSetBackgroundColor(10, 10, 15);
ofSetColor(255, 255, 255);
for (Planet i : SolarSystem) {
i.Draw();
}
ofSetColor(115, 50, 50);
for (Meteor i : Meteors) {
i.Draw();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
Meteors.push_back(Meteor());
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
|
#include "onefilter.h"
#include "ui_onefilter.h"
#include <QTimer>
#include <iodev.h>
OneFilter::OneFilter(IoDev &src,QWidget *parent) :
QDialog(parent),
m_ui(new Ui::OneFilter),
n(1),
s(src)
{
m_ui->setupUi(this);
QTimer *t=new QTimer(this);
t->setInterval(1000);
t->start();
connect(t,SIGNAL(timeout()),this,SLOT(updateData()));
connect(m_ui->bx_Am,SIGNAL(currentIndexChanged(int)),this,SLOT(setAm(int)));
}
OneFilter::~OneFilter()
{
delete m_ui;
}
void OneFilter::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
m_ui->retranslateUi(this);
break;
default:
break;
}
}
void OneFilter::setFn(int i)
{
n=i;
m_ui->le_Nf->setText(QString("%1").arg((i)));
// ініціалізувати перемикач режиму роботи.
int v=s.getValue16(QString("Am_%1_").arg(n));
m_ui->bx_Am->setCurrentIndex(v?1:0);
if(v)
{
disconnect(m_ui->cb_Vl_1_1,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
disconnect(m_ui->cb_Vl_1_2,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
disconnect(m_ui->cb_Vl_1_3,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
}
else
{
connect(m_ui->cb_Vl_1_1,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
connect(m_ui->cb_Vl_1_2,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
connect(m_ui->cb_Vl_1_3,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
}
}
void OneFilter::updateData()
{
qint16 mode;
mode=s.getValue16(QString("Amr_%1_").arg(n));
m_ui->le_Amr->setText(mode?tr("Remote"):tr("Local"));
if(mode==0 && m_ui->bx_Am->currentIndex()>0 ) // в локальному режимі
{
m_ui->bx_Am->setCurrentIndex(0); // вимкнути автомат
}
m_ui->cb_Cl_1_1->setChecked(s.getValue16(QString("Cl_%1_1").arg(n)));
m_ui->cb_Cl_1_2->setChecked(s.getValue16(QString("Cl_%1_2").arg(n)));
m_ui->cb_Cl_1_3->setChecked(s.getValue16(QString("Cl_%1_3").arg(n)));
if(m_ui->bx_Am->currentIndex()) // якщо працюємо в автоматичному режимі - показати команди
{
m_ui->cb_Vl_1_1->setChecked(s.getValue16(QString("Vl_%1_1").arg(n)));
m_ui->cb_Vl_1_2->setChecked(s.getValue16(QString("Vl_%1_2").arg(n)));
m_ui->cb_Vl_1_3->setChecked(s.getValue16(QString("Vl_%1_3").arg(n)));
}
}
void OneFilter::setAm(int v)
{
s.sendValue(QString("Am_%1_").arg(n),qint16(v?-1:0));
if(v)
{
disconnect(m_ui->cb_Vl_1_1,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
disconnect(m_ui->cb_Vl_1_2,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
disconnect(m_ui->cb_Vl_1_3,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
}
else
{
connect(m_ui->cb_Vl_1_1,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
connect(m_ui->cb_Vl_1_2,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
connect(m_ui->cb_Vl_1_3,SIGNAL(stateChanged(int)),this,SLOT(setValve(int)));
}
}
void OneFilter::setValve(int v)
{
qDebug() << sender()->objectName() << v;
int f=sender()->objectName().mid(8,1).toInt(); // визначити номер клапана
s.sendValue(QString("Vl_%1_%2").arg(n).arg(f),qint16(v?-1:0)); // відправити команду на клапан
}
|
#pragma once
#include <deque>
#include "input_utils.hpp"
#include <range/v3/all.hpp>
template<size_t PreambleSize> struct preamble_finder
{
using preamble = std::array<int, PreambleSize>;
static auto find_pair(preamble &p, size_t ¤t_pos, const int num) -> bool
{
auto sorted{ p };
ranges::sort(sorted);
auto l = std::begin(sorted);
auto r = std::prev(std::end(sorted));
auto found = false;
while (l < r) {
auto const sum = *l + *r;
if (sum == num) {
found = true;
break;
}
if (sum < num)
++l;
else
--r;
}
if (!found) return true;
p[current_pos] = num;
current_pos = (current_pos + 1) % PreambleSize;
return false;
}
static auto find_wrong_number(std::vector<int> const &numbers) -> auto
{
preamble preamble{};
std::copy_n(numbers.begin(), PreambleSize, preamble.begin());
size_t current_pos = 0;
auto const found =
ranges::find_if(numbers | ranges::views::drop(PreambleSize),
[&preamble, ¤t_pos](
const int value) { return find_pair(preamble, current_pos, value); });
return found;
}
static auto solve_part1(std::istream &input) -> std::string
{
auto const numbers = utils::split<int>(input);
auto const found = find_wrong_number(numbers);
return std::to_string(*found);
}
static auto solve_part2(std::istream &input) -> std::string
{
auto const numbers = utils::split<int>(input);
auto const found = *find_wrong_number(numbers);
std::deque<int> range{};
auto sum = 0;
auto range_end =
ranges::find_if(numbers, [found, &sum, &range](auto const num) {
sum += num;
range.push_back(num);
while (sum > found) {
auto const f = range.front();
sum -= f;
range.pop_front();
}
return found == sum;
});
const auto [min, max] = ranges::minmax_element(range);
return std::to_string(*min + *max);
}
};
|
#include <Wire.h>
void setup() {
Wire.begin();
Serial.begin(250000);
}
void loop() {
uint16_t u1 = pulseIn(A0, 1, 45000);
uint16_t u2 = pulseIn(A1, 1, 45000);
int8_t v1 = constrain(map(u1 < 1000 ? 1500 : u1 < 1480 ? u1 : u1 < 1520 ? 1500 : u1 < 2000 ? u1 : 1500, 1100, 1900, -127, 127), -127, 127);
int8_t v2 = constrain(map(u2 < 1000 ? 1500 : u2 < 1480 ? u2 : u2 < 1520 ? 1500 : u2 < 2000 ? u2 : 1500, 1100, 1900, -127, 127), -127, 127);
Wire.beginTransmission(8);
Wire.write(constrain(v2-v1,-127,127));
Wire.write(constrain(v2+v1,-127,127));
Wire.endTransmission();
Wire.beginTransmission(9);
Wire.write(constrain(v2-v1,-127,127));
Wire.write(constrain(v2+v1,-127,127));
Wire.endTransmission();
}
|
#include "Plane.h"
Plane::Plane(Vec3f a, Vec3f b, Vec3f c, Material M)
{
Vec3f AB = b - a;
Vec3f AC = c - a;
Vec3f normal = AB.cross(AC);
x = normal.getX();
y = normal.getY();
z = normal.getZ();
d = ((x * a.getX()) + (y * a.getY()) + (z * a.getZ())) * -1;
m = M;
}
Plane::Plane(double a, double b, double c, double D, Material M)
{
x = a;
y = b;
z = c;
d = D;
m = M;
}
double Plane::getX()
{
return x;
}
double Plane::getY()
{
return y;
}
double Plane::getZ()
{
return z;
}
double Plane::getD()
{
return d;
}
Material Plane::getMaterial()
{
return m;
}
Vec3f Plane::findCollision(Ray ray)
{
Vec3f origin = ray.getOrigin();
Vec3f direction = ray.getDirection();
double pXD = direction.getX() * x;
double pYD = direction.getY() * y;
double pZD = direction.getZ() * z;
double pXO = origin.getX() * x;
double pYO = origin.getY() * y;
double pZO = origin.getZ() * z;
double pO = pXO + pYO + pZO;
double pD = pXD + pYD + pZD;
double tempD = d * 1;
tempD -= pO;
double t = tempD / pD;
if(t <= 1)
{
return Vec3f(-1000000000, -100000000, -1000000000);
}
return Vec3f((t*direction.getX() + origin.getX()),(t*direction.getY() + origin.getY()),(t*direction.getZ() + origin.getZ()));
}
double Plane::findT(Ray ray)
{
Vec3f origin = ray.getOrigin();
Vec3f direction = ray.getDirection();
double pXD = direction.getX() * x;
double pYD = direction.getY() * y;
double pZD = direction.getZ() * z;
double pXO = origin.getX() * x;
double pYO = origin.getY() * y;
double pZO = origin.getZ() * z;
double pO = pXO + pYO + pZO;
double pD = pXD + pYD + pZD;
double tempD = d * 1;
tempD -= pO;
double t = tempD / pD;
if(t <= 1)
{
return -1000000000;
}
else{
return t;
}
}
|
/**
* Unit test harness
*/
#include <iostream>
#include ".generated/version.h"
#include "testcase.h"
#include <CORE/BASE/asserts.h>
#include <CORE/BASE/logging.h>
#include <CORE/VFS/vfs.h>
int main(int argc, char **argv) {
core::logging::RegisterSink(
std::make_shared< core::logging::iLogSink >(~core::types::BitSet< LL >()))
.ignoreErrors();
vfs::Mount("./", "./");
std::cout << "# Testing for build: " << BUILD_BRANCH_ID << "@"
<< BUILD_VERSION_HASH << " built on " << BUILD_TIMESTAMP
<< std::endl;
std::cout << "# Running tests..." << std::endl;
const int errorCount = testing::runRegisteredTests();
std::cout << "# Done. With " << errorCount << " errors." << std::endl;
vfs::UnmountAll();
ASSERT(errorCount == 0);
return ((errorCount == 0) ? 0 : 1);
}
|
vector<int> Solution::maxone(vector<int> &A, int B) {
int n=A.size();
int curr_left=0,curr_right=0;
int best_left=0,best_right=0;
int count0=0;
while(curr_right<n)
{
if(count0<=B)
{
if(A[curr_right]==0)
count0++;
curr_right++;
}
if(count0>B)
{
if(A[curr_left]==0)
count0--;
curr_left++;
}
if(curr_right-curr_left>best_right-best_left)
{
best_left=curr_left;
best_right=curr_right;
}
}
vector<int> ans;
for(int i=best_left;i<best_right;i++)
ans.push_back(i);
return ans;
}
|
#include "bintree.h"
BinTree *createBinTree()
{
BinTree *tree = new BinTree;
tree->root = nullptr;
tree->deep = 0;
return tree;
}
BinNode *createBinNode(char info, bool isNum)
{
BinNode *node = new BinNode;
node->info = info;
node->isLeaf = isNum;
node->left = nullptr;
node->right = nullptr;
return node;
}
BinNode *appendRight(BinNode *node, char info, bool isNum)
{
node->right = createBinNode(info, isNum);
return node->right;
}
BinNode *appendLeft(BinNode *node, char info, bool isNum)
{
node->left = createBinNode(info, isNum);
return node->left;
}
BinNode *setInfo(BinNode *node, char info, bool isNum)
{
if (node == nullptr)
return nullptr;
node->info = info;
node->isLeaf = isNum;
return node;
}
int countDeep(BinNode *&node)
{
if (node == nullptr)
return 0;
int cl = countDeep(node->left);
int cr = countDeep(node->right);
return 1 + ((cl>cr)?cl:cr);
}
int updateDeep(BinTree *tree)
{
tree->deep = countDeep(tree->root);
return tree->deep;
}
BinTree *getTreeFromArray(QStringList in, int &err)
{
stack <BinNode *> BNStack;
BinTree *tree = createBinTree();
tree->root = createBinNode('\0', 1);
BinNode *temp = tree->root;
BNStack.push(temp);
for (int i=0; i<in.length(); i++)
{
if (in[i] == "(")
{
BNStack.push(temp);
temp = appendLeft(temp, '\0', 1);
}
else if (in[i] == ")")
{
if (BNStack.empty() || temp->info == '\0')
{
err = INVAL_POST;
return tree;
}
if (temp == BNStack.top()->left)
{
temp = BNStack.top();
temp = appendRight(temp, '\0', 1);
}
else
{
temp = BNStack.top();
BNStack.pop();
}
}
else if (in[i] == "*" || in[i] == "/" || in[i] == "-" || in[i] == "+")
{
setInfo(temp, qPrintable(in[i])[0], 0);
}
else
{
if (in[i].length() > 1 || ((in[i][0] < 'a' || in[i][0] > 'z') && (!in[i][0].isDigit())))
{
err = INVAL_ARG;
return tree;
}
if (BNStack.empty())
{
err = INVAL_POST;
return tree;
}
setInfo(temp, qPrintable(in[i])[0], 1);
if (temp == BNStack.top()->left)
{
temp = BNStack.top();
temp = appendRight(temp, '\0', 1);
}
else
{
temp = BNStack.top();
BNStack.pop();
}
}
}
if (!BNStack.empty())
{
err = INVAL_POST;
return tree;
}
updateDeep(tree);
return tree;
}
QString getQStrFromTree(BinNode *root)
{
if (root == nullptr)
return "";
QString output;
if (root->left || root->right)
output += "(";
output += getQStrFromTree(root->left);
output += root->info;
output += getQStrFromTree(root->right);
if (root->left || root->right)
output += ")";
return output;
}
QString getListFromTree(BinNode *root, int indent)
{
if (root == nullptr)
return "";
QString output;
output += QString(indent, '.');
output += root->info;
output += "\n";
output += getListFromTree(root->left, indent+3);
output += getListFromTree(root->right, indent+3);
return output;
}
|
// Copyright 2016 Carrie Rebhuhn
#include "Domains/Rover/include/RoverDomain.h"
#include <algorithm>
#include <vector>
void append(matrix1d &a, const matrix1d &b) {
a.insert(a.end(), b.begin(), b.end());
}
int Loc::relQuadrant(Loc* l) {
double dx = l->x_ - x_;
double dy = l->y_ - y_;
int val = 2;
if (l->x_ - x_ > 0) {
val = 3;
if (l->y_ - y_ > 0) val = 0;
}
if (l->y_ - y_ > 0) val = 1;
return val;
}
double Loc::norm(Loc *l) {
double dx = l->x_ - x_;
double dy = l->y_ - y_;
return dx*dx + dy*dy;
}
void Loc::operator+=(std::vector<double> v) {
x_ += v[0];
y_ += v[1];
}
double Sensor::denom(const std::vector<bool> &in_quadrant) {
std::vector<double> deltas;
for (auto l : L_) deltas.push_back(delta(l));
return ifLeftAddRight(in_quadrant, deltas);
}
double Sensor::sense() {
std::vector<bool> in_quadrant(inQuadrant(L_));
double n = numer(in_quadrant);
if (n == 0) return 0;
return n / denom(in_quadrant);
}
std::vector<bool> Sensor::inQuadrant(Locs L) {
std::vector<bool> q;
for (auto l : L) q.push_back(l_->relQuadrant(l) == quadrant_);
return q;
}
Rover::Rover() : l_(new Loc(rand(0, XDIM), rand(0, YDIM))) {
for (int q = 0; q < 4; q++) {
psensor.push_back(POISensor(l_, q));
rsensor.push_back(RoverSensor(l_, q));
}
}
RoverDomain::RoverDomain() : IDomainStateful(8, 2, NROVS, 25) {
k_num_agents_ = NROVS;
//state_history_ = matrix2d(k_num_agents_);
//action_history_ = matrix2d(k_num_agents_); // append each time action taken
matrix2d pstartlocs(NPOIS, matrix1d(2));
for (int i = 0; i < NPOIS; i++) {
pois.push_back(new POI());
poi_start_locs_.push_back(*pois.back()->l_);
pstartlocs[i][0] = poi_start_locs_[i].x_;
pstartlocs[i][1] = poi_start_locs_[i].y_;
}
cio::print2(pstartlocs, "poi_xy.csv");
matrix2d rstartlocs(NROVS, matrix1d(2));
for (int j = 0; j < NROVS; j++) {
rovers.push_back(new Rover());
rover_start_locs_.push_back(*rovers.back()->l_);
rstartlocs[j][0] = rover_start_locs_[j].x_;
rstartlocs[j][1] = rover_start_locs_[j].y_;
}
cio::print2(rstartlocs, "rov_xy.csv");
initialize();
}
RoverDomain::~RoverDomain() {
for (auto p : pois) delete p;
for (auto r : rovers) delete r;
}
matrix2d RoverDomain::getStates() {
matrix2d S;
for (auto &r : rovers) {
S.push_back(matrix1d());
for (auto s : r->psensor) {
S.back().push_back(s.sense());
}
for (auto s : r->rsensor) {
S.back().push_back(s.sense());
}
}
return S;
}
void RoverDomain::initialize() {
Locs P, R;
P = Sensor::getLocs(pois);
R = Sensor::getLocs(rovers);
std::vector<double> v;
for (auto &p : pois) {
v.push_back(p->value_);
}
for (auto &r : rovers) {
for (auto &s : r->psensor) {
s.initialize(P);
s.value_ = v;
}
for (auto &s : r->rsensor) {
s.initialize(R);
}
}
}
double RoverDomain::mindist(POI *p) {
double minval = rovers[0]->psensor[0].delta(p->l_);
for (auto &r : rovers) {
minval = std::min(r->psensor[0].delta(p->l_), minval);
}
minval = std::max(rovers[0]->psensor[0].dmin_, minval);
return minval;
}
double RoverDomain::Gt() {
double global = 0.0; // g at a particular timestep
for (auto &p : pois)
global += p->value_ / mindist(p);
return global;
}
void RoverDomain::simulateStep(matrix2d A) {
matrix2d S = getStates();
if (seqs.size()==0) seqs = std::vector<IDomainStateful::StateActionSequence>(k_num_agents_);
if (seqs_alt.size()==0) seqs_alt = std::vector<IDomainStateful::StateActionSequence>(k_num_agents_);
for (uint i = 0; i < A.size(); i++) {
//append(state_history_[i], S[i]);
//append(action_history_[i], A[i]);
seqs[i].push_back(std::make_pair(S[i],A[i]));
seqs_alt[i].push_back(std::make_pair(S[i], matrix1d(A[i].size(),0.0)));
matrix1d xy(2);
xy[0] = rovers[i]->l_->x_;
xy[1] = rovers[i]->l_->y_;
rovers[i]->loc_history.push_back(xy);
(*rovers[i]->l_) += A[i];
}
g_cumulative_ += Gt();
if (*cur_step_ == k_num_steps_ - 1) {
//state_action_log_.push_back(getStateActionHistory());
G_log.push_back(g_cumulative_);
//state_history_saved_ = state_history_;
//action_history_saved_ = action_history_;
resetSAG();
}
}
void RoverDomain::reset() {
g_cumulative_ = 0.0;
for (int i = 0; i < NPOIS; i++) {
(*pois[i]->l_) = poi_start_locs_[i];
}
for (int j = 0; j < NROVS; j++) {
(*rovers[j]->l_) = rover_start_locs_[j];
rovers[j]->loc_history.clear();
}
initialize();
(*cur_step_) = 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Devices::Midi {
struct IMidiChannelPressureMessage;
struct IMidiChannelPressureMessageFactory;
struct IMidiControlChangeMessage;
struct IMidiControlChangeMessageFactory;
struct IMidiInPort;
struct IMidiInPortStatics;
struct IMidiMessage;
struct IMidiMessageReceivedEventArgs;
struct IMidiNoteOffMessage;
struct IMidiNoteOffMessageFactory;
struct IMidiNoteOnMessage;
struct IMidiNoteOnMessageFactory;
struct IMidiOutPort;
struct IMidiOutPortStatics;
struct IMidiPitchBendChangeMessage;
struct IMidiPitchBendChangeMessageFactory;
struct IMidiPolyphonicKeyPressureMessage;
struct IMidiPolyphonicKeyPressureMessageFactory;
struct IMidiProgramChangeMessage;
struct IMidiProgramChangeMessageFactory;
struct IMidiSongPositionPointerMessage;
struct IMidiSongPositionPointerMessageFactory;
struct IMidiSongSelectMessage;
struct IMidiSongSelectMessageFactory;
struct IMidiSynthesizer;
struct IMidiSynthesizerStatics;
struct IMidiSystemExclusiveMessageFactory;
struct IMidiTimeCodeMessage;
struct IMidiTimeCodeMessageFactory;
struct MidiActiveSensingMessage;
struct MidiChannelPressureMessage;
struct MidiContinueMessage;
struct MidiControlChangeMessage;
struct MidiInPort;
struct MidiMessageReceivedEventArgs;
struct MidiNoteOffMessage;
struct MidiNoteOnMessage;
struct MidiOutPort;
struct MidiPitchBendChangeMessage;
struct MidiPolyphonicKeyPressureMessage;
struct MidiProgramChangeMessage;
struct MidiSongPositionPointerMessage;
struct MidiSongSelectMessage;
struct MidiStartMessage;
struct MidiStopMessage;
struct MidiSynthesizer;
struct MidiSystemExclusiveMessage;
struct MidiSystemResetMessage;
struct MidiTimeCodeMessage;
struct MidiTimingClockMessage;
struct MidiTuneRequestMessage;
}
namespace Windows::Devices::Midi {
struct IMidiChannelPressureMessage;
struct IMidiChannelPressureMessageFactory;
struct IMidiControlChangeMessage;
struct IMidiControlChangeMessageFactory;
struct IMidiInPort;
struct IMidiInPortStatics;
struct IMidiMessage;
struct IMidiMessageReceivedEventArgs;
struct IMidiNoteOffMessage;
struct IMidiNoteOffMessageFactory;
struct IMidiNoteOnMessage;
struct IMidiNoteOnMessageFactory;
struct IMidiOutPort;
struct IMidiOutPortStatics;
struct IMidiPitchBendChangeMessage;
struct IMidiPitchBendChangeMessageFactory;
struct IMidiPolyphonicKeyPressureMessage;
struct IMidiPolyphonicKeyPressureMessageFactory;
struct IMidiProgramChangeMessage;
struct IMidiProgramChangeMessageFactory;
struct IMidiSongPositionPointerMessage;
struct IMidiSongPositionPointerMessageFactory;
struct IMidiSongSelectMessage;
struct IMidiSongSelectMessageFactory;
struct IMidiSynthesizer;
struct IMidiSynthesizerStatics;
struct IMidiSystemExclusiveMessageFactory;
struct IMidiTimeCodeMessage;
struct IMidiTimeCodeMessageFactory;
struct MidiActiveSensingMessage;
struct MidiChannelPressureMessage;
struct MidiContinueMessage;
struct MidiControlChangeMessage;
struct MidiInPort;
struct MidiMessageReceivedEventArgs;
struct MidiNoteOffMessage;
struct MidiNoteOnMessage;
struct MidiOutPort;
struct MidiPitchBendChangeMessage;
struct MidiPolyphonicKeyPressureMessage;
struct MidiProgramChangeMessage;
struct MidiSongPositionPointerMessage;
struct MidiSongSelectMessage;
struct MidiStartMessage;
struct MidiStopMessage;
struct MidiSynthesizer;
struct MidiSystemExclusiveMessage;
struct MidiSystemResetMessage;
struct MidiTimeCodeMessage;
struct MidiTimingClockMessage;
struct MidiTuneRequestMessage;
}
namespace Windows::Devices::Midi {
template <typename T> struct impl_IMidiChannelPressureMessage;
template <typename T> struct impl_IMidiChannelPressureMessageFactory;
template <typename T> struct impl_IMidiControlChangeMessage;
template <typename T> struct impl_IMidiControlChangeMessageFactory;
template <typename T> struct impl_IMidiInPort;
template <typename T> struct impl_IMidiInPortStatics;
template <typename T> struct impl_IMidiMessage;
template <typename T> struct impl_IMidiMessageReceivedEventArgs;
template <typename T> struct impl_IMidiNoteOffMessage;
template <typename T> struct impl_IMidiNoteOffMessageFactory;
template <typename T> struct impl_IMidiNoteOnMessage;
template <typename T> struct impl_IMidiNoteOnMessageFactory;
template <typename T> struct impl_IMidiOutPort;
template <typename T> struct impl_IMidiOutPortStatics;
template <typename T> struct impl_IMidiPitchBendChangeMessage;
template <typename T> struct impl_IMidiPitchBendChangeMessageFactory;
template <typename T> struct impl_IMidiPolyphonicKeyPressureMessage;
template <typename T> struct impl_IMidiPolyphonicKeyPressureMessageFactory;
template <typename T> struct impl_IMidiProgramChangeMessage;
template <typename T> struct impl_IMidiProgramChangeMessageFactory;
template <typename T> struct impl_IMidiSongPositionPointerMessage;
template <typename T> struct impl_IMidiSongPositionPointerMessageFactory;
template <typename T> struct impl_IMidiSongSelectMessage;
template <typename T> struct impl_IMidiSongSelectMessageFactory;
template <typename T> struct impl_IMidiSynthesizer;
template <typename T> struct impl_IMidiSynthesizerStatics;
template <typename T> struct impl_IMidiSystemExclusiveMessageFactory;
template <typename T> struct impl_IMidiTimeCodeMessage;
template <typename T> struct impl_IMidiTimeCodeMessageFactory;
}
namespace Windows::Devices::Midi {
enum class MidiMessageType
{
None = 0,
NoteOff = 128,
NoteOn = 144,
PolyphonicKeyPressure = 160,
ControlChange = 176,
ProgramChange = 192,
ChannelPressure = 208,
PitchBendChange = 224,
SystemExclusive = 240,
MidiTimeCode = 241,
SongPositionPointer = 242,
SongSelect = 243,
TuneRequest = 246,
EndSystemExclusive = 247,
TimingClock = 248,
Start = 250,
Continue = 251,
Stop = 252,
ActiveSensing = 254,
SystemReset = 255,
};
}
}
|
//
// Created by wqy on 19-11-28.
//
#ifndef VERIFIER_EDGE_H
#define VERIFIER_EDGE_H
#include "Vertex.h"
#include "Action/Action.h"
#include "Guard/Guard.h"
using std::list;
namespace esc {
class Edge {
private:
Vertex* from;
Vertex* to;
Guard* guard;
list<Action*> actions;
public:
Edge() : from(NULL), to(NULL), guard(NULL), actions(list<Action*>{}) {}
Edge(Vertex* _from, Vertex* _to) : from(_from), to(_to), guard(NULL), actions(list<Action*>{}) {}
Edge(Vertex* _from, Vertex* _to, Guard* _guard) : from(_from), to(_to), guard(_guard), actions(list<Action*>{}) {}
Edge(Vertex* _from, Vertex* _to, Guard* _guard, list<Action*> _actions) : from(_from), to(_to), guard(_guard), actions(_actions) {}
Vertex* getFrom() {return this->from;}
Vertex* getTo() {return this->to;}
Guard* getGuard() {return this->guard;}
list<Action*> getActions() {return this->actions;}
void setFromVertex(Vertex* _from);
void serToVertex(Vertex* _to);
void setGuard(Guard* _guard);
void setActions(list<Action*> _actions);
void addAction(Action* _action);
};
}
#endif //VERIFIER_EDGE_H
|
#include "gtest/gtest.h"
#include "config_parser.h"
#include <sstream>
#include <iterator>
class ConfigParserSemanticsTest : public ::testing::Test {
protected:
NginxConfigParser parser;
NginxConfig out_config;
std::string handler_text = // TODO: add quotes to url and root argument
"listen 8000;\n"
"location \"/echo\" EchoHandler {\n"
"}\n"
"location /static1 StaticHandler {\n"
" root /static_files1;\n"
"}\n"
"location \"/static 2\" StaticHandler {\n"
" root \"/static files 2\";\n"
"}\n"
"location \"/status\" StatusHandler {\n"
"}\n"
"location \"/health\" HealthHandler {\n"
"}\n"
"location \"/leaderboard\" LeaderboardHandler {\n"
"}\n"
"location \"/snake\" SnakeHandler {\n"
" root \"/game\";\n"
"}";
};
//
// unit tests for NginxConfigStatements
//
TEST(ConfigStatementTest, BasicStatement){
NginxConfigStatement statement;
EXPECT_TRUE(statement.getUrl() == "");
EXPECT_TRUE(statement.getStatementType() == NginxConfigStatement::Statement_Type::UNSPECIFIED);
EXPECT_TRUE(statement.getRoot() == "");
EXPECT_TRUE(statement.getPort() == 0);
}
TEST(ConfigStatementTest, BuildStatement){
NginxConfigStatement statement;
statement.setUrl("my url").setStatementType(NginxConfigStatement::Statement_Type::ECHO_HANDLER).setRoot("my root").setPort(8);
EXPECT_TRUE(statement.getUrl() == "my url");
EXPECT_TRUE(statement.getStatementType() == NginxConfigStatement::Statement_Type::ECHO_HANDLER);
EXPECT_TRUE(statement.getRoot() == "my root");
EXPECT_TRUE(statement.getPort() == 8);
}
TEST(ConfigStatementTest, CopyStatement){
NginxConfigStatement statementA;
statementA.setUrl("my url").setStatementType(NginxConfigStatement::Statement_Type::ECHO_HANDLER).setRoot("my root").setPort(8);
NginxConfigStatement statementB(statementA);
EXPECT_TRUE(statementB.getUrl() == "my url");
EXPECT_TRUE(statementB.getStatementType() == NginxConfigStatement::Statement_Type::ECHO_HANDLER);
EXPECT_TRUE(statementB.getRoot() == "my root");
EXPECT_TRUE(statementB.getPort() == 8);
}
//
// unit tests for parsing handler information from config file
//
TEST_F(ConfigParserSemanticsTest, HandlerConfig1) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[1];
EXPECT_TRUE(block->getUrl() == "/echo");
EXPECT_TRUE(block->getStatementType() == NginxConfigStatement::Statement_Type::ECHO_HANDLER);
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig2) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[1];
EXPECT_TRUE(block->getUrl() == "/echo");
EXPECT_TRUE(block->getRoot() == "");
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig3) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[2];
EXPECT_TRUE(block->getUrl() == "/static1");
EXPECT_TRUE(block->getStatementType() == NginxConfigStatement::Statement_Type::STATIC_HANDLER);
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig4) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[2];
EXPECT_TRUE(block->getUrl() == "/static1");
EXPECT_TRUE(block->getRoot() == "/static_files1");
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig5) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[3];
EXPECT_TRUE(block->getUrl() == "/static 2");
EXPECT_TRUE(block->getStatementType() == NginxConfigStatement::Statement_Type::STATIC_HANDLER);
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig6) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[3];
EXPECT_TRUE(block->getUrl() == "/static 2");
EXPECT_TRUE(block->getRoot() == "/static files 2");
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig7) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[4];
EXPECT_TRUE(block->getUrl() == "/status");
EXPECT_TRUE(block->getStatementType() == NginxConfigStatement::Statement_Type::STATUS_HANDLER);
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig8) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
for (const auto &block : config_blocks){
EXPECT_TRUE(block->getUrl() != "/nonexistent");
}
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig9) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
for (const auto &block : config_blocks){
EXPECT_TRUE(block->getUrl() != "/nonexistent");
}
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig10) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[5];
EXPECT_TRUE(block->getUrl() == "/health");
EXPECT_TRUE(block->getStatementType() == NginxConfigStatement::Statement_Type::HEALTH_HANDLER);
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig11) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[6];
EXPECT_TRUE(block->getUrl() == "/leaderboard");
EXPECT_TRUE(block->getStatementType() == NginxConfigStatement::Statement_Type::LEADERBOARD_HANDLER);
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig12) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[7];
EXPECT_TRUE(block->getUrl() == "/snake");
EXPECT_TRUE(block->getStatementType() == NginxConfigStatement::Statement_Type::SNAKE_HANDLER);
}
TEST_F(ConfigParserSemanticsTest, HandlerConfig13) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &block = config_blocks[7];
EXPECT_TRUE(block->getUrl() == "/snake");
EXPECT_TRUE(block->getRoot() == "/game");
}
//
// unit tests for parsing port number from config file
//
TEST_F(ConfigParserSemanticsTest, PortConfig1) {
std::stringstream handler_config(handler_text);
parser.Parse(&handler_config, &out_config);
std::map<std::string, std::string>::iterator it;
std::vector<std::shared_ptr<NginxConfig>> config_blocks = out_config.parse_handlers();
const auto &statement = config_blocks[0]->statements_[0];
EXPECT_TRUE(statement->getPort() == 8000);
EXPECT_TRUE(statement->getStatementType() == NginxConfigStatement::Statement_Type::PORT);
}
TEST_F(ConfigParserSemanticsTest, PortConfig2) {
std::stringstream port_config(handler_text);
parser.Parse(&port_config, &out_config);
unsigned short port = 0;
out_config.get_port_num(port);
EXPECT_TRUE(port == 8000);
}
TEST_F(ConfigParserSemanticsTest, PortConfig3) {
std::string port_config_text =
"listen 4189129;\n"
"location / EchoHandler {\n"
"}\n";
std::stringstream port_config(port_config_text);
parser.Parse(&port_config, &out_config);
unsigned short port = 0;
out_config.get_port_num(port);
EXPECT_TRUE(port == 0);
}
TEST_F(ConfigParserSemanticsTest, PortConfig4) {
std::string port_config_text =
"location /static1 StaticHandler {\n"
" root /static_files1;\n"
"}\n";
std::stringstream port_config(port_config_text);
parser.Parse(&port_config, &out_config);
unsigned short port = 0;
out_config.get_port_num(port);
EXPECT_TRUE(port == 0);
}
TEST_F(ConfigParserSemanticsTest, PortConfig5) {
std::string port_config_text =
"location /static1 StaticHandler {\n"
" root /static_files1;\n"
" listen 8000;"
"}\n";
std::stringstream port_config(port_config_text);
parser.Parse(&port_config, &out_config);
unsigned short port = 0;
out_config.get_port_num(port);
EXPECT_TRUE(port == 0);
}
|
#include <iostream>
#include <vector>
using namespace std;
/*
Implementation of a class stack, storing the stack elements in a vector.
constructor: initially the stack is empty
bool isEmpty() const: return whether the stack is empty
void push (int i): putting i on top of the stack
int top() const: return the top element from the stack but do not change the stack.
This function produces an error if the stack is empty.
void pop(): remove the top element from the stack. This function produces an error if
the stack is empty.
*/
class Stack{
private:
vector<int> stack;
public:
Stack();
bool isEmpty();
void push (int i);
int top() const;
void pop();
vector<int> getstackvalues();
bool empty;
};
Stack::Stack(){
vector<int> stack;
}
bool Stack::isEmpty(){
if(stack.size()==0){
cout << "---Stack is empty---" << endl;
empty = true;
}
else cout << "--Stack is not empty" << endl;
return empty;
}
void Stack::push(int i){
stack.push_back(i);
}
int Stack::top() const{
return stack.back();
}
void Stack::pop(){
stack.pop_back();
}
vector<int> Stack::getstackvalues(){
return stack;
}
int main(){
Stack s;
vector<int> stackvec;
s.isEmpty();
cout << "Stack after pushing" << endl;
s.push(1);
s.push(2);
s.push(3);
stackvec = s.getstackvalues();
for(int i=0; i<stackvec.size(); i++){
cout << stackvec[i] << endl;
}
cout << "Top element in the stack" << endl;
cout << s.top() << endl;
cout << "Stack after poping" << endl;
s.pop();
stackvec=s.getstackvalues();
for(int i=0; i<stackvec.size(); i++){
cout << stackvec[i] << endl;
}
return 0;
}
|
//! Bismillahi-Rahamanirahim.
/** ========================================**
** @Author: Md. Abu Farhad ( RUET, CSE'15)
** @Category:
/** ========================================**/
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define scl(n) scanf("%lld", &n)
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define pfl(x) printf("%lld\n",x)
int main()
{
ll m,n,c,d,i,j,k,x,y,z,l,q,r;
ll cnt=0,ans=0, ev1=0,ev2=0,od1=0,od2=0;
cin>>n>>m;
ll a[n],b[m];
for(i=0;i<n;i++) { cin>>a[i]; if(a[i]%2==0 ) ev1++; else od1++;}
for(i=0;i<m;i++) { cin>>b[i]; if(b[i]%2==0 )ev2++; else od2++;}
pfl( min(ev1, od2 ) + min( ev2, od1) );
return 0;
}
|
#pragma once
#include <vector>
#include <random>
using namespace std;
class VasicekModel
{
public:
VasicekModel(double a, double b, double Sigma, double r0) :
ma(a), mb(b), mSigma(Sigma), mr0(r0) {}
void GeneratePath(double Time, int Steps);
double PathDependentDF(double Time, int Steps);
double MCDF(double Time, int steps, int N, double &DFError);
double DiscountFactor(double Time);
double A(double Time);
double B(double Time);
double Rcc(double Time);
double Fcc(double Time, double epsilon);
private:
double ma;
double mb;
double mSigma;
double mr0;
vector<double> MyPath;
};
|
#include <iostream>
using namespace std;
// int add(int a, int b)
// {
// return a + b;
// }
template <typename T>
int addWithTemplate(T a, T b)
{
return a + b;
}
int main(int argc, char *argv[])
{
int a = 100;
int b = 10;
char c = 'a';
// cout << add(b, c) << endl;
// cout << addWithTemplate(a, c) << endl; // (int, char) err
cout << addWithTemplate(a, b) << endl; // (int, int) ok
cout << addWithTemplate<int>(a, c) << endl; // (int, char) ok
return 0;
}
|
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>
#include <math.h>
#define MAX 1001
using namespace std;
int N, S, Max = 0;
vector<int> Subway;
void Input()
{
cin >> N;
for(int i = 0; i < N; i++)
{
cin >> S;
Subway.push_back(S);
}
}
void Solution()
{
int Start = -1;
int End = -1;
if(Subway[0] == 0)
{
for(int i = 0; i < N; i++)
{
if(Subway[i] == 1) break;
Start++;
}
Max = Start + 1;
}
if(Subway[N - 1] == 0)
{
for(int i = N - 1; i >= Start + 1; i--)
{
if(Subway[i] == 1) break;
End++;
}
Max = max(Max, End + 1);
}
int Cnt = 0;
for(int i = Start + 1; i < N - (End + 1); i++)
{
if(Subway[i] == 0)
{
Cnt++;
}
else
{
Max = max(Max, (Cnt / 2) + 1);
Cnt = 0;
}
}
}
void Solve()
{
Solution();
cout << Max << endl;
}
int main()
{
Input();
Solve();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.